text
stringlengths
8
6.88M
/************************************************************************ * @project : $rootnamespace$ * @class : $safeitemrootname$ * @version : v1.0.0 * @description : * @author : $username$ * @creat : $time$ * @revise : $time$ ************************************************************************ * Copyright @ OscarShen 2017. All rights reserved. ************************************************************************/ #pragma once #ifndef SLOTH_TERRAIN_TEXTURE_H_ #define SLOTH_TERRAIN_TEXTURE_H_ #include <sloth.h> namespace sloth { class TerrainTexture { private: unsigned int m_ID; public: TerrainTexture(unsigned int id) :m_ID(id) {} inline unsigned int getID() const { return m_ID; } }; } #endif // !SLOTH_TERRAIN_TEXTURE_H_
/* * Copyright (C) 2007,2008 Alex Shulgin * * This file is part of png++ the C++ wrapper for libpng. PNG++ is free * software; the exact copying conditions are as follows: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 PNGPP_COLOR_HPP_INCLUDED #define PNGPP_COLOR_HPP_INCLUDED #pragma once #include <spdlog/spdlog.h> #include "types.hpp" namespace png { /** * \brief PNG color struct extension. Adds constructors. */ struct color : public png_color { inline constexpr explicit color(byte r = 0, byte g = 0, byte b = 0) noexcept { this->red = r; this->green = g; this->blue = b; if constexpr(enable_logging) { spdlog::info("color:explicit RGB constructor"); } } /** * \brief Initializes color with a copy of png_color object. */ inline constexpr color(const png_color& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("png_color:ctor"); } } // Rule of Five inline constexpr color(png_color&& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("png_color:mtor"); } } inline constexpr color& operator=(const png_color& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("png_color:copyassign"); } return *this; } inline constexpr color& operator=(png_color&& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("png_color:moveassign"); } return *this; } inline constexpr color(const color& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("color:ctor"); } } inline constexpr color(color&& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("color:mtor"); } } inline constexpr color& operator=(const color& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("color:copyassign"); } return *this; } inline constexpr color& operator=(color&& other) noexcept { this->red = other.red; this->green = other.green; this->blue = other.blue; if constexpr(enable_logging) { spdlog::info("color:moveassign"); } return *this; } inline constexpr ~color() noexcept = default; inline constexpr auto operator<=>(const color& other) const noexcept = default; }; } // namespace png #endif // PNGPP_COLOR_HPP_INCLUDED
// ========================================================================== // $Id: g_Vector.cpp 3389 2012-10-19 08:23:25Z jlang $ // Wrapper code to interface g_plane // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: Jochen Lang // Email: jlang@site.uottawa.ca // ========================================================================== // $Rev: 3389 $ // $LastChangedBy: jlang $ // $LastChangedDate: 2012-10-19 04:23:25 -0400 (Fri, 19 Oct 2012) $ // ========================================================================== #ifndef WRAPPER_G_VECTOR_CPP #define WRAPPER_G_VECTOR_CPP // Should use a namespace #include "g_Vector.h" g_Vector operator*(double _s,const g_Vector& _oVec) { g_Vector res(_oVec); res *= _s; return res; } #endif
/**************************************************************** * TianGong RenderLab * * Copyright (c) Gaiyitp9. All rights reserved. * * This code is licensed under the MIT License (MIT). * *****************************************************************/ #pragma once #include <iostream> namespace TG::Debug { template<typename Text> struct TextTraits { using TextType = Text; static constexpr bool IsText = std::is_same_v<TextType, char> || std::is_same_v<TextType, wchar_t>; static constexpr bool Wide = std::is_same_v<TextType, wchar_t>; }; template<typename Text> struct TextTraits<const Text> : TextTraits<Text> {}; // 移除Text的const修饰符 template<typename CharT> struct TextTraits<CharT*> : TextTraits<CharT> {}; template<typename CharT, size_t N> struct TextTraits<CharT[N]> : TextTraits<CharT> {}; template<typename CharT> struct TextTraits<std::basic_string<CharT>> : TextTraits<CharT> {}; template<typename CharT> struct TextTraits<std::basic_string_view<CharT>> : TextTraits<CharT> {}; // 窄文本概念,文本包含的字符是char类型 template<typename Text> concept NarrowText = TextTraits<Text>::IsText && !TextTraits<Text>::Wide; // 宽文本概念,文本包含的是wchar_t类型 template<typename Text> concept WideText = TextTraits<Text>::IsText && TextTraits<Text>::Wide; // 注:1. 尽量使用窄文本,性能比宽文本好 // 2. 换行符用\n,不要用std::endl,后者会刷新缓冲区到设备,会影响性能 template<NarrowText Text> inline void Log(const Text &log) { std::cout << log; } template<WideText Text> inline void Log(const Text &log) { std::wcout << log; } template<NarrowText Text> inline void LogLine(const Text &log) { std::cout << log << '\n'; } template<WideText Text> inline void LogLine(const Text &log) { std::wcout << log << L'\n'; } }
/* Copyright 2021 University of Manchester 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 "udma_memory_block.hpp" using orkhestrafs::dbmstodspi::UDMAMemoryBlock; UDMAMemoryBlock::~UDMAMemoryBlock() = default; // Needs to get rid of the volatile. Current stuff below doesn't make sense auto UDMAMemoryBlock::GetVirtualAddress() -> volatile uint32_t* { intptr_t address = reinterpret_cast<intptr_t>(udma_device_->map()); address += (-address) & 15; return reinterpret_cast<volatile uint32_t*>(address); } auto UDMAMemoryBlock::GetPhysicalAddress() -> volatile uint32_t* { intptr_t initial_address = reinterpret_cast<intptr_t>(udma_device_->map()); intptr_t offset = (-initial_address) & 15; return reinterpret_cast<volatile uint32_t*>(udma_device_->phys_addr + offset); } auto UDMAMemoryBlock::GetSize() -> const uint32_t { intptr_t initial_address = reinterpret_cast<intptr_t>(udma_device_->map()); intptr_t offset = (-initial_address) & 15; return udma_device_->size - offset; }
/* leetcode 39 * * * */ #include<stdio.h> #include<cstring> #include<iostream> #include<algorithm> // std::sort #include<cstring> #include<vector> #include<set> #include<string> #include<map> #include<queue> #include<stack> #include<deque> #include<unordered_set> #include<unordered_map> using namespace std; class Solution { public: vector<vector<int>> ans; void travel(vector<int>& cur, int sum, int begin, int target, vector<int>& candidates) { if (sum == target) { ans.push_back(cur); return; } if (sum > target) { return; } for (int i = begin; i < candidates.size(); i++) { cur.push_back(candidates.at(i)); travel(cur, sum + cur.back(), i, target, candidates); cur.pop_back(); } return; } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<int> cur; travel(cur, 0, 0, target, candidates); return ans; } }; /************************** run solution **************************/ vector<vector<int>> _solution_run(vector<int>& candidates, int target) { Solution leetcode_39; vector<vector<int>> ans = leetcode_39.combinationSum(candidates, target); return ans; } #ifdef USE_SOLUTION_CUSTOM string _solution_custom(TestCases &tc) { } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
#include <stdlib.h> #include <iostream> #include <fstream> #include <memory> #include <typeinfo.h> #include <msxml6.h> #include <vector> #include <exception> #include <Psapi.h> #include <algorithm> #include <map> #include "ConfigSetting.h" #include "stdafx.h" #import "msxml6.dll" namespace JNIBridge { namespace Config { class ConfigReader { private: HANDLE GetThreadToken(); BOOL LocateConfigFile(); void ProcessElementRecursively(IXMLDOMNodePtr& node); BOOL ParseConfigFile(const std::wstring& configFile); std::vector<JNIBridge::Structs::ConfigSetting> m_settings; void ExtractInformationFromElement(IXMLDOMNodePtr& node); std::map<const std::wstring, const std::wstring> Properties; BOOL SetPrivilege(HANDLE& hToken, LPCTSTR Privilege, BOOL bEnablePrivilege); std::wstring DoesConfigFileExist(const HANDLE& hProcess, std::vector<HMODULE>& hModules, const wchar_t* targetImage); protected: public: ConfigReader(); ~ConfigReader(); void ReadConfig(const char* configFile); const std::wstring GetSetting(const wchar_t* key); std::vector<JNIBridge::Structs::ConfigSetting>& Settings_get(); }; } }
#ifndef CModifyIdMessage_H #define CModifyIdMessage_H #include "CMessage.h" #include <QObject> //Ãŵê±àºÅ×¢²á class CModifyIdMessage : public CMessage { Q_OBJECT public: CModifyIdMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent = 0); ~CModifyIdMessage(); virtual bool packedSendMessage(NetMessage& netMessage); virtual bool treatMessage(const NetMessage& netMessage, CNetClt* pNet); }; #endif // CModifyIdMessage_H
#include <Main.h> int main() { ConcreteRenderController* renderController = new ConcreteRenderController(); renderController->infinity(); renderController->finish(); } float getFrameTimeSeconds() { return (float)ConcreteRenderController::getFrameTimeSeconds(); } vec2 getMousePosition() { return Mouse::getPosition(); } int getMouseLeftState(){ return Mouse::getLeftState(); } int getMouseRightState(){ return Mouse::getRightState(); return 0; } vec2 getDisplaySize() { return vec2(GUI::getWidth(), GUI::getHeight()); } int checkForOpenGLError(const char* file, int line) { // return 1 if an OpenGL error occured, 0 otherwise. /*GLenum glErr; int retCode = 0; glErr = glGetError(); while (glErr != GL_NO_ERROR) { cout << "glError in file " << file << "@line " << line << endl; retCode = 1; exit(EXIT_FAILURE); } return retCode;*/ return 0; }
#include "widget.h" #include <QApplication> #include <QDebug> //需求,为了传火箭类中的对象,保证只有一个对象实例 class ChairMan { //构造函数私有化 private: ChairMan(){ qDebug()<<"ChairMan"; } ChairMan(const ChairMan& p){} public: static ChairMan * getInstance() { return singleChairMAN; } private: static ChairMan * singleChairMAN; }; //ChairMan *ChairMan::singleChairMAN = new ChairMan; //void test01() //{ // ChairMan c1; // ChairMan *c2 = new ChairMan; //} //void test02() //{ // ChairMan::singleChairMAN; //} //class Printer{ //private: // Printer(){}; // Printer(const Printer &p){}; // static Printer *singlePrinter; //public: // Printer * getInstance(){ // return singlePrinter; // } // void printInl(QString & name) // { // qDebug()<<name; // } //}; //Printer* Printer::singlePrinter = new Printer(); //void test02() //{ // Printer *printer=Printer::getInstance(); // printer->printInl("123456"); //} class Cal { public: void setV1(int v1) { this->val1 = v1; } void setV2(int v2) { this->val2 = v2; } int GeyResult(QString oper) { if(oper =="+") { return this->val1+this->val2; } else if(oper =="-") { return this->val1-this->val2; } } int val1; int val2; }; void test01() { Cal cal; cal.setV1(1); cal.setV2(2); qDebug()<< cal.GeyResult("+"); } void test03() { // int array[10][10]={0}; int array[10]; for(int i=0;i<10;i++) { qDebug()<<array[i]; } } //利用多态实现计算器 class calBase{ public: void setV1(int v1) { this->val1 = v1; } void setV2(int v2) { this->val2 = v2; } virtual int getResult()=0;//纯虚函数 public: int val1; int val2; }; class jianfa:public calBase{ public: int getResult() { return this->val1-this->val2; } }; class jiafa:public calBase{ public: int getResult() { return this->val1+this->val2; } }; void test04() { calBase *abc = new jiafa; abc->setV1(1); abc->setV2(4 ); qDebug()<<abc->getResult(); } int main(int argc, char *argv[]) { QApplication a(argc, argv); test04(); return a.exec(); }
#ifndef TP_PPROJECT_BASECOMMAND_H #define TP_PPROJECT_BASECOMMAND_H #include <iostream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "src/server/lib/CompanyServer/MainServerLogic/MainLogic/Controller/Controller.h" /* * Base command class */ class BaseCommand { public: BaseCommand(const std::string &name) : name(name) {}; virtual ~BaseCommand() = default; /* * Executing a command */ virtual boost::property_tree::ptree execute(std::shared_ptr<Controller> controller) = 0; public: boost::property_tree::ptree commandParams; std::string name; }; #endif //TP_PPROJECT_BASECOMMAND_H
#include <Inventor/Win/SoWin.h> #include <Inventor/Win/viewers/SoWinExaminerViewer.h> #include "Mesh.h" #include "Painter.h" int main(int, char ** argv) { HWND window = SoWin::init(argv[0]); SoWinExaminerViewer * viewer = new SoWinExaminerViewer(window); //make a dead simple scene graph by using the Coin library, only containing a single cone under the scenegraph root SoSeparator * root = new SoSeparator; root->ref(); //stuff to be drawn on screen must be added to the root // SoCone * cone = new SoCone; // root->addChild(cone); Mesh* mesh = new Mesh(); Painter* painter = new Painter(); mesh->loadOff("0.off"); // mesh->createCube(20.0f); cout << "my (verts[4]) 1-ring neighborhood is: \n"; for (int nv = 0; nv < mesh->verts[4]->vertList.size(); nv++) cout << mesh->verts[4]->vertList[nv] << " neighbb\n"; cout << "my (verts[4]) 1-ring neighborhood is: \n"; for (int ne = 0; ne < mesh->verts[4]->edgeList.size(); ne++) if (mesh->edges[ mesh->verts[4]->edgeList[ne] ]->v1i == 4) cout << mesh->edges[ mesh->verts[4]->edgeList[ne] ]->v2i << " nnnnnnnnn\n"; else cout << mesh->edges[ mesh->verts[4]->edgeList[ne] ]->v1i << " nnnnnnnnn\n"; // cout << mesh->verts[4]->vertList[nv] << " neighbb\n"; root->addChild( painter->getShapeSep(mesh) ); viewer->setSize(SbVec2s(640, 480)); viewer->setSceneGraph(root); viewer->show(); SoWin::show(window); SoWin::mainLoop(); delete viewer; root->unref(); return 0; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; public slots: void SetLabelChange(); public: QString toKor(const char* str) { return QString::fromLocal8Bit(str); } }; #endif // MAINWINDOW_H
#include <iostream> #include <queue> #include <vector> using namespace std; #define MOD 1000003 // a x + b y = gcd(a, b) // ax = 1 // ax = 1 mod b long long extgcd(long long a, long long b, long long &x, long long &y) { long long g = a; x = 1; y = 0; if (b != 0) g = extgcd(b, a % b, y, x), y -= (a / b) * x; return g; } long long inverse(long long a, long long m){ long long ans, t; extgcd(a, m, ans, t); return (ans+MOD)%MOD; } long long factorial(long long n){ long long ans = 1; for(long long i = 2; i <= n; i++){ ans = (ans*i)%MOD; } return ans; } long long fast_exp(long long x, long long e){ if(e == 0) return 1; if(e%2 == 0){ long long k = fast_exp(x, e/2); return (k*k)%MOD; } else{ return (fast_exp(x, e-1)*x)%MOD; } } long long x[100100], n; int main(){ int t; cin >> t; for(int tc = 1; tc <= t; tc++){ cin >> n; long long sum = 0, pow2 = 1; for(int i = 0; i < n; i++){ cin >> x[i]; sum += x[i]; pow2 *= fast_exp(2, x[i]-1); pow2 %= MOD; } long long ans = 0; ans = factorial(sum); for(int i = 0; i < n; i++){ ans *= inverse(factorial(x[i]), MOD); ans %= MOD; } cout << "Case #" << tc << ": " << (ans*pow2)%MOD << endl; } }
// // Copyright 2015 Google Inc. // // 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. // // firebase-arduino is an Arduino client for Firebase. // It is currently limited to the ESP8266 board family. #ifndef firebase_h #define firebase_h //#include "WString.h" #include <Arduino.h> #include <ArduinoJson.h> #include <memory> #include "FirebaseError.h" #include "FirebaseHttpClient.h" #include "FirebaseObject.h" // Firebase REST API client. class Firebaseunused { public: Firebaseunused(const String&& host, const String&& auth = ""); const String& auth() const; // Fetch json encoded `value` at `path`. void get(const String& path); // Set json encoded `value` at `path`. void set(const String& path, const String& json); // Add new json encoded `value` to list at `path`. void push(const String& path, const String& json); // Delete value at `path`. void remove(const String& path); // Start a stream of events that affect value at `path`. void stream(const String& path); protected: // Used for testing. Firebaseunused() {} private: std::shared_ptr<FirebaseHttpClient> http_; String host_; String auth_; }; class FirebaseCall { public: FirebaseCall(const std::shared_ptr<FirebaseHttpClient> http = NULL) { http_ = http; } virtual ~FirebaseCall(); const std::shared_ptr<FirebaseError> error() const { return error_; } boolean analyzeError(const String& method, int status, const String& path_with_auth); const String& response() const { return response_; } // const void end(); const JsonObject& json(); int refreshLogin(const String& host, const String& path, const String& user, const String& password, String& refreshToken, String& auth); int refreshToken(const String& host, const String& path, const String& key, String& refreshToken, String& auth); protected: std::shared_ptr<FirebaseHttpClient> http_; std::shared_ptr<FirebaseError> error_; String response_; std::shared_ptr<StaticJsonBuffer<FIREBASE_JSONBUFFER_SIZE>> buffer_; }; class FirebaseRequest : public FirebaseCall { public: FirebaseRequest(const std::shared_ptr<FirebaseHttpClient> http = NULL) : FirebaseCall(http) {} virtual ~FirebaseRequest() {} int sendRequest(const String& host, const String& auth, const String& method, const String& path, const String& data = ""); }; class FirebaseStream : public FirebaseCall { public: FirebaseStream(const std::shared_ptr<FirebaseHttpClient> http = NULL) : FirebaseCall(http) {} virtual ~FirebaseStream() {} bool startStreaming(const String& host, const String& auth, const String& path); }; #endif // firebase_h
#ifndef SHOEMANAGERNETWORKRESULT_HPP #define SHOEMANAGERNETWORKRESULT_HPP #include "shoemanagernetwork_global.h" #include <QString> #include <QJsonObject> #include <QNetworkReply> #include <QJsonParseError> class SHOEMANAGERNETWORKSHARED_EXPORT ShoeManagerNetworkResult : public QObject { Q_OBJECT public: enum NetworkError{ Error_Network = -100, Error_ResponseFormat = -300, Error_NoCode = -1, Error_NoError = 0, }; signals: void requestFinished(); public: void parseReply(QNetworkReply *pReply); int oReturnCode; QString oReturnMessage; QJsonObject oRequestData; QJsonValue oReturnData; }; #endif // SHOEMANAGERNETWORKRESULT_HPP
#include<iostream> #include<stack> #include<algorithm> #include<vector> using namespace std; class MyQueue { public: /** Initialize your data structure here. */ MyQueue() { //基本思想:使用两个栈,入队O(n),出队O(1) //当栈push新进来一个元素val,则将栈里原来的所有元素依次出栈,val入栈,重新依次入栈,这样就使得新元素val位于栈底了而且原来元素顺序不变 } /** Push element x to the back of queue. */ void push(int x) { stack<int> st_temp; while (!st.empty()) { int temp = st.top(); st.pop(); st_temp.push(temp); } st.push(x); while (!st_temp.empty()) { int temp = st_temp.top(); st_temp.pop(); st.push(temp); } } /** Removes the element from in front of queue and returns that element. */ int pop() { int temp = st.top(); st.pop(); return temp; } /** Get the front element. */ int peek() { return st.top(); } /** Returns whether the queue is empty. */ bool empty() { return st.empty(); } private: stack<int> st; }; class MyQueue1 { public: /** Initialize your data structure here. */ MyQueue1() { //基本思想:使用两个栈,相当于模拟队列的两头一个栈模拟入队一头,一个栈模拟出队一头 } /** Push element x to the back of queue. */ void push(int x) { st1.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { if (!st2.empty()) { int temp = st2.top(); st2.pop(); return temp; } while (!st1.empty()) { int temp = st1.top(); st1.pop(); st2.push(temp); } int temp = st2.top(); st2.pop(); return temp; } /** Get the front element. */ int peek() { if (!st2.empty()) return st2.top(); while (!st1.empty()) { int temp = st1.top(); st1.pop(); st2.push(temp); } return st2.top(); } /** Returns whether the queue is empty. */ bool empty() { return st1.empty() && st2.empty(); } private: stack<int> st1; stack<int> st2; }; int main() { MyQueue1 queue; queue.push(1); queue.push(2); cout << queue.peek() << endl; // 返回 1 cout << queue.pop() << endl; // 返回 1 cout << queue.peek() << endl; // 返回 2 cout << queue.empty() << endl; // 返回 false return 0; }
#include <Arduino.h> #include <Ethernet.h> #include <Streaming.h> #include <SFEMP3Shield.h> // for debugging // #define DEBUG_RADIO // size of buffer #define MP3BUF_SIZE 65536 // must be a multiple of 32 // bytes in buffer to begin the reproduction (50 to 100% of MP3BUF_SIZE) #define MP3BUF_REFILL (65536/8)*7 #define METABUF_SIZE 4096 #define TITLE_SIZE 100 // max number of bytes read from internet stream #define CHUNK_SIZE 1024 class Radio : public EthernetClient { public: Radio( SFEMP3Shield mp3 ); boolean startRadio( char * name, char * server, char * url, uint16_t port ); void stopRadio(); boolean streamRadio(); void statistic( char * stat1, uint32_t * p_porcfill, uint32_t * p_fill ); private: int8_t connectRadio(); int32_t fillBuf( int32_t p ); void metadataTitle(); char * name; char * server; char * url; uint16_t port; SFEMP3Shield mp3; uint8_t mp3Buffer[ MP3BUF_SIZE ]; char metadataBuffer[ METABUF_SIZE ]; char titleBuffer[ TITLE_SIZE ]; boolean refill, doStream; int32_t p_read, p_write, nb_fill, nb_read; int32_t m_emptyBuf; uint8_t n_tryConnect; uint8_t fase; uint16_t metaint, metalen; int32_t b_read; int32_t t_fill, tnb_fill; int32_t filled, max_filled; #ifdef DEBUG_RADIO int32_t t_read; int32_t min_filled; uint32_t micros0, t_micros; #endif DEBUG_RADIO };
#include "heater.h" #include "arduinoIO.h" heaterSim::heaterSim(int heaterPinNr, adcSim* adc, int temperatureADCNr, float heaterStrength) { this->heaterPinNr = heaterPinNr; this->adc = adc; this->temperatureADCNr = temperatureADCNr; this->heaterStrength = heaterStrength; this->temperature = 20; } heaterSim::~heaterSim() { } void heaterSim::tick() { if (readOutput(heaterPinNr)) temperature += 0.03 * heaterStrength; else if (temperature > 20) temperature -= 0.03 * heaterStrength; adc->adcValue[temperatureADCNr] = 231 + temperature * 81 / 100;//Not accurate, but accurate enough. } void heaterSim::draw(int x, int y) { char buffer[32] = {0}; sprintf(buffer, "%iC", int(temperature)); drawString(x, y, buffer, 0xFFFFFF); }
/********************************** * Manchester Sampling Based Decode * Arduino Uno * pin 2 as external interrupt **********************************/ #define inputPin 2 #define debugLedPin 7 #define scopePin 6 int volatile pinRead = 0; unsigned long startTime = 0; unsigned long times[40]; boolean isReceiving = false; //flag when receving data boolean finish = false; //flag when finished 1 byte boolean reads[1024]; //array for input pin readings int index = 0; //reads array index int n = 0; void timer0_init() { // initialize timer0 TCCR0A = 0; TCCR0B = 0; TCNT0 = 0; OCR0A = 14; // T = 960us //TCCR0A |= (0 << WGM01); // normal mode TCCR0B |= (1 << CS00); // 101 TCCR0B |= (0 << CS01); // 1024x prescaler TCCR0B |= (1 << CS02); TIMSK0 |= (0 << OCIE0A); // enable timer0 TIMSK0 |= (0 << TOIE0); } void timer1_init() { // initialize timer1 TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; OCR1A = 79; //T = 40us TCCR1B |= (1 << WGM12); // CTC mode TCCR1B |= (0 << CS10); TCCR1B |= (1 << CS11); // 8x prescaler TCCR1B |= (0 << CS12); TIMSK1 |= (0 << OCIE1A); // enable timer compare interrupt } void setup() { // put your setup code here, to run once: pinMode(inputPin,INPUT); //pin 2 as input pin pinMode(3,OUTPUT); pinMode(debugLedPin,OUTPUT); digitalWrite(7,LOW); Serial.begin(9600); //serial init Serial.println("--Sampling Decode"); attachInterrupt(0,pin2ISR,FALLING); //interrupt on pin 2, falling timer0_init(); timer1_init(); } void loop() { //pinRead = digitalRead(inputPin); //Serial.println(pinRead); //delay(10); //Serial.println(digitalRead(inputPin)); if(finish) { //Serial.println(index); for(int i=0; i<n;i++) { Serial.print(reads[i]); } Serial.println(); finish = finish ^ 1; } } ///////////////////////// // ISR for Timer0 // Timer0 times out if no input in about 900 us //////////////////////// ISR(TIMER0_COMPA_vect) { isReceiving = false; //receive perioud timed out //Serial.println(index); TIMSK1 &= ~(1 << OCIE1A); //clear and stop timer1 TCCR0A = 0; TCCR1B = 0; TCNT1 = 0; TIMSK0 &= ~(1 << OCIE0A); //clear and stop timer0 TCCR0A = 0; TCCR0B = 0; TCNT0 = 0; //Serial.println("Timer0 isr"); //digitalWrite(6,HIGH); //digitalWrite(debugLedPin, digitalRead(debugLedPin) ^ 1); // toggle LED pin //Serial.println("Timer 0 isr"); if(index > 170){ detachInterrupt(0); //noInterrupts(); finish = true; n = index; } index = 0; } ///////////////////////// // ISR for Timer1 //////////////////////// ISR(TIMER1_COMPA_vect) { //read //Serial.println("timer 1 isr"); //digitalWrite(debugLedPin, digitalRead(debugLedPin)^1); reads[index] = digitalRead(inputPin) ^ 1; //digitalWrite(debugLedPin, reads[index] ^ 1); //Serial.print(reads[index]); index ++; } ///////////////////////// // ISR for inputPin (pin 2) //////////////////////// void pin2ISR() { if(isReceiving){ TCNT0 = 0; //feed timer0 } else { timer1_init(); TIMSK1 |= (1 << OCIE1A); timer0_init(); TIMSK0 |= (1 << OCIE0A); reads[index] = digitalRead(inputPin) ^ 1; index ++; isReceiving = true; //set receive flag //digitalWrite(debugLedPin, digitalRead(debugLedPin) ^ 1); } } void reset() { }
#ifndef GNCHARFUNCTIONS_H #define GNCHARFUNCTIONS_H #include <wchar.h> #include <string.h> #include <stdio.h> #include "GnSystemDefine.h" //GNFORCEINLINE gsize GnStrlen(const gchar* GNRESTRICT str); // //GNFORCEINLINE gchar* GnStrcpy(gchar* GNRESTRICT dest, const gchar* GNRESTRICT src, size_t destSize); // //GNFORCEINLINE gchar* GnStrncpy(gchar* GNRESTRICT dest, const gchar* GNRESTRICT src, size_t strLength, // size_t destSize); // //GNFORCEINLINE gint GnSprintf(gchar* GNRESTRICT buffer, gsize bufferSize, const gchar* GNRESTRICT format, ...); // //GNFORCEINLINE gchar* GnStrtok(gchar* GNRESTRICT pcString, const gchar* GNRESTRICTpcDelimit // , gchar** ppcContext); // //GNFORCEINLINE gint GnStrcmp(const gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2); // //GNFORCEINLINE gint GnStricmp(const gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2); // //GNFORCEINLINE const gchar* GnStrstr(const gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2); #ifdef WIN32 #define GnVssprintf vsprintf_s #else // WIN32 #define GnVssprintf vsprintf #endif // WIN32 typedef std::string gstring; gchar* GnAllocStrcpy(const gchar* GNRESTRICT src); static GNFORCEINLINE size_t GnStrlen(const gchar* GNRESTRICT str) { return strlen(str); } static GNFORCEINLINE gchar* GnStrcpy(gchar* GNRESTRICT dest, const gchar* GNRESTRICT src, size_t destSize) { #ifdef __GNUC__ return strcpy(dest, src); #else // #ifdef __GNUC__ strcpy_s(dest, destSize, src); return dest; #endif // #ifdef __GNUC__ } static GNFORCEINLINE gchar* GnStrncpy(gchar* GNRESTRICT dest, const gchar* src, size_t strLength, size_t destSize) { #ifdef __GNUC__ return strncpy(dest, src, strLength); #else // #ifdef __GNUC__ strncpy_s(dest, destSize, src, strLength); return dest; #endif // #ifdef __GNUC__ } static GNFORCEINLINE const gchar* GnStrcat(gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2, gsize destSize) { #ifdef __GNUC__ return strcat(pStr1, pStr2); #else // #ifdef __GNUC__ errno_t error = strcat_s(pStr1, destSize, pStr2); return pStr1; #endif // #ifdef __GNUC__ } static gint GnSprintf(gchar* GNRESTRICT buffer, gsize bufferSize, const gchar* GNRESTRICT format, ...) { va_list args; va_start( args, format ); #ifdef __GNUC__ gint ret = vsprintf(buffer, format, args); #else // #ifdef __GNUC__ gint ret = vsprintf_s(buffer, bufferSize, format, args); #endif // #ifdef __GNUC__ va_end(args); return ret; } static GNFORCEINLINE gchar* GnStrtok(gchar* GNRESTRICT pcString, const gchar* GNRESTRICT pcDelimit, gchar** GNRESTRICT ppcContext) { #if _MSC_VER >= 1400 return strtok_s(pcString, pcDelimit, ppcContext); #else // #if _MSC_VER >= 1400 return strtok(pcString, pcDelimit); #endif // #if _MSC_VER >= 1400 } static GNFORCEINLINE gint GnStrcmp(const gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2) { return strcmp(pStr1, pStr2); } static GNFORCEINLINE gint GnStricmp(const gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2) { #ifdef WIN32 return _stricmp(pStr1, pStr2); #else return strcasecmp(pStr1, pStr2); #endif // WIN32 } static GNFORCEINLINE const gchar* GnStrstr(const gchar* GNRESTRICT pStr1, const gchar* GNRESTRICT pStr2) { return strstr(pStr1, pStr2); } static GNFORCEINLINE gchar* GnStrchr(gchar* GNRESTRICT pStr1, int GNRESTRICT pStr2) { return strchr(pStr1, pStr2); } static GNFORCEINLINE const gchar* GnStrchr(const gchar* GNRESTRICT pStr1, int GNRESTRICT pStr2) { return strchr(pStr1, pStr2); } #endif // GNCHARFUNCTIONS_H
#include<bits/stdc++.h> #define rep(i, s, n) for (int i = (s); i < (int)(n); i++) #define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/ #define MOD 1000000007 using namespace std; using ll = long long; using Graph = vector<vector<int>>; using pint = pair<int,int>; const double PI = 3.14159265358979323846; int main(){ int N; cin >> N; vector<ll>A(N); rep(i,0,N)cin >> A[i]; vector<ll>sum(N); sum[0] = A[0]; rep(i,1,N)sum[i] = sum[i-1] + A[i]; ll ans = INF; for(int i = N-2; i >= 0 ; i--){ ans = min(ans, abs( (sum[N-1] - sum[i]) - sum[i] ) ); //ここまだ早くなりそう } cout << ans << endl; }
#ifndef TRANSITION #define TRANSITION #include <string> #include <iostream> #include <map> #include "element.hpp" #include "../../include/time_leak/place.hpp" class Place; namespace time_leak { class Transition : public time_leak::Element<Place> { public: enum TransitionType { high, low, lowStart, lowEnd, maxDuration }; private: bool highT; bool conditional = false; bool canDeduceEndTime(); bool canDeduceStartTime(); void analyzeIngoing(); TransitionType transitionType; public: Transition(std::string id, bool high = true, TransitionType type = TransitionType::high); TransitionType GetTransitionType(); bool IsHigh(); bool CheckIfLow(); bool Analyze(); std::string GetTransitionTypeString(); void SetTransitionType(TransitionType t); void SetConditional(bool value = true); bool GetConditional(); }; } // namespace time_leak #endif
/*...Part - 01...*/ #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <stack> #include <queue> #include <deque> #include <iterator> #include <bitset> #include <assert.h> #include <new> #include <sstream> //#include <bits/stdc++.h> using namespace std ; /*...Part - 02...*/ typedef long long ll ; typedef long double ld ; typedef unsigned long long ull ; typedef pair<int,int> pii ; typedef pair<ll,ll> pll ; typedef vector<int> vi ; typedef vector<ll> vll ; typedef vector<vector<int>> vvi ; int Int(){int x ; scanf("%d",&x) ; return x ;} ll Long(){ll x ; scanf("%lld",&x) ; return x ;} /*...Part - 03...*/ /*....Debugger....*/ #define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); } void err(istream_iterator<string> it) {cout << endl ;} template<typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = " << a << ' ' ; err(++it, args...); } /*...Part - 04...*/ /*...Needed to change according to problem requirements...*/ const int N = (int)2e5 + 5 ; const int maxN = (int)1e6 + 6 ; const ll Mod = (ll)1e9 + 7 ; const int inf = (int)2e9 ; const ll Inf = (ll)1e18 ; /*..........................................................*/ /*...Part - 05...*/ #define debug(x) cerr << #x << " = " << x << '\n' ; #define rep(i,b,e) for(__typeof(e) i = (b) ; i != (e + 1) - 2 * ((b) > (e)) ; i += 1 - 2 * ((b) > (e))) #define Int Int() #define Long Long() #define all(x) x.begin() , x.end() #define sz(x) (int)x.size() #define ff first #define ss second #define pb push_back #define eb emplace_back #define mem(a) memset(a , 0 ,sizeof a) #define memn(a) memset(a , -1 ,sizeof a) /*...Part - 06...*/ /*...... ! Code start from here ! ......*/ int team[N], par[N][20], low[N], in[N], ID[N], dep[N], comp[N]; int tm, cur, up[N], down[N]; vvi g ; vector < pii > brg ; void Set(){for(int i = 0 ; i < N ; ++i)team[i] = i ;} int Find(int s){return s == team[s] ? s : Find(team[s]) ;} void merge(int u, int v){team[Find(u)] = Find(v) ;} void bridge(int s, int p = 0){ low[s] = in[s] = ++tm ; int cnt = 0 ; for(int i : g[s]){ if(i == p){ if(cnt)low[s] = min(low[s], in[i]) ; else { cnt = 1 ; continue ; } } if(in[i])low[s] = min(low[s], in[i]) ; else{ bridge(i, s) ; low[s] = min(low[s], low[i]) ; if(low[i] > in[s]){ brg.pb({s, i}) ; } else{ merge(s, i) ; } } } } void dfs(int s, int p = 0){ par[s][0] = p ; dep[s] = 1 + dep[p] ; for(int i = 1 ; i < 17 ; ++i) par[s][i] = par[par[s][i - 1]][i - 1] ; for(int i : g[s]){ if(i - p)dfs(i, s) ; } } int LCA(int a, int b){ if(dep[a] < dep[b])swap(a, b) ; int d = dep[a] - dep[b] ; for(int i = 16 ; i >= 0 ; --i){ if(d & (1 << i))a = par[a][i] ; } if(a == b)return a; for(int i = 16 ; i >= 0 ; --i){ if(par[a][i] != par[b][i]) a = par[a][i], b = par[b][i] ; } return par[a][0] ; } int intersection(int a, int b, int c, int d){ int x = LCA(a, c) ; x = a ^ c ^ x ; int y = LCA(b, d) ; int dist = dep[y] - dep[x] ; return max(0, dist) ; } int main(){ int test = 1 , tc = 0 ; while(test--){ int n = Int, m = Int, q = Int ; g.resize(n + 1) ; for(int i = 1 ; i <= m ; ++i){ int x = Int, y = Int ; g[x].pb(y) ; g[y].pb(x) ; } Set() ; bridge(1) ; for(int i = 1 ; i <= n ; ++i){ comp[i] = Find(i) ; } vi st(n + 1, 0), box ; for(int i = 1 ; i <= n ; ++i){ int x = comp[i] ; if(st[x])continue ; box.pb(x) ; st[x] = 1 ; } sort(all(box)) ; n = sz(box) ; int cc = 0 ; for(int i : box){ ID[i] = ++cc ; } g.clear() ; g.resize(n + 1) ; for(auto i: brg){ int u = comp[i.ff], v = comp[i.ss] ; g[ID[u]].pb(ID[v]) ; g[ID[v]].pb(ID[u]) ; } dfs(1) ; while(q--){ int a = Int, b = Int, c = Int, d = Int ; a = ID[comp[a]], b = ID[comp[b]], c = ID[comp[c]], d = ID[comp[d]] ; int lca_ab = LCA(a, b) ; int lca_cd = LCA(c, d) ; int lca_abcd = LCA(lca_ab, lca_cd) ; int tot = dep[c] + dep[d] - 2 * dep[lca_cd] ; if(lca_abcd ^ lca_cd and lca_abcd ^ lca_ab){ printf("%d\n",tot); continue ; } int inter = intersection(lca_ab, a, lca_cd, c) ; inter += intersection(lca_ab, a, lca_cd, d) ; inter += intersection(lca_ab, b, lca_cd, c) ; inter += intersection(lca_ab, b, lca_cd, d) ; printf("%d\n",tot - inter); } } return 0 ; } /*...Always look at the part - 04...*/ /*...............END................*/
#pragma once #include "Productos.h" class Nodo { public: Productos* producto; Nodo* IZQUIERDA = nullptr; Nodo* DERECHA = nullptr; Nodo* ABAJO = nullptr; Nodo* ARRIBA = nullptr; public: Nodo(Productos* produc); Nodo(); };
/* +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Mel Dafert (mel@dafert.at) | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "../intl_cppshims.h" #include <unicode/dtptngen.h> extern "C" { #define USE_DATETIMEPATTERNGENERATOR_POINTER 1 #include "datepatterngenerator_class.h" #include "datepatterngenerator_arginfo.h" #include <zend_exceptions.h> #include <assert.h> } using icu::DateTimePatternGenerator; using icu::Locale; zend_class_entry *IntlDatePatternGenerator_ce_ptr; zend_object_handlers IntlDatePatternGenerator_handlers; static zend_object *IntlDatePatternGenerator_object_clone(zend_object *object) { intl_error_reset(NULL); IntlDatePatternGenerator_object *dtpgo_orig = php_intl_datepatterngenerator_fetch_object(object); intl_error_reset(DTPATTERNGEN_ERROR_P(dtpgo_orig)); zend_object *ret_val = IntlDatePatternGenerator_ce_ptr->create_object(object->ce); IntlDatePatternGenerator_object *dtpgo_new = php_intl_datepatterngenerator_fetch_object(ret_val); zend_objects_clone_members(&dtpgo_new->zo, &dtpgo_orig->zo); if (dtpgo_orig->dtpg != NULL) { DateTimePatternGenerator *newDtpg = dtpgo_orig->dtpg->clone(); if (!newDtpg) { zend_string *err_msg; intl_errors_set_code(DTPATTERNGEN_ERROR_P(dtpgo_orig), U_MEMORY_ALLOCATION_ERROR); intl_errors_set_custom_msg(DTPATTERNGEN_ERROR_P(dtpgo_orig), "Could not clone IntlDatePatternGenerator", 0); err_msg = intl_error_get_message(DTPATTERNGEN_ERROR_P(dtpgo_orig)); zend_throw_exception(NULL, ZSTR_VAL(err_msg), 0); zend_string_free(err_msg); } else { dtpgo_new->dtpg = newDtpg; } } else { zend_throw_exception(NULL, "Cannot clone unconstructed IntlDatePatternGenerator", 0); } return ret_val; } /* * Initialize internals of IntlDatePatternGenerator_object not specific to zend standard objects. */ static void IntlDatePatternGenerator_object_init(IntlDatePatternGenerator_object *co) { intl_error_init(DTPATTERNGEN_ERROR_P(co)); co->dtpg = NULL; } static void IntlDatePatternGenerator_object_free(zend_object *object) { IntlDatePatternGenerator_object* co = php_intl_datepatterngenerator_fetch_object(object); if (co->dtpg) { delete co->dtpg; co->dtpg = NULL; } intl_error_reset(DTPATTERNGEN_ERROR_P(co)); zend_object_std_dtor(&co->zo); } static zend_object *IntlDatePatternGenerator_object_create(zend_class_entry *ce) { IntlDatePatternGenerator_object *intern = (IntlDatePatternGenerator_object*) zend_object_alloc(sizeof(IntlDatePatternGenerator_object), ce); zend_object_std_init(&intern->zo, ce); object_properties_init(&intern->zo, ce); IntlDatePatternGenerator_object_init(intern); return &intern->zo; } /* * 'IntlDatePatternGenerator' class registration structures & functions */ /* * Initialize 'IntlDatePatternGenerator' class */ void dateformat_register_IntlDatePatternGenerator_class( void ) { /* Create and register 'IntlDatePatternGenerator' class. */ IntlDatePatternGenerator_ce_ptr = register_class_IntlDatePatternGenerator(); IntlDatePatternGenerator_ce_ptr->create_object = IntlDatePatternGenerator_object_create; IntlDatePatternGenerator_ce_ptr->default_object_handlers = &IntlDatePatternGenerator_handlers; memcpy(&IntlDatePatternGenerator_handlers, &std_object_handlers, sizeof IntlDatePatternGenerator_handlers); IntlDatePatternGenerator_handlers.offset = XtOffsetOf(IntlDatePatternGenerator_object, zo); IntlDatePatternGenerator_handlers.clone_obj = IntlDatePatternGenerator_object_clone; IntlDatePatternGenerator_handlers.free_obj = IntlDatePatternGenerator_object_free; }
#include <iostream> #include <stack> #include <forward_list> using namespace std; template <typename T> class MyStack : public stack<T> { private: forward_list<T> min_list {}; public: void push(const T& val) { if (min_list.empty() || (val < min_list.front())) { min_list.push_front(val); } stack<T>::push(val); } void pop() { if (stack<T>::top() == min_list.front()) { min_list.pop_front(); } stack<T>::pop(); } T& min() { return min_list.front(); } }; int main() { MyStack<int> myStack {}; for (auto i : {5, 6, 2, 19, 20, 4, 1, 3, 10, 11}) { cout << i << ", "; myStack.push(i); } cout << endl << endl; cout << "Min: " << myStack.min() << endl; cout << "Top: " << myStack.top() << endl; cout << endl; for (int i = 0; i < 4; i++) { myStack.pop(); } cout << "Min: " << myStack.min() << endl; cout << "Top: " << myStack.top() << endl; cout << endl; for (int i = 0; i < 2; i++) { myStack.pop(); } cout << "Min: " << myStack.min() << endl; cout << "Top: " << myStack.top() << endl; cout << endl; for (int i = 0; i < 2; i++) { myStack.pop(); } cout << "Min: " << myStack.min() << endl; cout << "Top: " << myStack.top() << endl; cout << endl; }
#include "../inc/SEOpenGLRenderService.h" #include "../inc/SEOpenGLRenderObject.h" #include "../inc/SEOpenGLCamera.h" #include "../inc/SEOpenGLLight.h" #include "../inc/SEOpenGLPrimitive.h" #include "../inc/SEDebugTools.h" #include "../inc/SEMath.h" #include <stdexcept> USEDUMPFLAG; int SEOpenGLRenderService::startup() { DUMPFLAG(true); DUMPONCE("==========BEGIN_STARTUP_DUMP=========="); // Configurações perenes da máquina de estado do OpenGL configureOpenGL(); // Cria e configura a câmera padrão int c = createRO(SEROType::CAMERA_RO, SECameraType::STATIC_CAM); c_[c]->setTranslation(0,0,20); c_[c]->usePerspectiveProjection(); DUMPONCE("===========END_STARTUP_DUMP==========="<<std::endl<<std::endl); //DUMPFLAG(false); return(0); } int SEOpenGLRenderService::shutdown() { l_.clear(); c_.clear(); for (tROVectorIt it=ro_.begin();it!=ro_.end();++it) delete(*it); ro_.clear(); return(0); } void SEOpenGLRenderService::renderFrame() const { startFrame(); setupCamera(); configureLighting(); configureTexturing(); for (tROVector::const_iterator it = ro_.begin(); it != ro_.end(); ++it) { if ((*it)!=NULL) (*it)->render(*this); } endFrame(); } int SEOpenGLRenderService::createRO(SEROType::tRenderObject t, int t1, int t2, int t3) { int ix=-1; switch (t) { case SEROType::CAMERA_RO: { SEOpenGLCamera *c; try { SECameraType::tCamera tc = static_cast<SECameraType::tCamera>(t1); c = new SEOpenGLCamera(tc); } catch (...) { c = new SEOpenGLCamera(); } ix = ro_.size(); ro_.push_back(c); c_[ix]=c; if (currentCamera < 0) setCamera(ix); } break; case SEROType::PRIMITIVE_RO: { SEOpenGLRenderObject *p=NULL; try { SEPrimTypes::tPrimitive pt = static_cast<SEPrimTypes::tPrimitive>(t1); switch (pt) { case SEPrimTypes::CONE_PRIM: p = new SEOpenGLCone(); break; case SEPrimTypes::CUBE_PRIM: p = new SEOpenGLCube(); break; case SEPrimTypes::SPHERE_PRIM: p = new SEOpenGLSphere(); break; case SEPrimTypes::TORUS_PRIM: p = new SEOpenGLTorus(); break; case SEPrimTypes::TEAPOT_PRIM: p = new SEOpenGLTeapot(); break; } if (p!=NULL) { ix = ro_.size(); ro_.push_back(p); } } catch (...) { } } break; case SEROType::LIGHT_RO: { SEOpenGLLight *l=NULL; try { SELightTypes::tLight tli = static_cast<SELightTypes::tLight>(t1); switch (tli) { case SELightTypes::AMBIENT: l = new SEOpenGLAmbientLight(); break; case SELightTypes::AREA: break; case SELightTypes::DIRECTIONAL: l = new SEOpenGLDirectionalLight(); break; case SELightTypes::POINT: l = new SEOpenGLPointLight(); break; case SELightTypes::SPOT: l = new SEOpenGLSpotLight(); break; default: break; } if (l!=NULL) { ix = ro_.size(); ro_.push_back(l); l_[ix]=l; } } catch (...) { } } break; default: break; } return(ix); } void SEOpenGLRenderService::destroyRO(uint32_t i) { if (c_.count(i) > 0) { c_[i]=NULL; if (currentCamera==i) setCamera(-1); } if (l_.count(i) > 0) l_[i]=NULL; try { if (ro_.at(i) != NULL) { delete ro_[i]; ro_[i]=NULL; } } catch (const std::out_of_range &oor) { } } void SEOpenGLRenderService::activateLight(uint32_t l) { try { if (!l_[l]->isOn) l_[l]->toggle(); } catch (...) { } } void SEOpenGLRenderService::deactivateLight(uint32_t l) { try { if (l_[l]->isOn) l_[l]->toggle(); } catch (...) { } } const SERenderObject<GLfloat> * SEOpenGLRenderService::getObject(uint32_t o) const { try { return ro_.at(o); } catch (const std::out_of_range &oor) { return NULL; } } const SECamera<GLfloat> * SEOpenGLRenderService::getCamera(uint32_t c) const { try { tCamMap::const_iterator it = c_.find(c); if (it!=c_.end()) return (*it).second; else return NULL; } catch (...) { return NULL; } } const SELight<GLfloat> * SEOpenGLRenderService::getLight(uint32_t l) const { try { tLightMap::const_iterator it = l_.find(l); if (it!=l_.end()) return (*it).second; else return NULL; } catch (...) { return NULL; } } SERenderObject<GLfloat> * SEOpenGLRenderService::getObject(uint32_t o) { try { return ro_.at(o); } catch (const std::out_of_range &oor) { return NULL; } } SECamera<GLfloat> * SEOpenGLRenderService::getCamera(uint32_t c) { try { tCamMapIt it = c_.find(c); if (it!=c_.end()) return (*it).second; else return NULL; } catch (...) { return NULL; } } SELight<GLfloat> * SEOpenGLRenderService::getLight(uint32_t l) { try { tLightMapIt it = l_.find(l); if (it!=l_.end()) return (*it).second; else return NULL; } catch (...) { return NULL; } } void SEOpenGLRenderService::setGlobalAmbientLight(GLfloat r, GLfloat g, GLfloat b, GLfloat a) const { DUMPONCE("===SEOpenGLRenderService::setGlobalAmbientLight("<<r<<","<<g<<","<<b<<","<<a<<")==="); SEVec4<GLfloat> c(CLAMP(r,0,1), CLAMP(g,0,1), CLAMP(b,0,1), CLAMP(a,0,1)); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, c.v); DUMPONCE("glLightModelfv(GL_LIGHT_MODEL_AMBIENT, "<<c<<")"); } void SEOpenGLRenderService::setGlobalAmbientLighti(int r, int g, int b, int a) const { DUMPONCE("===SEOpenGLRenderService::setGlobalAmbientLighti("<<r<<","<<g<<","<<b<<","<<a<<")==="); SEVec4<GLfloat> c(CLAMP(r,0,255), CLAMP(g,0,255), CLAMP(b,0,255), CLAMP(a,0,255)); c/=255.0; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, c.v); DUMPONCE("glLightModelfv(GL_LIGHT_MODEL_AMBIENT, "<<c<<")"); } void SEOpenGLRenderService::configureLighting() const { DUMPONCE("===SEOpenGLRenderService::configureLighting()==="); if (isLightingEnabled) { glEnable(GL_LIGHTING); DUMPONCE("glEnable(GL_LIGHTING)"); glShadeModel(GL_SMOOTH); DUMPONCE("glShadeModel(GL_SMOOTH)"); for (tLightMap::const_iterator it=l_.begin();it!=l_.end();++it) if ((*it).second->isOn) { (*it).second->enable(); (*it).second->configure(); } } else { for (tLightMap::const_iterator it=l_.begin();it!=l_.end();++it) if ((*it).second->isOn) { (*it).second->disable(); } glDisable(GL_LIGHTING); DUMPONCE("glDisable(GL_LIGHTING)"); } } void SEOpenGLRenderService::configureTexturing() const { DUMPONCE("===SEOpenGLRenderService::configureTexturing()==="); if (isTexturingEnabled) { glEnable(GL_TEXTURE_2D); DUMPONCE("glEnable(GL_TEXTURE_2D)"); } else { glDisable(GL_TEXTURE_2D); DUMPONCE("glDisable(GL_TEXTURE_2D)"); } } bool SEOpenGLRenderService::objectExists(uint32_t o) const { if (o < ro_.size()) return false; if (ro_[o]!=NULL) return true; return false; } bool SEOpenGLRenderService::cameraExists(uint32_t c) const { if (c_.find(c)!=c_.end()) return true; return false; } bool SEOpenGLRenderService::lightExists(uint32_t l) const { if (l_.find(l)!=l_.end()) return true; return false; } void SEOpenGLRenderService::startFrame() const { DUMPONCE("==============BEGIN_FRAME_DUMP=============="); DUMPONCE("===SEOpenGLRenderService::startFrame()==="); glEnable(GL_DEPTH_TEST); DUMPONCE("glEnable(GL_DEPTH_TEST)"); glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT); DUMPONCE("glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT)"); } void SEOpenGLRenderService::endFrame() const { DUMPONCE("===SEOpenGLRenderService::endFrame()==="); glFlush(); DUMPONCE("glFlush()"); DUMPONCE("===============END_FRAME_DUMP==============="<<std::endl<<std::endl); DUMPFLAG(false); } void SEOpenGLRenderService::configureOpenGL() const { DUMPONCE("===SEOpenGLRenderService::configureOpengl()==="); glClearColor(0.0, 0.0, 0.0, 0.0); DUMPONCE("glClearColor(0.0, 0.0, 0.0, 0.0)"); glClearDepth(1.0); DUMPONCE("glClearDepth(1.0)"); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); DUMPONCE("glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)"); glDisable(GL_FOG); DUMPONCE("glDisable(GL_FOG)"); glEnable(GL_CULL_FACE); DUMPONCE("glEnable(GL_CULL_FACE)"); glCullFace(GL_BACK); DUMPONCE("glCullFace(GL_BACK)"); glEnable(GL_DEPTH_TEST); DUMPONCE("glEnable(GL_DEPTH_TEST)"); glDepthFunc(GL_LESS); DUMPONCE("glDepthFunc(GL_LESS)"); glDepthMask(GL_TRUE); DUMPONCE("glDepthMask(GL_TRUE)"); glPolygonMode(GL_FRONT,GL_FILL); DUMPONCE("glPolygonMode(GL_FRONT,GL_FILL)"); glPolygonMode(GL_BACK,GL_FILL); DUMPONCE("glPolygonMode(GL_BACK,GL_FILL)"); setupTexturing(); setupLighting(); } void SEOpenGLRenderService::setupCamera() const { tCamMap::const_iterator it = c_.find(currentCamera); if (it != c_.end()) (*it).second->setupFrame(); } void SEOpenGLRenderService::setupLighting() const { DUMPONCE("===SEOpenGLRenderService::setupLighting()==="); glShadeModel(GL_SMOOTH); DUMPONCE("glShadeModel(GL_SMOOTH)"); // Desabilita luz ambiente global por padrão const GLfloat al[] = {0.0, 0.0, 0.0, 1.0}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, al); DUMPONCE("glLightModelfv(GL_LIGHT_MODEL_AMBIENT,{0.0, 0.0, 0.0, 1.0})"); } void SEOpenGLRenderService::setupTexturing() const { DUMPONCE("===SEOpenGLRenderService::setupTexturing()==="); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); DUMPONCE("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)"); glEnable(GL_BLEND); DUMPONCE("glEnable(GL_BLEND)"); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); DUMPONCE("glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)"); glEnable(GL_ALPHA_TEST); DUMPONCE("glEnable(GL_ALPHA_TEST)"); glAlphaFunc(GL_GREATER,0.5); DUMPONCE("glAlphaFunc(GL_GREATER,0.5)"); }
/** * @copyright (c) 2020, Kartik Venkat, Nidhi Bhojak * * @file test.cpp * * @authors * Part 1: * Kartik Venkat (kartikv97) ---- Driver \n * Nidhi Bhojak (nbhojak07) ---- Navigator\n * * @version 1.0 * * @section LICENSE * * BSD 3-Clause License * * * 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 copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * This is a test function to test the methods of the PID controller implementation. */ #include <gtest/gtest.h> #include "lib.hpp" /** * @brief This Test function aims to test the calculateCurrentError method of the * ComputePID class. * @param PID_Test2 : - Test Name * @param errorCalculationTest : - Test description. * @return none */ TEST(PID_Test1, errorCalculationTest) { double kp = 10; double ki = 2; double kd = 5; ComputePID obj(kp, ki, kd); double TargetVelocity = 25; double ActualVelocity = 23; double CurrentError; CurrentError = obj.calculateCurrentError(TargetVelocity, ActualVelocity); EXPECT_EQ(CurrentError, 2); } /** * @brief This Test function aims to test the calculateAccumulatedError method of the * ComputePID class. * @param PID_Test3 : - Test Name * @param computeMethodTest : - Test description. * @return none */ TEST(PID_Test2, accumulatedErrorTest) { double kp = 10; double ki = 2; double kd = 5; ComputePID obj(kp, ki, kd); double TargetVelocity = 25; double ActualVelocity = 23; double CurrentError; double AccumulatedError; std::vector <double> AccumulatedErrors = { 7, 5, 3 }; CurrentError = obj.calculateCurrentError(TargetVelocity, ActualVelocity); AccumulatedError = obj.calculateAccumulatedError(CurrentError, AccumulatedErrors); EXPECT_EQ(CurrentError, 2); EXPECT_EQ(AccumulatedError, 17); } /** * @brief This Test function aims to test the calculatePID method of the * ComputePID class. * @param PID_Test3 : - Test Name * @param computeMethodTest : - Test description. * @return none */ TEST(PID_Test3, computeMethodTest) { double kp = 10; double ki = 2; double kd = 5; ComputePID obj(kp, ki, kd); double TargetVelocity = 25; double ActualVelocity = 23; double PreviousError = 3; double CurrentError; double PID_Output; double AccumulatedError; std::vector <double> AccumulatedErrors = { 7, 5, 3 }; CurrentError = obj.calculateCurrentError(TargetVelocity, ActualVelocity); AccumulatedError = obj.calculateAccumulatedError(CurrentError, AccumulatedErrors); PID_Output = obj.calculatePID(CurrentError, PreviousError, AccumulatedError); EXPECT_EQ(CurrentError, 2); EXPECT_EQ(AccumulatedError, 17); EXPECT_EQ(PID_Output, 49); }
// http://oj.leetcode.com/problems/unique-binary-search-trees-ii/ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // Should really care about how function returns. class Solution { vector<TreeNode*>* generate(int from, int to) { vector<TreeNode *>* ret = new vector<TreeNode *>(); if (from < 1 || from > to) { ret->push_back(nullptr); return ret; } for (int i = from; i <= to; i++) { vector<TreeNode *>* rleft = generate(from, i - 1); vector<TreeNode *>* rright = generate(i + 1, to); for (int j = 0; j < rleft->size(); j++) { for (int k = 0; k < rright->size(); k++) { TreeNode *root = new TreeNode(i); root->left = (*rleft)[j]; root->right = (*rright)[k]; ret->push_back(root); } } } return ret; } public: vector<TreeNode *> generateTrees(int n) { return *generate(1, n); } };
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. \*********************************************************/ /* We don't use the Direct3D headers from the DirectX SDK because there are several issues: - Licensing: It's not allowed to redistribute the Direct3D headers, meaning everyone would have to get them somehow before compiling this project - The Direct3D headers are somewhat chaotic and include tons of other headers. This slows down compilation and the more headers are included, the higher the risk of naming or redefinition conflicts. Do not include this header within headers which are usually used by users as well, do only use it inside cpp-files. It must still be possible that users of this renderer interface can use the Direct3D headers for features not covered by this renderer interface. */ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <Renderer/WindowsHeader.h> __pragma(warning(push)) __pragma(warning(disable: 4668)) // warning C4668: '<x>' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' #include <Unknwn.h> // For "IUnknown" __pragma(warning(pop)) //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] struct DXGI_RGBA; struct DXGI_RESIDENCY; struct DXGI_MATRIX_3X2_F; struct DXGI_SURFACE_DESC; struct DXGI_ADAPTER_DESC; struct DXGI_SHARED_RESOURCE; struct DXGI_FRAME_STATISTICS; struct DXGI_SWAP_CHAIN_DESC1; struct DXGI_PRESENT_PARAMETERS; struct DXGI_SWAP_CHAIN_FULLSCREEN_DESC; struct IDXGIOutput; struct IDXGISurface; struct IDXGIAdapter; struct IDXGIAdapter1; struct D3D12_HEAP_DESC; struct D3D12_TILE_SHAPE; struct D3D12_SAMPLER_DESC; struct D3D12_DISCARD_REGION; struct D3D12_QUERY_HEAP_DESC; struct D3D12_PACKED_MIP_INFO; struct D3D12_TILE_REGION_SIZE; struct D3D12_TILE_RANGE_FLAGS; struct D3D12_SUBRESOURCE_TILING; struct D3D12_SO_DECLARATION_ENTRY; struct D3D12_COMMAND_SIGNATURE_DESC; struct D3D12_STREAM_OUTPUT_BUFFER_VIEW; struct D3D12_TILED_RESOURCE_COORDINATE; struct D3D12_UNORDERED_ACCESS_VIEW_DESC; struct D3D12_COMPUTE_PIPELINE_STATE_DESC; struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT; struct ID3D12Heap; struct ID3D12Resource; struct ID3D12QueryHeap; struct ID3D12RootSignature; struct ID3D12CommandSignature; // TODO(co) Direct3D 12 update struct ID3D10Blob; struct D3D10_SHADER_MACRO; typedef __interface ID3DInclude *LPD3D10INCLUDE; struct ID3DX12ThreadPump; typedef DWORD D3DCOLOR; //[-------------------------------------------------------] //[ Definitions ] //[-------------------------------------------------------] // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgiformat.h" typedef enum DXGI_FORMAT { DXGI_FORMAT_UNKNOWN = 0, DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DXGI_FORMAT_R32G32B32A32_UINT = 3, DXGI_FORMAT_R32G32B32A32_SINT = 4, DXGI_FORMAT_R32G32B32_TYPELESS = 5, DXGI_FORMAT_R32G32B32_FLOAT = 6, DXGI_FORMAT_R32G32B32_UINT = 7, DXGI_FORMAT_R32G32B32_SINT = 8, DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DXGI_FORMAT_R16G16B16A16_UNORM = 11, DXGI_FORMAT_R16G16B16A16_UINT = 12, DXGI_FORMAT_R16G16B16A16_SNORM = 13, DXGI_FORMAT_R16G16B16A16_SINT = 14, DXGI_FORMAT_R32G32_TYPELESS = 15, DXGI_FORMAT_R32G32_FLOAT = 16, DXGI_FORMAT_R32G32_UINT = 17, DXGI_FORMAT_R32G32_SINT = 18, DXGI_FORMAT_R32G8X24_TYPELESS = 19, DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, DXGI_FORMAT_R10G10B10A2_UNORM = 24, DXGI_FORMAT_R10G10B10A2_UINT = 25, DXGI_FORMAT_R11G11B10_FLOAT = 26, DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, DXGI_FORMAT_R8G8B8A8_UNORM = 28, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, DXGI_FORMAT_R8G8B8A8_UINT = 30, DXGI_FORMAT_R8G8B8A8_SNORM = 31, DXGI_FORMAT_R8G8B8A8_SINT = 32, DXGI_FORMAT_R16G16_TYPELESS = 33, DXGI_FORMAT_R16G16_FLOAT = 34, DXGI_FORMAT_R16G16_UNORM = 35, DXGI_FORMAT_R16G16_UINT = 36, DXGI_FORMAT_R16G16_SNORM = 37, DXGI_FORMAT_R16G16_SINT = 38, DXGI_FORMAT_R32_TYPELESS = 39, DXGI_FORMAT_D32_FLOAT = 40, DXGI_FORMAT_R32_FLOAT = 41, DXGI_FORMAT_R32_UINT = 42, DXGI_FORMAT_R32_SINT = 43, DXGI_FORMAT_R24G8_TYPELESS = 44, DXGI_FORMAT_D24_UNORM_S8_UINT = 45, DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, DXGI_FORMAT_R8G8_TYPELESS = 48, DXGI_FORMAT_R8G8_UNORM = 49, DXGI_FORMAT_R8G8_UINT = 50, DXGI_FORMAT_R8G8_SNORM = 51, DXGI_FORMAT_R8G8_SINT = 52, DXGI_FORMAT_R16_TYPELESS = 53, DXGI_FORMAT_R16_FLOAT = 54, DXGI_FORMAT_D16_UNORM = 55, DXGI_FORMAT_R16_UNORM = 56, DXGI_FORMAT_R16_UINT = 57, DXGI_FORMAT_R16_SNORM = 58, DXGI_FORMAT_R16_SINT = 59, DXGI_FORMAT_R8_TYPELESS = 60, DXGI_FORMAT_R8_UNORM = 61, DXGI_FORMAT_R8_UINT = 62, DXGI_FORMAT_R8_SNORM = 63, DXGI_FORMAT_R8_SINT = 64, DXGI_FORMAT_A8_UNORM = 65, DXGI_FORMAT_R1_UNORM = 66, DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, DXGI_FORMAT_R8G8_B8G8_UNORM = 68, DXGI_FORMAT_G8R8_G8B8_UNORM = 69, DXGI_FORMAT_BC1_TYPELESS = 70, DXGI_FORMAT_BC1_UNORM = 71, DXGI_FORMAT_BC1_UNORM_SRGB = 72, DXGI_FORMAT_BC2_TYPELESS = 73, DXGI_FORMAT_BC2_UNORM = 74, DXGI_FORMAT_BC2_UNORM_SRGB = 75, DXGI_FORMAT_BC3_TYPELESS = 76, DXGI_FORMAT_BC3_UNORM = 77, DXGI_FORMAT_BC3_UNORM_SRGB = 78, DXGI_FORMAT_BC4_TYPELESS = 79, DXGI_FORMAT_BC4_UNORM = 80, DXGI_FORMAT_BC4_SNORM = 81, DXGI_FORMAT_BC5_TYPELESS = 82, DXGI_FORMAT_BC5_UNORM = 83, DXGI_FORMAT_BC5_SNORM = 84, DXGI_FORMAT_B5G6R5_UNORM = 85, DXGI_FORMAT_B5G5R5A1_UNORM = 86, DXGI_FORMAT_B8G8R8A8_UNORM = 87, DXGI_FORMAT_B8G8R8X8_UNORM = 8, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, DXGI_FORMAT_BC6H_TYPELESS = 94, DXGI_FORMAT_BC6H_UF16 = 95, DXGI_FORMAT_BC6H_SF16 = 96, DXGI_FORMAT_BC7_TYPELESS = 97, DXGI_FORMAT_BC7_UNORM = 98, DXGI_FORMAT_BC7_UNORM_SRGB = 99, DXGI_FORMAT_AYUV = 100, DXGI_FORMAT_Y410 = 101, DXGI_FORMAT_Y416 = 102, DXGI_FORMAT_NV12 = 103, DXGI_FORMAT_P010 = 104, DXGI_FORMAT_P016 = 105, DXGI_FORMAT_420_OPAQUE = 106, DXGI_FORMAT_YUY2 = 107, DXGI_FORMAT_Y210 = 108, DXGI_FORMAT_Y216 = 109, DXGI_FORMAT_NV11 = 110, DXGI_FORMAT_AI44 = 111, DXGI_FORMAT_IA44 = 112, DXGI_FORMAT_P8 = 113, DXGI_FORMAT_A8P8 = 114, DXGI_FORMAT_B4G4R4A4_UNORM = 115, DXGI_FORMAT_P208 = 130, DXGI_FORMAT_V208 = 131, DXGI_FORMAT_V408 = 132, DXGI_FORMAT_FORCE_UINT = 0xffffffff } DXGI_FORMAT; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef struct DXGI_RATIONAL { UINT Numerator; UINT Denominator; } DXGI_RATIONAL; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef enum DXGI_MODE_SCANLINE_ORDER { DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED = 0, DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE = 1, DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = 2, DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = 3 } DXGI_MODE_SCANLINE_ORDER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef enum DXGI_MODE_SCALING { DXGI_MODE_SCALING_UNSPECIFIED = 0, DXGI_MODE_SCALING_CENTERED = 1, DXGI_MODE_SCALING_STRETCHED = 2 } DXGI_MODE_SCALING; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef struct DXGI_MODE_DESC { UINT Width; UINT Height; DXGI_RATIONAL RefreshRate; DXGI_FORMAT Format; DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; DXGI_MODE_SCALING Scaling; } DXGI_MODE_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef struct DXGI_SAMPLE_DESC { UINT Count; UINT Quality; } DXGI_SAMPLE_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef enum DXGI_MODE_ROTATION { DXGI_MODE_ROTATION_UNSPECIFIED = 0, DXGI_MODE_ROTATION_IDENTITY = 1, DXGI_MODE_ROTATION_ROTATE90 = 2, DXGI_MODE_ROTATION_ROTATE180 = 3, DXGI_MODE_ROTATION_ROTATE270 = 4 } DXGI_MODE_ROTATION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h" typedef enum DXGI_COLOR_SPACE_TYPE { DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 = 0, DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 = 1, DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709 = 2, DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P2020 = 3, DXGI_COLOR_SPACE_RESERVED = 4, DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 = 5, DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 = 6, DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601 = 7, DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 = 8, DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709 = 9, DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 = 10, DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 = 11, DXGI_COLOR_SPACE_CUSTOM = 0xFFFFFFFF } DXGI_COLOR_SPACE_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" typedef UINT DXGI_USAGE; #define DXGI_MWA_NO_ALT_ENTER (1 << 1) #define DXGI_USAGE_RENDER_TARGET_OUTPUT 0x00000020UL // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" typedef enum DXGI_SWAP_EFFECT { DXGI_SWAP_EFFECT_DISCARD = 0, DXGI_SWAP_EFFECT_SEQUENTIAL = 1, DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = 3, DXGI_SWAP_EFFECT_FLIP_DISCARD = 4 } DXGI_SWAP_EFFECT; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" typedef struct DXGI_SWAP_CHAIN_DESC { DXGI_MODE_DESC BufferDesc; DXGI_SAMPLE_DESC SampleDesc; DXGI_USAGE BufferUsage; UINT BufferCount; HWND OutputWindow; BOOL Windowed; DXGI_SWAP_EFFECT SwapEffect; UINT Flags; } DXGI_SWAP_CHAIN_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h" enum D3D_FEATURE_LEVEL { D3D_FEATURE_LEVEL_9_1 = 0x9100, D3D_FEATURE_LEVEL_9_2 = 0x9200, D3D_FEATURE_LEVEL_9_3 = 0x9300, D3D_FEATURE_LEVEL_10_0 = 0xa000, D3D_FEATURE_LEVEL_10_1 = 0xa100, D3D_FEATURE_LEVEL_11_0 = 0xb000, D3D_FEATURE_LEVEL_11_1 = 0xb100, D3D_FEATURE_LEVEL_12_0 = 0xc000, D3D_FEATURE_LEVEL_12_1 = 0xc100 }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h" typedef enum D3D_PRIMITIVE_TOPOLOGY { D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0, D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1, D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2, D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4, D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5, D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10, D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12, D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13, D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33, D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34, D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35, D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36, D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37, D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38, D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39, D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40, D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41, D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42, D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43, D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44, D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45, D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46, D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47, D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48, D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49, D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50, D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51, D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52, D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53, D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54, D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55, D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56, D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57, D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58, D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59, D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60, D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61, D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62, D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63, D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64, D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, D3D10_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST, D3D10_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST, D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST, D3D11_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST, D3D11_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST } D3D_PRIMITIVE_TOPOLOGY; // "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h" struct D3D_SHADER_MACRO { LPCSTR Name; LPCSTR Definition; }; enum D3D_INCLUDE_TYPE { D3D_INCLUDE_LOCAL = 0, D3D_INCLUDE_SYSTEM = (D3D_INCLUDE_LOCAL + 1), D3D10_INCLUDE_LOCAL = D3D_INCLUDE_LOCAL, D3D10_INCLUDE_SYSTEM = D3D_INCLUDE_SYSTEM, D3D_INCLUDE_FORCE_DWORD = 0x7fffffff }; DECLARE_INTERFACE(ID3DInclude) { STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) PURE; STDMETHOD(Close)(THIS_ LPCVOID pData) PURE; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h" typedef ID3D10Blob ID3DBlob; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3dcompiler.h" #define D3DCOMPILE_DEBUG (1 << 0) #define D3DCOMPILE_SKIP_VALIDATION (1 << 1) #define D3DCOMPILE_SKIP_OPTIMIZATION (1 << 2) #define D3DCOMPILE_ENABLE_STRICTNESS (1 << 11) #define D3DCOMPILE_OPTIMIZATION_LEVEL0 (1 << 14) #define D3DCOMPILE_OPTIMIZATION_LEVEL1 0 #define D3DCOMPILE_OPTIMIZATION_LEVEL2 ((1 << 14) | (1 << 15)) #define D3DCOMPILE_OPTIMIZATION_LEVEL3 (1 << 15) #define D3DCOMPILE_WARNINGS_ARE_ERRORS (1 << 18) // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_VIEWPORT { FLOAT TopLeftX; FLOAT TopLeftY; FLOAT Width; FLOAT Height; FLOAT MinDepth; FLOAT MaxDepth; } D3D12_VIEWPORT; typedef RECT D3D12_RECT; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_BOX { UINT left; UINT top; UINT front; UINT right; UINT bottom; UINT back; } D3D12_BOX; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_INPUT_CLASSIFICATION { D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1 } D3D12_INPUT_CLASSIFICATION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_INPUT_ELEMENT_DESC { LPCSTR SemanticName; UINT SemanticIndex; DXGI_FORMAT Format; UINT InputSlot; UINT AlignedByteOffset; D3D12_INPUT_CLASSIFICATION InputSlotClass; UINT InstanceDataStepRate; } D3D12_INPUT_ELEMENT_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_RESOURCE_DIMENSION { D3D12_RESOURCE_DIMENSION_UNKNOWN = 0, D3D12_RESOURCE_DIMENSION_BUFFER = 1, D3D12_RESOURCE_DIMENSION_TEXTURE1D = 2, D3D12_RESOURCE_DIMENSION_TEXTURE2D = 3, D3D12_RESOURCE_DIMENSION_TEXTURE3D = 4 } D3D12_RESOURCE_DIMENSION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_TEXTURE_LAYOUT { D3D12_TEXTURE_LAYOUT_UNKNOWN = 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR = 1, D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2, D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3 } D3D12_TEXTURE_LAYOUT; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_RESOURCE_FLAGS { D3D12_RESOURCE_FLAG_NONE = 0, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET = 0x1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL = 0x2, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS = 0x4, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE = 0x8, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER = 0x10, D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS = 0x20 } D3D12_RESOURCE_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RESOURCE_DESC { D3D12_RESOURCE_DIMENSION Dimension; UINT64 Alignment; UINT64 Width; UINT Height; UINT16 DepthOrArraySize; UINT16 MipLevels; DXGI_FORMAT Format; DXGI_SAMPLE_DESC SampleDesc; D3D12_TEXTURE_LAYOUT Layout; D3D12_RESOURCE_FLAGS Flags; } D3D12_RESOURCE_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_RESOURCE_STATES { D3D12_RESOURCE_STATE_COMMON = 0, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER = 0x1, D3D12_RESOURCE_STATE_INDEX_BUFFER = 0x2, D3D12_RESOURCE_STATE_RENDER_TARGET = 0x4, D3D12_RESOURCE_STATE_UNORDERED_ACCESS = 0x8, D3D12_RESOURCE_STATE_DEPTH_WRITE = 0x10, D3D12_RESOURCE_STATE_DEPTH_READ = 0x20, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE = 0x40, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE = 0x80, D3D12_RESOURCE_STATE_STREAM_OUT = 0x100, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT = 0x200, D3D12_RESOURCE_STATE_COPY_DEST = 0x400, D3D12_RESOURCE_STATE_COPY_SOURCE = 0x800, D3D12_RESOURCE_STATE_RESOLVE_DEST = 0x1000, D3D12_RESOURCE_STATE_RESOLVE_SOURCE = 0x2000, D3D12_RESOURCE_STATE_GENERIC_READ = ((((( 0x1 | 0x2) | 0x40) | 0x80) | 0x200) | 0x800), D3D12_RESOURCE_STATE_PRESENT = 0, D3D12_RESOURCE_STATE_PREDICATION = 0x200 } D3D12_RESOURCE_STATES; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_RESOURCE_BARRIER_TYPE { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION = 0, D3D12_RESOURCE_BARRIER_TYPE_ALIASING = (D3D12_RESOURCE_BARRIER_TYPE_TRANSITION + 1), D3D12_RESOURCE_BARRIER_TYPE_UAV = (D3D12_RESOURCE_BARRIER_TYPE_ALIASING + 1) } D3D12_RESOURCE_BARRIER_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_RESOURCE_BARRIER_FLAGS { D3D12_RESOURCE_BARRIER_FLAG_NONE = 0, D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY = 0x1, D3D12_RESOURCE_BARRIER_FLAG_END_ONLY = 0x2 } D3D12_RESOURCE_BARRIER_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RESOURCE_TRANSITION_BARRIER { ID3D12Resource *pResource; UINT Subresource; D3D12_RESOURCE_STATES StateBefore; D3D12_RESOURCE_STATES StateAfter; } D3D12_RESOURCE_TRANSITION_BARRIER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RESOURCE_ALIASING_BARRIER { ID3D12Resource *pResourceBefore; ID3D12Resource *pResourceAfter; } D3D12_RESOURCE_ALIASING_BARRIER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RESOURCE_UAV_BARRIER { ID3D12Resource *pResource; } D3D12_RESOURCE_UAV_BARRIER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER_TYPE Type; D3D12_RESOURCE_BARRIER_FLAGS Flags; union { D3D12_RESOURCE_TRANSITION_BARRIER Transition; D3D12_RESOURCE_ALIASING_BARRIER Aliasing; D3D12_RESOURCE_UAV_BARRIER UAV; }; } D3D12_RESOURCE_BARRIER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_RTV_DIMENSION { D3D12_RTV_DIMENSION_UNKNOWN = 0, D3D12_RTV_DIMENSION_BUFFER = 1, D3D12_RTV_DIMENSION_TEXTURE1D = 2, D3D12_RTV_DIMENSION_TEXTURE1DARRAY = 3, D3D12_RTV_DIMENSION_TEXTURE2D = 4, D3D12_RTV_DIMENSION_TEXTURE2DARRAY = 5, D3D12_RTV_DIMENSION_TEXTURE2DMS = 6, D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, D3D12_RTV_DIMENSION_TEXTURE3D = 8 } D3D12_RTV_DIMENSION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_BUFFER_RTV { UINT64 FirstElement; UINT NumElements; } D3D12_BUFFER_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX1D_RTV { UINT MipSlice; } D3D12_TEX1D_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX1D_ARRAY_RTV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; } D3D12_TEX1D_ARRAY_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2D_RTV { UINT MipSlice; UINT PlaneSlice; } D3D12_TEX2D_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2DMS_RTV { UINT UnusedField_NothingToDefine; } D3D12_TEX2DMS_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2D_ARRAY_RTV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; UINT PlaneSlice; } D3D12_TEX2D_ARRAY_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2DMS_ARRAY_RTV { UINT FirstArraySlice; UINT ArraySize; } D3D12_TEX2DMS_ARRAY_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX3D_RTV { UINT MipSlice; UINT FirstWSlice; UINT WSize; } D3D12_TEX3D_RTV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RENDER_TARGET_VIEW_DESC { DXGI_FORMAT Format; D3D12_RTV_DIMENSION ViewDimension; union { D3D12_BUFFER_RTV Buffer; D3D12_TEX1D_RTV Texture1D; D3D12_TEX1D_ARRAY_RTV Texture1DArray; D3D12_TEX2D_RTV Texture2D; D3D12_TEX2D_ARRAY_RTV Texture2DArray; D3D12_TEX2DMS_RTV Texture2DMS; D3D12_TEX2DMS_ARRAY_RTV Texture2DMSArray; D3D12_TEX3D_RTV Texture3D; }; } D3D12_RENDER_TARGET_VIEW_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_COMMAND_LIST_TYPE { D3D12_COMMAND_LIST_TYPE_DIRECT = 0, D3D12_COMMAND_LIST_TYPE_BUNDLE = 1, D3D12_COMMAND_LIST_TYPE_COMPUTE = 2, D3D12_COMMAND_LIST_TYPE_COPY = 3 } D3D12_COMMAND_LIST_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RANGE { SIZE_T Begin; SIZE_T End; } D3D12_RANGE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef UINT64 D3D12_GPU_VIRTUAL_ADDRESS; #define D3D12_REQ_SUBRESOURCES 30720 #define D3D12_FLOAT32_MAX 3.402823466e+38f #define D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES 0xffffffff #define D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND 0xffffffff #define D3D12_DEFAULT_DEPTH_BIAS 0 #define D3D12_DEFAULT_DEPTH_BIAS_CLAMP 0.0f #define D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS 0.0f #define D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT 8 #define D3D12_SHADER_COMPONENT_MAPPING_MASK 0x7 #define D3D12_SHADER_COMPONENT_MAPPING_SHIFT 3 #define D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES (1<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*4)) #define D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(Src0,Src1,Src2,Src3) ((((Src0)&D3D12_SHADER_COMPONENT_MAPPING_MASK)| \ (((Src1)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<<D3D12_SHADER_COMPONENT_MAPPING_SHIFT)| \ (((Src2)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*2))| \ (((Src3)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*3))| \ D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES)) #define D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(ComponentToExtract,Mapping) ((D3D12_SHADER_COMPONENT_MAPPING)(Mapping >> (D3D12_SHADER_COMPONENT_MAPPING_SHIFT*ComponentToExtract) & D3D12_SHADER_COMPONENT_MAPPING_MASK)) #define D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0,1,2,3) // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_COMMAND_QUEUE_FLAGS { D3D12_COMMAND_QUEUE_FLAG_NONE = 0, D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT = 0x1 } D3D12_COMMAND_QUEUE_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_COMMAND_QUEUE_PRIORITY { D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0, D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100 } D3D12_COMMAND_QUEUE_PRIORITY; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_COMMAND_QUEUE_DESC { D3D12_COMMAND_LIST_TYPE Type; INT Priority; D3D12_COMMAND_QUEUE_FLAGS Flags; UINT NodeMask; } D3D12_COMMAND_QUEUE_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RESOURCE_ALLOCATION_INFO { UINT64 SizeInBytes; UINT64 Alignment; } D3D12_RESOURCE_ALLOCATION_INFO; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_HEAP_TYPE { D3D12_HEAP_TYPE_DEFAULT = 1, D3D12_HEAP_TYPE_UPLOAD = 2, D3D12_HEAP_TYPE_READBACK = 3, D3D12_HEAP_TYPE_CUSTOM = 4 } D3D12_HEAP_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_CPU_PAGE_PROPERTY { D3D12_CPU_PAGE_PROPERTY_UNKNOWN = 0, D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE = 1, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE = 2, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK = 3 } D3D12_CPU_PAGE_PROPERTY; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_MEMORY_POOL { D3D12_MEMORY_POOL_UNKNOWN = 0, D3D12_MEMORY_POOL_L0 = 1, D3D12_MEMORY_POOL_L1 = 2 } D3D12_MEMORY_POOL; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_HEAP_PROPERTIES { D3D12_HEAP_TYPE Type; D3D12_CPU_PAGE_PROPERTY CPUPageProperty; D3D12_MEMORY_POOL MemoryPoolPreference; UINT CreationNodeMask; UINT VisibleNodeMask; } D3D12_HEAP_PROPERTIES; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_HEAP_FLAGS { D3D12_HEAP_FLAG_NONE = 0, D3D12_HEAP_FLAG_SHARED = 0x1, D3D12_HEAP_FLAG_DENY_BUFFERS = 0x4, D3D12_HEAP_FLAG_ALLOW_DISPLAY = 0x8, D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER = 0x20, D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES = 0x40, D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES = 0x80, D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES = 0, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS = 0xc0, D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44, D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES = 0x84 } D3D12_HEAP_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_DEPTH_STENCIL_VALUE { FLOAT Depth; UINT8 Stencil; } D3D12_DEPTH_STENCIL_VALUE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_CLEAR_VALUE { DXGI_FORMAT Format; union { FLOAT Color[4]; D3D12_DEPTH_STENCIL_VALUE DepthStencil; }; } D3D12_CLEAR_VALUE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_FENCE_FLAGS { D3D12_FENCE_FLAG_NONE = 0, D3D12_FENCE_FLAG_SHARED = 0x1, D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER = 0x2 } D3D12_FENCE_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_FEATURE { D3D12_FEATURE_D3D12_OPTIONS = 0, D3D12_FEATURE_ARCHITECTURE = (D3D12_FEATURE_D3D12_OPTIONS + 1), D3D12_FEATURE_FEATURE_LEVELS = (D3D12_FEATURE_ARCHITECTURE + 1), D3D12_FEATURE_FORMAT_SUPPORT = (D3D12_FEATURE_FEATURE_LEVELS + 1), D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = (D3D12_FEATURE_FORMAT_SUPPORT + 1), D3D12_FEATURE_FORMAT_INFO = (D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS + 1), D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = (D3D12_FEATURE_FORMAT_INFO + 1) } D3D12_FEATURE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_TILE_MAPPING_FLAGS { D3D12_TILE_MAPPING_FLAG_NONE = 0, D3D12_TILE_MAPPING_FLAG_NO_HAZARD = 0x1 } D3D12_TILE_MAPPING_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_CPU_DESCRIPTOR_HANDLE { SIZE_T ptr; } D3D12_CPU_DESCRIPTOR_HANDLE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_GPU_DESCRIPTOR_HANDLE { UINT64 ptr; } D3D12_GPU_DESCRIPTOR_HANDLE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_DESCRIPTOR_HEAP_TYPE { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV = 0, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER = (D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + 1), D3D12_DESCRIPTOR_HEAP_TYPE_RTV = (D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + 1), D3D12_DESCRIPTOR_HEAP_TYPE_DSV = (D3D12_DESCRIPTOR_HEAP_TYPE_RTV + 1), D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES = (D3D12_DESCRIPTOR_HEAP_TYPE_DSV + 1) } D3D12_DESCRIPTOR_HEAP_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_DESCRIPTOR_HEAP_FLAGS { D3D12_DESCRIPTOR_HEAP_FLAG_NONE = 0, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE = 0x1 } D3D12_DESCRIPTOR_HEAP_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_DESCRIPTOR_HEAP_DESC { D3D12_DESCRIPTOR_HEAP_TYPE Type; UINT NumDescriptors; D3D12_DESCRIPTOR_HEAP_FLAGS Flags; UINT NodeMask; } D3D12_DESCRIPTOR_HEAP_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_TILE_COPY_FLAGS { D3D12_TILE_COPY_FLAG_NONE = 0, D3D12_TILE_COPY_FLAG_NO_HAZARD = 0x1, D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2, D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4 } D3D12_TILE_COPY_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_PRIMITIVE_TOPOLOGY_TYPE { D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED = 0, D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT = 1, D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE = 2, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE = 3, D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH = 4 } D3D12_PRIMITIVE_TOPOLOGY_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef D3D_PRIMITIVE_TOPOLOGY D3D12_PRIMITIVE_TOPOLOGY; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_CLEAR_FLAGS { D3D12_CLEAR_FLAG_DEPTH = 0x1, D3D12_CLEAR_FLAG_STENCIL = 0x2 } D3D12_CLEAR_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_QUERY_TYPE { D3D12_QUERY_TYPE_OCCLUSION = 0, D3D12_QUERY_TYPE_BINARY_OCCLUSION = 1, D3D12_QUERY_TYPE_TIMESTAMP = 2, D3D12_QUERY_TYPE_PIPELINE_STATISTICS = 3, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 = 4, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1 = 5, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2 = 6, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3 = 7 } D3D12_QUERY_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_PREDICATION_OP { D3D12_PREDICATION_OP_EQUAL_ZERO = 0, D3D12_PREDICATION_OP_NOT_EQUAL_ZERO = 1 } D3D12_PREDICATION_OP; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_VERTEX_BUFFER_VIEW { D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; UINT SizeInBytes; UINT StrideInBytes; } D3D12_VERTEX_BUFFER_VIEW; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_INDEX_BUFFER_VIEW { D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; UINT SizeInBytes; DXGI_FORMAT Format; } D3D12_INDEX_BUFFER_VIEW; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_CONSTANT_BUFFER_VIEW_DESC { D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; UINT SizeInBytes; } D3D12_CONSTANT_BUFFER_VIEW_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_DSV_DIMENSION { D3D12_DSV_DIMENSION_UNKNOWN = 0, D3D12_DSV_DIMENSION_TEXTURE1D = 1, D3D12_DSV_DIMENSION_TEXTURE1DARRAY = 2, D3D12_DSV_DIMENSION_TEXTURE2D = 3, D3D12_DSV_DIMENSION_TEXTURE2DARRAY = 4, D3D12_DSV_DIMENSION_TEXTURE2DMS = 5, D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY = 6 } D3D12_DSV_DIMENSION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_DSV_FLAGS { D3D12_DSV_FLAG_NONE = 0, D3D12_DSV_FLAG_READ_ONLY_DEPTH = 0x1, D3D12_DSV_FLAG_READ_ONLY_STENCIL = 0x2 } D3D12_DSV_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX1D_DSV { UINT MipSlice; } D3D12_TEX1D_DSV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX1D_ARRAY_DSV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; } D3D12_TEX1D_ARRAY_DSV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2D_DSV { UINT MipSlice; } D3D12_TEX2D_DSV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2D_ARRAY_DSV { UINT MipSlice; UINT FirstArraySlice; UINT ArraySize; } D3D12_TEX2D_ARRAY_DSV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2DMS_DSV { UINT UnusedField_NothingToDefine; } D3D12_TEX2DMS_DSV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2DMS_ARRAY_DSV { UINT FirstArraySlice; UINT ArraySize; } D3D12_TEX2DMS_ARRAY_DSV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_DEPTH_STENCIL_VIEW_DESC { DXGI_FORMAT Format; D3D12_DSV_DIMENSION ViewDimension; D3D12_DSV_FLAGS Flags; union { D3D12_TEX1D_DSV Texture1D; D3D12_TEX1D_ARRAY_DSV Texture1DArray; D3D12_TEX2D_DSV Texture2D; D3D12_TEX2D_ARRAY_DSV Texture2DArray; D3D12_TEX2DMS_DSV Texture2DMS; D3D12_TEX2DMS_ARRAY_DSV Texture2DMSArray; }; } D3D12_DEPTH_STENCIL_VIEW_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_SRV_DIMENSION { D3D12_SRV_DIMENSION_UNKNOWN = 0, D3D12_SRV_DIMENSION_BUFFER = 1, D3D12_SRV_DIMENSION_TEXTURE1D = 2, D3D12_SRV_DIMENSION_TEXTURE1DARRAY = 3, D3D12_SRV_DIMENSION_TEXTURE2D = 4, D3D12_SRV_DIMENSION_TEXTURE2DARRAY = 5, D3D12_SRV_DIMENSION_TEXTURE2DMS = 6, D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, D3D12_SRV_DIMENSION_TEXTURE3D = 8, D3D12_SRV_DIMENSION_TEXTURECUBE = 9, D3D12_SRV_DIMENSION_TEXTURECUBEARRAY = 10 } D3D12_SRV_DIMENSION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_BUFFER_SRV_FLAGS { D3D12_BUFFER_SRV_FLAG_NONE = 0, D3D12_BUFFER_SRV_FLAG_RAW = 0x1 } D3D12_BUFFER_SRV_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_BUFFER_SRV { UINT64 FirstElement; UINT NumElements; UINT StructureByteStride; D3D12_BUFFER_SRV_FLAGS Flags; } D3D12_BUFFER_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX1D_SRV { UINT MostDetailedMip; UINT MipLevels; FLOAT ResourceMinLODClamp; } D3D12_TEX1D_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX1D_ARRAY_SRV { UINT MostDetailedMip; UINT MipLevels; UINT FirstArraySlice; UINT ArraySize; FLOAT ResourceMinLODClamp; } D3D12_TEX1D_ARRAY_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2D_SRV { UINT MostDetailedMip; UINT MipLevels; UINT PlaneSlice; FLOAT ResourceMinLODClamp; } D3D12_TEX2D_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2D_ARRAY_SRV { UINT MostDetailedMip; UINT MipLevels; UINT FirstArraySlice; UINT ArraySize; UINT PlaneSlice; FLOAT ResourceMinLODClamp; } D3D12_TEX2D_ARRAY_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2DMS_SRV { UINT UnusedField_NothingToDefine; } D3D12_TEX2DMS_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX2DMS_ARRAY_SRV { UINT FirstArraySlice; UINT ArraySize; } D3D12_TEX2DMS_ARRAY_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEX3D_SRV { UINT MostDetailedMip; UINT MipLevels; FLOAT ResourceMinLODClamp; } D3D12_TEX3D_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEXCUBE_SRV { UINT MostDetailedMip; UINT MipLevels; FLOAT ResourceMinLODClamp; } D3D12_TEXCUBE_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEXCUBE_ARRAY_SRV { UINT MostDetailedMip; UINT MipLevels; UINT First2DArrayFace; UINT NumCubes; FLOAT ResourceMinLODClamp; } D3D12_TEXCUBE_ARRAY_SRV; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_SHADER_RESOURCE_VIEW_DESC { DXGI_FORMAT Format; D3D12_SRV_DIMENSION ViewDimension; UINT Shader4ComponentMapping; union { D3D12_BUFFER_SRV Buffer; D3D12_TEX1D_SRV Texture1D; D3D12_TEX1D_ARRAY_SRV Texture1DArray; D3D12_TEX2D_SRV Texture2D; D3D12_TEX2D_ARRAY_SRV Texture2DArray; D3D12_TEX2DMS_SRV Texture2DMS; D3D12_TEX2DMS_ARRAY_SRV Texture2DMSArray; D3D12_TEX3D_SRV Texture3D; D3D12_TEXCUBE_SRV TextureCube; D3D12_TEXCUBE_ARRAY_SRV TextureCubeArray; }; } D3D12_SHADER_RESOURCE_VIEW_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_SUBRESOURCE_DATA { const void *pData; LONG_PTR RowPitch; LONG_PTR SlicePitch; } D3D12_SUBRESOURCE_DATA; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_MEMCPY_DEST { void *pData; SIZE_T RowPitch; SIZE_T SlicePitch; } D3D12_MEMCPY_DEST; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_SUBRESOURCE_FOOTPRINT { DXGI_FORMAT Format; UINT Width; UINT Height; UINT Depth; UINT RowPitch; } D3D12_SUBRESOURCE_FOOTPRINT; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT { UINT64 Offset; D3D12_SUBRESOURCE_FOOTPRINT Footprint; } D3D12_PLACED_SUBRESOURCE_FOOTPRINT; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_TEXTURE_COPY_TYPE { D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX = 0, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT = 1 } D3D12_TEXTURE_COPY_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_TEXTURE_COPY_LOCATION { ID3D12Resource *pResource; D3D12_TEXTURE_COPY_TYPE Type; union { D3D12_PLACED_SUBRESOURCE_FOOTPRINT PlacedFootprint; UINT SubresourceIndex; }; } D3D12_TEXTURE_COPY_LOCATION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_DESCRIPTOR_RANGE_TYPE { D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0, D3D12_DESCRIPTOR_RANGE_TYPE_UAV = (D3D12_DESCRIPTOR_RANGE_TYPE_SRV + 1), D3D12_DESCRIPTOR_RANGE_TYPE_CBV = (D3D12_DESCRIPTOR_RANGE_TYPE_UAV + 1), D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = (D3D12_DESCRIPTOR_RANGE_TYPE_CBV + 1) } D3D12_DESCRIPTOR_RANGE_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_DESCRIPTOR_RANGE { D3D12_DESCRIPTOR_RANGE_TYPE RangeType; UINT NumDescriptors; UINT BaseShaderRegister; UINT RegisterSpace; UINT OffsetInDescriptorsFromTableStart; } D3D12_DESCRIPTOR_RANGE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D_ROOT_SIGNATURE_VERSION { D3D_ROOT_SIGNATURE_VERSION_1 = 0x1 } D3D_ROOT_SIGNATURE_VERSION; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_ROOT_PARAMETER_TYPE { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS = (D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE + 1), D3D12_ROOT_PARAMETER_TYPE_CBV = (D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS + 1), D3D12_ROOT_PARAMETER_TYPE_SRV = (D3D12_ROOT_PARAMETER_TYPE_CBV + 1), D3D12_ROOT_PARAMETER_TYPE_UAV = (D3D12_ROOT_PARAMETER_TYPE_SRV + 1) } D3D12_ROOT_PARAMETER_TYPE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_ROOT_DESCRIPTOR_TABLE { UINT NumDescriptorRanges; _Field_size_full_(NumDescriptorRanges) const D3D12_DESCRIPTOR_RANGE *pDescriptorRanges; } D3D12_ROOT_DESCRIPTOR_TABLE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_ROOT_CONSTANTS { UINT ShaderRegister; UINT RegisterSpace; UINT Num32BitValues; } D3D12_ROOT_CONSTANTS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_ROOT_DESCRIPTOR { UINT ShaderRegister; UINT RegisterSpace; } D3D12_ROOT_DESCRIPTOR; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_SHADER_VISIBILITY { D3D12_SHADER_VISIBILITY_ALL = 0, D3D12_SHADER_VISIBILITY_VERTEX = 1, D3D12_SHADER_VISIBILITY_HULL = 2, D3D12_SHADER_VISIBILITY_DOMAIN = 3, D3D12_SHADER_VISIBILITY_GEOMETRY = 4, D3D12_SHADER_VISIBILITY_PIXEL = 5 } D3D12_SHADER_VISIBILITY; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_ROOT_PARAMETER { D3D12_ROOT_PARAMETER_TYPE ParameterType; union { D3D12_ROOT_DESCRIPTOR_TABLE DescriptorTable; D3D12_ROOT_CONSTANTS Constants; D3D12_ROOT_DESCRIPTOR Descriptor; }; D3D12_SHADER_VISIBILITY ShaderVisibility; } D3D12_ROOT_PARAMETER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_STATIC_BORDER_COLOR { D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK = 0, D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK = (D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK + 1), D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE = (D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK + 1) } D3D12_STATIC_BORDER_COLOR; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_FILTER { D3D12_FILTER_MIN_MAG_MIP_POINT = 0, D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1, D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5, D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10, D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14, D3D12_FILTER_MIN_MAG_MIP_LINEAR = 0x15, D3D12_FILTER_ANISOTROPIC = 0x55, D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80, D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, D3D12_FILTER_COMPARISON_ANISOTROPIC = 0xd5, D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100, D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, D3D12_FILTER_MINIMUM_ANISOTROPIC = 0x155, D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180, D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, D3D12_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5 } D3D12_FILTER; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_TEXTURE_ADDRESS_MODE { D3D12_TEXTURE_ADDRESS_MODE_WRAP = 1, D3D12_TEXTURE_ADDRESS_MODE_MIRROR = 2, D3D12_TEXTURE_ADDRESS_MODE_CLAMP = 3, D3D12_TEXTURE_ADDRESS_MODE_BORDER = 4, D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE = 5 } D3D12_TEXTURE_ADDRESS_MODE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_COMPARISON_FUNC { D3D12_COMPARISON_FUNC_NEVER = 1, D3D12_COMPARISON_FUNC_LESS = 2, D3D12_COMPARISON_FUNC_EQUAL = 3, D3D12_COMPARISON_FUNC_LESS_EQUAL = 4, D3D12_COMPARISON_FUNC_GREATER = 5, D3D12_COMPARISON_FUNC_NOT_EQUAL = 6, D3D12_COMPARISON_FUNC_GREATER_EQUAL = 7, D3D12_COMPARISON_FUNC_ALWAYS = 8 } D3D12_COMPARISON_FUNC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_STATIC_SAMPLER_DESC { D3D12_FILTER Filter; D3D12_TEXTURE_ADDRESS_MODE AddressU; D3D12_TEXTURE_ADDRESS_MODE AddressV; D3D12_TEXTURE_ADDRESS_MODE AddressW; FLOAT MipLODBias; UINT MaxAnisotropy; D3D12_COMPARISON_FUNC ComparisonFunc; D3D12_STATIC_BORDER_COLOR BorderColor; FLOAT MinLOD; FLOAT MaxLOD; UINT ShaderRegister; UINT RegisterSpace; D3D12_SHADER_VISIBILITY ShaderVisibility; } D3D12_STATIC_SAMPLER_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_ROOT_SIGNATURE_FLAGS { D3D12_ROOT_SIGNATURE_FLAG_NONE = 0, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1, D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2, D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS = 0x4, D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8, D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10, D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT = 0x40 } D3D12_ROOT_SIGNATURE_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_ROOT_SIGNATURE_DESC { UINT NumParameters; _Field_size_full_(NumParameters) const D3D12_ROOT_PARAMETER *pParameters; UINT NumStaticSamplers; _Field_size_full_(NumStaticSamplers) const D3D12_STATIC_SAMPLER_DESC *pStaticSamplers; D3D12_ROOT_SIGNATURE_FLAGS Flags; } D3D12_ROOT_SIGNATURE_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_SHADER_BYTECODE { _Field_size_bytes_full_(BytecodeLength) const void *pShaderBytecode; SIZE_T BytecodeLength; } D3D12_SHADER_BYTECODE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_STREAM_OUTPUT_DESC { _Field_size_full_(NumEntries) const D3D12_SO_DECLARATION_ENTRY *pSODeclaration; UINT NumEntries; _Field_size_full_(NumStrides) const UINT *pBufferStrides; UINT NumStrides; UINT RasterizedStream; } D3D12_STREAM_OUTPUT_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_BLEND { D3D12_BLEND_ZERO = 1, D3D12_BLEND_ONE = 2, D3D12_BLEND_SRC_COLOR = 3, D3D12_BLEND_INV_SRC_COLOR = 4, D3D12_BLEND_SRC_ALPHA = 5, D3D12_BLEND_INV_SRC_ALPHA = 6, D3D12_BLEND_DEST_ALPHA = 7, D3D12_BLEND_INV_DEST_ALPHA = 8, D3D12_BLEND_DEST_COLOR = 9, D3D12_BLEND_INV_DEST_COLOR = 10, D3D12_BLEND_SRC_ALPHA_SAT = 11, D3D12_BLEND_BLEND_FACTOR = 14, D3D12_BLEND_INV_BLEND_FACTOR = 15, D3D12_BLEND_SRC1_COLOR = 16, D3D12_BLEND_INV_SRC1_COLOR = 17, D3D12_BLEND_SRC1_ALPHA = 18, D3D12_BLEND_INV_SRC1_ALPHA = 19 } D3D12_BLEND; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_BLEND_OP { D3D12_BLEND_OP_ADD = 1, D3D12_BLEND_OP_SUBTRACT = 2, D3D12_BLEND_OP_REV_SUBTRACT = 3, D3D12_BLEND_OP_MIN = 4, D3D12_BLEND_OP_MAX = 5 } D3D12_BLEND_OP; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_LOGIC_OP { D3D12_LOGIC_OP_CLEAR = 0, D3D12_LOGIC_OP_SET = (D3D12_LOGIC_OP_CLEAR + 1), D3D12_LOGIC_OP_COPY = (D3D12_LOGIC_OP_SET + 1), D3D12_LOGIC_OP_COPY_INVERTED = (D3D12_LOGIC_OP_COPY + 1), D3D12_LOGIC_OP_NOOP = (D3D12_LOGIC_OP_COPY_INVERTED + 1), D3D12_LOGIC_OP_INVERT = (D3D12_LOGIC_OP_NOOP + 1), D3D12_LOGIC_OP_AND = (D3D12_LOGIC_OP_INVERT + 1), D3D12_LOGIC_OP_NAND = (D3D12_LOGIC_OP_AND + 1), D3D12_LOGIC_OP_OR = (D3D12_LOGIC_OP_NAND + 1), D3D12_LOGIC_OP_NOR = (D3D12_LOGIC_OP_OR + 1), D3D12_LOGIC_OP_XOR = (D3D12_LOGIC_OP_NOR + 1), D3D12_LOGIC_OP_EQUIV = (D3D12_LOGIC_OP_XOR + 1), D3D12_LOGIC_OP_AND_REVERSE = (D3D12_LOGIC_OP_EQUIV + 1), D3D12_LOGIC_OP_AND_INVERTED = (D3D12_LOGIC_OP_AND_REVERSE + 1), D3D12_LOGIC_OP_OR_REVERSE = (D3D12_LOGIC_OP_AND_INVERTED + 1), D3D12_LOGIC_OP_OR_INVERTED = (D3D12_LOGIC_OP_OR_REVERSE + 1) } D3D12_LOGIC_OP; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RENDER_TARGET_BLEND_DESC { BOOL BlendEnable; BOOL LogicOpEnable; D3D12_BLEND SrcBlend; D3D12_BLEND DestBlend; D3D12_BLEND_OP BlendOp; D3D12_BLEND SrcBlendAlpha; D3D12_BLEND DestBlendAlpha; D3D12_BLEND_OP BlendOpAlpha; D3D12_LOGIC_OP LogicOp; UINT8 RenderTargetWriteMask; } D3D12_RENDER_TARGET_BLEND_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_BLEND_DESC { BOOL AlphaToCoverageEnable; BOOL IndependentBlendEnable; D3D12_RENDER_TARGET_BLEND_DESC RenderTarget[8]; } D3D12_BLEND_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_COLOR_WRITE_ENABLE { D3D12_COLOR_WRITE_ENABLE_RED = 1, D3D12_COLOR_WRITE_ENABLE_GREEN = 2, D3D12_COLOR_WRITE_ENABLE_BLUE = 4, D3D12_COLOR_WRITE_ENABLE_ALPHA = 8, D3D12_COLOR_WRITE_ENABLE_ALL = (((D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN) | D3D12_COLOR_WRITE_ENABLE_BLUE | D3D12_COLOR_WRITE_ENABLE_ALPHA)) } D3D12_COLOR_WRITE_ENABLE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_CONSERVATIVE_RASTERIZATION_MODE { D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = 0, D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = 1 } D3D12_CONSERVATIVE_RASTERIZATION_MODE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_FILL_MODE { D3D12_FILL_MODE_WIREFRAME = 2, D3D12_FILL_MODE_SOLID = 3 } D3D12_FILL_MODE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_CULL_MODE { D3D12_CULL_MODE_NONE = 1, D3D12_CULL_MODE_FRONT = 2, D3D12_CULL_MODE_BACK = 3 } D3D12_CULL_MODE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_RASTERIZER_DESC { D3D12_FILL_MODE FillMode; D3D12_CULL_MODE CullMode; BOOL FrontCounterClockwise; INT DepthBias; FLOAT DepthBiasClamp; FLOAT SlopeScaledDepthBias; BOOL DepthClipEnable; BOOL MultisampleEnable; BOOL AntialiasedLineEnable; UINT ForcedSampleCount; D3D12_CONSERVATIVE_RASTERIZATION_MODE ConservativeRaster; } D3D12_RASTERIZER_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_STENCIL_OP { D3D12_STENCIL_OP_KEEP = 1, D3D12_STENCIL_OP_ZERO = 2, D3D12_STENCIL_OP_REPLACE = 3, D3D12_STENCIL_OP_INCR_SAT = 4, D3D12_STENCIL_OP_DECR_SAT = 5, D3D12_STENCIL_OP_INVERT = 6, D3D12_STENCIL_OP_INCR = 7, D3D12_STENCIL_OP_DECR = 8 } D3D12_STENCIL_OP; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_DEPTH_STENCILOP_DESC { D3D12_STENCIL_OP StencilFailOp; D3D12_STENCIL_OP StencilDepthFailOp; D3D12_STENCIL_OP StencilPassOp; D3D12_COMPARISON_FUNC StencilFunc; } D3D12_DEPTH_STENCILOP_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_DEPTH_WRITE_MASK { D3D12_DEPTH_WRITE_MASK_ZERO = 0, D3D12_DEPTH_WRITE_MASK_ALL = 1 } D3D12_DEPTH_WRITE_MASK; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_DEPTH_STENCIL_DESC { BOOL DepthEnable; D3D12_DEPTH_WRITE_MASK DepthWriteMask; D3D12_COMPARISON_FUNC DepthFunc; BOOL StencilEnable; UINT8 StencilReadMask; UINT8 StencilWriteMask; D3D12_DEPTH_STENCILOP_DESC FrontFace; D3D12_DEPTH_STENCILOP_DESC BackFace; } D3D12_DEPTH_STENCIL_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_INPUT_LAYOUT_DESC { _Field_size_full_(NumElements) const D3D12_INPUT_ELEMENT_DESC *pInputElementDescs; UINT NumElements; } D3D12_INPUT_LAYOUT_DESC; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_INDEX_BUFFER_STRIP_CUT_VALUE { D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED = 0, D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF = 1, D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF = 2 } D3D12_INDEX_BUFFER_STRIP_CUT_VALUE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_CACHED_PIPELINE_STATE { _Field_size_bytes_full_(CachedBlobSizeInBytes) const void *pCachedBlob; SIZE_T CachedBlobSizeInBytes; } D3D12_CACHED_PIPELINE_STATE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef enum D3D12_PIPELINE_STATE_FLAGS { D3D12_PIPELINE_STATE_FLAG_NONE = 0, D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG = 0x1 } D3D12_PIPELINE_STATE_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" typedef struct D3D12_GRAPHICS_PIPELINE_STATE_DESC { ID3D12RootSignature *pRootSignature; D3D12_SHADER_BYTECODE VS; D3D12_SHADER_BYTECODE PS; D3D12_SHADER_BYTECODE DS; D3D12_SHADER_BYTECODE HS; D3D12_SHADER_BYTECODE GS; D3D12_STREAM_OUTPUT_DESC StreamOutput; D3D12_BLEND_DESC BlendState; UINT SampleMask; D3D12_RASTERIZER_DESC RasterizerState; D3D12_DEPTH_STENCIL_DESC DepthStencilState; D3D12_INPUT_LAYOUT_DESC InputLayout; D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue; D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType; UINT NumRenderTargets; DXGI_FORMAT RTVFormats[8]; DXGI_FORMAT DSVFormat; DXGI_SAMPLE_DESC SampleDesc; UINT NodeMask; D3D12_CACHED_PIPELINE_STATE CachedPSO; D3D12_PIPELINE_STATE_FLAGS Flags; } D3D12_GRAPHICS_PIPELINE_STATE_DESC; #ifdef RENDERER_DEBUG // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h" typedef enum D3D12_DEBUG_FEATURE { D3D12_DEBUG_FEATURE_NONE = 0, D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DRAW = 0x1, D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DISPATCH = 0x2 } D3D12_DEBUG_FEATURE; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h" typedef enum D3D12_RLDO_FLAGS { D3D12_RLDO_NONE = 0, D3D12_RLDO_SUMMARY = 0x1, D3D12_RLDO_DETAIL = 0x2, D3D12_RLDO_IGNORE_INTERNAL = 0x4 } D3D12_RLDO_FLAGS; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "pix_win.h" static const UINT PIX_EVENT_ANSI_VERSION = 1; #endif //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("aec22fb8-76f3-4639-9be0-28eb43a67a2e") IDXGIObject : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetPrivateData(_In_ REFGUID Name, UINT DataSize, _In_reads_bytes_(DataSize) const void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(_In_ REFGUID Name, _In_ const IUnknown *pUnknown) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrivateData(_In_ REFGUID Name, _Inout_ UINT *pDataSize, _Out_writes_bytes_(*pDataSize) void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE GetParent(_In_ REFIID riid, _COM_Outptr_ void **ppParent) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("3d3e0379-f9de-4d58-bb6c-18d62992f1a6") IDXGIDeviceSubObject : public IDXGIObject { public: virtual HRESULT STDMETHODCALLTYPE GetDevice(_In_ REFIID riid, _COM_Outptr_ void **ppDevice) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("310d36a0-d2e7-4c0a-aa04-6a9d23b8886a") IDXGISwapChain : public IDXGIDeviceSubObject { public: virtual HRESULT STDMETHODCALLTYPE Present(UINT SyncInterval, UINT Flags) = 0; virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT Buffer, _In_ REFIID riid, _COM_Outptr_ void **ppSurface) = 0; virtual HRESULT STDMETHODCALLTYPE SetFullscreenState(BOOL Fullscreen, _In_opt_ IDXGIOutput *pTarget) = 0; virtual HRESULT STDMETHODCALLTYPE GetFullscreenState(_Out_opt_ BOOL *pFullscreen, _COM_Outptr_opt_result_maybenull_ IDXGIOutput **ppTarget) = 0; virtual HRESULT STDMETHODCALLTYPE GetDesc(_Out_ DXGI_SWAP_CHAIN_DESC *pDesc) = 0; virtual HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags) = 0; virtual HRESULT STDMETHODCALLTYPE ResizeTarget(_In_ const DXGI_MODE_DESC *pNewTargetParameters) = 0; virtual HRESULT STDMETHODCALLTYPE GetContainingOutput(_COM_Outptr_ IDXGIOutput **ppOutput) = 0; virtual HRESULT STDMETHODCALLTYPE GetFrameStatistics(_Out_ DXGI_FRAME_STATISTICS *pStats) = 0; virtual HRESULT STDMETHODCALLTYPE GetLastPresentCount(_Out_ UINT *pLastPresentCount) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgi1_2.h" MIDL_INTERFACE("790a45f7-0d42-4876-983a-0a55cfe6f4aa") IDXGISwapChain1 : public IDXGISwapChain { public: virtual HRESULT STDMETHODCALLTYPE GetDesc1(_Out_ DXGI_SWAP_CHAIN_DESC1 *pDesc) = 0; virtual HRESULT STDMETHODCALLTYPE GetFullscreenDesc(_Out_ DXGI_SWAP_CHAIN_FULLSCREEN_DESC *pDesc) = 0; virtual HRESULT STDMETHODCALLTYPE GetHwnd(_Out_ HWND *pHwnd) = 0; virtual HRESULT STDMETHODCALLTYPE GetCoreWindow(_In_ REFIID refiid, _COM_Outptr_ void **ppUnk) = 0; virtual HRESULT STDMETHODCALLTYPE Present1(UINT SyncInterval, UINT PresentFlags, _In_ const DXGI_PRESENT_PARAMETERS *pPresentParameters) = 0; virtual BOOL STDMETHODCALLTYPE IsTemporaryMonoSupported(void) = 0; virtual HRESULT STDMETHODCALLTYPE GetRestrictToOutput(_Out_ IDXGIOutput **ppRestrictToOutput) = 0; virtual HRESULT STDMETHODCALLTYPE SetBackgroundColor(_In_ const DXGI_RGBA *pColor) = 0; virtual HRESULT STDMETHODCALLTYPE GetBackgroundColor(_Out_ DXGI_RGBA *pColor) = 0; virtual HRESULT STDMETHODCALLTYPE SetRotation(_In_ DXGI_MODE_ROTATION Rotation) = 0; virtual HRESULT STDMETHODCALLTYPE GetRotation(_Out_ DXGI_MODE_ROTATION *pRotation) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgi1_3.h" MIDL_INTERFACE("a8be2ac4-199f-4946-b331-79599fb98de7") IDXGISwapChain2 : public IDXGISwapChain1 { public: virtual HRESULT STDMETHODCALLTYPE SetSourceSize(UINT Width, UINT Height) = 0; virtual HRESULT STDMETHODCALLTYPE GetSourceSize(_Out_ UINT *pWidth, _Out_ UINT *pHeight) = 0; virtual HRESULT STDMETHODCALLTYPE SetMaximumFrameLatency(UINT MaxLatency) = 0; virtual HRESULT STDMETHODCALLTYPE GetMaximumFrameLatency(_Out_ UINT *pMaxLatency) = 0; virtual HANDLE STDMETHODCALLTYPE GetFrameLatencyWaitableObject(void) = 0; virtual HRESULT STDMETHODCALLTYPE SetMatrixTransform(const DXGI_MATRIX_3X2_F *pMatrix) = 0; virtual HRESULT STDMETHODCALLTYPE GetMatrixTransform(_Out_ DXGI_MATRIX_3X2_F *pMatrix) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgi1_4.h" MIDL_INTERFACE("94d99bdb-f1f8-4ab0-b236-7da0170edab1") IDXGISwapChain3 : public IDXGISwapChain2 { public: virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex(void) = 0; virtual HRESULT STDMETHODCALLTYPE CheckColorSpaceSupport(_In_ DXGI_COLOR_SPACE_TYPE ColorSpace, _Out_ UINT *pColorSpaceSupport) = 0; virtual HRESULT STDMETHODCALLTYPE SetColorSpace1(_In_ DXGI_COLOR_SPACE_TYPE ColorSpace) = 0; virtual HRESULT STDMETHODCALLTYPE ResizeBuffers1(_In_ UINT BufferCount, _In_ UINT Width, _In_ UINT Height, _In_ DXGI_FORMAT Format, _In_ UINT SwapChainFlags, _In_reads_(BufferCount) const UINT *pCreationNodeMask, _In_reads_(BufferCount) IUnknown *const *ppPresentQueue) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("7b7166ec-21c7-44ae-b21a-c9ae321ae369") IDXGIFactory : public IDXGIObject { public: virtual HRESULT STDMETHODCALLTYPE EnumAdapters(UINT Adapter, _COM_Outptr_ IDXGIAdapter **ppAdapter) = 0; virtual HRESULT STDMETHODCALLTYPE MakeWindowAssociation(HWND WindowHandle, UINT Flags) = 0; virtual HRESULT STDMETHODCALLTYPE GetWindowAssociation(_Out_ HWND *pWindowHandle) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(_In_ IUnknown *pDevice, _In_ DXGI_SWAP_CHAIN_DESC *pDesc, _COM_Outptr_ IDXGISwapChain **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE Module, _COM_Outptr_ IDXGIAdapter **ppAdapter) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("770aae78-f26f-4dba-a829-253c83d1b387") IDXGIFactory1 : public IDXGIFactory { public: virtual HRESULT STDMETHODCALLTYPE EnumAdapters1(UINT Adapter, __out IDXGIAdapter1 **ppAdapter) = 0; virtual BOOL STDMETHODCALLTYPE IsCurrent(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("50c83a1c-e072-4c48-87b0-3630fa36a6d0") IDXGIFactory2 : public IDXGIFactory1 { public: virtual BOOL STDMETHODCALLTYPE IsWindowedStereoEnabled(void) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(_In_ IUnknown *pDevice, _In_ HWND hWnd, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ const DXGI_SWAP_CHAIN_FULLSCREEN_DESC *pFullscreenDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(_In_ IUnknown *pDevice, _In_ IUnknown *pWindow, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0; virtual HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(_In_ HANDLE hResource, _Out_ LUID *pLuid) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(_In_ HWND WindowHandle, _In_ UINT wMsg, _Out_ DWORD *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(_In_ HANDLE hEvent, _Out_ DWORD *pdwCookie) = 0; virtual void STDMETHODCALLTYPE UnregisterStereoStatus(_In_ DWORD dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(_In_ HWND WindowHandle, _In_ UINT wMsg, _Out_ DWORD *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(_In_ HANDLE hEvent, _Out_ DWORD *pdwCookie) = 0; virtual void STDMETHODCALLTYPE UnregisterOcclusionStatus(_In_ DWORD dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(_In_ IUnknown *pDevice, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("25483823-cd46-4c7d-86ca-47aa95b837bd") IDXGIFactory3 : public IDXGIFactory2 { public: virtual UINT STDMETHODCALLTYPE GetCreationFlags(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("1bc6ea02-ef36-464f-bf0c-21ca39e5168a") IDXGIFactory4 : public IDXGIFactory3 { public: virtual HRESULT STDMETHODCALLTYPE EnumAdapterByLuid(_In_ LUID AdapterLuid, _In_ REFIID riid, _COM_Outptr_ void **ppvAdapter) = 0; virtual HRESULT STDMETHODCALLTYPE EnumWarpAdapter(_In_ REFIID riid, _COM_Outptr_ void **ppvAdapter) = 0; }; // "Microsoft DirectX SDK (June 2010)" -> "DXGI.h" struct DXGI_ADAPTER_DESC { WCHAR Description[128]; UINT VendorId; UINT DeviceId; UINT SubSysId; UINT Revision; SIZE_T DedicatedVideoMemory; SIZE_T DedicatedSystemMemory; SIZE_T SharedSystemMemory; LUID AdapterLuid; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("2411e7e1-12ac-4ccf-bd14-9798e8534dc0") IDXGIAdapter : public IDXGIObject { public: virtual HRESULT STDMETHODCALLTYPE EnumOutputs(UINT Output, __out IDXGIOutput **ppOutput) = 0; virtual HRESULT STDMETHODCALLTYPE GetDesc(__out DXGI_ADAPTER_DESC *pDesc) = 0; virtual HRESULT STDMETHODCALLTYPE CheckInterfaceSupport(__in REFGUID InterfaceName, __out LARGE_INTEGER *pUMDVersion) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h" MIDL_INTERFACE("54ec77fa-1377-44e6-8c32-88fd5f44c84c") IDXGIDevice : public IDXGIObject { public: virtual HRESULT STDMETHODCALLTYPE GetAdapter(_COM_Outptr_ IDXGIAdapter **pAdapter) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSurface(_In_ const DXGI_SURFACE_DESC *pDesc, UINT NumSurfaces, DXGI_USAGE Usage, _In_opt_ const DXGI_SHARED_RESOURCE *pSharedResource, _COM_Outptr_ IDXGISurface **ppSurface) = 0; virtual HRESULT STDMETHODCALLTYPE QueryResourceResidency(_In_reads_(NumResources) IUnknown *const *ppResources, _Out_writes_(NumResources) DXGI_RESIDENCY *pResidencyStatus, UINT NumResources) = 0; virtual HRESULT STDMETHODCALLTYPE SetGPUThreadPriority(INT Priority) = 0; virtual HRESULT STDMETHODCALLTYPE GetGPUThreadPriority(_Out_ INT *pPriority) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h" MIDL_INTERFACE("8BA5FB08-5195-40e2-AC58-0D989C3A0102") ID3D10Blob : public IUnknown { public: virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0; virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("c4fec28f-7966-4e95-9f94-f431cb56c3b8") ID3D12Object : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetPrivateData(_In_ REFGUID guid, _Inout_ UINT *pDataSize, _Out_writes_bytes_opt_( *pDataSize ) void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateData(_In_ REFGUID guid, _In_ UINT DataSize, _In_reads_bytes_opt_(DataSize) const void *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(_In_ REFGUID guid, _In_opt_ const IUnknown *pData) = 0; virtual HRESULT STDMETHODCALLTYPE SetName(_In_z_ LPCWSTR Name) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("905db94b-a00c-4140-9df5-2b64ca9ea357") ID3D12DeviceChild : public ID3D12Object { public: virtual HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, _COM_Outptr_opt_ void **ppvDevice) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("c54a6b66-72df-4ee8-8be5-a946a1429214") ID3D12RootSignature : public ID3D12DeviceChild { // Nothing here }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("63ee58fb-1268-4835-86da-f008ce62f0d6") ID3D12Pageable : public ID3D12DeviceChild { // Nothing here }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("0a753dcf-c4d8-4b91-adf6-be5a60d95a76") ID3D12Fence : public ID3D12Pageable { public: virtual UINT64 STDMETHODCALLTYPE GetCompletedValue(void) = 0; virtual HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64 Value, HANDLE hEvent) = 0; virtual HRESULT STDMETHODCALLTYPE Signal(UINT64 Value) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("696442be-a72e-4059-bc79-5b5c98040fad") ID3D12Resource : public ID3D12Pageable { public: virtual HRESULT STDMETHODCALLTYPE Map(UINT Subresource, _In_opt_ const D3D12_RANGE *pReadRange, _Outptr_opt_result_bytebuffer_(_Inexpressible_("Dependent on resource")) void **ppData) = 0; virtual void STDMETHODCALLTYPE Unmap(UINT Subresource, _In_opt_ const D3D12_RANGE *pWrittenRange) = 0; virtual D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc(void) = 0; virtual D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress( void) = 0; virtual HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT DstSubresource, _In_opt_ const D3D12_BOX *pDstBox, _In_ const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) = 0; virtual HRESULT STDMETHODCALLTYPE ReadFromSubresource(_Out_ void *pDstData, UINT DstRowPitch, UINT DstDepthPitch, UINT SrcSubresource, _In_opt_ const D3D12_BOX *pSrcBox) = 0; virtual HRESULT STDMETHODCALLTYPE GetHeapProperties(_Out_opt_ D3D12_HEAP_PROPERTIES *pHeapProperties, _Out_opt_ D3D12_HEAP_FLAGS *pHeapFlags) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("765a30f3-f624-4c6f-a828-ace948622445") ID3D12PipelineState : public ID3D12Pageable { public: virtual HRESULT STDMETHODCALLTYPE GetCachedBlob(_COM_Outptr_ ID3DBlob* *ppBlob) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("8efb471d-616c-4f49-90f7-127bb763fa51") ID3D12DescriptorHeap : public ID3D12Pageable { public: virtual D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE GetDesc(void) = 0; virtual D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetCPUDescriptorHandleForHeapStart(void) = 0; virtual D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetGPUDescriptorHandleForHeapStart(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("6102dee4-af59-4b09-b999-b44d73f09b24") ID3D12CommandAllocator : public ID3D12Pageable { public: virtual HRESULT STDMETHODCALLTYPE Reset(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("7116d91c-e7e4-47ce-b8c6-ec8168f437e5") ID3D12CommandList : public ID3D12DeviceChild { public: virtual D3D12_COMMAND_LIST_TYPE STDMETHODCALLTYPE GetType(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("5b160d0f-ac1b-4185-8ba8-b3ae42a5a455") ID3D12GraphicsCommandList : public ID3D12CommandList { public: virtual HRESULT STDMETHODCALLTYPE Close(void) = 0; virtual HRESULT STDMETHODCALLTYPE Reset(_In_ ID3D12CommandAllocator *pAllocator, _In_opt_ ID3D12PipelineState *pInitialState) = 0; virtual void STDMETHODCALLTYPE ClearState(_In_opt_ ID3D12PipelineState *pPipelineState) = 0; virtual void STDMETHODCALLTYPE DrawInstanced(_In_ UINT VertexCountPerInstance, _In_ UINT InstanceCount, _In_ UINT StartVertexLocation, _In_ UINT StartInstanceLocation) = 0; virtual void STDMETHODCALLTYPE DrawIndexedInstanced(_In_ UINT IndexCountPerInstance, _In_ UINT InstanceCount, _In_ UINT StartIndexLocation, _In_ INT BaseVertexLocation, _In_ UINT StartInstanceLocation) = 0; virtual void STDMETHODCALLTYPE Dispatch(_In_ UINT ThreadGroupCountX, _In_ UINT ThreadGroupCountY, _In_ UINT ThreadGroupCountZ) = 0; virtual void STDMETHODCALLTYPE CopyBufferRegion(_In_ ID3D12Resource *pDstBuffer, UINT64 DstOffset, _In_ ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT64 NumBytes) = 0; virtual void STDMETHODCALLTYPE CopyTextureRegion(_In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, UINT DstX, UINT DstY, UINT DstZ, _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, _In_opt_ const D3D12_BOX *pSrcBox) = 0; virtual void STDMETHODCALLTYPE CopyResource(_In_ ID3D12Resource *pDstResource, _In_ ID3D12Resource *pSrcResource) = 0; virtual void STDMETHODCALLTYPE CopyTiles(_In_ ID3D12Resource *pTiledResource, _In_ const D3D12_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate, _In_ const D3D12_TILE_REGION_SIZE *pTileRegionSize, _In_ ID3D12Resource *pBuffer, UINT64 BufferStartOffsetInBytes, D3D12_TILE_COPY_FLAGS Flags) = 0; virtual void STDMETHODCALLTYPE ResolveSubresource(_In_ ID3D12Resource *pDstResource, _In_ UINT DstSubresource, _In_ ID3D12Resource *pSrcResource, _In_ UINT SrcSubresource, _In_ DXGI_FORMAT Format) = 0; virtual void STDMETHODCALLTYPE IASetPrimitiveTopology(_In_ D3D12_PRIMITIVE_TOPOLOGY PrimitiveTopology) = 0; virtual void STDMETHODCALLTYPE RSSetViewports(_In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumViewports, _In_reads_( NumViewports) const D3D12_VIEWPORT *pViewports) = 0; virtual void STDMETHODCALLTYPE RSSetScissorRects(_In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumRects, _In_reads_( NumRects) const D3D12_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE OMSetBlendFactor(_In_opt_ const FLOAT BlendFactor[4]) = 0; virtual void STDMETHODCALLTYPE OMSetStencilRef(_In_ UINT StencilRef) = 0; virtual void STDMETHODCALLTYPE SetPipelineState(_In_ ID3D12PipelineState *pPipelineState) = 0; virtual void STDMETHODCALLTYPE ResourceBarrier(_In_ UINT NumBarriers, _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers) = 0; virtual void STDMETHODCALLTYPE ExecuteBundle(_In_ ID3D12GraphicsCommandList *pCommandList) = 0; virtual void STDMETHODCALLTYPE SetDescriptorHeaps(_In_ UINT NumDescriptorHeaps, _In_reads_(NumDescriptorHeaps) ID3D12DescriptorHeap **ppDescriptorHeaps) = 0; virtual void STDMETHODCALLTYPE SetComputeRootSignature(_In_ ID3D12RootSignature *pRootSignature) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRootSignature(_In_ ID3D12RootSignature *pRootSignature) = 0; virtual void STDMETHODCALLTYPE SetComputeRootDescriptorTable(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRootDescriptorTable(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) = 0; virtual void STDMETHODCALLTYPE SetComputeRoot32BitConstant(_In_ UINT RootParameterIndex, _In_ UINT SrcData, _In_ UINT DestOffsetIn32BitValues) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRoot32BitConstant(_In_ UINT RootParameterIndex, _In_ UINT SrcData, _In_ UINT DestOffsetIn32BitValues) = 0; virtual void STDMETHODCALLTYPE SetComputeRoot32BitConstants(_In_ UINT RootParameterIndex, _In_ UINT Num32BitValuesToSet, _In_reads_(Num32BitValuesToSet * sizeof(UINT)) const void *pSrcData, _In_ UINT DestOffsetIn32BitValues) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRoot32BitConstants(_In_ UINT RootParameterIndex, _In_ UINT Num32BitValuesToSet, _In_reads_(Num32BitValuesToSet * sizeof(UINT)) const void *pSrcData, _In_ UINT DestOffsetIn32BitValues) = 0; virtual void STDMETHODCALLTYPE SetComputeRootConstantBufferView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRootConstantBufferView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0; virtual void STDMETHODCALLTYPE SetComputeRootShaderResourceView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRootShaderResourceView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0; virtual void STDMETHODCALLTYPE SetComputeRootUnorderedAccessView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0; virtual void STDMETHODCALLTYPE SetGraphicsRootUnorderedAccessView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0; virtual void STDMETHODCALLTYPE IASetIndexBuffer(_In_opt_ const D3D12_INDEX_BUFFER_VIEW *pView) = 0; virtual void STDMETHODCALLTYPE IASetVertexBuffers(_In_ UINT StartSlot, _In_ UINT NumViews, _In_reads_opt_(NumViews) const D3D12_VERTEX_BUFFER_VIEW *pViews) = 0; virtual void STDMETHODCALLTYPE SOSetTargets(_In_ UINT StartSlot, _In_ UINT NumViews, _In_reads_opt_(NumViews) const D3D12_STREAM_OUTPUT_BUFFER_VIEW *pViews) = 0; virtual void STDMETHODCALLTYPE OMSetRenderTargets(_In_ UINT NumRenderTargetDescriptors, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE *pRenderTargetDescriptors, _In_ BOOL RTsSingleHandleToDescriptorRange, _In_opt_ const D3D12_CPU_DESCRIPTOR_HANDLE *pDepthStencilDescriptor) = 0; virtual void STDMETHODCALLTYPE ClearDepthStencilView(_In_ D3D12_CPU_DESCRIPTOR_HANDLE DepthStencilView, _In_ D3D12_CLEAR_FLAGS ClearFlags, _In_ FLOAT Depth, _In_ UINT8 Stencil, _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE ClearRenderTargetView(_In_ D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView, _In_ const FLOAT ColorRGBA[4], _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(_In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, _In_ ID3D12Resource *pResource, _In_ const UINT Values[4], _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(_In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, _In_ ID3D12Resource *pResource, _In_ const FLOAT Values[4], _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0; virtual void STDMETHODCALLTYPE DiscardResource(_In_ ID3D12Resource *pResource, _In_opt_ const D3D12_DISCARD_REGION *pRegion) = 0; virtual void STDMETHODCALLTYPE BeginQuery(_In_ ID3D12QueryHeap *pQueryHeap, _In_ D3D12_QUERY_TYPE Type, _In_ UINT Index) = 0; virtual void STDMETHODCALLTYPE EndQuery(_In_ ID3D12QueryHeap *pQueryHeap, _In_ D3D12_QUERY_TYPE Type, _In_ UINT Index) = 0; virtual void STDMETHODCALLTYPE ResolveQueryData(_In_ ID3D12QueryHeap *pQueryHeap, _In_ D3D12_QUERY_TYPE Type, _In_ UINT StartIndex, _In_ UINT NumQueries, _In_ ID3D12Resource *pDestinationBuffer, _In_ UINT64 AlignedDestinationBufferOffset) = 0; virtual void STDMETHODCALLTYPE SetPredication(_In_opt_ ID3D12Resource *pBuffer, _In_ UINT64 AlignedBufferOffset, _In_ D3D12_PREDICATION_OP Operation) = 0; virtual void STDMETHODCALLTYPE SetMarker(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0; virtual void STDMETHODCALLTYPE BeginEvent(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0; virtual void STDMETHODCALLTYPE EndEvent(void) = 0; virtual void STDMETHODCALLTYPE ExecuteIndirect(_In_ ID3D12CommandSignature *pCommandSignature, _In_ UINT MaxCommandCount, _In_ ID3D12Resource *pArgumentBuffer, _In_ UINT64 ArgumentBufferOffset, _In_opt_ ID3D12Resource *pCountBuffer, _In_ UINT64 CountBufferOffset) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("0ec870a6-5d7e-4c22-8cfc-5baae07616ed") ID3D12CommandQueue : public ID3D12Pageable { public: virtual void STDMETHODCALLTYPE UpdateTileMappings(_In_ ID3D12Resource *pResource, UINT NumResourceRegions, _In_reads_opt_(NumResourceRegions) const D3D12_TILED_RESOURCE_COORDINATE *pResourceRegionStartCoordinates, _In_reads_opt_(NumResourceRegions) const D3D12_TILE_REGION_SIZE *pResourceRegionSizes, _In_opt_ ID3D12Heap *pHeap, UINT NumRanges, _In_reads_opt_(NumRanges) const D3D12_TILE_RANGE_FLAGS *pRangeFlags, _In_reads_opt_(NumRanges) const UINT *pHeapRangeStartOffsets, _In_reads_opt_(NumRanges) const UINT *pRangeTileCounts, D3D12_TILE_MAPPING_FLAGS Flags) = 0; virtual void STDMETHODCALLTYPE CopyTileMappings(_In_ ID3D12Resource *pDstResource, _In_ const D3D12_TILED_RESOURCE_COORDINATE *pDstRegionStartCoordinate, _In_ ID3D12Resource *pSrcResource, _In_ const D3D12_TILED_RESOURCE_COORDINATE *pSrcRegionStartCoordinate, _In_ const D3D12_TILE_REGION_SIZE *pRegionSize, D3D12_TILE_MAPPING_FLAGS Flags) = 0; virtual void STDMETHODCALLTYPE ExecuteCommandLists(_In_ UINT NumCommandLists, _In_reads_(NumCommandLists) ID3D12CommandList *const *ppCommandLists) = 0; virtual void STDMETHODCALLTYPE SetMarker(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0; virtual void STDMETHODCALLTYPE BeginEvent(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0; virtual void STDMETHODCALLTYPE EndEvent(void) = 0; virtual HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence *pFence, UINT64 Value) = 0; virtual HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence *pFence, UINT64 Value) = 0; virtual HRESULT STDMETHODCALLTYPE GetTimestampFrequency(_Out_ UINT64 *pFrequency) = 0; virtual HRESULT STDMETHODCALLTYPE GetClockCalibration(_Out_ UINT64 *pGpuTimestamp, _Out_ UINT64 *pCpuTimestamp) = 0; virtual D3D12_COMMAND_QUEUE_DESC STDMETHODCALLTYPE GetDesc(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h" MIDL_INTERFACE("189819f1-1db6-4b57-be54-1821339b85f7") ID3D12Device : public ID3D12Object { public: virtual UINT STDMETHODCALLTYPE GetNodeCount(void) = 0; virtual HRESULT STDMETHODCALLTYPE CreateCommandQueue(_In_ const D3D12_COMMAND_QUEUE_DESC *pDesc, REFIID riid, _COM_Outptr_ void **ppCommandQueue) = 0; virtual HRESULT STDMETHODCALLTYPE CreateCommandAllocator(_In_ D3D12_COMMAND_LIST_TYPE type, REFIID riid, _COM_Outptr_ void **ppCommandAllocator) = 0; virtual HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(_In_ const D3D12_GRAPHICS_PIPELINE_STATE_DESC *pDesc, REFIID riid, _COM_Outptr_ void **ppPipelineState) = 0; virtual HRESULT STDMETHODCALLTYPE CreateComputePipelineState(_In_ const D3D12_COMPUTE_PIPELINE_STATE_DESC *pDesc, REFIID riid, _COM_Outptr_ void **ppPipelineState) = 0; virtual HRESULT STDMETHODCALLTYPE CreateCommandList(_In_ UINT nodeMask, _In_ D3D12_COMMAND_LIST_TYPE type, _In_ ID3D12CommandAllocator *pCommandAllocator, _In_opt_ ID3D12PipelineState *pInitialState, REFIID riid, _COM_Outptr_ void **ppCommandList) = 0; virtual HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE Feature, _Inout_updates_bytes_(FeatureSupportDataSize) void *pFeatureSupportData, UINT FeatureSupportDataSize) = 0; virtual HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(_In_ const D3D12_DESCRIPTOR_HEAP_DESC *pDescriptorHeapDesc, REFIID riid, _COM_Outptr_ void **ppvHeap) = 0; virtual UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(_In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapType) = 0; virtual HRESULT STDMETHODCALLTYPE CreateRootSignature(_In_ UINT nodeMask, _In_reads_(blobLengthInBytes) const void *pBlobWithRootSignature, _In_ SIZE_T blobLengthInBytes, REFIID riid, _COM_Outptr_ void **ppvRootSignature) = 0; virtual void STDMETHODCALLTYPE CreateConstantBufferView(_In_opt_ const D3D12_CONSTANT_BUFFER_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0; virtual void STDMETHODCALLTYPE CreateShaderResourceView(_In_opt_ ID3D12Resource *pResource, _In_opt_ const D3D12_SHADER_RESOURCE_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0; virtual void STDMETHODCALLTYPE CreateUnorderedAccessView(_In_opt_ ID3D12Resource *pResource, _In_opt_ ID3D12Resource *pCounterResource, _In_opt_ const D3D12_UNORDERED_ACCESS_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0; virtual void STDMETHODCALLTYPE CreateRenderTargetView(_In_opt_ ID3D12Resource *pResource, _In_opt_ const D3D12_RENDER_TARGET_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0; virtual void STDMETHODCALLTYPE CreateDepthStencilView(_In_opt_ ID3D12Resource *pResource, _In_opt_ const D3D12_DEPTH_STENCIL_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0; virtual void STDMETHODCALLTYPE CreateSampler(_In_ const D3D12_SAMPLER_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0; virtual void STDMETHODCALLTYPE CopyDescriptors(_In_ UINT NumDestDescriptorRanges, _In_reads_(NumDestDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE *pDestDescriptorRangeStarts, _In_reads_opt_(NumDestDescriptorRanges) const UINT *pDestDescriptorRangeSizes, _In_ UINT NumSrcDescriptorRanges, _In_reads_(NumSrcDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE *pSrcDescriptorRangeStarts, _In_reads_opt_(NumSrcDescriptorRanges) const UINT *pSrcDescriptorRangeSizes, _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType) = 0; virtual void STDMETHODCALLTYPE CopyDescriptorsSimple(_In_ UINT NumDescriptors, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptorRangeStart, _In_ D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRangeStart, _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType) = 0; virtual D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo(_In_ UINT visibleMask, _In_ UINT numResourceDescs, _In_reads_(numResourceDescs) const D3D12_RESOURCE_DESC *pResourceDescs) = 0; virtual D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(_In_ UINT nodeMask, D3D12_HEAP_TYPE heapType) = 0; virtual HRESULT STDMETHODCALLTYPE CreateCommittedResource(_In_ const D3D12_HEAP_PROPERTIES *pHeapProperties, D3D12_HEAP_FLAGS HeapFlags, _In_ const D3D12_RESOURCE_DESC *pResourceDesc, D3D12_RESOURCE_STATES InitialResourceState, _In_opt_ const D3D12_CLEAR_VALUE *pOptimizedClearValue, REFIID riidResource, _COM_Outptr_opt_ void **ppvResource) = 0; virtual HRESULT STDMETHODCALLTYPE CreateHeap(_In_ const D3D12_HEAP_DESC *pDesc, REFIID riid, _COM_Outptr_opt_ void **ppvHeap) = 0; virtual HRESULT STDMETHODCALLTYPE CreatePlacedResource(_In_ ID3D12Heap *pHeap, UINT64 HeapOffset, _In_ const D3D12_RESOURCE_DESC *pDesc, D3D12_RESOURCE_STATES InitialState, _In_opt_ const D3D12_CLEAR_VALUE *pOptimizedClearValue, REFIID riid, _COM_Outptr_opt_ void **ppvResource) = 0; virtual HRESULT STDMETHODCALLTYPE CreateReservedResource(_In_ const D3D12_RESOURCE_DESC *pDesc, D3D12_RESOURCE_STATES InitialState, _In_opt_ const D3D12_CLEAR_VALUE *pOptimizedClearValue, REFIID riid, _COM_Outptr_opt_ void **ppvResource) = 0; virtual HRESULT STDMETHODCALLTYPE CreateSharedHandle(_In_ ID3D12DeviceChild *pObject, _In_opt_ const SECURITY_ATTRIBUTES *pAttributes, DWORD Access, _In_opt_ LPCWSTR Name, _Out_ HANDLE *pHandle) = 0; virtual HRESULT STDMETHODCALLTYPE OpenSharedHandle(_In_ HANDLE NTHandle, REFIID riid, _COM_Outptr_opt_ void **ppvObj) = 0; virtual HRESULT STDMETHODCALLTYPE OpenSharedHandleByName(_In_ LPCWSTR Name, DWORD Access, _Out_ HANDLE *pNTHandle) = 0; virtual HRESULT STDMETHODCALLTYPE MakeResident(UINT NumObjects, _In_reads_(NumObjects) ID3D12Pageable *const *ppObjects) = 0; virtual HRESULT STDMETHODCALLTYPE Evict(UINT NumObjects, _In_reads_(NumObjects) ID3D12Pageable *const *ppObjects) = 0; virtual HRESULT STDMETHODCALLTYPE CreateFence(UINT64 InitialValue, D3D12_FENCE_FLAGS Flags, REFIID riid, _COM_Outptr_ void **ppFence) = 0; virtual HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason(void) = 0; virtual void STDMETHODCALLTYPE GetCopyableFootprints(_In_ const D3D12_RESOURCE_DESC *pResourceDesc, _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, UINT64 BaseOffset, _Out_writes_opt_(NumSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT *pLayouts, _Out_writes_opt_(NumSubresources) UINT *pNumRows, _Out_writes_opt_(NumSubresources) UINT64 *pRowSizeInBytes, _Out_opt_ UINT64 *pTotalBytes) = 0; virtual HRESULT STDMETHODCALLTYPE CreateQueryHeap(_In_ const D3D12_QUERY_HEAP_DESC *pDesc, REFIID riid, _COM_Outptr_opt_ void **ppvHeap) = 0; virtual HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL Enable) = 0; virtual HRESULT STDMETHODCALLTYPE CreateCommandSignature(_In_ const D3D12_COMMAND_SIGNATURE_DESC *pDesc, _In_opt_ ID3D12RootSignature *pRootSignature, REFIID riid, _COM_Outptr_opt_ void **ppvCommandSignature) = 0; virtual void STDMETHODCALLTYPE GetResourceTiling(_In_ ID3D12Resource *pTiledResource, _Out_opt_ UINT *pNumTilesForEntireResource, _Out_opt_ D3D12_PACKED_MIP_INFO *pPackedMipDesc, _Out_opt_ D3D12_TILE_SHAPE *pStandardTileShapeForNonPackedMips, _Inout_opt_ UINT *pNumSubresourceTilings, _In_ UINT FirstSubresourceTilingToGet, _Out_writes_(*pNumSubresourceTilings) D3D12_SUBRESOURCE_TILING *pSubresourceTilingsForNonPackedMips) = 0; virtual LUID STDMETHODCALLTYPE GetAdapterLuid(void) = 0; }; #ifdef RENDERER_DEBUG // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h" MIDL_INTERFACE("344488b7-6846-474b-b989-f027448245e0") ID3D12Debug : public IUnknown { public: virtual void STDMETHODCALLTYPE EnableDebugLayer(void) = 0; }; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h" MIDL_INTERFACE("3febd6dd-4973-4787-8194-e45f9e28923e") ID3D12DebugDevice : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetFeatureMask(D3D12_DEBUG_FEATURE Mask) = 0; virtual D3D12_DEBUG_FEATURE STDMETHODCALLTYPE GetFeatureMask(void) = 0; virtual HRESULT STDMETHODCALLTYPE ReportLiveDeviceObjects(D3D12_RLDO_FLAGS Flags) = 0; }; #endif
#include "transfert.h" Transfert::Transfert() { } Transfert::Transfert(int ID_client_t,QString Type,QString Position,QString Date_T,QString Equipe) {this->ID_client_t=ID_client_t; this->Type=Type; this->Position=Position; this->Date_T=Date_T; this->Equipe=Equipe; } bool Transfert:: AjoutTransfert(Transfert *TR) { //Personne::AjoutPersonne(); QString ID_client_t= QString::number(TR->getID_client_t()); QSqlQuery qry; QString str = "SELECT ID FROM Personne WHERE ID = '"+ ID_client_t+"'"; qDebug()<<str; if(qry.exec(str)) { int count=0; while(qry.next()) { count++; } if(count==1) { //ui->A->setText("LE CLIENT EXISTE"); QSqlQuery query; QString IDD= QString::number(TR->getID_client_t()); QString str= "insert into Transfert values('"+IDD+"','"+TR->getType()+"','"+TR->getPosition()+"','"+TR->getDate_T()+"','"+TR->getEquipe()+"')"; qDebug()<<str; if (query.exec(str)) return true; else return false; } if(count==0) { } } } QSqlQueryModel * Transfert::AfficherTransfert() { QSqlQueryModel * model= new QSqlQueryModel(); // model->setQuery("select * from Personne p, Client c where (p.ID=c.ID_client)"); model->setQuery("select Nom,Prenom,Num_Tel,CIN,Adresse,ID_client,Age,Date_N,Date_D,Date_F,Taille,Poids,Number,Type,Position,Date_T ,Equipe from Personne p , Client c ,Transfert t where ((p.ID=c.ID_client)and (p.ID=t.ID_client_t))"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("NOM")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("PRENOM")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUM_TEL")); return model; } QSqlQueryModel *Transfert::RechercherTransfert(int ID_client_t) { QSqlQueryModel * model= new QSqlQueryModel(); QString str="select * from Personne p,Transfert t where ( (p.ID=t.ID_client_t)and (t.ID_client_t="+QString::number(ID_client_t)+"))"; qDebug()<<str; // QString str="select * from Client where ID_client="+QString::number(ID_client); model->setQuery(str); return model; } bool Transfert::SupprimerTransfert(int ID_client_t) { QSqlQuery query; QString str="delete from Transfert where ID_client_t ="+QString::number( ID_client_t); qDebug()<<str; bool res = query.exec(str); return res; } bool Transfert::ModifierTransfert(Transfert *TR) { createConnection(); QSqlQuery query; QString IDDt= QString::number(TR->getID_client_t()); QString str=("update Transfert set ID_client_t='"+IDDt+"'"",Type='"+TR->getType()+"'"",Position='"+TR->getPosition()+"'"",Date_t='"+TR->getDate_T()+"'" ",Equipe='"+TR->getEquipe()+"'where ID_client_t='"+IDDt+"'"); qDebug()<<str; bool res =query.exec(str); return res; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long ll; ll t, n, occur[1000001], temp, eleCount, sameEleCount; vector<int> a; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; for (int i = 0; i < t; i++) { cin >> n; for (int j = 0; j < n; j++) { cin >> temp; if (occur[temp] == 0) a.push_back(temp); occur[temp]++; } eleCount = sameEleCount = 0; for (auto ele = a.begin(); ele < a.end(); ele++) { for (auto ele2 = a.begin(); ele2 < a.end(); ele2++) { if (occur[*ele] >= *ele2 && occur[*ele2] >= *ele) eleCount++; } // cout << *ele << " " <<eleCount << endl; } a.clear(); fill_n(occur, 1000001, 0); cout << eleCount << endl; } }
int ledNumber[] = { 0,1,2,3,4,5,6,7}; int rowNumber[] = { 10,9,8}; int levelNumber[] = { A3,A1,A2,13,A4,A0,12,A5}; int oc = 11; void setup() { pinMode(oc, OUTPUT); for(int i = 0; i<8;i++){ pinMode(ledNumber[i],OUTPUT); } for(int i = 0; i<3;i++){ pinMode(rowNumber[i],OUTPUT); } for(int i = 0; i<8;i++){ pinMode(levelNumber[i],OUTPUT); } resetAll(); simpleTests(1); } void loop() { //onAll(500); resetAll(); rain(100); // simpleTests(10); //onAll(500); } void simpleTests(int del){ testLevelsX(del); testLevelsY(del); testLevelsZ(del); } void rain(int del){ resetAll(); int r[] ={ 1,1,1,1,1,1,1,1 }; int rOff[] ={ 0,0,0,0,0,0,0,0 }; for(int k=9;k>=-3;k--){ rowOn(r,2,k); delay(del); resetLevel(k+3); // rowOn(rOff,k,k-1); } resetAll(); } void testLevelsX(int del){ resetAll(); for(int z = 0; z<8;z++){ int r[] ={ 0,0,0,0,0,0,0,0 }; r[z] = 1; for(int i=0;i<8;i++){ for(int j =0;j<8;j++){ rowOn(r,j,i); delay(del); } delay(del); } for(int i=7;i>=0;i--){ resetLevel(i); delay(del*2); } } resetAll(); } void testLevelsY(int del){ resetAll(); int rOn[] ={ 1,1,1,1,1,1,1,1 }; int rOff[] ={ 0,0,0,0,0,0,0,0 }; for(int i=0;i<8;i++){ for(int j =0;j<8;j++){ rowOn(rOn,i,j); delay(del); // rowOn(rOff,i,j); // delay(del); } } for(int i=0;i<8;i++){ for(int j =0;j<8;j++){ rowOn(rOff,i,j); delay(del); // rowOn(rOff,i,j); // delay(del); } // for(int j=7;j>=0;j--){ // rowOn(rOff,i,j); // resetLevel(j); // delay(del); // } } resetAll(); } void testLevelsZ(int del){ resetAll(); del=del*10; int r[] ={ 1,1,1,1,1,1,1,1 }; for(int i=0;i<8;i++){ for(int j =0;j<8;j++){ rowOn(r,j,i); } delay(del); resetLevel(i); } resetAll(); } void rowOn(int r[], int row){ setRow(row); setLeds(r); } void rowOn(int r[], int row, int level){ setRow(row); setLeds(r); digitalWrite(oc, LOW); setLevel(level); } void onAll(int del){ resetAll(); for(int i = 0; i<8;i++){ setLevel(i); int r[] = { 1,1,1,1,1,1,1,1 }; for(int j=0; j<8;j++){ rowOn(r,j); } } delay(del); resetAll(); delay(del); } void setLeds(int ledsNum[]){ for(int i =0; i<8; i++){ if(ledsNum[i]==0){ digitalWrite(ledNumber[i], LOW); } if(ledsNum[i]==1){ digitalWrite(ledNumber[i], HIGH); } digitalWrite(oc, LOW); } } void setLevel(int levelNum){ digitalWrite(levelNumber[levelNum], HIGH); } void resetLevel(int levelNum){ digitalWrite(levelNumber[levelNum], LOW); } void setRow(int rowNum){ switch(rowNum){ case 0: { digitalWrite(rowNumber[0], LOW); digitalWrite(rowNumber[1], LOW); digitalWrite(rowNumber[2], LOW); break; } case 1: { digitalWrite(rowNumber[0], HIGH); digitalWrite(rowNumber[1], LOW); digitalWrite(rowNumber[2], LOW); break; } case 2: { digitalWrite(rowNumber[0], LOW); digitalWrite(rowNumber[1], HIGH); digitalWrite(rowNumber[2], LOW); break; } case 3: { digitalWrite(rowNumber[0], HIGH); digitalWrite(rowNumber[1], HIGH); digitalWrite(rowNumber[2], LOW); break; } case 4: { digitalWrite(rowNumber[0], LOW); digitalWrite(rowNumber[1], LOW); digitalWrite(rowNumber[2], HIGH); break; } case 5: { digitalWrite(rowNumber[0], HIGH); digitalWrite(rowNumber[1], LOW); digitalWrite(rowNumber[2], HIGH); break; } case 6: { digitalWrite(rowNumber[0], LOW); digitalWrite(rowNumber[1], HIGH); digitalWrite(rowNumber[2], HIGH); break; } case 7: { digitalWrite(rowNumber[0], HIGH); digitalWrite(rowNumber[1], HIGH); digitalWrite(rowNumber[2], HIGH); break; } } } void reset(){ for(int i =7; i>=0; i--){ digitalWrite(levelNumber[i], LOW); } } void resetAll(){ reset(); for(int j=0;j<8;j++){ setRow(j); for(int i = 0; i<8;i++){ digitalWrite(ledNumber[i], LOW); } } digitalWrite(oc, HIGH); }
//--------------------------------------------------------------------------- #ifndef FrmSetupH #define FrmSetupH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> //--------------------------------------------------------------------------- class TSetupFrm : public TForm { __published: // IDE-managed Components TLabel *Label1; TComboBox *cbLanguage; void __fastcall cbLanguageChange(TObject *Sender); private: // User declarations public: // User declarations __fastcall TSetupFrm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TSetupFrm *SetupFrm; //--------------------------------------------------------------------------- #endif
#pragma once #include "ofMain.h" #include "bson/bsonobjbuilder.h" class ofxBson: public ofBaseFileSerializer { protected: class BSONArrayNode; class BSONObjNode; class BSONGUIDNode; class BSONObjWithGUIDNode; class BSONNode { public: ofxBson* bson; static ofBuffer emptyBuffer; weak_ptr<BSONNode> parent; weak_ptr<BSONNode> tempParent; BSONNode(weak_ptr<BSONNode> parent = weak_ptr<BSONNode>(), ofxBson *bson = 0) : parent(parent), bson(bson) {} virtual ~BSONNode() {} virtual bool isObject() const { return false; } virtual bool isArray() const { return false; } virtual bool isString() const { return false; } virtual bool isNumber() const { return false; } virtual bool isInt32() const { return false; } virtual bool isInt64() const { return false; } virtual bool isBuffer() const { return false; } virtual bool isBool() const { return false; } virtual bool isNull() const { return false; } virtual bool isUndefined() const { return false; } virtual bool isGUID() const { return false; } virtual bool isBuilt() const { return false; } virtual bool isObjectInstance() const { return isGUID(); } virtual string getString() const { return ""; } virtual double getNumber() const { return numeric_limits<double>::signaling_NaN(); } virtual bool getBool() const { return false; } virtual int32_t getInt32() const { return numeric_limits<int32_t>::min(); } virtual int64_t getInt64() const { return numeric_limits<int64_t>::min(); } virtual const ofBuffer& getBuffer() const { return emptyBuffer; } virtual shared_ptr<BSONArrayNode> getArray() { return shared_ptr<BSONArrayNode>(); } virtual shared_ptr<BSONObjNode> getObject() { return shared_ptr<BSONObjNode>(); } virtual string getGUID() const { return ""; } weak_ptr<BSONNode> getParent() { if (tempParent.expired()) { return parent; } weak_ptr<BSONNode> tempTempParent; tempTempParent.swap(tempParent); return tempTempParent; } }; class BSONUndefinedNode : public BSONNode { public: BSONUndefinedNode(weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()) : BSONNode(parent) {} bool isUndefined() const { return true; } }; class BSONNullNode : public BSONNode { public: BSONNullNode(weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()): BSONNode(parent) {} bool isNull() const { return true; } }; class BSONStringNode : public BSONNode, public enable_shared_from_this<BSONStringNode> { protected: string str; public: BSONStringNode(const string& str = "", weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()) : BSONNode(parent), str(str) {} bool isString() const { return true; } virtual string getString() const { return str; } }; class BSONInt32Node : public BSONNode { protected: int32_t n; public: BSONInt32Node(int32_t n = 0, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()) : BSONNode(parent), n(n) { } bool isInt32() const { return true; } int32_t getInt32() const { return n; } int64_t getInt64() const { return n; } }; class BSONInt64Node : public BSONNode { protected: int64_t n; public: BSONInt64Node(int64_t n = 0, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()) : BSONNode(parent), n(n) { } bool isInt64() const { return true; } int64_t getInt64() const { return n; } }; class BSONNumberNode : public BSONNode { protected: double n; public: BSONNumberNode(double d = 0.0, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()): BSONNode(parent), n(d) {} bool isNumber() const { return true; } double getNumber() const { return n; } }; class BSONBoolNode : public BSONNode { protected: bool b; public: BSONBoolNode(bool b = false, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()): BSONNode(parent), b(b) {} bool isBool() const { return true; } bool getBool() const { return b; } }; class BSONBufferNode : public BSONNode { protected: ofBuffer buf; public: BSONBufferNode(const ofBuffer& b, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()): BSONNode(parent), buf(b) { } bool isBuffer() const { return true; } const ofBuffer& getBuffer() const { return buf; } }; class BSONArrayNode : public BSONNode, public enable_shared_from_this<BSONArrayNode> { protected: vector<shared_ptr<BSONNode>> items; public: BSONArrayNode(weak_ptr<BSONNode> parent = weak_ptr<BSONNode>(), ofxBson *bson = 0):BSONNode(parent, bson) {} bool isArray() const { return true; } shared_ptr<BSONArrayNode> getArray() { return shared_from_this(); } void constructInBuilder(_bson::bsonobjbuilder &builder) { int c = 0; for (auto& item : items) { if (item->isNull()) { builder.appendNull(ofToString(c)); } else if (item->isBool()) { builder.appendBool(ofToString(c), item->getBool()); } else if (item->isNumber()) { builder.appendNumber(ofToString(c), item->getNumber()); } else if (item->isInt32()) { builder.appendIntOrLL(ofToString(c), item->getInt32()); } else if (item->isInt64()) { builder.append(ofToString(c), item->getInt64()); } else if (item->isBuffer()) { builder.appendBinData(ofToString(c), item->getBuffer().size(), _bson::BinDataType::BinDataGeneral, item->getBuffer().getBinaryBuffer()); } else if (item->isString()) { builder.append(ofToString(c), item->getString()); } else if (item->isArray()) { _bson::bsonobjbuilder b(builder.subarrayStart(ofToString(c))); item->getArray()->constructInBuilder(b); b._done(); } else if (item->isObject()) { _bson::bsonobjbuilder b(builder.subobjStart(ofToString(c))); item->getObject()->constructInBuilder(b); b._done(); } else if (item->isGUID()) { builder.append(ofToString(c), _bson::OID(item->getGUID())); } c++; } } size_t length() const { return items.size(); } shared_ptr<BSONNode> getAt(size_t i) const { if (i < length()) { return items[i]; } else { return shared_ptr<BSONNode>(); } } size_t push(shared_ptr<BSONNode> node) { items.push_back(node); return items.size() - 1; } size_t pushNull() { return push(make_shared<BSONNullNode>(shared_from_this())); } size_t pushBool(bool b) { return push(make_shared<BSONBoolNode>(b, shared_from_this())); } size_t pushNumber(double d) { return push(make_shared<BSONNumberNode>(d, shared_from_this())); } size_t pushInt32(int32_t i) { return push(make_shared<BSONInt32Node>(i, shared_from_this())); } size_t pushInt64(int64_t i) { return push(make_shared<BSONInt64Node>(i, shared_from_this())); } size_t pushString(const string& str) { return push(make_shared<BSONStringNode>(str, shared_from_this())); } size_t pushNewObject() { return push(make_shared<BSONObjNode>(shared_from_this())); } size_t pushNewArray() { return push(make_shared<BSONArrayNode>(shared_from_this())); } size_t pushBuffer(const ofBuffer& buf) { return push(make_shared<BSONBufferNode>(buf, shared_from_this())); } size_t pushGUIDObject(const string& guid, bool& already_in_store); }; class BSONObjNode: public BSONNode, public enable_shared_from_this<BSONObjNode> { protected: map<string, shared_ptr<BSONNode>> content; string type; public: BSONObjNode() {} BSONObjNode(weak_ptr<BSONNode> parent, ofxBson *bson = 0): BSONNode(parent, bson) {} BSONObjNode(const _bson::bsonobj& obj, weak_ptr<BSONNode> _parent = weak_ptr<BSONNode>()); virtual void addChild(const string& name) { content[name] = make_shared<BSONObjNode>(shared_from_this(), bson); } virtual void addNull(const string& name) { content[name] = make_shared<BSONNullNode>(shared_from_this()); } virtual void addString(const string& name, const string& value) { content[name] = make_shared<BSONStringNode>(value, shared_from_this()); } virtual void addNumber(const string& name, double value) { content[name] = make_shared<BSONNumberNode>(value, shared_from_this()); } virtual void addInt32(const string& name, int32_t value) { content[name] = make_shared<BSONInt32Node>(value, shared_from_this()); } virtual void addInt64(const string& name, int64_t value) { content[name] = make_shared<BSONInt64Node>(value, shared_from_this()); } virtual void addBool(const string& name, bool value) { content[name] = make_shared<BSONBoolNode>(value, shared_from_this()); } virtual void addBuffer(const string& name, const ofBuffer& buf) { content[name] = make_shared<BSONBufferNode>(buf, shared_from_this()); } virtual void addArray(const string& name) { content[name] = make_shared<BSONArrayNode>(shared_from_this(), bson); } virtual void addGUIDObject(const string& name, const string& guid, const string& type, bool& already_in_store); virtual bool exists(const string& name) const; virtual shared_ptr<BSONNode> getChild(const string& name) const { return content.find(name)->second; } virtual shared_ptr<BSONObjNode> getObject() { return shared_from_this(); } virtual double getNumber(const string& name) const { return getChild(name)->getNumber(); } virtual int32_t getInt32(const string& name) const { return getChild(name)->getInt32(); } virtual int64_t getInt64(const string& name) const { return getChild(name)->getInt64(); } virtual const ofBuffer& getBuffer(const string& name) const { return getChild(name)->getBuffer(); } virtual bool getBool(const string& name) const { return getChild(name)->getBool(); } virtual string getString(const string& name) const { return getChild(name)->getString(); } virtual shared_ptr<BSONArrayNode> getArray(const string& name) const { return getChild(name)->getArray(); } virtual string getGUID(const string& name) const { return getChild(name)->getGUID(); } virtual bool isChild(const string& name) const { return (content.find(name) != content.cend()); } virtual bool isNull(const string& name) const { return isChild(name) && getChild(name)->isNull(); } virtual bool isBool(const string& name) const { return isChild(name) && getChild(name)->isBool(); } virtual bool isNumber(const string& name) const { return isChild(name) && getChild(name)->isNumber(); } virtual bool isInt32(const string& name) const { return isChild(name) && getChild(name)->isInt32(); } virtual bool isInt64(const string& name) const { return isChild(name) && getChild(name)->isInt64(); } virtual bool isBuffer(const string& name) const { return isChild(name) && getChild(name)->isBuffer(); } virtual bool isString(const string& name) const { return isChild(name) && getChild(name)->isString();; } virtual bool isObject(const string& name) const { return isChild(name) && getChild(name)->isObject(); } virtual bool isArray(const string& name) const { return isChild(name) && getChild(name)->isArray(); } virtual bool isGUID(const string& name) const { return isChild(name) && getChild(name)->isGUID(); } virtual void constructInBuilder(_bson::bsonobjbuilder &b) const; _bson::bsonobj obj() const; }; class BSONObjWithGUIDNode : public BSONObjNode { public: string guid; string type; shared_ptr<void> constructedObject; shared_ptr<void> construct(ofxBson& b); BSONObjWithGUIDNode(const string& guid, const string& type, weak_ptr<BSONNode> parent, ofxBson *bson): BSONObjNode(parent, bson), guid(guid), type(type) {} BSONObjWithGUIDNode(const _bson::bsonobj & obj, weak_ptr<BSONNode> parent); void constructInBuilder(_bson::bsonobjbuilder &b) const; bool isGUID() const { return true; } string getGUID() const { return guid; } }; public: typedef function<shared_ptr<void>(ofxBson&)> constructor_fn; protected: class BSONGUIDNode : public BSONObjNode { public: shared_ptr<BSONObjWithGUIDNode> reference; BSONGUIDNode(const string& guid, const string& type, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>(), ofxBson *bson = 0): BSONObjNode(parent, bson) { auto found = bson->storedObjects.find(guid); if (found == bson->storedObjects.cend()) { // bson->storedObjects[guid] = make_shared<BSONObjWithGUIDNode>(guid, type, parent, bson); } else { reference = found->second; } } BSONGUIDNode(const string& guid, weak_ptr<BSONNode> parent = weak_ptr<BSONNode>()): BSONObjNode(parent, bson) { } shared_ptr<BSONObjNode> getObject() const; shared_ptr<void> getConstructedObject(ofxBson& b) const; virtual void addChild(const string& name) { reference->addChild(name); } virtual void addNull(const string& name) { reference->addNull(name); } virtual void addString(const string& name, const string& value) { reference->addString(name, value); } virtual void addNumber(const string& name, double value) { reference->addNumber(name, value); } virtual void addInt32(const string& name, int32_t value) { reference->addInt32(name, value); } virtual void addInt64(const string& name, int64_t value) { reference->addInt64(name, value); } virtual void addBool(const string& name, bool value) { reference->addBool(name, value); } virtual void addBuffer(const string& name, const ofBuffer& buf) { reference->addBuffer(name, buf); } virtual void addArray(const string& name) { reference->addArray(name); } virtual void addGUIDObject(const string& name, const string& guid, const string& type, bool& already_in_store) { reference->addGUIDObject(name, guid, type, already_in_store); } virtual bool exists(const string& name) const { return reference->exists(name); } virtual shared_ptr<BSONNode> getChild(const string& name) const { return reference->getChild(name); } virtual shared_ptr<BSONObjNode> getObject() { return shared_from_this(); } virtual bool isChild(const string& name) const { return reference->isChild(name); } }; map<string, constructor_fn> constructors; map<string, shared_ptr<BSONObjWithGUIDNode>> storedObjects; shared_ptr<BSONNode> root; shared_ptr<BSONNode> current; friend class BSONObjWithGUIDNode; public: ofxBson(): root(make_shared<BSONObjNode>()), current(root) {} bool exists(const string& name) const; bool exists(size_t index) const; void addChild(const string& name); size_t addChildToArray(); void addArray(const string& name); size_t addArrayToArray(); bool setTo(const string& name); bool setTo(size_t index); void setToParent(); void setValue(const string& name, const string& value); size_t pushValue(const string& value); void setValue(const string& name, double value); size_t pushValue(double value); void setValue(const string& name, bool value); size_t pushValue(bool value); void setValue(const string& name, int32_t value); size_t pushValue(int32_t value); void setValue(const string& name, int64_t value); size_t pushValue(int64_t value); void setNull(const string& name); size_t pushNull(); size_t pushObject(); size_t pushArray(); void setBuffer(const string& name, const ofBuffer& value); size_t pushBuffer(const ofBuffer& buf); void setGUIDObject(const string& name, const string& guid, bool& already_in_store); void setGUIDObject(const string& name, const string& guid, const string& type, bool& already_in_store); size_t pushGUIDObject(const string& guid, bool& already_in_store); size_t pushGUIDObject(const string& guid, const string& type, bool& already_in_store); size_t getSize() const; int getIntValue(const string& name) const; int getIntValue(size_t index) const; float getFloatValue(const string& name) const; float getFloatValue(size_t index) const; double getDoubleValue(const string& name) const; double getDoubleValue(size_t index) const; int64_t getInt64Value(const string& name) const; int64_t getInt64Value(size_t index) const; bool getBoolValue(const string& name) const; bool getBoolValue(size_t index) const; string getValue(const string& name) const; string getValue(size_t index) const; string getGUID(const string& name) const; string getGUID(size_t index) const; void setConstructor(const string& type_name, constructor_fn fn) { constructors[type_name] = fn; } template <typename T> shared_ptr<T> getConstructedObjectByGUID(const string& guid) { auto found = storedObjects.find(guid); if (found != storedObjects.cend()) { if (!found->second->constructedObject) { return static_pointer_cast<T>(found->second->construct(*this)); } return static_pointer_cast<T>(found->second->constructedObject); } return shared_ptr<T>(); } virtual void serialize(const ofAbstractParameter & parameter) override; virtual void deserialize(ofAbstractParameter & parameter) override; virtual bool load(const string & path) override; virtual bool save(const string & path) override; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright 2002-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Peter Krefting */ #ifndef PC_DOC_H #define PC_DOC_H #include "modules/prefs/prefsmanager/opprefscollection_override.h" #include "modules/prefs/prefsmanager/prefstypes.h" #include "modules/prefsfile/prefsfile.h" #include "modules/url/url_sn.h" #include "modules/util/adt/opvector.h" /** Global PrefsCollectionDoc object (singleton). */ #define g_pcdoc (g_opera->prefs_module.PrefsCollectionDoc()) #ifdef PREFS_HAS_PREFSFILE #define HAVE_HANDLERS_FILE #endif // PREFS_HAS_PREFSFILE /** * Various uncategorized preferences used in the document code * (doc, dochand, logdoc). * * @author Peter Krefting */ class PrefsCollectionDoc : public OpPrefsCollectionWithHostOverride { public: /** * Create method. * * This method preforms all actions required to construct the object. * PrefsManager calls this method to initialize the object, and will * not call the normal constructor directly. * * @param reader Pointer to the PrefsFile object. * @return Pointer to the created object. */ static PrefsCollectionDoc *CreateL(PrefsFile *reader); virtual ~PrefsCollectionDoc(); #include "modules/prefs/prefsmanager/collections/pc_doc_h.inl" // Read ------ /** * Read an integer preference. * * @param which Selects the preference to retrieve. * @param host Host context to retrieve the preference for. NULL will * retrieve the default context. */ inline int GetIntegerPref(integerpref which, const uni_char *host = NULL) const { return OpPrefsCollectionWithHostOverride::GetIntegerPref(int(which), host); } /** @overload */ inline int GetIntegerPref(integerpref which, const ServerName *host) const { return OpPrefsCollectionWithHostOverride::GetIntegerPref(int(which), host ? host->UniName() : NULL); } /** @overload */ inline int GetIntegerPref(integerpref which, const URL &host) const { return OpPrefsCollectionWithHostOverride::GetIntegerPref(int(which), host); } /** * Read a string preference. * * @param which Selects the preference to retrieve. * @param result Variable where the value will be stored. * @param host Host context to retrieve the preference for. NULL will * retrieve the default context. */ inline void GetStringPrefL(stringpref which, OpString &result, const uni_char *host = NULL) const { result.SetL(GetStringPref(which, host)); } /** @overload */ inline void GetStringPrefL(stringpref which, OpString &result, const ServerName *host) const { result.SetL(GetStringPref(which, host)); } /** @overload */ inline void GetStringPrefL(stringpref which, OpString &result, const URL &host) const { result.SetL(GetStringPref(which, host)); } /** * Read a string preference. This method will return a pointer to internal * data. The object is only guaranteed to live until the next call to any * Write method. * * @param which Selects the preference to retrieve. * @param host Host context to retrieve the preference for. NULL will * retrieve the default context. */ inline const OpStringC GetStringPref(stringpref which, const uni_char *host = NULL) const { RETURN_OPSTRINGC(OpPrefsCollectionWithHostOverride::GetStringPref(int(which), host)); } /** @overload */ inline const OpStringC GetStringPref(stringpref which, const ServerName *host) const { RETURN_OPSTRINGC(OpPrefsCollectionWithHostOverride::GetStringPref(int(which), host ? host->UniName() : NULL)); } /** @overload */ inline const OpStringC GetStringPref(stringpref which, const URL &host) const { RETURN_OPSTRINGC(OpPrefsCollectionWithHostOverride::GetStringPref(int(which), host)); } #ifdef PREFS_HOSTOVERRIDE /** * Check if integer preference is overridden for this host. * * @param which Selects the preference to check. * @param host Host context to check for override. * @return TRUE if preference is overridden. */ inline BOOL IsPreferenceOverridden(integerpref which, const uni_char *host) const { return IsIntegerOverridden(int(which), host); } inline BOOL IsPreferenceOverridden(integerpref which, URL &host) const { return IsIntegerOverridden(int(which), host); } /** * Check if string preference is overridden for this host. * * @param which Selects the preference to check. * @param host Host context to check for override. * @return TRUE if preference is overridden. */ inline BOOL IsPreferenceOverridden(stringpref which, const uni_char *host) const { return IsStringOverridden(int(which), host); } inline BOOL IsPreferenceOverridden(stringpref which, URL &host) const { return IsStringOverridden(int(which), host); } #endif // PREFS_HOSTOVERRIDE #ifdef PREFS_HAVE_STRING_API virtual BOOL GetPreferenceL(IniSection section, const char *key, OpString &target, BOOL defval, const uni_char *host) { return OpPrefsCollectionWithHostOverride::GetPreferenceInternalL( section, key, target, defval, host, m_stringprefdefault, PCDOC_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCDOC_NUMBEROFINTEGERPREFS); } #endif // Defaults ------ /** * Get default value for an integer preference. * * @param which Selects the preference to retrieve. * @return The default value. */ inline int GetDefaultIntegerPref(integerpref which) const { return m_integerprefdefault[which].defval; } /** * Get default value for a string preference. * * @param which Selects the preference to retrieve. * @return The default value. */ inline const uni_char *GetDefaultStringPref(stringpref which) const { return m_stringprefdefault[which].defval; } #ifdef PREFS_WRITE // Write ------ # ifdef PREFS_HOSTOVERRIDE /** Write overridden integer preferences. * * @param host Host to write an override for * @param which The preference to override. * @param value Value for the override. * @param from_user TRUE if the preference is entered by the user. * @return ERR_NO_ACCESS if override is not allowed, OK otherwise. */ inline OP_STATUS OverridePrefL(const uni_char *host, integerpref which, int value, BOOL from_user) { return OpPrefsCollectionWithHostOverride::OverridePrefL(host, &m_integerprefdefault[which], int(which), value, from_user); } # endif // PREFS_HOSTOVERRIDE # ifdef PREFS_HOSTOVERRIDE /** Write overridden string preferences. * * @param host Host to write an override for * @param which The preference to override. * @param value Value for the override. * @param from_user TRUE if the preference is entered by the user. * @return ERR_NO_ACCESS if override is not allowed, OK otherwise. */ inline OP_STATUS OverridePrefL(const uni_char *host, stringpref which, const OpStringC &value, BOOL from_user) { return OpPrefsCollectionWithHostOverride::OverridePrefL(host, &m_stringprefdefault[which], int(which), value, from_user); } # endif // PREFS_HOSTOVERRIDE /** Write a string preference. * * @param which The preference to write. * @param value Value for the write. * @return ERR_NO_ACCESS if override is not allowed, OK otherwise. */ inline OP_STATUS WriteStringL(stringpref which, const OpStringC &value) { return OpPrefsCollection::WriteStringL(&m_stringprefdefault[which], int(which), value); } /** Write an integer preference. * * @param which The preference to write. * @param value Value for the write. * @return ERR_NO_ACCESS if override is not allowed, OK otherwise. */ inline OP_STATUS WriteIntegerL(integerpref which, int value) { return OpPrefsCollection::WriteIntegerL(&m_integerprefdefault[which], int(which), value); } # ifdef PREFS_HAVE_STRING_API virtual BOOL WritePreferenceL(IniSection section, const char *key, const OpStringC &value) { return OpPrefsCollection::WritePreferenceInternalL( section, key, value, m_stringprefdefault, PCDOC_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCDOC_NUMBEROFINTEGERPREFS); } # ifdef PREFS_HOSTOVERRIDE virtual BOOL OverridePreferenceL(const uni_char *host, IniSection section, const char *key, const OpStringC &value, BOOL from_user) { return OpPrefsCollectionWithHostOverride::OverridePreferenceInternalL( host, section, key, value, from_user, m_stringprefdefault, PCDOC_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCDOC_NUMBEROFINTEGERPREFS); } virtual BOOL RemoveOverrideL(const uni_char *host, IniSection section, const char *key, BOOL from_user) { return OpPrefsCollectionWithHostOverride::RemoveOverrideInternalL( host, section, key, from_user, m_stringprefdefault, PCDOC_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCDOC_NUMBEROFINTEGERPREFS); } # endif # endif #endif // PREFS_WRITE #ifdef PREFS_WRITE // Reset ------ /** Reset a string preference. Resets the preference to default by * removing the set value from the preference storage. * * @param which The preference to reset. * @return TRUE if the delete succeeded. */ inline BOOL ResetStringL(stringpref which) { return OpPrefsCollection::ResetStringL(&m_stringprefdefault[which], int(which)); } /** Reset an integer preference. Resets the preference to default by * removing the set value from the preference storage. * * @param which The preference to reset. * @return TRUE if the delete succeeded. */ inline BOOL ResetIntegerL(integerpref which) { return OpPrefsCollection::ResetIntegerL(&m_integerprefdefault[which], int(which)); } #endif // PREFS_WRITE // Fetch preferences from file ------ virtual void ReadAllPrefsL(PrefsModule::PrefsInitInfo *info); #ifdef PREFS_HOSTOVERRIDE virtual void ReadOverridesL(const uni_char *host, PrefsSection *section, BOOL active, BOOL from_user); #endif // Helpers ------ /** Retrieve total number of trusted external protocols. */ int GetNumberOfTrustedProtocols() { return static_cast<int>(m_trusted_applications.GetCount()); } /** Retrieve name of a trusted external protocol. */ OpStringC GetTrustedProtocol(int i) { return m_trusted_applications.Get(i)->protocol; } /** * Store information about a trusted external protocol. The information will * not be saved to disk until WriteTrustedProtocolsL() is called. A new entry * must specify a protocol. Modifying an existing entry will be rejected if * the data flag field includes 'TP_Protocol' and the corresponding string is empty * * @param index An index of the position the protocol info is supposed to be placed at. * @param data Collection of data to be stored. The actual stored data depends datas sate * @return TRUE on success, otherwise FALSE if index is out of range protocol not valid */ BOOL SetTrustedProtocolInfoL(int index, const TrustedProtocolData& data); /** * Retrieve information about a trusted external protocol. * * @param index Number of protocol to retrieve. * @param data protocol data on a valid return * @return TRUE on success, otherwise FALSE if index is out of range */ BOOL GetTrustedProtocolInfo(int index, TrustedProtocolData& data); /** * Retrieve information about a trusted external protocol. * * @param protocol The protocol value to retrieve data from * @param data protocol data on a valid return * @return -1 on failure, otherwise index of matched protocol */ int GetTrustedProtocolInfo(const OpStringC &protocol, TrustedProtocolData& data); /** * Look up the index where the protocol is stored. The index can * be used for @ref SetTrustedProtocolInfoL and @GetTrustedProtocolInfo * and be used to test if an entry for the protocol exists * * @param protocol The protocol to examine * @return -1 if no match exists, otherwise index of matched protocol */ int GetTrustedProtocolIndex(const OpStringC& protocol); /** * Removes information about a trusted external protocol. * * @param index The number of a protocol info to remove. */ void RemoveTrustedProtocolInfo(int index); /** * Removes information about a trusted external protocol. * * @param protocol The name of a protocol the info about which should be removed. * @param save_changes If TRUE the changes are written to the file. */ void RemoveTrustedProtocolInfoL(const OpStringC& protocol, BOOL save_changes = TRUE); /** * Retrieve information about a trusted external protocol. * This function is obsolete. It can not manage web handlers. * Use @ref GetTrustedProtocolInfo(int, TrustedProtocolData&) instead. * * @param index Number of protocol to retrieve. * @param[out] protocol Name of protocol assigned to this slot. * @param[out] filename Application associated with this protocol. * @param[out] description The description of the application associated with this protocol. * @param[out] viewer_mode Value describing how to handle protocol. * @param[out] in_terminal Whether to open protocol in terminal. * @param[out] user_defined Whether the trusted protocol is defined by a user. * */ DEPRECATED(BOOL GetTrustedProtocolInfoL(int index, OpString &protocol, OpString &filename, OpString &description, ViewerMode &viewer_mode, BOOL &in_terminal, BOOL &user_defined)); /** * Retrieve information about a trusted external protocol. * This function is obsolete. It can not manage web handlers. * Use @ref GetTrustedProtocolInfo(const OpStringC&, TrustedProtocolData&) instead. * * @param protocol Name of protocol to get info about. * @param[out] filename Application associated with this protocol. * @param[out] description The description of the application associated with this protocol. * @param[out] in_terminal Whether to open protocol in terminal. * @param[out] user_defined Whether the trusted protocol is defined by a user. * * @return Index of the protocol, -1 if not found. */ DEPRECATED(int GetTrustedApplicationL(const OpStringC &protocol, OpString &filename, OpString &description, BOOL &in_terminal, BOOL &user_defined)); /** Store info about a trusted external protocol. The information will * not be saved to disk until WriteTrustedProtocolsL() is called. * This function is obsolete. It can not manage web handlers. * Use @ref SetTrustedProtocolInfoL(int, const TrustedProtocolData&) instead. * * @param index An index of the position the protocol info is supposed to be placed at. * @param protocol A name of protocol to set. * @param filename An application associated with this protocol. * @param description The description of the application associated with this protocol. * @param viewer_mode A value describing how to handle the protocol. * @param in_terminal Whether to open the protocol in a terminal. * @param user_defined Whether the trusted protocol is defined by a user. */ DEPRECATED(BOOL SetTrustedProtocolInfoL(int index, const OpStringC &protocol, const OpStringC &filename, const OpStringC &description, ViewerMode handler_mode, BOOL in_terminal, BOOL user_defined = FALSE)); #if defined HAVE_HANDLERS_FILE && defined PREFSFILE_WRITE /** * Write stored information about trusted protocols. */ void WriteTrustedProtocolsL(int num_trusted_protocols); # endif // defined HAVE_HANDLERS_FILE && defined PREFSFILE_WRITE /** * Read stored information about trusted protocols. */ void ReadTrustedProtocolsL(); #ifdef PREFS_ENUMERATE // Enumeration helpers ------ // Trusted protocols not supported virtual unsigned int GetNumberOfPreferences() const { return PCDOC_NUMBEROFSTRINGPREFS + PCDOC_NUMBEROFINTEGERPREFS; } virtual unsigned int GetPreferencesL(struct prefssetting *settings) const { return OpPrefsCollection::GetPreferencesInternalL(settings, m_stringprefdefault, PCDOC_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCDOC_NUMBEROFINTEGERPREFS); } #endif #ifdef HAVE_HANDLERS_FILE PrefsFile& GetHandlerFile() { return m_handlers_file; } #endif // HAVE_HANDLERS_FILE private: /** Single-phase constructor. * * @param reader Pointer to the PrefsFile object. */ PrefsCollectionDoc(PrefsFile *reader) : OpPrefsCollectionWithHostOverride(Doc, reader) #ifdef HAVE_HANDLERS_FILE , m_handlers_file(PREFS_INI) #endif // HAVE_HANDLERS_FILE { #ifndef HAS_COMPLEX_GLOBALS InitStrings(); InitInts(); #endif } /** String preference information and default values */ PREFS_STATIC struct stringprefdefault m_stringprefdefault[PCDOC_NUMBEROFSTRINGPREFS + 1]; /** Integer preference information and default values */ PREFS_STATIC struct integerprefdefault m_integerprefdefault[PCDOC_NUMBEROFINTEGERPREFS + 1]; #ifdef PREFS_VALIDATE virtual void CheckConditionsL(int which, int *value, const uni_char *host); virtual BOOL CheckConditionsL(int which, const OpStringC &invalue, OpString **outvalue, const uni_char *host); #endif #ifdef PREFS_HAVE_STRING_API virtual int GetDefaultIntegerInternal(int, const struct integerprefdefault *); #endif struct trusted_apps { OpString protocol; ///< Name of protocol. OpString filename; ///< Application (if any) associated with protocol. OpString webhandler; ///< Web handler (if any) associated with protocol. OpString description; ///< Description of a handler int flags; ///< Bit field describing how to handle protocol. }; OpAutoVector<trusted_apps> m_trusted_applications; #ifndef HAS_COMPLEX_GLOBALS void InitStrings(); void InitInts(); #endif #ifdef HAVE_HANDLERS_FILE PrefsFile m_handlers_file; #endif // HAVE_HANDLERS_FILE }; #endif // PC_CORE_H
#ifndef DOUBLYLINKEDLIST_H #define DOUBLYLINKEDLIST_H #include "ListNode.h" #include <stdlib.h> using namespace std; template <typename E> //.h class DoublyLinkedList{ public: int size; ListNode<E>* front; ListNode<E>* back; DoublyLinkedList(); ~DoublyLinkedList(); void insertFront(E data); void insertBack(E data); E removeFront(); E deletePos(E key); }; //.cpp template <typename E> DoublyLinkedList<E>::DoublyLinkedList(){ front = new ListNode<E>(); back = new ListNode<E>(); front ->next = back; back->prev = front; size = 0; } template <typename E> DoublyLinkedList<E>::~DoublyLinkedList(){} //inserts from the front template <typename E> void DoublyLinkedList<E>::insertFront(E data){ ListNode<E> *node = new ListNode<E>(data); if(size==0){ back = node; } else { node->next = front; front->prev = node; } front = node; ++size; } //inserts from the back template <typename E> void DoublyLinkedList<E>::insertBack(E data){ ListNode<E> *node = new ListNode<E>(data); if(size == 0){ front = node; } else { back->next = node; node->prev = back; } back = node; size ++; } //removes the first node template <typename E> E DoublyLinkedList<E>::removeFront(){ //make neccessary checks ListNode<E> *temp = front; if(front->next == NULL){ back = NULL; } else { front->next->prev = NULL; } front = front ->next; E val = temp -> data; temp->next = NULL; delete temp; --size; return val; } //deletes from any position template <typename E> E DoublyLinkedList<E>::deletePos(E key){ E temp; ListNode<E> *current = front; //search while(!(current->data == key)){ current = current->next; if(current == NULL){ return -1; } } //ok we found it lets check our conditions temp = current->data; if(current == front){ front = current -> next; } else if (current == back){ back = current->prev; back->next = NULL; } else { current->prev->next = current -> next; current->next->prev = current -> prev; } current->next = NULL; current->prev = NULL; --size; //create temp to hold value delete current; return temp; } #endif
/****************************************************************************** * This file is part of the Geometric harmonization project * * * * (C) 2014 Azamat Shakhimardanov * * Herman Bruyninckx * * azamat.shakhimardanov@mech.kuleuven.be * * Department of Mechanical Engineering, * * Katholieke Universiteit Leuven, Belgium. * * * * You may redistribute this software and/or modify it under either the * * terms of the GNU Lesser General Public License version 2.1 (LGPLv2.1 * * <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>) or (at your * * discretion) of the Modified BSD License: * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote * * products derived from this software without specific prior written * * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * * *******************************************************************************/ /* This example is a first attempt to construct a kinematic chain that has complete geometric semantics. The segment or joint primitives used in the example are standard KDL primitives and do not take geometric semantics as parameters. Therefore, the semantics constraints are validated on poses and twists whose specific coordinates (e.g. PoseCoordinates using KDL::Frame) are then used to instantiate segment and joint models. Hence, many expressions in this example * still use such things as matrix multiplication. For an example that uses kinematic primitives with geometric semantics check the example chain_composition_geometricsemantics.cpp*/ #define COMPARISON_TEST #include <kdl/chainidsolver_recursive_newton_euler.hpp> #include <kdl/chainfksolverpos_recursive.hpp> #include <kdl/chainfksolvervel_recursive.hpp> #include <kdl_extensions/functionalcomputation_kdl.hpp> #include <Position/Position.h> #include <Orientation/Orientation.h> #include <Pose/Pose.h> #include <LinearVelocity/LinearVelocity.h> #include <AngularVelocity/AngularVelocity.h> #include <Twist/Twist.h> #include <Force/Force.h> #include <Torque/Torque.h> #include <Wrench/Wrench.h> #include <Position/PositionCoordinatesKDL.h> #include <Orientation/OrientationCoordinatesKDL.h> #include <Pose/PoseCoordinatesKDL.h> #include <LinearVelocity/LinearVelocityCoordinatesKDL.h> #include <AngularVelocity/AngularVelocityCoordinatesKDL.h> #include <Twist/TwistCoordinatesKDL.h> #include <Force/ForceCoordinatesKDL.h> #include <Torque/TorqueCoordinatesKDL.h> #include <Wrench/WrenchCoordinatesKDL.h> namespace grs = geometric_semantics; using namespace std; using namespace KDL; int main(int argc, char** argv) { KDL::JntArray q(3); q(0)=-M_PI/6.0; q(1)=M_PI/24.0; q(2)=-M_PI/12.0; KDL::JntArray qdot(3); qdot(0)=0.5; qdot(1)=-0.25; qdot(2)=0.35; KDL::JntArray qdotdot(3); qdotdot(0)=0.115; qdotdot(1)=-0.225; qdotdot(2)=0.375; //SEGMENT1 //SEGMENT METADATA // joint1 with respect to Base/World. In ideal case one should have a frame data to construct a joint KDL::Vector joint1_position1_B = KDL::Vector(0.1,0,0); //position of joint frame's origin KDL::Rotation joint1_coord_orientation1_B = Rotation::RotZ(0.0); KDL::Vector joint1_rotation_axis; double starting_angle = joint1_coord_orientation1_B.GetRotAngle(joint1_rotation_axis,0.00001); //rotation axis grs::PoseCoordinates<KDL::Frame> pose_coord_joint1_B(KDL::Frame(joint1_coord_orientation1_B, joint1_position1_B)); grs::PoseCoordinatesSemantics pose_joint1_B_semantics("j1","J1","Segment1.Joint1","b","B","Base","B"); grs::Pose<KDL::Frame> posejoint1_B(pose_joint1_B_semantics, pose_coord_joint1_B); Joint joint1 = Joint("Segment1.Joint1", joint1_position1_B, joint1_rotation_axis, Joint::RotAxis, 1, 0, 0.01); //Link1 tip frame1 wrt B KDL::Vector link1tip_position1_B = Vector(0.4, 0.0, 0.0); KDL::Rotation link1tip_coord_orientation1_B = Rotation::Identity(); grs::PoseCoordinates<KDL::Frame> pose_coord_link1tip_B(KDL::Frame(link1tip_coord_orientation1_B, link1tip_position1_B)); grs::PoseCoordinatesSemantics pose_link1tip_B_semantics("l1","L1","Segment1.Link1","b","B","Base","B"); grs::Pose<KDL::Frame> poselink1tip_B(pose_link1tip_B_semantics, pose_coord_link1tip_B); KDL::Frame tip_frame1 = poselink1tip_B.getCoordinates().getCoordinates(); Segment segment1 = Segment("Segment1.Link1", joint1, tip_frame1); //~SEGMENT METADATA //POSES std::cout << std::endl<< std::endl<< "POSES" << std::endl<<std::endl<< std::endl; //Link1 tip with respect to joint1 at 0 defines the length of the segment grs::Pose<KDL::Frame> pose_l1_j1_0 = grs::compose(posejoint1_B.inverse2(), poselink1tip_B); // joint1 with respect to Base/World at some value q=M_PI/2.0 KDL::Rotation joint1_coord_orientation1_q_B = joint1.pose(q(0)).M; grs::PoseCoordinates<KDL::Frame> pose_coord_joint1_q_B(KDL::Frame(joint1_coord_orientation1_q_B, joint1_position1_B)); grs::Pose<KDL::Frame> posejoint1_q_B(pose_joint1_B_semantics, pose_coord_joint1_q_B); //Link tip with respect to B while q is changing (segment.pose(q)) grs::Pose<KDL::Frame> pose_l1_b_q = grs::compose(posejoint1_q_B, pose_l1_j1_0); if(pose_l1_b_q.getCoordinates().getCoordinates() == segment1.pose(q(0)) ) { std::cout <<"Tip L1 with respect to B at value q " << pose_l1_b_q << std::endl; cout << endl; } //~POSES //TWISTS std::cout << std::endl<< std::endl<< "TWISTS " << std::endl<<std::endl<< std::endl; //j1 on Segment1.Joint1 twist w.r.t Base grs::LinearVelocityCoordinatesSemantics linear_vel_coord_seman_j1("j1","Segment1","Base","J1"); KDL::Vector coordinatesLinearVelocity_j1 = joint1.twist(qdot(0)).vel; grs::LinearVelocity<KDL::Vector> linearVelocity_j1(linear_vel_coord_seman_j1 ,coordinatesLinearVelocity_j1); grs::AngularVelocityCoordinatesSemantics ang_vel_coord_seman_j1("Segment1","Base","J1"); KDL::Vector coordinatesAngularVelocity_j1 = joint1.twist(qdot(0)).rot; grs::AngularVelocity<KDL::Vector> angularVelocity_j1(ang_vel_coord_seman_j1, coordinatesAngularVelocity_j1); //joint.twist returns this. grs::Twist<KDL::Vector,KDL::Vector> twist_j1(linearVelocity_j1, angularVelocity_j1); // l1 on Segment1.Link1 twist w.r.t Base //distance between points j1 and l1 at changing value of q; at 0 it is pose_l1_j1_0.p // needs to be put in different coordinates with the same origin. grs::PositionCoordinates<KDL::Vector> distance = posejoint1_q_B.getCoordinates().getCoordinates().M * (-1*pose_l1_j1_0.getCoordinates().getCoordinates().p); grs::Position<KDL::Vector> position_l1_j1_q("j1","Segment1","l1", "Segment1", "J1", distance); //std::cout<< "distance " << distance << std::endl; grs::OrientationCoordinates<KDL::Rotation> orientation = pose_l1_b_q.getCoordinates().getCoordinates().M.Inverse(); grs::Orientation<KDL::Rotation> orientation_l1_j1_q("J1","Segment1", "L1","Segment1","L1", orientation); //std::cout<< "orientation " << orientation << std::endl; if(twist_j1.changePointBody(position_l1_j1_q)) { std::cout << "Change reference point of joint twist " << std::endl << twist_j1 << std::endl;//segment.twist returns this. Segment tip twist with respect to previous segment tip if(twist_j1.changeCoordinateFrame(orientation_l1_j1_q)) { std::cout << "J1 TWIST CONTRIBUTION " << std::endl << twist_j1 << std::endl; //M.Inv(segment.twist) returns this. Segment tip twist with respect to joint frame } } //l1 on Segment1.Link1 twist w.r.t Joint1 expressed in L1 //for the 1st link twist01 = twist_j1 (in terms of values) grs::LinearVelocityCoordinatesSemantics twist01_lin_sem("l1","Segment1","Segment1", "L1"); KDL::Vector twist01_lin_coord = twist_j1.getLinearVelocity().getCoordinates().getCoordinates(); grs::LinearVelocity<KDL::Vector> twist01_lin(twist01_lin_sem,twist01_lin_coord); grs::AngularVelocityCoordinatesSemantics twist01_ang_sem("Segment1","Segment1", "L1"); KDL::Vector twist01_ang_coord = twist_j1.getAngularVelocity().getCoordinates().getCoordinates(); grs::AngularVelocity<KDL::Vector> twist01_ang(twist01_ang_sem, twist01_ang_coord); grs::Twist<KDL::Vector, KDL::Vector> twist01(twist01_lin, twist01_ang); std::cout << "L1 TWIST01 " << std::endl << twist01 << std::endl << std::endl; //UNIT TWIST in Segment tip frame grs::LinearVelocityCoordinatesSemantics linear_vel_coord_seman_j1_unit("j1","Segment1","Base","J1"); KDL::Vector coordinatesLinearVelocity_j1_unit = joint1.twist(1.0).vel; grs::LinearVelocity<KDL::Vector> linearVelocity_j1_unit(linear_vel_coord_seman_j1_unit ,coordinatesLinearVelocity_j1_unit); grs::AngularVelocityCoordinatesSemantics ang_vel_coord_seman_j1_unit("Segment1","Base","J1"); KDL::Vector coordinatesAngularVelocity_j1_unit = joint1.twist(1.0).rot; grs::AngularVelocity<KDL::Vector> angularVelocity_j1_unit(ang_vel_coord_seman_j1_unit, coordinatesAngularVelocity_j1_unit); //unit joint.twist grs::Twist<KDL::Vector,KDL::Vector> twist_j1_unit(linearVelocity_j1_unit, angularVelocity_j1_unit); //unit twist in segment tip frame //it is computed in the same manner as the tip frame twist twist_j1_unit.changePointBody(position_l1_j1_q); twist_j1_unit.changeCoordinateFrame(orientation_l1_j1_q); std::cout << "L1 UNIT TWIST " << std::endl << twist_j1_unit << std::endl; //ACC TWIST std::cout << std::endl<< std::endl<< std::endl<< "ACCTWISTS " << std::endl<<std::endl<< std::endl; //acctwist consists of 3 components: PARENT acctwist; JOINT acctwist; BIAS acctwist //all the constraints and operation on velocity twists apply here //JOINT ACCTWIST //it can also be computed by multiplying qdotdot with unit twist //here we compute by changing its ref. point grs::LinearVelocityCoordinatesSemantics linear_acc_coord_seman_j1("j1","Segment1","Base","J1"); KDL::Vector coordinatesLinearAcc_j1 = joint1.twist(qdotdot(0)).vel; grs::LinearVelocity<KDL::Vector> linearAcc_j1(linear_acc_coord_seman_j1 ,coordinatesLinearAcc_j1); grs::AngularVelocityCoordinatesSemantics ang_acc_coord_seman_j1("Segment1","Base","J1"); KDL::Vector coordinatesAngularAcc_j1 = joint1.twist(qdotdot(0)).rot; grs::AngularVelocity<KDL::Vector> angularAcc_j1(ang_acc_coord_seman_j1, coordinatesAngularAcc_j1); grs::Twist<KDL::Vector,KDL::Vector> acctwist_j1(linearAcc_j1, angularAcc_j1); if(acctwist_j1.changePointBody(position_l1_j1_q)) { if(acctwist_j1.changeCoordinateFrame(orientation_l1_j1_q)) { std::cout << "J1 ACCTWIST CONTRIBUTION " << std::endl << acctwist_j1 << std::endl; //M.Inv(segment.twist) returns this. Segment tip twist with respect to joint frame } } //BIAS ACCTWIST grs::LinearVelocityCoordinatesSemantics biasacctwist01_lin_sem("l1","Segment1","Segment1", "L1"); KDL::Vector biasacctwist01_lin_coord = twist01.getAngularVelocity().getCoordinates().getCoordinates()*twist_j1.getLinearVelocity().getCoordinates().getCoordinates() + twist01.getLinearVelocity().getCoordinates().getCoordinates()*twist_j1.getAngularVelocity().getCoordinates().getCoordinates(); grs::LinearVelocity<KDL::Vector> biasacctwist01_lin(biasacctwist01_lin_sem, biasacctwist01_lin_coord); grs::AngularVelocityCoordinatesSemantics biasacctwist01_ang_sem("Segment1","Segment1", "L1"); KDL::Vector biasacctwist01_ang_coord = twist01.getAngularVelocity().getCoordinates().getCoordinates()*twist_j1.getAngularVelocity().getCoordinates().getCoordinates(); grs::AngularVelocity<KDL::Vector> biasacctwist01_ang(biasacctwist01_ang_sem, biasacctwist01_ang_coord); grs::Twist<KDL::Vector, KDL::Vector> biasacctwist01(biasacctwist01_lin, biasacctwist01_ang); std::cout << "BIAS ACCTWIST CONTRIBUTION " << std::endl << biasacctwist01 << std::endl<< std::endl;; //PARENT(here it is BASE) ACCTWIST grs::LinearVelocityCoordinatesSemantics acctwist00_lin_sem("b","Base","World", "B"); KDL::Vector acctwist00_lin_coord = KDL::Vector(0, 0, 9.8); grs::LinearVelocity<KDL::Vector> acctwist00_lin(acctwist00_lin_sem, acctwist00_lin_coord); grs::AngularVelocityCoordinatesSemantics acctwist00_ang_sem("Base","World", "B"); KDL::Vector acctwist00_ang_coord = KDL::Vector::Zero(); grs::AngularVelocity<KDL::Vector> acctwist00_ang(acctwist00_ang_sem, acctwist00_ang_coord); grs::Twist<KDL::Vector, KDL::Vector> acctwist00(acctwist00_lin, acctwist00_ang); grs::Position<KDL::Vector> position_l1_b_q("b","Base","l1", "Segment1", "B", distance); grs::Orientation<KDL::Rotation> orientation_l1_b_q("B","Base", "L1","Segment1","L1", orientation); if(acctwist00.changePointBody(position_l1_b_q)) { if(acctwist00.changeCoordinateFrame(orientation_l1_b_q)) { std::cout << "L1 ACCTWIST PARENT " << std::endl << acctwist00 << std::endl; } } std::cout << std::endl << "L1 ACCTWIST COMPOSITIONS" << std::endl<< std::endl; grs::Twist<KDL::Vector, KDL::Vector> acctwist1 = grs::compose(grs::compose(acctwist_j1,acctwist00), biasacctwist01); std::cout << "L1 ACCTWIST " << std::endl << acctwist1 << std::endl; //~TWISTS //~SEGMENT1 //SEGMENT2 //SEGMENT METADATA // joint2 with respect to L1 KDL::Vector joint2_position2_L1 = KDL::Vector(0.0,0,0); //position of joint frame's origin KDL::Rotation joint2_coord_orientation2_L1 = Rotation::RotZ(0.0); KDL::Vector joint2_rotation_axis; starting_angle = joint2_coord_orientation2_L1.GetRotAngle(joint2_rotation_axis,0.00001); //rotation axis grs::PoseCoordinates<KDL::Frame> pose_coord_joint2_L1(KDL::Frame(joint2_coord_orientation2_L1, joint2_position2_L1)); grs::PoseCoordinatesSemantics pose_joint2_L1_semantics("j2","J2","Segment2.Joint2","l1","L1","Segment1.Link1","L1"); grs::Pose<KDL::Frame> posejoint2_L1(pose_joint2_L1_semantics, pose_coord_joint2_L1); Joint joint2 = Joint("Segment2.Joint2", joint2_position2_L1, joint2_rotation_axis, Joint::RotAxis, 1, 0, 0.01); //Link2 tip frame2 w.r.t L1 KDL::Vector link2tip_position2_L1 = Vector(0.4, 0.0, 0.0); KDL::Rotation link2tip_coord_orientation2_L1 = Rotation::Identity(); grs::PoseCoordinates<KDL::Frame> pose_coord_link2tip_L1(KDL::Frame(link2tip_coord_orientation2_L1, link2tip_position2_L1)); grs::PoseCoordinatesSemantics pose_link2tip_L1_semantics("l2","L2","Segment2.Link2","l1","L1","Segment1.Link1","L1"); grs::Pose<KDL::Frame> poselink2tip_L1(pose_link2tip_L1_semantics, pose_coord_link2tip_L1); KDL::Frame tip_frame2 = poselink2tip_L1.getCoordinates().getCoordinates(); Segment segment2 = Segment("Segment2.Link2", joint2, tip_frame2); //~SEGMENT METADATA //POSES std::cout << std::endl<< std::endl<< "POSES" << std::endl<<std::endl<< std::endl; //Link2 tip with respect to joint2 at 0 defines the length of the segment grs::Pose<KDL::Frame> pose_l2_j2_0 = grs::compose(posejoint2_L1.inverse2() ,poselink2tip_L1); // joint2 with respect to L1 at some value q=M_PI/2.0 Rotation joint2_coord_orientation2_q_L1 = joint2.pose(q(1)).M; grs::PoseCoordinates<KDL::Frame> pose_coord_joint2_q_L1(KDL::Frame(joint2_coord_orientation2_q_L1, joint2_position2_L1)); grs::Pose<KDL::Frame> posejoint2_q_L1(pose_joint2_L1_semantics, pose_coord_joint2_q_L1); //Link tip with respect to L1 while q is changing grs::Pose<KDL::Frame> pose_l2_l1_q = grs::compose(posejoint2_q_L1, pose_l2_j2_0); if(pose_l2_l1_q.getCoordinates().getCoordinates() == segment2.pose(q(1)) ) { std::cout <<"Tip L2 with respect to L1 at value q " << pose_l2_l1_q << std::endl; cout << endl; } //~POSES //TWISTS std::cout << std::endl<< std::endl<< std::endl<< std::endl<< "TWISTS " << std::endl << std::endl; //j2 on Segment2.Joint2 twist w.r.t Segment1.Link1 grs::LinearVelocityCoordinatesSemantics linear_vel_coord_seman_j2("j2","Segment2","Segment1","J2"); KDL::Vector coordinatesLinearVelocity_j2 = joint2.twist(qdot(1)).vel; grs::LinearVelocity<KDL::Vector> linearVelocity_j2(linear_vel_coord_seman_j2 ,coordinatesLinearVelocity_j2); grs::AngularVelocityCoordinatesSemantics ang_vel_coord_seman_j2("Segment2","Segment1","J2"); KDL::Vector coordinatesAngularVelocity_j2 = joint2.twist(qdot(1)).rot; grs::AngularVelocity<KDL::Vector> angularVelocity_j2(ang_vel_coord_seman_j2, coordinatesAngularVelocity_j2); //joint.twist returns this. grs::Twist<KDL::Vector,KDL::Vector> twist_j2(linearVelocity_j2, angularVelocity_j2); // l2 on Segment2.Link2 twist w.r.t Segment1.Link1 //distance between points j2 and l2 at changing value of q; at 0 it is pose_l2_j2_0.p // needs to be put in different coordinates with the same origin. grs::PositionCoordinates<KDL::Vector> distance2 = posejoint2_q_L1.getCoordinates().getCoordinates().M * (-1*pose_l2_j2_0.getCoordinates().getCoordinates().p); grs::Position<KDL::Vector> position_l2_j2_q("j2","Segment2","l2", "Segment2", "J2", distance2); grs::OrientationCoordinates<KDL::Rotation> orientation2 = pose_l2_l1_q.getCoordinates().getCoordinates().M.Inverse(); grs::Orientation<KDL::Rotation> orientation_l2_j2_q("J2","Segment2", "L2","Segment2","L2", orientation2); if(twist_j2.changePointBody(position_l2_j2_q)) { if(twist_j2.changeCoordinateFrame(orientation_l2_j2_q)) { std::cout << "J2 TWIST CONTRIBUTION " << std::endl << twist_j2 << std::endl; //M.Inv(segment.twist) returns this. Segment tip twist with respect to joint frame } } //l1 on Segment1.Link1 twist w.r.t Joint1 expressed in L1 //for the 2st link twist02 = twist01 + twist_j2 (in terms of values) grs::Position<KDL::Vector> position_l2_l1_q("l1","Segment1","l2", "Segment2", "L1", distance2); twist01.changePointBody(position_l2_l1_q); // std::cout << std::endl<< std::endl<< std::endl<<"CHANGE FRAME OF LINK " << std::endl<< std::endl<< std::endl; grs::Orientation<KDL::Rotation> orientation_l2_l1_q("L1","Segment1", "L2","Segment2","L2", orientation2); twist01.changeCoordinateFrame(orientation_l2_l1_q); std::cout << std::endl<< std::endl<< std::endl<<"LINK CONTRIBUTION " << std::endl << twist01 << std::endl<< std::endl; std::cout << std::endl<< std::endl<< std::endl<<"COMPOSITION " << std::endl<< std::endl<< std::endl; grs::Twist<KDL::Vector, KDL::Vector> twist02 = grs::compose(twist_j2,twist01); std::cout << "L2 TWIST02 " << std::endl << twist02 << std::endl << std::endl; //UNIT TWIST in Segment tip frame grs::LinearVelocityCoordinatesSemantics linear_vel_coord_seman_j2_unit("j2","Segment2","Segment1","J2"); KDL::Vector coordinatesLinearVelocity_j2_unit = joint2.twist(1.0).vel; grs::LinearVelocity<KDL::Vector> linearVelocity_j2_unit(linear_vel_coord_seman_j2_unit ,coordinatesLinearVelocity_j2_unit); grs::AngularVelocityCoordinatesSemantics ang_vel_coord_seman_j2_unit("Segment2","Segment1","J2"); KDL::Vector coordinatesAngularVelocity_j2_unit = joint2.twist(1.0).rot; grs::AngularVelocity<KDL::Vector> angularVelocity_j2_unit(ang_vel_coord_seman_j2_unit, coordinatesAngularVelocity_j2_unit); //unit joint.twist grs::Twist<KDL::Vector,KDL::Vector> twist_j2_unit(linearVelocity_j2_unit, angularVelocity_j2_unit); //unit twist in segment tip frame //it is computed in the same manner as the tip frame twist twist_j2_unit.changePointBody(position_l2_j2_q); twist_j2_unit.changeCoordinateFrame(orientation_l2_j2_q); std::cout << "L2 UNIT TWIST " << std::endl << twist_j2_unit << std::endl; //ACC TWIST std::cout << std::endl<< std::endl<< std::endl<< "ACCTWISTS " << std::endl<<std::endl<< std::endl; //acctwist consists of 3 components: PARENT acctwist; JOINT acctwist; BIAS acctwist //all the constraints and operation on velocity twists apply here //JOINT ACCTWIST //it can also be computed by multiplying qdotdot with unit twist //here we compute by changing its ref. point grs::LinearVelocityCoordinatesSemantics linear_acc_coord_seman_j2("j2","Segment2","Segment1","J2"); KDL::Vector coordinatesLinearAcc_j2 = joint2.twist(qdotdot(1)).vel; grs::LinearVelocity<KDL::Vector> linearAcc_j2(linear_acc_coord_seman_j2 ,coordinatesLinearAcc_j2); grs::AngularVelocityCoordinatesSemantics ang_acc_coord_seman_j2("Segment2","Segment1","J2"); KDL::Vector coordinatesAngularAcc_j2 = joint2.twist(qdotdot(1)).rot; grs::AngularVelocity<KDL::Vector> angularAcc_j2(ang_acc_coord_seman_j2, coordinatesAngularAcc_j2); grs::Twist<KDL::Vector,KDL::Vector> acctwist_j2(linearAcc_j2, angularAcc_j2); if(acctwist_j2.changePointBody(position_l2_j2_q)) { if(acctwist_j2.changeCoordinateFrame(orientation_l2_j2_q)) { std::cout << "J2 ACCTWIST CONTRIBUTION " << std::endl << acctwist_j2 << std::endl; //M.Inv(segment.twist) returns this. Segment tip twist with respect to joint frame } } //BIAS ACCTWIST grs::LinearVelocityCoordinatesSemantics biasacctwist02_lin_sem("l2","Segment2","Segment2", "L2"); KDL::Vector biasacctwist02_lin_coord = twist02.getAngularVelocity().getCoordinates().getCoordinates()*twist_j2.getLinearVelocity().getCoordinates().getCoordinates() + twist02.getLinearVelocity().getCoordinates().getCoordinates()*twist_j2.getAngularVelocity().getCoordinates().getCoordinates(); grs::LinearVelocity<KDL::Vector> biasacctwist02_lin(biasacctwist02_lin_sem, biasacctwist02_lin_coord); grs::AngularVelocityCoordinatesSemantics biasacctwist02_ang_sem("Segment2","Segment2", "L2"); KDL::Vector biasacctwist02_ang_coord = twist02.getAngularVelocity().getCoordinates().getCoordinates()*twist_j2.getAngularVelocity().getCoordinates().getCoordinates(); grs::AngularVelocity<KDL::Vector> biasacctwist02_ang(biasacctwist02_ang_sem, biasacctwist02_ang_coord); grs::Twist<KDL::Vector, KDL::Vector> biasacctwist02(biasacctwist02_lin, biasacctwist02_ang); std::cout << "BIAS ACCTWIST CONTRIBUTION " << std::endl << biasacctwist02 << std::endl<< std::endl;; //PARENT(here it is BASE) ACCTWIST // std::cout << std::endl<< std::endl<< std::endl<<"CHANGE FRAME OF LINK " << std::endl<< std::endl<< std::endl; if(acctwist1.changePointBody(position_l2_l1_q)) { if(acctwist1.changeCoordinateFrame(orientation_l2_l1_q)) { std::cout << "L2 ACCTWIST PARENT " << std::endl << acctwist1 << std::endl; } } std::cout << std::endl << "L2 ACCTWIST COMPOSITIONS" << std::endl<< std::endl; grs::Twist<KDL::Vector, KDL::Vector> acctwist2 = grs::compose(grs::compose(acctwist_j2,acctwist1), biasacctwist02); std::cout << "L2 ACCTWIST " << std::endl << acctwist2 << std::endl; //~TWISTS //~SEGMENT2 //SEGMENT3 //SEGMENT METADATA // joint3 with respect to L2 Joint joint3 = Joint("Segment3.Joint3", Vector(-0.1, 0.0, 0),Vector(0,0,1),Joint::RotAxis, 1, 0, 0.01); grs::PoseCoordinatesSemantics pose_joint3_L2("j3","J3","Segment3.Joint3","l2","L2","Segment2.Link2","L2"); Vector joint3_position3_L2 = joint3.JointOrigin(); Rotation joint3_coord_orientation3_L2=joint3.pose(0).M; grs::PoseCoordinates<KDL::Frame> pose_coord_joint3_L2(KDL::Frame(joint3_coord_orientation3_L2, joint3_position3_L2)); grs::Pose<KDL::Frame> posejoint3_L2(pose_joint3_L2, pose_coord_joint3_L2); //Link3 tip frame3 grs::PoseCoordinatesSemantics pose_link3tip_L2("l3","L3","Segment3.Link3","l2","L2","Segment2.Link2","L2"); Vector link3tip_position3_L2 = Vector(0.4, 0.0, 0); Rotation link3tip_coord_orientation3_L2 = Rotation::Identity(); grs::PoseCoordinates<KDL::Frame> pose_coord_link3tip_L2(KDL::Frame(link3tip_coord_orientation3_L2, link3tip_position3_L2)); grs::Pose<KDL::Frame> poselink3tip_L2(pose_link3tip_L2, pose_coord_link3tip_L2); Frame frame3 = poselink3tip_L2.getCoordinates().getCoordinates(); Segment segment3 = Segment("Link3", joint3, frame3); //~SEGMENT METADATA //POSES std::cout << std::endl<< std::endl<< "POSES" << std::endl<<std::endl<< std::endl; //Link3 tip with respect to joint3 at 0 defines the length of the segment grs::Pose<KDL::Frame> pose_l3_j3_0 = grs::compose(posejoint3_L2.inverse2() ,poselink3tip_L2); // joint3 with respect to L2 at some value q=M_PI/2.0 Rotation joint3_coord_orientation3_q_L2=joint3.pose(q(2)).M; grs::PoseCoordinates<KDL::Frame> pose_coord_joint3_q_L2(KDL::Frame(joint3_coord_orientation3_q_L2, joint3_position3_L2)); grs::Pose<KDL::Frame> posejoint3_q_L2(pose_joint3_L2, pose_coord_joint3_q_L2); //Link tip with respect to L2 while q is changing grs::Pose<KDL::Frame> pose_l3_l2_q = grs::compose(posejoint3_q_L2, pose_l3_j3_0); if( pose_l3_l2_q.getCoordinates().getCoordinates() == segment3.pose(q(2)) ) { std::cout <<"Tip L3 with respect to L2 at value q " << pose_l3_l2_q << std::endl; cout << endl; } //~POSES //TWISTS std::cout << std::endl<< std::endl<< std::endl<< std::endl<< "TWISTS " << std::endl << std::endl; //j3 on Segment3.Joint3 twist w.r.t Segment2.Link2 grs::LinearVelocityCoordinatesSemantics linear_vel_coord_seman_j3("j3","Segment3","Segment2","J3"); KDL::Vector coordinatesLinearVelocity_j3 = joint3.twist(qdot(2)).vel; grs::LinearVelocity<KDL::Vector> linearVelocity_j3(linear_vel_coord_seman_j3 ,coordinatesLinearVelocity_j3); grs::AngularVelocityCoordinatesSemantics ang_vel_coord_seman_j3("Segment3","Segment2","J3"); KDL::Vector coordinatesAngularVelocity_j3 = joint3.twist(qdot(2)).rot; grs::AngularVelocity<KDL::Vector> angularVelocity_j3(ang_vel_coord_seman_j3, coordinatesAngularVelocity_j3); //joint.twist returns this. grs::Twist<KDL::Vector,KDL::Vector> twist_j3(linearVelocity_j3, angularVelocity_j3); // l1 on Segment1.Link1 twist w.r.t Base //distance between points j1 and l1 at changing value of q; at 0 it is pose_l1_j1_0.p // needs to be put in different coordinates with the same origin. grs::PositionCoordinates<KDL::Vector> distance3 = posejoint3_q_L2.getCoordinates().getCoordinates().M * (-1* pose_l3_j3_0.getCoordinates().getCoordinates().p); grs::Position<KDL::Vector> position_l3_j3_q("j3","Segment3","l3", "Segment3", "J3", distance3); //std::cout<< "distance " << distance3 << std::endl; grs::OrientationCoordinates<KDL::Rotation> orientation3 = pose_l3_l2_q.getCoordinates().getCoordinates().M.Inverse(); grs::Orientation<KDL::Rotation> orientation_l3_j3_q("J3","Segment3", "L3","Segment3","L3", orientation3); //std::cout<< "orientation " << orientation3 << std::endl; if(twist_j3.changePointBody(position_l3_j3_q)) { if(twist_j3.changeCoordinateFrame(orientation_l3_j3_q)) { std::cout << "J3 TWIST CONTRIBUTION " << std::endl << twist_j3 << std::endl; //M.Inv(segment.twist) returns this. Segment tip twist with respect to joint frame } } //l1 on Segment1.Link1 twist w.r.t Joint1 expressed in L1 //for the 2st link twist02 = twist01 + twist_j2 (in terms of values) grs::Position<KDL::Vector> position_l3_l2_q("l2","Segment2","l3", "Segment3", "L2", distance3); twist02.changePointBody(position_l3_l2_q); grs::Orientation<KDL::Rotation> orientation_l3_l2_q("L2","Segment2", "L3","Segment3","L3", orientation3); //std::cout << "Change reference point of L2 twist02 " << std::endl << twist02 << std::endl; twist02.changeCoordinateFrame(orientation_l3_l2_q); std::cout << std::endl<< std::endl<< std::endl<<"LINK CONTRIBUTION " << std::endl << twist02 << std::endl<< std::endl; std::cout << std::endl<< std::endl<< std::endl<<"COMPOSITION " << std::endl<< std::endl<< std::endl; grs::Twist<KDL::Vector, KDL::Vector> twist03 = grs::compose(twist02,twist_j3); std::cout << "L3 TWIST03 " << twist03 << std::endl << std::endl; //UNIT TWIST in Segment tip frame grs::LinearVelocityCoordinatesSemantics linear_vel_coord_seman_j3_unit("j3","Segment3","Segment2","J3"); KDL::Vector coordinatesLinearVelocity_j3_unit = joint3.twist(1.0).vel; grs::LinearVelocity<KDL::Vector> linearVelocity_j3_unit(linear_vel_coord_seman_j3_unit ,coordinatesLinearVelocity_j3_unit); grs::AngularVelocityCoordinatesSemantics ang_vel_coord_seman_j3_unit("Segment3","Segment2","J3"); KDL::Vector coordinatesAngularVelocity_j3_unit = joint3.twist(1.0).rot; grs::AngularVelocity<KDL::Vector> angularVelocity_j3_unit(ang_vel_coord_seman_j3_unit, coordinatesAngularVelocity_j3_unit); //unit joint.twist grs::Twist<KDL::Vector,KDL::Vector> twist_j3_unit(linearVelocity_j3_unit, angularVelocity_j3_unit); //unit twist in segment tip frame //it is computed in the same manner as the tip frame twist twist_j3_unit.changePointBody(position_l3_j3_q); twist_j3_unit.changeCoordinateFrame(orientation_l3_j3_q); std::cout << "L3 UNIT TWIST " << std::endl << twist_j3_unit << std::endl; //ACC TWIST std::cout << std::endl<< std::endl<< std::endl<< "ACCTWISTS " << std::endl<<std::endl<< std::endl; //acctwist consists of 3 components: PARENT acctwist; JOINT acctwist; BIAS acctwist //all the constraints and operation on velocity twists apply here //JOINT ACCTWIST //it can also be computed by multiplying qdotdot with unit twist //here we compute by changing its ref. point grs::LinearVelocityCoordinatesSemantics linear_acc_coord_seman_j3("j3","Segment3","Segment2","J3"); KDL::Vector coordinatesLinearAcc_j3 = joint3.twist(qdotdot(2)).vel; grs::LinearVelocity<KDL::Vector> linearAcc_j3(linear_acc_coord_seman_j3 ,coordinatesLinearAcc_j3); grs::AngularVelocityCoordinatesSemantics ang_acc_coord_seman_j3("Segment3","Segment2","J3"); KDL::Vector coordinatesAngularAcc_j3 = joint3.twist(qdotdot(2)).rot; grs::AngularVelocity<KDL::Vector> angularAcc_j3(ang_acc_coord_seman_j3, coordinatesAngularAcc_j3); grs::Twist<KDL::Vector,KDL::Vector> acctwist_j3(linearAcc_j3, angularAcc_j3); if(acctwist_j3.changePointBody(position_l3_j3_q)) { if(acctwist_j3.changeCoordinateFrame(orientation_l3_j3_q)) { std::cout << "J3 ACCTWIST CONTRIBUTION " << std::endl << acctwist_j3 << std::endl; //M.Inv(segment.twist) returns this. Segment tip twist with respect to joint frame } } //BIAS ACCTWIST grs::LinearVelocityCoordinatesSemantics biasacctwist03_lin_sem("l3","Segment3","Segment3", "L3"); KDL::Vector biasacctwist03_lin_coord = twist03.getAngularVelocity().getCoordinates().getCoordinates()*twist_j3.getLinearVelocity().getCoordinates().getCoordinates() + twist03.getLinearVelocity().getCoordinates().getCoordinates()*twist_j3.getAngularVelocity().getCoordinates().getCoordinates(); grs::LinearVelocity<KDL::Vector> biasacctwist03_lin(biasacctwist03_lin_sem, biasacctwist03_lin_coord); grs::AngularVelocityCoordinatesSemantics biasacctwist03_ang_sem("Segment3","Segment3", "L3"); KDL::Vector biasacctwist03_ang_coord = twist03.getAngularVelocity().getCoordinates().getCoordinates()*twist_j3.getAngularVelocity().getCoordinates().getCoordinates(); grs::AngularVelocity<KDL::Vector> biasacctwist03_ang(biasacctwist03_ang_sem, biasacctwist03_ang_coord); grs::Twist<KDL::Vector, KDL::Vector> biasacctwist03(biasacctwist03_lin, biasacctwist03_ang); std::cout << "BIAS ACCTWIST CONTRIBUTION " << std::endl << biasacctwist03 << std::endl<< std::endl;; //PARENT(here it is BASE) ACCTWIST // std::cout << std::endl<< std::endl<< std::endl<<"CHANGE FRAME OF LINK " << std::endl<< std::endl<< std::endl; if(acctwist2.changePointBody(position_l3_l2_q)) { if(acctwist2.changeCoordinateFrame(orientation_l3_l2_q)) { std::cout << "L3 ACCTWIST PARENT " << std::endl << acctwist2 << std::endl; } } std::cout << std::endl << "L3 ACCTWIST COMPOSITIONS" << std::endl<< std::endl; grs::Twist<KDL::Vector, KDL::Vector> acctwist3 = grs::compose(grs::compose(acctwist_j3,acctwist2), biasacctwist03); std::cout << "L3 ACCTWIST " << std::endl << acctwist3 << std::endl; //~TWISTS //~SEGMENT3 //FK grs::Pose<KDL::Frame> fk_pose_L3_B_q = grs::compose(pose_l1_b_q, grs::compose(pose_l2_l1_q,pose_l3_l2_q) ); std::cout <<"Tip L3 with respect to B at value q " << fk_pose_L3_B_q << std::endl; cout << endl; #ifdef COMPARISON_TEST KDL::Chain achain; achain.addSegment(segment1); achain.addSegment(segment2); achain.addSegment(segment3); ChainFkSolverPos_recursive fksolvertest(achain); ChainFkSolverVel_recursive fkvelsolvertest(achain); ChainIdSolver_RNE idsolvertest(achain, KDL::Vector(0,0,-9.8)); Frame tempEEtest[3]; Frame tempLocal[3]; Twist tempTwist[3]; FrameVel tempVeltest[3]; KDL::JntArray jointInitialPose(achain.getNrOfJoints()); jointInitialPose(0)= q(0); jointInitialPose(1)= q(1); jointInitialPose(2)= q(2); KDL::JntArrayVel jointInitialRate(achain.getNrOfJoints()); jointInitialRate.q(0)= q(0); jointInitialRate.q(1)= q(1); jointInitialRate.q(2)= q(2); jointInitialRate.qdot(0)= qdot(0); jointInitialRate.qdot(1)= qdot(1); jointInitialRate.qdot(2)= qdot(2); KDL::JntArray torques(achain.getNrOfJoints()); KDL::Wrenches fext; fext.resize(achain.getNrOfSegments(),KDL::Wrench()); std::cout << idsolvertest.CartToJnt(q,qdot,qdotdot, fext, torques) << std::endl; std::cout << std::endl << std::endl<< std::endl << std::endl; for(unsigned int i=0; i<achain.getNrOfSegments();i++) { std::cout <<"Tip Frame " << achain.getSegment(i).getFrameToTip()<< std::endl; tempLocal[i]=achain.getSegment(i).pose(jointInitialPose(i)); std::cout <<"Segment tip pose " << achain.getSegment(i).pose(jointInitialPose(i)) << std::endl; std::cout <<"Joint twist " << achain.getSegment(i).getJoint().twist(jointInitialRate.qdot(i)) << std::endl; std::cout <<"Segment tip twist " << achain.getSegment(i).twist(jointInitialPose(i), jointInitialRate.qdot(i)) << std::endl; std::cout <<"Segment tip twist inv " << tempLocal[i].M.Inverse(achain.getSegment(i).twist(jointInitialPose(i), jointInitialRate.qdot(i))) << std::endl; std::cout <<"Segment tip Unit twist inv " << tempLocal[i].M.Inverse(achain.getSegment(i).twist(jointInitialPose(i), 1.0)) << std::endl; std::cout <<"Segment tip ACC twist Joint Cont" << tempLocal[i].M.Inverse(achain.getSegment(i).twist(jointInitialPose(i), 1.0))*qdotdot(i) << std::endl; if(i == 0) { tempTwist[i] = tempLocal[i].M.Inverse(achain.getSegment(i).twist(jointInitialPose(i), jointInitialRate.qdot(i))); std::cout <<"Total twist " << tempTwist[i] << std::endl; } if(i!=0) { tempTwist[i] = tempLocal[i].Inverse(tempTwist[i-1]) + tempLocal[i].M.Inverse(achain.getSegment(i).twist(jointInitialPose(i), jointInitialRate.qdot(i))) ; std::cout <<"Total twist " << tempTwist[i] << std::endl; } } #endif return 0; }
// // Created by igor on 12/11/19. // #include <iostream> #include "OpenGL_CallBack.h" //Definição de variáveis int width; int height; bool fullScreen = false; bool animate = false; bool pause = false; float xCamera = 0; float yCamera = -2; bool perspective = true; float zdist = 4.0; float rotationX = 0; float rotationY = 0; int last_x; int last_y; int onStartScreen; int gameStarted =0; float initialDirection = 0; bool venceu = false; bool perdeu = false; void reshape(int w, int h) { width = w; height = h; glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 200.0); } void Spekeyboard(int key, int x, int y) { switch (key) { case GLUT_KEY_F12: fullScreen = !fullScreen; if (fullScreen) { glutFullScreen(); } else { glutReshapeWindow(1000, 600); } break; } } // Motion callback void motion(int x, int y) { if(pause ==1){/// Se o game está pausado, então eu posso girar a câmera livremente rotationX += (float) (y - last_y); last_y = y; rotationY += (float) (x - last_x); last_x = x; } } // Mouse callback void mouse(int button, int state, int x, int y) { if(!animate && !pause) { if ((button == GLUT_LEFT_BUTTON ) && (state == GLUT_DOWN)) { if(onStartScreen){ onStartScreen =0; } else { animate = !animate; gameStarted = 1; } } else if(button == 3) { initialDirection += 3; } else { initialDirection -= 3; } initialDirection = fixRange(initialDirection, -180, 180, true); direction[0] = cos((initialDirection + 90) * M_PI / 180); direction[1] = sin((initialDirection + 90) * M_PI / 180); } } void reiniciaJogo() { for(int i = 0; i < NUMRETAN;++i) { retangulos[i].colisao = false; retangulos[i].reduzir = false; retangulos[i].escala = 1.0; } pause = false; venceu = false; animate = false; perdeu = false; rebatedor.atualizaPosicao(); initialDirection = 0; initialDirection = fixRange(initialDirection, -180, 180, true); position[0] = 0; position[1] = -1.01; direction[0] = cos((initialDirection + 90) * M_PI / 180); direction[1] = sin((initialDirection + 90) * M_PI / 180); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/display/color.h" #include "modules/logdoc/htm_lex.h" #include "modules/style/css_types.h" COLORREF CheckColorContrast(COLORREF font_color, COLORREF bg_color, int minimum_contrast, COLORREF light_font_color, COLORREF dark_font_color) { font_color = HTM_Lex::GetColValByIndex(font_color); bg_color = HTM_Lex::GetColValByIndex(bg_color); int font_brightness = (OP_GET_R_VALUE(font_color) * 299 + OP_GET_G_VALUE(font_color) * 587 + OP_GET_B_VALUE(font_color) * 114) / 1000; int bg_brightness = (OP_GET_R_VALUE(bg_color) * 299 + OP_GET_G_VALUE(bg_color) * 587 + OP_GET_B_VALUE(bg_color) * 114) / 1000; if (op_abs(font_brightness - bg_brightness) < minimum_contrast) return bg_brightness < 125 ? light_font_color : dark_font_color; else return font_color; } COLORREF GetRGBA(COLORREF col_ref) { if (COLOR_is_rgba(col_ref)) return col_ref; else if (COLOR_is_indexed(col_ref)) return HTM_Lex::GetColValByIndex(col_ref); else if (col_ref == CSS_COLOR_transparent) return OP_RGBA(0,0,0,0); else { OP_ASSERT(col_ref == CSS_COLOR_invert || col_ref == CSS_COLOR_inherit || col_ref == CSS_COLOR_current_color || col_ref == USE_DEFAULT_COLOR); return USE_DEFAULT_COLOR; } } COLORREF InterpolatePremultipliedRGBA(COLORREF from, COLORREF to, double point) { int from_r = OP_GET_R_VALUE(from); int from_g = OP_GET_G_VALUE(from); int from_b = OP_GET_B_VALUE(from); int from_a = OP_GET_A_VALUE(from); int to_r = OP_GET_R_VALUE(to); int to_g = OP_GET_G_VALUE(to); int to_b = OP_GET_B_VALUE(to); int to_a = OP_GET_A_VALUE(to); /* In premultiplied space, the point |t| is: rgba( ((1-t)r1*a1 + t*r2*a2) / a3, ((1-t)g1*a1 + t*g2*a2) / a3, ((1-t)b1*a1 + t*b2*a2) / a3, a3) where a3 = (1-t)*a1 + t*a2. */ double mult_1 = (1-point) * from_a; double mult_2 = point * to_a; double a3 = mult_1 + mult_2; to_r = a3 == 0 ? 0 : static_cast<int>(OpRound((mult_1*from_r + mult_2*to_r) / a3)); to_g = a3 == 0 ? 0 : static_cast<int>(OpRound((mult_1*from_g + mult_2*to_g) / a3)); to_b = a3 == 0 ? 0 : static_cast<int>(OpRound((mult_1*from_b + mult_2*to_b) / a3)); to_a = static_cast<int>(OpRound(a3)); return OP_RGBA(to_r, to_g, to_b, to_a); }
// // include: normal_estimation.h // // last update: '18.xx.xx // author: matchey // // memo: // #ifndef NORMAL_ESTIMATION_H #define NORMAL_ESTIMATION_H #include <Eigen/Core> #include "perfect_velodyne/point_types.h" namespace perfect_velodyne { using VPoint = PointXYZIRNormal; using VPointCloud = pcl::PointCloud<VPoint>; using VPointCloudPtr = VPointCloud::Ptr; using PointT = pcl::PointXYZ; using PointCloud = pcl::PointCloud<PointT>; using PointCloudPtr = PointCloud::Ptr; class NormalEstimator { public: NormalEstimator(); void normalSetter(VPointCloudPtr&); // calc normal with singular value decomposition private: bool getNeighbors(const int&, PointCloudPtr&); void showNeighbor(const int&); size_t getIndex(const size_t&); int num_vertical; // vertical num for PCA int num_horizontal; // horizontal num for PCA bool flag_omp; // whether to use OpenMP const int num_lasers; // HDL32e -> 32 VPointCloudPtr vpc; // input pointcloud size_t npoints; //number of input points }; } // namespace perfect_velodyne #endif
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_BITMAP_INTERFACE_H_ #define BAJKA_BITMAP_INTERFACE_H_ #include <Object.h> #include "../../geometry/Box.h" namespace View { /** * Czyste dane bitmapowe - żadnego renderowania. */ class IBitmap : public Core::Object { public: virtual ~IBitmap () {} /** * Format danych RGBA 8888. */ virtual void *getData () = 0; virtual int getWidth () const = 0; virtual int getHeight () const = 0; /** * Tworzy nową, pustą bitmapę o rozmiarach destW x destH. Następnie kopiuje do niej * obszar srcRect z tej (this) bitmapy i wkleja go w górnym lewym rogu. * - Jeśli srcRect jest null, to kopiowany jest cały obszar źródłowej (tej) bitmapy. * - Jeśli destW jest równe -1, to domyślnie zostanie uzyta szerokość prostokąta źródłowego. * - Jeśli destH jest równe -1, to domyślnie zostanie uzyta wysokość prostokąta źródłowego. */ virtual Ptr <IBitmap> blit (Geometry::Box const *srcRect = NULL, int destW = -1, int destH = -1) = 0; // virtual IBitmap *blit (IBitmap *dest, Geometry::Box const *srcRect = NULL, int destW = -1, int destH = -1) = 0; }; } /* namespace View */ #endif /* BITMAP_H_ */
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; bool btw(int x, int y, int z) { return abs(x - y) + abs(x - z) == abs(y - z); } int n; int sf, sx, sy; int ff; int was[5555]; struct Tp { int x, y, s, f; } a[5555]; double Dist(int x, int y, int xx, int yy) { return sqrtl((x - xx) * (x - xx) + (y - yy) * (y - yy)); } double D[5555]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d", &n); scanf("%d%d", &sf, &ff); scanf("%d%d", &sx, &sy); if (sf == ff) { puts("0"); return 0; } for (int i = 0; i < n; ++i) { scanf("%d%d%d%d", &a[i].x, &a[i].y, &a[i].s, &a[i].f); if (btw(sf, a[i].s, a[i].f) && sx == a[i].x && sy == a[i].y) sf = a[i].f; } for (int i = 0; i < n; ++i) D[i] = 1e100; for (int i = 0; i < n; ++i) if (btw(sf, a[i].s, a[i].f)) { D[i] = Dist(a[i].x, a[i].y, sx, sy); } while (true) { double mi = 1e100; int mii = -1; for (int j = 0; j < n; ++j) if (!was[j] && D[j] < mi) { mi = D[j]; mii = j; } if (mii == -1) break; if (a[mii].f == ff) { cout.precision(12); cout << fixed; cout << mi << endl; return 0; } was[mii] = true; for (int j = 0; j < n; ++j) if (!was[j] && btw(a[mii].f, a[j].s, a[j].f)) { double dd = mi + Dist(a[mii].x, a[mii].y, a[j].x, a[j].y); if (dd < D[j]) D[j] = dd; } } puts("-1"); return 0; }
#ifndef VnaTimeSweep_H #define VnaTimeSweep_H // RsaToolbox #include "Definitions.h" // Etc // Qt #include <QObject> #include <QScopedPointer> namespace RsaToolbox { class Vna; class VnaChannel; class VnaTimeSweep : public QObject { Q_OBJECT public: explicit VnaTimeSweep(QObject *parent = 0); VnaTimeSweep(VnaTimeSweep &other); VnaTimeSweep(Vna *vna, VnaChannel *channel, QObject *parent = 0); VnaTimeSweep(Vna *vna, uint channelIndex, QObject *parent = 0); ~VnaTimeSweep(); uint points(); void setPoints(uint numberOfPoints); double frequency_Hz(); void setFrequency(double frequency, SiPrefix prefix = SiPrefix::None); double power_dBm(); void setPower(double power_dBm); double ifBandwidth_Hz(); void setIfBandwidth(double bandwidth, SiPrefix prefix = SiPrefix::None); double time_s(); void setTime(double time, SiPrefix prefix = SiPrefix::None); void operator=(VnaTimeSweep const &other); // void moveToThread(QThread *thread); private: Vna *_vna; QScopedPointer<Vna> placeholder; QScopedPointer<VnaChannel> _channel; uint _channelIndex; bool isFullyInitialized() const; }; } #endif // VnaTimeSweep_H
#ifndef PERL_REGEX #define PERL_REGEX #include <string> #include <boost/regex/icu.hpp> #include <boost/container_hash/hash.hpp> namespace moses { namespace tokenizer { typedef UChar32 char_type; typedef std::vector<char_type> string_type; void StrToUChar(std::string const &str, string_type &vec); void UCharToStr(string_type const &vec, std::string &str); string_type StrToUChar(std::string const &str); // handy class ReplaceOp { public: ReplaceOp(std::string const &pattern, std::string const &replacement, std::string const &original_pattern); ReplaceOp(std::string const &pattern, std::string const &replacement); void operator()(string_type &text, string_type &out) const; private: std::string pattern_; boost::u32regex regex_; std::string replacement_; }; class SearchOp { public: SearchOp(std::string const &pattern); bool operator()(string_type const &text) const; private: boost::u32regex regex_; }; template <typename... T> struct ChainOp { inline void operator()(string_type &text, string_type &out) const { std::swap(text, out); } }; template <typename T, typename... R> struct ChainOp<T, R...> { ChainOp(T&& op, R&& ...rest) : op(op), rest(std::forward<R>(rest)...) { // }; inline void operator()(string_type &text, string_type &out) const { op(text, out); std::swap(text, out); rest(text, out); } T op; ChainOp<R...> rest; }; template <typename Init, typename Cond, typename Op, typename Fin> struct LoopOp { Init initial; Cond condition; Op operation; Fin finalize; LoopOp(Init initial, Cond condition, Op operation, Fin finalize) : initial(initial) , condition(condition) , operation(operation) , finalize(finalize) { // } void operator()(string_type &text, string_type &out) const { initial(text, out); std::swap(out, text); while (condition(text)) { operation(text, out); std::swap(out, text); } finalize(text, out); } }; struct Noop { void operator()(string_type &text, string_type &out) const { std::swap(text, out); } }; /** * Shortcuts */ SearchOp Search(const std::string &pattern); ReplaceOp Replace(const std::string &pattern, const std::string &replacement); template <typename... T> ChainOp<T...> Chain(T&&... args) { return ChainOp<T...>(std::forward<T>(args)...); } template <typename Init, typename Cond, typename Op, typename Fin> LoopOp<Init, Cond, Op, Fin> Loop(Init initial, Cond condition, Op operation, Fin finalize) { return LoopOp<Init, Cond, Op, Fin>(initial, condition, operation, finalize); } } } // enc namespace namespace std { template<> struct hash<moses::tokenizer::string_type> { std::size_t operator()(moses::tokenizer::string_type const &str) const { std::size_t seed = 0; for (auto chr : str) boost::hash_combine(seed, chr); return seed; } }; } #endif
#include "view.h" #include <QDebug> #include <QMouseEvent> #include <QtMath> View::View(Scene* scene) { this->scene = scene; setScene(scene); centerOn(0, 0); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setFrameStyle(0); // Оставить для маски //setMask(QRegion(QRect(100, 100, 200, 200))); scaleAnimationTimeLine = new QTimeLine(400, this); scaleAnimationTimeLine->setUpdateInterval(20); connect(scaleAnimationTimeLine, &QTimeLine::valueChanged, this, &View::processScaling); } void View::changeCenterOn(const QVariant& value) { if (value.type() == QVariant::Invalid) { return; } clearMask(); QPointF scenePoint = value.toPointF(); centerOn(value.toPointF()); scene->invalidate(scenePoint.x() - 350, scenePoint.y() - 350, 700, 700); // Оставить для маски //QPointF viewPoint = mapFromScene(scenePoint); //setMask(QRegion(viewPoint.x() - 350, viewPoint.y() - 350, 700, 700, QRegion::Ellipse)); } void View::wheelEvent(QWheelEvent *event) { if (scaleAnimationTimeLine->state() == QTimeLine::Running) { scaleAnimationTimeLine->stop(); } int numDegrees = event->angleDelta().y() / 8; int numSteps = numDegrees / 15; if (numScheduledScalings * numSteps < 0) { numScheduledScalings = numSteps; } scaleAnimationTimeLine->start(); } void View::processScaling() { qreal factor = 1.0 + qreal(numScheduledScalings) / 200.0; scale(factor, factor); }
#include "MetaDataCache.hpp" using namespace Elysium::Data::Description; Elysium::Data::Caching::MetaDataCache::MetaDataCache() : Elysium::Core::Object() { } Elysium::Data::Caching::MetaDataCache::~MetaDataCache() { } void Elysium::Data::Caching::MetaDataCache::Register(EntityDescriptor * EntityDescriptor) { /* if (EntityDescriptor == nullptr) { throw ArgumentNullException("EntityDescriptor"); } */ _EntityDescriptorMap[EntityDescriptor->Namespace + "." + EntityDescriptor->InternalName] = *EntityDescriptor; } std::vector<std::string> Elysium::Data::Caching::MetaDataCache::GetEntityNames() { std::vector<std::string> EntityNames; for (std::map<std::string, EntityDescriptor>::iterator Iterator = _EntityDescriptorMap.begin(); Iterator != _EntityDescriptorMap.end(); ++Iterator) { EntityNames.push_back(Iterator->first); } return EntityNames; } Elysium::Data::Description::EntityDescriptor Elysium::Data::Caching::MetaDataCache::GetEntityDescriptor(std::string * Name) { return _EntityDescriptorMap[*Name]; }
#ifndef CMESSAGEFACTORY_H #define CMESSAGEFACTORY_H #include "../SMonitorServer/CNetMessage.h" #include <QObject> #include "CMessageEventMediator.h" class CNetClt; class CMessage; class CLogininMessage; class CRegisterIdMessage; class CMessageEventMediator; class CRequestXmlMessage; class CModifyIdMessage; class CSoftInstallMessage; class CRequestHelpInfoMessage; class CDistributeMessage; class CRequestMsgMessage; class CSoftUploadMessage; class CMessageFactory : public QObject { Q_OBJECT public: CMessageFactory(CMessageEventMediator* pMessageEventMediator, CNetClt* pNet, QObject *parent = 0); ~CMessageFactory(); //发送消息 virtual bool sendMessage(const MsgHead msgHead, bool bSendAnsyc); //处理消息 virtual bool treatMessage(const NetMessage& netMessage); protected: //分发消息 CMessage* dispatchMessage(MsgHead msgHead); void Init(); void Clear(); protected: CLogininMessage* m_pLogininMessage; CRegisterIdMessage* m_pRegisterMessage; CRequestXmlMessage* m_pRequestXmlMessage; CModifyIdMessage* m_pModifyIdMessage; CSoftInstallMessage* m_pSoftInstallMessage; CRequestHelpInfoMessage* m_pRequestHelpInfoMessage; CDistributeMessage* m_pDistributeMessage; CRequestMsgMessage* m_pRequestMsgMessage; CSoftUploadMessage* m_pSoftUploadMessage; private: CNetClt* m_pNet; CMessageEventMediator* m_pMessageEventMediator; }; #endif // CMESSAGEFACTORY_H
#include <iostream> #include <vector> using namespace std; //write your class here //the class should be named "ArrayPQ" template <typename T> class ArrayPQ { protected: vector<T> x; public: size_t size() {return x.size(); } bool empty() {return x.empty(); } T top() {return x.back(); } void pop() {x.pop_back(); } void push(const T& value) { //write your code here //x.push_back(value); //sort(x.begin(),x.end()); // <---- this is O(n lg n) // for (int i = 0;i < size()-1;i++) { // if ((value > x[i]) && (value < x[i+1])) { // x.insert(x.begin() + i + 1,value); // // } // bool added = false; // for (int i = 0;i < size();i++) { // if (value <= x[i]) { // x.insert(x.begin()+i,value); // added = true; // break; // } // } // if (added == false) { // x.push_back(value); // // } auto it = x.begin(); while (it != x.end()); { if (value < *it) { break; } it++; } x.insert(it,value); } }; int main() { ArrayPQ<int> p; p.push(1); p.push(10); p.push(5); p.push(3); while (p.empty() == false) { cout << "Size = " << p.size() << " top = " << p.top() << endl; p.pop(); } }
#include "TcpServer.h" namespace chatty { namespace net { void TcpServer::start() { // acceptor_.bind(); acceptor_.listen(); // acceptor_.setRead acceptChannel_(acceptor.fd()); acceptChannel_.setReadCallBack(std::bind(&acceptor::accept, this)); } } // namespace net } // namespace chatty
// Created on: 1993-08-11 // Created by: Bruno DUMORTIER // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ProjLib_HeaderFile #define _ProjLib_HeaderFile #include <Adaptor3d_Surface.hxx> #include <Geom2d_Curve.hxx> class gp_Pnt2d; class gp_Pln; class gp_Pnt; class gp_Lin2d; class gp_Lin; class gp_Circ2d; class gp_Circ; class gp_Elips2d; class gp_Elips; class gp_Parab2d; class gp_Parab; class gp_Hypr2d; class gp_Hypr; class gp_Cylinder; class gp_Cone; class gp_Sphere; class gp_Torus; class ProjLib_ProjectedCurve; //! The ProjLib package first provides projection of curves on a plane along a given Direction. //! The result will be a 3D curve. //! //! The ProjLib package provides projection of curves on surfaces to compute the curve in the parametric space. //! It is assumed that the curve is on the surface. //! //! It provides: //! //! * Package methods to handle the easiest cases: //! - Line, Circle, Ellipse, Parabola, Hyperbola on plane. //! - Line, Circle on cylinder. //! - Line, Circle on cone. //! //! * Classes to handle the general cases: //! - Plane. //! - Cylinder. //! - Cone. //! - Sphere. //! - Torus. //! //! * A generic class to handle a Adaptor3d_Curve on a Adaptor3d_Surface. class ProjLib { public: DEFINE_STANDARD_ALLOC Standard_EXPORT static gp_Pnt2d Project (const gp_Pln& Pl, const gp_Pnt& P); Standard_EXPORT static gp_Lin2d Project (const gp_Pln& Pl, const gp_Lin& L); Standard_EXPORT static gp_Circ2d Project (const gp_Pln& Pl, const gp_Circ& C); Standard_EXPORT static gp_Elips2d Project (const gp_Pln& Pl, const gp_Elips& E); Standard_EXPORT static gp_Parab2d Project (const gp_Pln& Pl, const gp_Parab& P); Standard_EXPORT static gp_Hypr2d Project (const gp_Pln& Pl, const gp_Hypr& H); Standard_EXPORT static gp_Pnt2d Project (const gp_Cylinder& Cy, const gp_Pnt& P); Standard_EXPORT static gp_Lin2d Project (const gp_Cylinder& Cy, const gp_Lin& L); Standard_EXPORT static gp_Lin2d Project (const gp_Cylinder& Cy, const gp_Circ& Ci); Standard_EXPORT static gp_Pnt2d Project (const gp_Cone& Co, const gp_Pnt& P); Standard_EXPORT static gp_Lin2d Project (const gp_Cone& Co, const gp_Lin& L); Standard_EXPORT static gp_Lin2d Project (const gp_Cone& Co, const gp_Circ& Ci); Standard_EXPORT static gp_Pnt2d Project (const gp_Sphere& Sp, const gp_Pnt& P); Standard_EXPORT static gp_Lin2d Project (const gp_Sphere& Sp, const gp_Circ& Ci); Standard_EXPORT static gp_Pnt2d Project (const gp_Torus& To, const gp_Pnt& P); Standard_EXPORT static gp_Lin2d Project (const gp_Torus& To, const gp_Circ& Ci); //! Make empty P-Curve <aC> of relevant to <PC> type Standard_EXPORT static void MakePCurveOfType (const ProjLib_ProjectedCurve& PC, Handle(Geom2d_Curve)& aC); //! Returns "true" if surface is analytical, that is it can be //! Plane, Cylinder, Cone, Sphere, Torus. //! For all other types of surface method returns "false". Standard_EXPORT static Standard_Boolean IsAnaSurf (const Handle(Adaptor3d_Surface)& theAS); }; #endif // _ProjLib_HeaderFile
#pragma once #include <iberbar/RHI/D3D11/Headers.h> #include <iberbar/RHI/Types.h> namespace iberbar { namespace RHI { namespace D3D11 { class CDevice; class CStateCache { public: CStateCache( CDevice* pDevice ); ~CStateCache(); void SetBlendFactor( const float Factor[4], uint32 SamplerMask ); void SetBlendState( ID3D11BlendState* pD3DBlendState, const float Factor[4], uint32 SamplerMask ); void SetDepthStencilState( ID3D11DepthStencilState* pD3DDepthStencilState, uint32 Ref ); void SetVertexShader( ID3D11VertexShader* pShader ); void SetPixelShader( ID3D11PixelShader* pShader ); void SetGeometryShader( ID3D11GeometryShader* pShader ); void SetDomainShader( ID3D11DomainShader* pShader ); void SetHullShader( ID3D11HullShader* pShader ); void SetComputeShader( ID3D11ComputeShader* pShader ); void SetConstantBuffer( ID3D11Buffer* pConstantBuffer, EShaderType nShaderType, uint32 nSlotIndex ); void ClearConstantBuffers( EShaderType nShaderType ); void SetInputLayout( ID3D11InputLayout* pInputLayout ); void SetStreamStrides( const uint32 nStrides[ MaxVertexElementCount ] ); void SetStreamSource( ID3D11Buffer* pVertexBuffer, uint32 nStreamIndex, uint32 nOffset ); void SetStreamSource( ID3D11Buffer* pVertexBuffer, uint32 nStreamIndex, uint32 nStride, uint32 nOffset ); void SetIndexBuffer( ID3D11Buffer* pIndexBuffer, DXGI_FORMAT Format, uint32 Offset ); void SetShaderResourceView( ID3D11ShaderResourceView* pD3DSRV, EShaderType nShaderType, uint32 nResourceIndex ); void SetSamplerState( ID3D11SamplerState* pD3DSamplerState, EShaderType nShaderType, uint32 nSamplerIndex ); protected: void InternalSetSetConstantBuffer( EShaderType nShaderType, uint32 SlotIndex, ID3D11Buffer*& ConstantBuffer ); protected: ComPtr<ID3D11DeviceContext> m_pD3DDeviceContext; float m_BlendFactor[4]; uint32 m_BlendSampleMask; ComPtr<ID3D11BlendState> m_pD3DBlendState; ID3D11DepthStencilState* m_pD3DDepthStencilState; UINT m_nDepthStencilRef; ID3D11ShaderResourceView* m_D3DShaderResourceViews[ (int)EShaderType::__Count ][ D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ]; ID3D11SamplerState* m_D3DSamplerStates[ (int)EShaderType::__Count ][ D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT ]; ID3D11InputLayout* m_pD3DInputLayout; ID3D11VertexShader* m_pD3DVertexShader; ID3D11PixelShader* m_pD3DPixelShader; ID3D11GeometryShader* m_pD3DGeometryShader; ID3D11DomainShader* m_pD3DDomainShader; ID3D11HullShader* m_pD3DHullShader; ID3D11ComputeShader* m_pD3DComputeShader; UINT m_StreamStrides[ MaxVertexElementCount ]; // Vertex Buffer State struct UVertexBufferState { ID3D11Buffer* pD3DVertexBuffer; UINT nStride; UINT nOffset; } m_VertexBufferStates[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; // Index Buffer State ID3D11Buffer* m_pD3DIndexBuffer; DXGI_FORMAT m_nIndexFormat; UINT m_nIndexOffset; // Constant Buffer State struct UConstantBufferState { ID3D11Buffer* Buffer; uint32 FirstConstant; uint32 NumConstants; } m_ConstantBufferStates[ (int)EShaderType::__Count ][ D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ]; }; } } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetBlendFactor( const float Factor[4], uint32 SamplerMask ) { if ( memcmp( m_BlendFactor, Factor, sizeof( m_BlendFactor ) ) == 0 && m_BlendSampleMask == SamplerMask ) return; memcpy_s( m_BlendFactor, sizeof( m_BlendFactor ), Factor, sizeof( m_BlendFactor ) ); m_BlendSampleMask = SamplerMask; m_pD3DDeviceContext->OMSetBlendState( m_pD3DBlendState.Get(), m_BlendFactor, m_BlendSampleMask ); } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetBlendState( ID3D11BlendState* pD3DBlendState, const float Factor[4], uint32 SamplerMask ) { if ( m_pD3DBlendState.Get() == pD3DBlendState && memcmp( m_BlendFactor, Factor, sizeof( m_BlendFactor ) ) == 0 && m_BlendSampleMask == SamplerMask ) return; m_pD3DBlendState = pD3DBlendState; memcpy_s( m_BlendFactor, sizeof( m_BlendFactor ), Factor, sizeof( m_BlendFactor ) ); m_BlendSampleMask = SamplerMask; m_pD3DDeviceContext->OMSetBlendState( m_pD3DBlendState.Get(), m_BlendFactor, m_BlendSampleMask ); } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetDepthStencilState( ID3D11DepthStencilState* pD3DDepthStencilState, uint32 nStencilRef ) { if ( m_pD3DDepthStencilState != pD3DDepthStencilState || m_nDepthStencilRef != nStencilRef ) { m_pD3DDepthStencilState = pD3DDepthStencilState; m_nDepthStencilRef = nStencilRef; m_pD3DDeviceContext->OMSetDepthStencilState( m_pD3DDepthStencilState, m_nDepthStencilRef ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetVertexShader( ID3D11VertexShader* pShader ) { if ( m_pD3DVertexShader != pShader ) { m_pD3DVertexShader = pShader; m_pD3DDeviceContext->VSSetShader( m_pD3DVertexShader, nullptr, 0 ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetPixelShader( ID3D11PixelShader* pShader ) { if ( m_pD3DPixelShader != pShader ) { m_pD3DPixelShader = pShader; m_pD3DDeviceContext->PSSetShader( m_pD3DPixelShader, nullptr, 0 ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetGeometryShader( ID3D11GeometryShader* pShader ) { if ( m_pD3DGeometryShader != pShader ) { m_pD3DGeometryShader = pShader; m_pD3DDeviceContext->GSSetShader( m_pD3DGeometryShader, nullptr, 0 ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetDomainShader( ID3D11DomainShader* pShader ) { if ( m_pD3DDomainShader != pShader ) { m_pD3DDomainShader = pShader; m_pD3DDeviceContext->DSSetShader( m_pD3DDomainShader, nullptr, 0 ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetHullShader( ID3D11HullShader* pShader ) { if ( m_pD3DHullShader != pShader ) { m_pD3DHullShader = pShader; m_pD3DDeviceContext->HSSetShader( m_pD3DHullShader, nullptr, 0 ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetComputeShader( ID3D11ComputeShader* pShader ) { if ( m_pD3DComputeShader != pShader ) { m_pD3DComputeShader = pShader; m_pD3DDeviceContext->CSSetShader( m_pD3DComputeShader, nullptr, 0 ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetConstantBuffer( ID3D11Buffer* pConstantBuffer, EShaderType nShaderType, uint32 nSlotIndex ) { UConstantBufferState& Slot = m_ConstantBufferStates[ (int)nShaderType ][ nSlotIndex ]; if ( Slot.Buffer != pConstantBuffer ) { Slot.Buffer = pConstantBuffer; Slot.FirstConstant = 0; Slot.NumConstants = D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT; InternalSetSetConstantBuffer( nShaderType, nSlotIndex, Slot.Buffer ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::ClearConstantBuffers( EShaderType nShaderType ) { memset( m_ConstantBufferStates[(int)nShaderType], 0, sizeof( UConstantBufferState ) * D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ); ID3D11Buffer* Empty[D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT] = { 0 }; switch ( nShaderType ) { case EShaderType::VertexShader: m_pD3DDeviceContext->VSSetConstantBuffers( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, Empty ); break; case EShaderType::HullShader: m_pD3DDeviceContext->HSSetConstantBuffers( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, Empty ); break; case EShaderType::DomainShader: m_pD3DDeviceContext->DSSetConstantBuffers( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, Empty ); break; case EShaderType::GeometryShader: m_pD3DDeviceContext->GSSetConstantBuffers( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, Empty ); break; case EShaderType::PixelShader: m_pD3DDeviceContext->PSSetConstantBuffers( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, Empty ); break; case EShaderType::ComputeShader: m_pD3DDeviceContext->CSSetConstantBuffers( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, Empty ); break; } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetInputLayout( ID3D11InputLayout* pInputLayout ) { if ( m_pD3DInputLayout != pInputLayout ) { m_pD3DInputLayout = pInputLayout; m_pD3DDeviceContext->IASetInputLayout( pInputLayout ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetStreamStrides( const uint32 Strides[MaxVertexElementCount] ) { memcpy_s( m_StreamStrides, sizeof( m_StreamStrides ), Strides, sizeof( m_StreamStrides ) ); } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetStreamSource( ID3D11Buffer* pVertexBuffer, uint32 nStreamIndex, uint32 nOffset ) { SetStreamSource( pVertexBuffer, nStreamIndex, m_StreamStrides[nStreamIndex], nOffset ); } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetStreamSource( ID3D11Buffer* pVertexBuffer, uint32 nStreamIndex, uint32 nStride, uint32 nOffset ) { assert( nStride == m_StreamStrides[nStreamIndex] ); assert( nStreamIndex < D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ); UVertexBufferState& Slot = m_VertexBufferStates[nStreamIndex]; if ( Slot.pD3DVertexBuffer != pVertexBuffer || Slot.nStride != nStride || Slot.nOffset != nOffset ) { Slot.pD3DVertexBuffer = pVertexBuffer; Slot.nStride = nStride; Slot.nOffset = nOffset; m_pD3DDeviceContext->IASetVertexBuffers( nStreamIndex, 1, &Slot.pD3DVertexBuffer, &Slot.nStride, &Slot.nOffset ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetIndexBuffer( ID3D11Buffer* pIndexBuffer, DXGI_FORMAT Format, uint32 Offset ) { if ( m_pD3DIndexBuffer != pIndexBuffer || m_nIndexFormat != Format || m_nIndexOffset != Offset ) { m_pD3DIndexBuffer = pIndexBuffer; m_nIndexFormat = Format; m_nIndexOffset = Offset; m_pD3DDeviceContext->IASetIndexBuffer( m_pD3DIndexBuffer, m_nIndexFormat, m_nIndexOffset ); } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetShaderResourceView( ID3D11ShaderResourceView* pD3DSRV, EShaderType nShaderType, uint32 nResourceIndex ) { assert( nResourceIndex < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ); ID3D11ShaderResourceView* pD3DSRV_Current = m_D3DShaderResourceViews[ (int)nShaderType ][ nResourceIndex ]; if ( pD3DSRV_Current != pD3DSRV ) { if ( pD3DSRV_Current ) { pD3DSRV_Current->Release(); } m_D3DShaderResourceViews[ (int)nShaderType ][ nResourceIndex ] = pD3DSRV; if ( pD3DSRV ) { pD3DSRV->AddRef(); } switch ( nShaderType ) { case EShaderType::VertexShader: m_pD3DDeviceContext->VSSetShaderResources( nResourceIndex, 1, &pD3DSRV ); break; case EShaderType::PixelShader: m_pD3DDeviceContext->PSSetShaderResources( nResourceIndex, 1, &pD3DSRV ); break; case EShaderType::GeometryShader: m_pD3DDeviceContext->GSSetShaderResources( nResourceIndex, 1, &pD3DSRV ); break; case EShaderType::DomainShader: m_pD3DDeviceContext->DSSetShaderResources( nResourceIndex, 1, &pD3DSRV ); break; case EShaderType::HullShader: m_pD3DDeviceContext->HSSetShaderResources( nResourceIndex, 1, &pD3DSRV ); break; case EShaderType::ComputeShader: m_pD3DDeviceContext->CSSetShaderResources( nResourceIndex, 1, &pD3DSRV ); break; } } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::SetSamplerState( ID3D11SamplerState* pD3DSamplerState, EShaderType nShaderType, uint32 nSamplerIndex ) { assert( nSamplerIndex < D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT ); if ( m_D3DSamplerStates[ (int)nShaderType ][ nSamplerIndex ] != pD3DSamplerState ) { m_D3DSamplerStates[ (int)nShaderType ][ nSamplerIndex ] = pD3DSamplerState; switch ( nShaderType ) { case EShaderType::VertexShader: m_pD3DDeviceContext->VSSetSamplers( nSamplerIndex, 1, &pD3DSamplerState ); break; case EShaderType::PixelShader: m_pD3DDeviceContext->PSSetSamplers( nSamplerIndex, 1, &pD3DSamplerState ); break; case EShaderType::GeometryShader: m_pD3DDeviceContext->GSSetSamplers( nSamplerIndex, 1, &pD3DSamplerState ); break; case EShaderType::DomainShader: m_pD3DDeviceContext->DSSetSamplers( nSamplerIndex, 1, &pD3DSamplerState ); break; case EShaderType::HullShader: m_pD3DDeviceContext->HSSetSamplers( nSamplerIndex, 1, &pD3DSamplerState ); break; case EShaderType::ComputeShader: m_pD3DDeviceContext->CSSetSamplers( nSamplerIndex, 1, &pD3DSamplerState ); break; } } } FORCEINLINE void iberbar::RHI::D3D11::CStateCache::InternalSetSetConstantBuffer( EShaderType nShaderType, uint32 SlotIndex, ID3D11Buffer*& ConstantBuffer ) { switch ( nShaderType ) { case EShaderType::VertexShader: m_pD3DDeviceContext->VSSetConstantBuffers( SlotIndex, 1, &ConstantBuffer ); break; case EShaderType::HullShader: m_pD3DDeviceContext->HSSetConstantBuffers( SlotIndex, 1, &ConstantBuffer ); break; case EShaderType::DomainShader: m_pD3DDeviceContext->DSSetConstantBuffers( SlotIndex, 1, &ConstantBuffer ); break; case EShaderType::GeometryShader: m_pD3DDeviceContext->GSSetConstantBuffers( SlotIndex, 1, &ConstantBuffer ); break; case EShaderType::PixelShader: m_pD3DDeviceContext->PSSetConstantBuffers( SlotIndex, 1, &ConstantBuffer ); break; case EShaderType::ComputeShader: m_pD3DDeviceContext->CSSetConstantBuffers( SlotIndex, 1, &ConstantBuffer ); break; } }
#include "stdafx.h" #include <SFML/Graphics.hpp> #include "map.h" #include "View.h" #include <sstream> #include <string> #include "mission.h" #include <iostream> using namespace sf; class Player { // класс Игрока private: float x, y; public: float w, h, dx, dy, speed; //координаты игрока х и у, высота ширина, ускорение (по х и по у), сама скорость int dir, playerScore, health; //направление (direction) движения игрока String File; //файл с расширением Image image;//сфмл изображение Texture texture;//сфмл текстура Sprite sprite;//сфмл спрайт bool life;//переменная жизнь, логическая Player(String F, float X, float Y, float W, float H) { //Конструктор с параметрами(формальными) для класса Player. При создании объекта класса мы будем задавать имя файла, координату Х и У, ширину и высоту playerScore = 0; dy = 0; speed = 0; dir = 0; health = 100; File = F;//имя файла+расширение w = W; h = H;//высота и ширина image.loadFromFile("images/" + File);//запихиваем в image наше изображение вместо File мы передадим то, что пропишем при создании объекта. В нашем случае "hero.png" и получится запись идентичная image.loadFromFile("images/hero/png"); image.createMaskFromColor(Color(41, 33, 59));//убираем ненужный темно-синий цвет, эта тень мне показалась не красивой. texture.loadFromImage(image);//закидываем наше изображение в текстуру sprite.setTexture(texture);//заливаем спрайт текстурой x = X; y = Y;//координата появления спрайта sprite.setTextureRect(IntRect(0, 0, w, h)); //Задаем спрайту один прямоугольник для вывода одного льва, а не кучи львов сразу. IntRect - приведение типов } void update(float time) //функция "оживления" объекта класса. update - обновление. принимает в себя время SFML , вследствие чего работает бесконечно, давая персонажу движение. { switch (dir)//реализуем поведение в зависимости от направления. (каждая цифра соответствует направлению) { case 0: dx = speed; dy = 0; break;//по иксу задаем положительную скорость, по игреку зануляем. получаем, что персонаж идет только вправо case 1: dx = -speed; dy = 0; break;//по иксу задаем отрицательную скорость, по игреку зануляем. получается, что персонаж идет только влево case 2: dx = 0; dy = speed; break;//по иксу задаем нулевое значение, по игреку положительное. получается, что персонаж идет только вниз case 3: dx = 0; dy = -speed; break;//по иксу задаем нулевое значение, по игреку отрицательное. получается, что персонаж идет только вверх } x += dx*time;//то движение из прошлого урока. наше ускорение на время получаем смещение координат и как следствие движение y += dy*time;//аналогично по игреку speed = 0;//зануляем скорость, чтобы персонаж остановился. sprite.setPosition(x, y); //выводим спрайт в позицию x y , посередине. бесконечно выводим в этой функции, иначе бы наш спрайт стоял на месте. interactionWithMap(); if (health <= 0) { life = false; speed = 0; } } float getplayercoordinateX() { //этим методом будем забирать координату Х return x; } float getplayercoordinateY() { //этим методом будем забирать координату Y return y; } void interactionWithMap()//ф-ция взаимодействия с картой { for (int i = y / 32; i < (y + h) / 32; i++)//проходимся по тайликам, контактирующим с игроком, то есть по всем квадратикам размера 32*32, которые мы окрашивали в 9 уроке. про условия читайте ниже. for (int j = x / 32; j<(x + w) / 32; j++)//икс делим на 32, тем самым получаем левый квадратик, с которым персонаж соприкасается. (он ведь больше размера 32*32, поэтому может одновременно стоять на нескольких квадратах). А j<(x + w) / 32 - условие ограничения координат по иксу. то есть координата самого правого квадрата, который соприкасается с персонажем. таким образом идем в цикле слева направо по иксу, проходя по от левого квадрата (соприкасающегося с героем), до правого квадрата (соприкасающегося с героем) { if (TileMap[i][j] == 'b')//если наш квадратик соответствует символу 0 (стена), то проверяем "направление скорости" персонажа: { if (dy>0)//если мы шли вниз, { y = i * 32 - h;//то стопорим координату игрек персонажа. сначала получаем координату нашего квадратика на карте(стены) и затем вычитаем из высоты спрайта персонажа. } if (dy<0) { y = i * 32 + 32;//аналогично с ходьбой вверх. dy<0, значит мы идем вверх (вспоминаем координаты паинта) } if (dx>0) { x = j * 32 - w;//если идем вправо, то координата Х равна стена (символ 0) минус ширина персонажа } if (dx < 0) { x = j * 32 + 32;//аналогично идем влево } } if (TileMap[i][j] == 's') { //если символ равен 's' (камень) TileMap[i][j] = ' ';//убираем камень playerScore++; } if (TileMap[i][j] == 'f') { health -= 40;//если взяли ядовитейший в мире цветок,то переменная health=health-40; TileMap[i][j] = ' ';//убрали цветок } if (TileMap[i][j] == 'h') { health += 20;//если взяли сердечко,то переменная health=health+20; TileMap[i][j] = ' ';//убрали сердечко } } } }; int main() { RenderWindow window(VideoMode(1280, 720), ""); view.reset(sf::FloatRect(0, 0, 1280, 720));//размер "вида" камеры при создании объекта вида камеры. Clock clock; float time = clock.getElapsedTime().asMicroseconds(); //дать прошедшее время в микросекундах clock.restart(); //перезагружает время //time = time; //скорость игры Font font;//шрифт font.loadFromFile("resources/CyrilicOld.ttf");//передаем нашему шрифту файл шрифта Text text("", font, 20);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка) text.setFillColor(Color::Black);//покрасили текст в красный. если убрать эту строку, то по умолчанию он белый bool showMissionText = true;//логическая переменная, отвечающая за появление текста миссии на экране Image quest_image; quest_image.loadFromFile("images/missionbg.jpg"); quest_image.createMaskFromColor(Color(0, 0, 0)); Texture quest_texture; quest_texture.loadFromImage(quest_image); Sprite s_quest; s_quest.setTexture(quest_texture); s_quest.setTextureRect(IntRect(0, 0, 340, 510)); //приведение типов, размеры картинки исходные s_quest.setScale(0.6f, 0.6f);//чуть уменьшили картинку, => размер стал меньше float CurrentFrame = 0;//хранит текущий кадр Player hero("hero.png", 250, 250, 96.0, 96.0);//создаем объект p класса player,задаем "hero.png" как имя файла+расширение, далее координата Х,У, ширина, высота Image map_image;//объект изображения для карты map_image.loadFromFile("images/map.png");//загружаем файл для карты Texture map;//текстура карты map.loadFromImage(map_image);//заряжаем текстуру картинкой Sprite s_map;//создаём спрайт для карты s_map.setTexture(map);//заливаем текстуру спрайтом randomStoneMapGenerate(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == Event::KeyPressed)//событие нажатия клавиши if ((event.key.code == Keyboard::Tab)) { switch (showMissionText) {//переключатель, реагирующий на логическую переменную showMissionText case true: { text.setString("Здоровье:" + std::to_string(hero.health) + "\n" + getTextMission(getCurrentMission(hero.getplayercoordinateX())));//задаем строку тексту и вызываем сформированную выше строку методом .str() text.setPosition(view.getCenter().x - 165, view.getCenter().y - 200);//задаем позицию текста, отступая от центра камеры s_quest.setPosition(view.getCenter().x + 115, view.getCenter().y - 130);//позиция фона для блока showMissionText = false;//эта строка позволяет убрать все что мы вывели на экране break;//выходим , чтобы не выполнить условие "false" (которое ниже) } case false: { text.setString("");//если не нажата клавиша таб, то весь этот текст пустой showMissionText = true;// а эта строка позволяет снова нажать клавишу таб и получить вывод на экран break; } } } } if (hero.life) { if (Keyboard::isKeyPressed(Keyboard::Left)) { hero.dir = 1; hero.speed = 1.f; CurrentFrame += 0.025*time; if (CurrentFrame > 3) CurrentFrame -= 3; hero.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 96, 96, 96)); } if (Keyboard::isKeyPressed(Keyboard::Right)) { hero.dir = 0; hero.speed = 1.f; CurrentFrame += 0.025*time; if (CurrentFrame > 3) CurrentFrame -= 3; hero.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 192, 96, 96)); } if (Keyboard::isKeyPressed(Keyboard::Up)) { hero.dir = 3; hero.speed = 1.f; CurrentFrame += 0.025*time; if (CurrentFrame > 3) CurrentFrame -= 3; hero.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 307, 96, 96));// } if (Keyboard::isKeyPressed(Keyboard::Down)) { hero.dir = 2; hero.speed = 1.f; CurrentFrame += 0.025*time; if (CurrentFrame > 3) CurrentFrame -= 3; hero.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 0, 96, 96)); } } getplayercoordinateforview(hero.getplayercoordinateX(), hero.getplayercoordinateY()); hero.update(time);//оживляем объект p класса Player с помощью времени sfml, передавая время в качестве параметра функции update. благодаря этому персонаж может двигать window.setView(view); window.clear(); for (int i = 0; i < HEIGHT_MAP; i++) for (int j = 0; j < WIDTH_MAP; j++) { if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(0, 0, 32, 32)); if (TileMap[i][j] == 's') s_map.setTextureRect(IntRect(32, 0, 32, 32)); if ((TileMap[i][j] == 'b')) s_map.setTextureRect(IntRect(64, 0, 32, 32)); if ((TileMap[i][j] == 'h')) s_map.setTextureRect(IntRect(128, 0, 32, 32));//и сердечко s_map.setPosition(j * 32, i * 32); window.draw(s_map);//рисуем квадратики на экран } if (!showMissionText) { text.setPosition(view.getCenter().x + 125, view.getCenter().y - 130);//позиция всего этого текстового блока s_quest.setPosition(view.getCenter().x + 115, view.getCenter().y - 130);//позиция фона для блока window.draw(s_quest); window.draw(text); //рисуем спрайт свитка (фон для текста миссии). а затем и текст. все это завязано на логическую переменную, которая меняет свое состояние от нажатия клавиши ТАБ } window.draw(hero.sprite); if (!hero.life) { text.setString("Игра окончена\n Ваши очки: " + std::to_string(hero.playerScore));//задаем строку тексту и вызываем сформированную выше строку методом .str() text.setPosition(view.getCenter().x, view.getCenter().y);//задаем позицию текста, отступая от центра камеры window.draw(text);//рисую этот текст } window.draw(text);//рисую этот текст window.display(); } return 0; }
#include "../../headers/server/Server.h" int count = 0; void *clientThread(void *arg); void runServer(int port) { int re = 0; int server_sck = socket(AF_INET, SOCK_STREAM, 0); errorHandler(server_sck, (char *)"Initialize server socket failed"); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; memset(addr.sin_zero, '\0', sizeof(addr.sin_zero)); re = bind(server_sck, (sockaddr *)&addr, sizeof(addr)); errorHandler(re, (char *)"Binding failed"); re = listen(server_sck, QUEUE); errorHandler(re, (char *)"Listening failed"); std::vector<pthread_t> tids; int pots_temp_b[5] = {0, 0, 0, 0, 0}; int *pot_pb = (int *)calloc(sizeof(int), 5); pot_pb = pots_temp_b; int pots_temp_p[5] = {0, 0, 0, 0, 0}; int *pot_pp = (int *)calloc(sizeof(int), 5); pot_pp = pots_temp_p; while (true) { ClientData *client = (ClientData *)calloc(sizeof(ClientData), 1); socklen_t clientSize = sizeof(client->addr); client->potsAreBrewing = pot_pb; client->potsArePooring = pot_pp; client->sck = accept(server_sck, (sockaddr *)&client->addr, &clientSize); while (count >= 5) { } pthread_t tid; re = pthread_create(&tid, NULL, clientThread, client); errorHandler(re, (char *)"Create thread failed"); tids.push_back(tid); } } void *clientThread(void *arg) { count++; ClientData *client = (ClientData *)arg; clientHandler(client); count--; pthread_exit(0); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <glog/logging.h> #include <fizz/crypto/Utils.h> #include <folly/init/Init.h> #include <folly/io/async/HHWheelTimer.h> #include <folly/portability/GFlags.h> #include <folly/stats/Histogram.h> #include <quic/QuicConstants.h> #include <quic/client/QuicClientTransport.h> #include <quic/common/test/TestClientUtils.h> #include <quic/common/test/TestUtils.h> #include <quic/congestion_control/ServerCongestionControllerFactory.h> #include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h> #include <quic/server/AcceptObserver.h> #include <quic/server/QuicServer.h> #include <quic/server/QuicServerTransport.h> #include <quic/server/QuicSharedUDPSocketFactory.h> #include <quic/tools/tperf/PacingObserver.h> #include <quic/tools/tperf/TperfDSRSender.h> #include <quic/tools/tperf/TperfQLogger.h> DEFINE_string(host, "::1", "TPerf server hostname/IP"); DEFINE_int32(port, 6666, "TPerf server port"); DEFINE_string(mode, "server", "Mode to run in: 'client' or 'server'"); DEFINE_int32(duration, 10, "Duration of test in seconds"); DEFINE_uint64( block_size, 1024 * 1024, "Amount of data written to stream each iteration"); DEFINE_uint64(writes_per_loop, 44, "Amount of socket writes per event loop"); DEFINE_uint64(window, 1024 * 1024, "Flow control window size"); DEFINE_bool(autotune_window, true, "Automatically increase the receive window"); DEFINE_string(congestion, "cubic", "newreno/cubic/bbr/none"); DEFINE_bool(pacing, false, "Enable pacing"); DEFINE_uint64( max_pacing_rate, std::numeric_limits<uint64_t>::max(), "Max pacing rate to use in bytes per second"); DEFINE_bool(gso, true, "Enable GSO writes to the socket"); DEFINE_uint32( client_transport_timer_resolution_ms, 1, "Timer resolution for Ack and Loss timeout in client transport"); DEFINE_string( server_qlogger_path, "", "Path to the directory where qlog files will be written. File will be named" " as <CID>.qlog where CID is the DCID from client's perspective."); DEFINE_uint32( max_cwnd_mss, quic::kLargeMaxCwndInMss, "Max cwnd in the unit of mss"); DEFINE_uint32(num_streams, 1, "Number of streams to send on simultaneously"); DEFINE_uint64( bytes_per_stream, 0, "Maximum number of bytes per stream. " "0 (the default) means the stream lives for the whole duration of the test."); DEFINE_string( pacing_observer, "none", "none/time/rtt/ack: Pacing observer bucket type: per 3ms, per rtt or per ack"); DEFINE_uint32( max_receive_packet_size, quic::kDefaultMaxUDPPayload, "Maximum packet size to advertise to the peer."); DEFINE_bool( override_packet_size, true, "Sender trusts the peer's advertised max packet size."); DEFINE_bool(use_inplace_write, true, "Data path type"); DEFINE_double(latency_factor, 0.5, "Latency factor (delta) for Copa"); DEFINE_uint32( num_server_worker, 1, "Max number of mvfst server worker threads"); DEFINE_bool(log_rtt_sample, false, "Log rtt sample events"); DEFINE_bool(log_loss, false, "Log packet loss events"); DEFINE_bool(log_app_rate_limited, false, "Log app rate limited events"); DEFINE_string( transport_knob_params, "", "JSON-serialized dictionary of transport knob params"); DEFINE_bool(dsr, false, "if you want to debug perf"); DEFINE_bool( use_ack_receive_timestamps, false, "Replace the ACK frame with ACK_RECEIVE_TIMESTAMPS frame" "which carries the received packet timestamps"); DEFINE_uint32( max_ack_receive_timestamps_to_send, quic::kMaxReceivedPktsTimestampsStored, "Controls how many packet receive timestamps the peer should send"); namespace quic { namespace tperf { namespace { class TPerfObserver : public LegacyObserver { public: using LegacyObserver::LegacyObserver; void appRateLimited( QuicSocket* /* socket */, const quic::SocketObserverInterface:: AppLimitedEvent& /* appLimitedEvent */) override { if (FLAGS_log_app_rate_limited) { LOG(INFO) << "appRateLimited detected"; } } void packetLossDetected( QuicSocket*, /* socket */ const struct LossEvent& /* lossEvent */) override { if (FLAGS_log_loss) { LOG(INFO) << "packetLoss detected"; } } void rttSampleGenerated( QuicSocket*, /* socket */ const PacketRTT& /* RTT sample */) override { if (FLAGS_log_rtt_sample) { LOG(INFO) << "rttSample generated"; } } }; /** * A helper acceptor observer that installs life cycle observers to * transport upon accept */ class TPerfAcceptObserver : public AcceptObserver { public: TPerfAcceptObserver() { // Create an observer config, only enabling events we are interested in // receiving. LegacyObserver::EventSet eventSet; eventSet.enable( SocketObserverInterface::Events::appRateLimitedEvents, SocketObserverInterface::Events::rttSamples, SocketObserverInterface::Events::lossEvents); tperfObserver_ = std::make_unique<TPerfObserver>(eventSet); } void accept(QuicTransportBase* transport) noexcept override { transport->addObserver(tperfObserver_.get()); } void acceptorDestroy(QuicServerWorker* /* worker */) noexcept override { LOG(INFO) << "quic server worker destroyed"; } void observerAttach(QuicServerWorker* /* worker */) noexcept override { LOG(INFO) << "TPerfAcceptObserver attached"; } void observerDetach(QuicServerWorker* /* worker */) noexcept override { LOG(INFO) << "TPerfAcceptObserver detached"; } private: std::unique_ptr<TPerfObserver> tperfObserver_; }; } // namespace class ServerStreamHandler : public quic::QuicSocket::ConnectionSetupCallback, public quic::QuicSocket::ConnectionCallback, public quic::QuicSocket::ReadCallback, public quic::QuicSocket::WriteCallback { public: explicit ServerStreamHandler( folly::EventBase* evbIn, uint64_t blockSize, uint32_t numStreams, uint64_t maxBytesPerStream, QuicAsyncUDPSocketType& sock, bool dsrEnabled) : evb_(evbIn), blockSize_(blockSize), numStreams_(numStreams), maxBytesPerStream_(maxBytesPerStream), udpSock_(sock), dsrEnabled_(dsrEnabled) { buf_ = folly::IOBuf::createCombined(blockSize_); } void setQuicSocket(std::shared_ptr<quic::QuicSocket> socket) { sock_ = socket; } void onNewBidirectionalStream(quic::StreamId id) noexcept override { LOG(INFO) << "Got bidirectional stream id=" << id; sock_->setReadCallback(id, this); } void onNewUnidirectionalStream(quic::StreamId id) noexcept override { LOG(INFO) << "Got unidirectional stream id=" << id; sock_->setReadCallback(id, this); } void onStopSending( quic::StreamId id, quic::ApplicationErrorCode error) noexcept override { LOG(INFO) << "Got StopSending stream id=" << id << " error=" << error; } void onConnectionEnd() noexcept override { LOG(INFO) << "Socket closed"; sock_.reset(); } void onConnectionSetupError(QuicError error) noexcept override { onConnectionError(std::move(error)); } void onConnectionError(QuicError error) noexcept override { LOG(ERROR) << "Conn errorCoded=" << toString(error.code) << ", errorMsg=" << error.message; } void onTransportReady() noexcept override { if (FLAGS_max_pacing_rate != std::numeric_limits<uint64_t>::max()) { sock_->setMaxPacingRate(FLAGS_max_pacing_rate); } LOG(INFO) << "Starting sends to client."; for (uint32_t i = 0; i < numStreams_; i++) { createNewStream(); } } void createNewStream() noexcept { if (!sock_) { VLOG(4) << __func__ << ": socket is closed."; return; } auto stream = sock_->createUnidirectionalStream(); VLOG(5) << "New Stream with id = " << stream.value(); CHECK(stream.hasValue()); bytesPerStream_[stream.value()] = 0; notifyDataForStream(stream.value()); } void notifyDataForStream(quic::StreamId id) { evb_->runInEventBaseThread([&, id]() { if (!sock_) { VLOG(5) << "notifyDataForStream(" << id << "): socket is closed."; return; } auto res = sock_->notifyPendingWriteOnStream(id, this); if (res.hasError()) { LOG(FATAL) << quic::toString(res.error()); } }); } void readAvailable(quic::StreamId id) noexcept override { LOG(INFO) << "read available for stream id=" << id; } void readError(quic::StreamId id, QuicError error) noexcept override { LOG(ERROR) << "Got read error on stream=" << id << " error=" << toString(error); // A read error only terminates the ingress portion of the stream state. // Your application should probably terminate the egress portion via // resetStream } void onStreamWriteReady(quic::StreamId id, uint64_t maxToSend) noexcept override { bool eof = false; uint64_t toSend = std::min<uint64_t>(maxToSend, blockSize_); if (maxBytesPerStream_ > 0) { toSend = std::min<uint64_t>(toSend, maxBytesPerStream_ - bytesPerStream_[id]); bytesPerStream_[id] += toSend; if (bytesPerStream_[id] >= maxBytesPerStream_) { eof = true; } } if (dsrEnabled_ && (((id - 3) / 4) % 2) == 0) { dsrSend(id, toSend, eof); } else { regularSend(id, toSend, eof); } if (!eof) { notifyDataForStream(id); } else { bytesPerStream_.erase(id); createNewStream(); } } void onStreamWriteError(quic::StreamId id, QuicError error) noexcept override { LOG(ERROR) << "write error with stream=" << id << " error=" << toString(error); } folly::EventBase* getEventBase() { return evb_; } private: void dsrSend(quic::StreamId id, uint64_t toSend, bool eof) { if (streamsHavingDSRSender_.find(id) == streamsHavingDSRSender_.end()) { auto dsrSender = std::make_unique<TperfDSRSender>(buf_->clone(), udpSock_); auto serverTransport = dynamic_cast<QuicServerTransport*>(sock_.get()); dsrSender->setCipherInfo(serverTransport->getOneRttCipherInfo()); auto res = sock_->setDSRPacketizationRequestSender(id, std::move(dsrSender)); if (res.hasError()) { LOG(FATAL) << "Got error on write: " << quic::toString(res.error()); } // OK I don't know when to erase it... streamsHavingDSRSender_.insert(id); // Some real data has to be written before BufMeta is written, and we // can only do it once: res = sock_->writeChain(id, folly::IOBuf::copyBuffer("Lame"), false); if (res.hasError()) { LOG(FATAL) << "Got error on write: " << quic::toString(res.error()); } } BufferMeta bufferMeta(toSend); auto res = sock_->writeBufMeta(id, bufferMeta, eof, nullptr); if (res.hasError()) { LOG(FATAL) << "Got error on write: " << quic::toString(res.error()); } } void regularSend(quic::StreamId id, uint64_t toSend, bool eof) { auto sendBuffer = buf_->clone(); sendBuffer->append(toSend); auto res = sock_->writeChain(id, std::move(sendBuffer), eof, nullptr); if (res.hasError()) { LOG(FATAL) << "Got error on write: " << quic::toString(res.error()); } } private: std::shared_ptr<quic::QuicSocket> sock_; folly::EventBase* evb_; uint64_t blockSize_; std::unique_ptr<folly::IOBuf> buf_; uint32_t numStreams_; uint64_t maxBytesPerStream_; std::unordered_map<quic::StreamId, uint64_t> bytesPerStream_; std::set<quic::StreamId> streamsHavingDSRSender_; QuicAsyncUDPSocketType& udpSock_; bool dsrEnabled_; }; class TPerfServerTransportFactory : public quic::QuicServerTransportFactory { public: ~TPerfServerTransportFactory() override = default; explicit TPerfServerTransportFactory( uint64_t blockSize, uint32_t numStreams, uint64_t maxBytesPerStream, bool dsrEnabled) : blockSize_(blockSize), numStreams_(numStreams), maxBytesPerStream_(maxBytesPerStream), dsrEnabled_(dsrEnabled) {} quic::QuicServerTransport::Ptr make( folly::EventBase* evb, std::unique_ptr<QuicAsyncUDPSocketType> sock, const folly::SocketAddress&, QuicVersion, std::shared_ptr<const fizz::server::FizzServerContext> ctx) noexcept override { CHECK_EQ(evb, sock->getEventBase()); auto serverHandler = std::make_unique<ServerStreamHandler>( evb, blockSize_, numStreams_, maxBytesPerStream_, *sock, dsrEnabled_); auto transport = quic::QuicServerTransport::make( evb, std::move(sock), serverHandler.get(), serverHandler.get(), ctx); if (!FLAGS_server_qlogger_path.empty()) { auto qlogger = std::make_shared<TperfQLogger>( VantagePoint::Server, FLAGS_server_qlogger_path); setPacingObserver(qlogger, transport.get(), FLAGS_pacing_observer); transport->setQLogger(std::move(qlogger)); } serverHandler->setQuicSocket(transport); handlers_.push_back(std::move(serverHandler)); return transport; } private: void setPacingObserver( std::shared_ptr<TperfQLogger>& qlogger, quic::QuicServerTransport* transport, const std::string& pacingObserverType) { if (pacingObserverType == "time") { qlogger->setPacingObserver( std::make_unique<FixedBucketQLogPacingObserver>(qlogger, 3ms)); } else if (pacingObserverType == "rtt") { qlogger->setPacingObserver(std::make_unique<RttBucketQLogPacingObserver>( qlogger, *transport->getState())); } else if (pacingObserverType == "ack") { qlogger->setPacingObserver(std::make_unique<QLogPacingObserver>(qlogger)); } } std::vector<std::unique_ptr<ServerStreamHandler>> handlers_; uint64_t blockSize_; uint32_t numStreams_; uint64_t maxBytesPerStream_; bool dsrEnabled_; }; class TPerfServer { public: explicit TPerfServer( const std::string& host, uint16_t port, uint64_t blockSize, uint64_t writesPerLoop, quic::CongestionControlType congestionControlType, bool gso, uint32_t maxCwndInMss, bool pacing, uint32_t numStreams, uint64_t maxBytesPerStream, uint32_t maxReceivePacketSize, bool useInplaceWrite, bool dsrEnabled, bool overridePacketSize) : host_(host), port_(port), acceptObserver_(std::make_unique<TPerfAcceptObserver>()), server_(QuicServer::createQuicServer()) { eventBase_.setName("tperf_server"); server_->setQuicServerTransportFactory( std::make_unique<TPerfServerTransportFactory>( blockSize, numStreams, maxBytesPerStream, dsrEnabled)); auto serverCtx = quic::test::createServerCtx(); serverCtx->setClock(std::make_shared<fizz::SystemClock>()); server_->setFizzContext(serverCtx); quic::TransportSettings settings; if (useInplaceWrite && gso) { settings.dataPathType = DataPathType::ContinuousMemory; } else { settings.dataPathType = DataPathType::ChainedMemory; } settings.maxCwndInMss = maxCwndInMss; settings.writeConnectionDataPacketsLimit = writesPerLoop; settings.defaultCongestionController = congestionControlType; settings.pacingEnabled = pacing; if (pacing) { settings.pacingTickInterval = 200us; settings.writeLimitRttFraction = 0; } if (gso) { settings.batchingMode = QuicBatchingMode::BATCHING_MODE_GSO; settings.maxBatchSize = writesPerLoop; } settings.maxRecvPacketSize = maxReceivePacketSize; settings.canIgnorePathMTU = overridePacketSize; settings.copaDeltaParam = FLAGS_latency_factor; if (FLAGS_use_ack_receive_timestamps) { LOG(INFO) << " Using ACK receive timestamps on server"; settings.maybeAckReceiveTimestampsConfigSentToPeer.assign( {FLAGS_max_ack_receive_timestamps_to_send, kDefaultReceiveTimestampsExponent}); } server_->setCongestionControllerFactory( std::make_shared<ServerCongestionControllerFactory>()); server_->setTransportSettings(settings); } void start() { // Create a SocketAddress and the default or passed in host. folly::SocketAddress addr1(host_.c_str(), port_); addr1.setFromHostPort(host_, port_); server_->start(addr1, FLAGS_num_server_worker); auto workerEvbs = server_->getWorkerEvbs(); for (auto evb : workerEvbs) { server_->addAcceptObserver(evb, acceptObserver_.get()); } LOG(INFO) << "tperf server started at: " << addr1.describe(); eventBase_.loopForever(); } private: std::string host_; uint16_t port_; folly::EventBase eventBase_; std::unique_ptr<TPerfAcceptObserver> acceptObserver_; std::shared_ptr<quic::QuicServer> server_; }; class TPerfClient : public quic::QuicSocket::ConnectionSetupCallback, public quic::QuicSocket::ConnectionCallback, public quic::QuicSocket::ReadCallback, public quic::QuicSocket::WriteCallback, public folly::HHWheelTimer::Callback { public: TPerfClient( const std::string& host, uint16_t port, std::chrono::milliseconds transportTimerResolution, int32_t duration, uint64_t window, bool autotuneWindow, bool gso, quic::CongestionControlType congestionControlType, uint32_t maxReceivePacketSize, bool useInplaceWrite) : host_(host), port_(port), eventBase_(transportTimerResolution), duration_(duration), window_(window), autotuneWindow_(autotuneWindow), gso_(gso), congestionControlType_(congestionControlType), maxReceivePacketSize_(maxReceivePacketSize), useInplaceWrite_(useInplaceWrite) { eventBase_.setName("tperf_client"); } void timeoutExpired() noexcept override { quicClient_->closeNow(folly::none); constexpr double bytesPerMegabit = 131072; LOG(INFO) << "Received " << receivedBytes_ << " bytes in " << duration_.count() << " seconds."; LOG(INFO) << "Overall throughput: " << (receivedBytes_ / bytesPerMegabit) / duration_.count() << "Mb/s"; // Per Stream Stats LOG(INFO) << "Average per Stream throughput: " << ((receivedBytes_ / receivedStreams_) / bytesPerMegabit) / duration_.count() << "Mb/s over " << receivedStreams_ << " streams"; if (receivedStreams_ != 1) { LOG(INFO) << "Histogram per Stream bytes: " << std::endl; LOG(INFO) << "Lo\tHi\tNum\tSum"; for (const auto bytes : bytesPerStream_) { bytesPerStreamHistogram_.addValue(bytes.second); } std::ostringstream os; bytesPerStreamHistogram_.toTSV(os); std::vector<std::string> lines; folly::split('\n', os.str(), lines); for (const auto& line : lines) { LOG(INFO) << line; } LOG(INFO) << "Per stream bytes breakdown: "; for (const auto& [k, v] : bytesPerStream_) { LOG(INFO) << fmt::format("stream: {}, bytes: {}", k, v); } } } virtual void callbackCanceled() noexcept override {} void readAvailable(quic::StreamId streamId) noexcept override { auto readData = quicClient_->read(streamId, 0); if (readData.hasError()) { LOG(FATAL) << "TPerfClient failed read from stream=" << streamId << ", error=" << (uint32_t)readData.error(); } auto readBytes = readData->first->computeChainDataLength(); receivedBytes_ += readBytes; bytesPerStream_[streamId] += readBytes; if (readData.value().second) { bytesPerStreamHistogram_.addValue(bytesPerStream_[streamId]); bytesPerStream_.erase(streamId); } } void readError( quic::StreamId /*streamId*/, QuicError /*error*/) noexcept override { // A read error only terminates the ingress portion of the stream state. // Your application should probably terminate the egress portion via // resetStream } void onNewBidirectionalStream(quic::StreamId id) noexcept override { LOG(INFO) << "TPerfClient: new bidirectional stream=" << id; quicClient_->setReadCallback(id, this); } void onNewUnidirectionalStream(quic::StreamId id) noexcept override { VLOG(5) << "TPerfClient: new unidirectional stream=" << id; if (!timerScheduled_) { timerScheduled_ = true; eventBase_.timer().scheduleTimeout(this, duration_); } quicClient_->setReadCallback(id, this); receivedStreams_++; } void onTransportReady() noexcept override { LOG(INFO) << "TPerfClient: onTransportReady"; } void onStopSending( quic::StreamId id, quic::ApplicationErrorCode /*error*/) noexcept override { VLOG(10) << "TPerfClient got StopSending stream id=" << id; } void onConnectionEnd() noexcept override { LOG(INFO) << "TPerfClient connection end"; eventBase_.terminateLoopSoon(); } void onConnectionSetupError(QuicError error) noexcept override { onConnectionError(std::move(error)); } void onConnectionError(QuicError error) noexcept override { LOG(ERROR) << "TPerfClient error: " << toString(error.code); eventBase_.terminateLoopSoon(); } void onStreamWriteReady(quic::StreamId id, uint64_t maxToSend) noexcept override { LOG(INFO) << "TPerfClient stream" << id << " is write ready with maxToSend=" << maxToSend; } void onStreamWriteError(quic::StreamId id, QuicError error) noexcept override { LOG(ERROR) << "TPerfClient write error with stream=" << id << " error=" << toString(error); } void start() { folly::SocketAddress addr(host_.c_str(), port_); auto sock = std::make_unique<QuicAsyncUDPSocketType>(&eventBase_); auto fizzClientContext = FizzClientQuicHandshakeContext::Builder() .setCertificateVerifier(test::createTestCertificateVerifier()) .build(); quicClient_ = std::make_shared<quic::QuicClientTransport>( &eventBase_, std::move(sock), std::move(fizzClientContext)); quicClient_->setHostname("tperf"); quicClient_->addNewPeerAddress(addr); quicClient_->setCongestionControllerFactory( std::make_shared<DefaultCongestionControllerFactory>()); auto settings = quicClient_->getTransportSettings(); settings.advertisedInitialUniStreamFlowControlWindow = std::numeric_limits<uint32_t>::max(); settings.advertisedInitialConnectionFlowControlWindow = window_; settings.autotuneReceiveConnFlowControl = autotuneWindow_; settings.connectUDP = true; settings.shouldRecvBatch = true; settings.shouldUseRecvmmsgForBatchRecv = true; settings.maxRecvBatchSize = 64; settings.numGROBuffers_ = 64; settings.defaultCongestionController = congestionControlType_; if (congestionControlType_ == quic::CongestionControlType::BBR || congestionControlType_ == CongestionControlType::BBRTesting) { settings.pacingEnabled = true; settings.pacingTickInterval = 200us; settings.writeLimitRttFraction = 0; } if (gso_) { settings.batchingMode = QuicBatchingMode::BATCHING_MODE_GSO; settings.maxBatchSize = 16; } settings.maxRecvPacketSize = maxReceivePacketSize_; if (!FLAGS_transport_knob_params.empty()) { settings.knobs.push_back( {kDefaultQuicTransportKnobSpace, kDefaultQuicTransportKnobId, FLAGS_transport_knob_params}); } if (FLAGS_use_ack_receive_timestamps) { LOG(INFO) << " Using ACK receive timestamps on client"; settings.maybeAckReceiveTimestampsConfigSentToPeer.assign( {FLAGS_max_ack_receive_timestamps_to_send, kDefaultReceiveTimestampsExponent}); } if (useInplaceWrite_) { settings.maxBatchSize = 1; settings.dataPathType = DataPathType::ContinuousMemory; } quicClient_->setTransportSettings(settings); LOG(INFO) << "TPerfClient connecting to " << addr.describe(); quicClient_->start(this, this); eventBase_.loopForever(); } ~TPerfClient() override = default; private: bool timerScheduled_{false}; std::string host_; uint16_t port_; std::shared_ptr<quic::QuicClientTransport> quicClient_; folly::EventBase eventBase_; uint64_t receivedBytes_{0}; uint64_t receivedStreams_{0}; std::map<quic::StreamId, uint64_t> bytesPerStream_; folly::Histogram<uint64_t> bytesPerStreamHistogram_{ 1024, 0, 1024 * 1024 * 1024}; std::chrono::seconds duration_; uint64_t window_; bool autotuneWindow_{false}; bool gso_; quic::CongestionControlType congestionControlType_; uint32_t maxReceivePacketSize_; bool useInplaceWrite_{false}; }; } // namespace tperf } // namespace quic using namespace quic::tperf; quic::CongestionControlType flagsToCongestionControlType( const std::string& congestionControlFlag) { auto ccType = quic::congestionControlStrToType(congestionControlFlag); if (!ccType) { throw std::invalid_argument(folly::to<std::string>( "Unknown congestion controller ", congestionControlFlag)); } return *ccType; } int main(int argc, char* argv[]) { #if FOLLY_HAVE_LIBGFLAGS // Enable glog logging to stderr by default. gflags::SetCommandLineOptionWithMode( "logtostderr", "1", gflags::SET_FLAGS_DEFAULT); #endif gflags::ParseCommandLineFlags(&argc, &argv, false); folly::Init init(&argc, &argv); fizz::CryptoUtils::init(); if (FLAGS_mode == "server") { TPerfServer server( FLAGS_host, FLAGS_port, FLAGS_block_size, FLAGS_writes_per_loop, flagsToCongestionControlType(FLAGS_congestion), FLAGS_gso, FLAGS_max_cwnd_mss, FLAGS_pacing, FLAGS_num_streams, FLAGS_bytes_per_stream, FLAGS_max_receive_packet_size, FLAGS_use_inplace_write, FLAGS_dsr, FLAGS_override_packet_size); server.start(); } else if (FLAGS_mode == "client") { if (FLAGS_num_streams != 1) { LOG(ERROR) << "num_streams option is server only"; return 1; } if (FLAGS_bytes_per_stream != 0) { LOG(ERROR) << "bytes_per_stream option is server only"; return 1; } TPerfClient client( FLAGS_host, FLAGS_port, std::chrono::milliseconds(FLAGS_client_transport_timer_resolution_ms), FLAGS_duration, FLAGS_window, FLAGS_autotune_window, FLAGS_gso, flagsToCongestionControlType(FLAGS_congestion), FLAGS_max_receive_packet_size, FLAGS_use_inplace_write); client.start(); } return 0; }
// // GnIListCtrl.h // Core // // Created by Max Yoon on 11. 7. 27.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef Core_GnIListCtrl_h #define Core_GnIListCtrl_h #include "GnInterfaceGroup.h" #include "GnIListCtrlItem.h" class GnIListCtrl : public GnInterfaceGroup { public: enum eMoveType { /// Horizontal Left-Right eMoveUpDown, /// Horizontal Right-Left eMoveLeftRight, /// not move eNone, }; private: eMoveType mMoveType; gtuint mColumnSize; gtuint mRowSize; float mColumnGab; float mRowGab; GnTimer mTimer; eMoveType mIsRevision; GnVector2 mStartUIPosition; GnVector2 mMovePosition; GnTPrimitiveArray< GnTObjectArray<GnIListCtrlItemPtr>* > mListItems; GnVector2 mLasterMovePosition; GnVector2 mRevisionPosition; gtuint mViewRowSize; gtuint mViewColumnSize; float mRevisionDelta; gtuint mItemCount; GnSimpleString mEmptyItemFileName; public: static GnIListCtrl* CreateListCtrl(GnVector2 cStartUIPosition, gtuint numColumn, gtuint numRow , float fColumnGab, float fRowGab); virtual ~GnIListCtrl(); public: void SetSize(gtuint uiNumColumn, gtuint uiNumRow); void AddColumn(); void AddRow(); void SetItem(gtuint uiCol, gtuint uiRow, GnIListCtrlItem* pItem); void AddItem(GnIListCtrlItem* pItem); GnIListCtrlItemPtr RemoveItem(GnIListCtrlItem* pItem); GnIListCtrlItemPtr RemoveItem(gtuint uiCol, gtuint uiRow, GnIListCtrlItem* pItem); void MoveX(float fMove); void MoveY(float fMove); public: bool Push(float fPointX, float fPointY); void PushUp(); bool PushMove(float fPointX, float fPointY); void Update(float fTime); public: inline void SetMoveType(eMoveType eType, gtuint uiViewCountColumn, gtuint uiViewCountRow) { mMoveType = eType; mViewRowSize = uiViewCountRow; mViewColumnSize = uiViewCountColumn; } inline gtuint GetColumnSize() { return mColumnSize; } inline gtuint GetRowSize() { return mRowSize; } inline GnIListCtrlItem* GetItem(gtuint uiCol, gtuint uiRow) { GnTObjectArray<GnIListCtrlItemPtr>* columns = mListItems.GetAt( uiCol ); if( columns ) return columns->GetAt( uiRow ); return NULL; }; inline void SetEmptyItemFileName(const gchar* pcName) { mEmptyItemFileName = pcName; } inline gtuint GetItemCount() { return mItemCount; } protected: void Init(GnVector2 cStartUIPosition, gtuint numColumn, gtuint numRow , float fColumnGab, float fRowGab); void SetItemCell(gtuint uiCol, gtuint uiRow, GnIListCtrlItem* pItem); private: void SetMovedPositionY(gtuint uiRow, GnVector2 cCurrentUIPosition); private: inline float GetBasePositionX(gtuint uiCol) { return mStartUIPosition.x + ( mColumnGab * uiCol ); } inline float GetBasePositionY(gtuint uiRow) { return mStartUIPosition.y + ( mRowGab * uiRow ); } }; #endif
#include "List.hpp" List::List(int n) { int i; root = NULL; for(i = 0; i < n; i++){ Node* node = new Node(i); node->edges.resize(1); node->edges[NEXT] = NULL; cout << "inserting " << node->val << endl; Insert(node); } size = i; } List::~List() { Node* next, *cur; cout << "dtor has memory leak due to cyclic list...will segfault" << endl; cur = root; while(cur != NULL){ next = cur->edges[NEXT]; delete cur; cur = next; } } //Just push front. No sorted insertion, nor end insertion, since I'm intentionally going to build a list with a cycle at the end (hence, infinite loops) void List::Insert(Node* node) { if(node != NULL){ if(node->edges.size() < (NEXT+1)) node->edges.resize(NEXT+1); node->edges[NEXT] = root; root = node; } } /* This makes a cycle in a non-cyclic list by pointing the end of the list to the midpoint of the list. The principle of pointing to the middle of the list is useful for other things: one pointer moves at rate k secon pointer moves at rate 2k When second pointer reaches end of list, first pointer will be about halfway. Use similar update properties to segment lists in various multiples. */ void List::MakeCycle() { Node *hare, *tortoise, *end; //find midpoint of list using two pointer method hare = tortoise = root; while(hare != NULL){ tortoise = tortoise->edges[NEXT]; end = hare; hare = hare->edges[NEXT]; if(hare != NULL){ end = hare; hare = hare->edges[NEXT]; } } //post: tortoise points at node halfway in list if(end == NULL){ cout << "ERROR end is NULL" << endl; exit(0); } if(tortoise == NULL){ cout << "ERROR tortoise is NULL" << endl; exit(0); } end->edges[NEXT] = tortoise; } void List::FloydsAlgorithm() { Node* tortoise, *hare; if(root == NULL){ cout << "ERROR list too short for floyds" << endl; exit(0); } if(root->edges[NEXT] == NULL){ cout << "ERROR list too short for floyds" << endl; exit(0); } tortoise = root; hare = tortoise->edges[NEXT]; while(hare != NULL && tortoise != NULL){ //cout << "searching" << endl; if(tortoise == hare){ cout << "cycle detected" << endl; return; } if(tortoise != NULL){ tortoise = tortoise->edges[NEXT]; } hare = hare->edges[NEXT]; if(hare != NULL){ hare = hare->edges[NEXT]; } } } bool List::HasCycle() //aka, hasCycle() { Node* tortoise, *hare; if(root == NULL){ cout << "ERROR list too short for floyds" << endl; exit(0); } if(root->edges[NEXT] == NULL){ cout << "ERROR list too short for floyds" << endl; exit(0); } tortoise = root; hare = tortoise->edges[NEXT]; while(hare != NULL && tortoise != NULL){ //cout << "searching" << endl; if(tortoise == hare){ cout << "cycle detected" << endl; return true; } if(tortoise != NULL){ tortoise = tortoise->edges[NEXT]; } hare = hare->edges[NEXT]; if(hare != NULL){ hare = hare->edges[NEXT]; } } cout << "no cycle" << endl; return false; } void List::Print() { Node *node = NULL; if(HasCycle()){ cout << "WARN list has cycle, cannot print" << endl; return; } cout << "continuing" << endl; node = root; while(node != NULL){ cout << node->val << "->"; node = node->edges[NEXT]; } } /* Prints a cycle, with stats. */ void List::PrintCycle() //aka, hasCycle() { int i, j, k; Node* tortoise, *hare; if(root == NULL){ cout << "ERROR list too short for floyds" << endl; exit(0); } if(root->edges[NEXT] == NULL){ cout << "ERROR list too short for floyds" << endl; exit(0); } i = j = k = 0; tortoise = root; hare = tortoise->edges[NEXT]; while(hare != NULL){ if(tortoise == hare){ cout << "cycle detected at i/j: " << i << "/" << j << endl; //count number of nodes in cycle for(k = 1, hare = hare->edges[NEXT]; hare != tortoise; hare = hare->edges[NEXT], k++); cout << "cycle contains period of " << k << " nodes" << endl; return; } i++; tortoise = tortoise->edges[NEXT]; j++; hare = hare->edges[NEXT]; if(hare != NULL){ j++; hare = hare->edges[NEXT]; } } cout << "no cycle" << endl; } int main(void) { List m_list(50); cout << "printing list" << endl; m_list.Print(); if(!m_list.HasCycle()){ cout << "List does not have a cycle" << endl; } cout << "making cycle..." << endl; m_list.MakeCycle(); if(m_list.HasCycle()){ cout << "List now has a cycle" << endl; } m_list.PrintCycle(); return 0; }
#include <iostream> #include "vector.h" using namespace std; template <class T> void print(const vector<T> &vec) { for (int i = 0; i < vec.size(); ++i) cout << " ," << vec[i] << ", "; cout << "\n"; } string str(int n) { return string(1, '0' + n); } int main() { int n = 10; vector<string> v(n); print(v); for (int i = 0; i < v.size(); ++i) { v[i] = str(i); } print(v); for (int i = 0; i < 10; ++i) { v.push_back(str(i)); } print(v); vector<int> d(5); for (int i = 0; i < 6; ++i) d[i] = i + 1; print(d); for (int i = 0; i < 7; ++i) d.push_back(i); print(d); cout << " Size str: " << d.size() << endl; d.resize(10); cout << " Size str: " << d.size() << endl; return 0; }
const int LED = 4, dotlen=200; char* letters[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", // A-I ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", // J-R "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." // S-Z }; char* numbers[] = {"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."}; void setup() { pinMode(LED,OUTPUT); Serial.begin(9600); } void flashsign(char si) { digitalWrite(LED,HIGH); if (si == '.') delay(dotlen); else delay(dotlen*3); digitalWrite(LED,LOW); } void flashchar(char *ch) { int i = 0; while (ch[i] != '\0') {flashsign(ch[i]);delay(dotlen);i++;} delay(dotlen*2); } void loop() { char ch; if (Serial.available()) { ch = Serial.read(); if ('a' <= ch && ch <= 'z') flashchar(letters[ch-'a']); else if ('A' <= ch && ch <= 'Z') flashchar(letters[ch-'A']); else if ('0' <= ch && ch <= '9') flashchar(numbers[ch-'0']); else if (ch == ' ') delay(dotlen*7); } }
 // 3.23实验View.h: CMy323实验View 类的接口 // #pragma once class CMy323实验View : public CView { protected: // 仅从序列化创建 CMy323实验View() noexcept; DECLARE_DYNCREATE(CMy323实验View) // 特性 public: CMy323实验Doc* GetDocument() const; // 操作 public: int N; CArray<CRect, CRect> ca; bool set; CRect m_window; CRect cr; // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: // 实现 public: virtual ~CMy323实验View(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnCircles(); afx_msg void OnTimer(UINT_PTR nIDEvent); }; #ifndef _DEBUG // 3.23实验View.cpp 中的调试版本 inline CMy323实验Doc* CMy323实验View::GetDocument() const { return reinterpret_cast<CMy323实验Doc*>(m_pDocument); } #endif
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<vector<string>> partition(string s) { auto isPalin = [&](const string str) { if (str.length() == 1) return true; int x = 0, y = str.size() - 1; while (x < y) { if (str[x] != str[y]) return false; x++; y--; } return true; }; vector<vector<string>> ans; function<void(int, vector<string>)> bt = [&](int i, vector<string> vec) { if (i >= s.length()) { ans.push_back(vec); return; } string str = ""; for (int j = i; j < s.length(); j++) { str += s[j]; if (!isPalin(str)) continue; // cout << str << " "; vec.push_back(str); bt(j + 1, vec); vec.pop_back(); } }; vector<string> vec; bt(0, vec); return ans; } };
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> using namespace std; struct Record { char plate[8]; int time; bool inout; }; long long str_to_int(char* s) { long long res = 0, factor = 1; for (int i = 6; i >= 0; i--) { if ('0' <= s[i] && s[i] <= '9') res += (s[i] - '0') * factor; else if ('A' <= s[i] && s[i] <= 'Z') res += (s[i] - 'A' + 10) * factor; factor *= 36; } return res; } int calc_time(int h, int m, int s) { return h * 60 * 60 + m * 60 + s; } bool comp(const Record& a, const Record& b) { return a.time < b.time; } bool comp1(const Record& a, const Record& b) { if (strcmp(a.plate, b.plate) == 0) return a.time < b.time; return strcmp(a.plate, b.plate) < 0; } int main() { /*freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);*/ int n, k, h, m, s; char inout[4]; scanf("%d %d", &n, &k); vector<Record> records, validRecords; records.resize(n); for (int i = 0; i < n; i++) { scanf("%s %d:%d:%d %s", records[i].plate, &h, &m, &s, inout); records[i].inout = inout[0] == 'i'; records[i].time = calc_time(h, m, s); } unordered_map<string, int> total_time; sort(records.begin(), records.end(), comp1); int i1 = 0, i2 = 1; while (i2 < n) { if (strcmp(records[i1].plate, records[i2].plate) == 0 && records[i1].inout && !records[i2].inout) { validRecords.push_back(records[i1]); validRecords.push_back(records[i2]); total_time[records[i1].plate] += records[i2].time - records[i1].time; i1 += 2; i2 += 2; } else { i1++; i2++; } } sort(validRecords.begin(), validRecords.end(), comp); int index = 0, total = 0; while (k--) { scanf("%d:%d:%d", &h, &m, &s); int t = calc_time(h, m, s); for (index; index < validRecords.size() && validRecords[index].time <= t; index++) { if (validRecords[index].inout) total++; else total--; } printf("%d\n", total); } if (!total_time.empty()) { int longest = -1; vector<string> v; for (auto item : total_time) { if (item.second > longest) { longest = item.second; v.clear(); v.push_back(item.first); } else if (item.second == longest) { v.push_back(item.first); } } sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) { printf("%s ", v[i].data()); } printf("%02d:%02d:%02d\n", longest / 3600, longest / 60 % 60, longest % 60); } return 0; }
/* * Copyright (C) 2013 Tom Wong. All rights reserved. */ #include "gtfttemp.h" #include "gtftmessage.pb.h" #include <QtCore/QDebug> #include <QtCore/QDir> GT_BEGIN_NAMESPACE class GtFTTempPrivate { Q_DECLARE_PUBLIC(GtFTTemp) public: explicit GtFTTempPrivate(GtFTTemp *q); ~GtFTTempPrivate(); public: bool saveMeta(); protected: GtFTTemp *q_ptr; QString fileId; QString metaPath; QString dataPath; QFile metaFile; QFile dataFile; GtFTTempMeta tempMeta; QList<GtFTTempData*> tempDatas; }; GtFTTempPrivate::GtFTTempPrivate(GtFTTemp *q) : q_ptr(q) { } GtFTTempPrivate::~GtFTTempPrivate() { } bool GtFTTempPrivate::saveMeta() { tempMeta.clear_datas(); foreach(GtFTTempData *p, tempDatas) { *tempMeta.add_datas() = *p; } int size = tempMeta.ByteSize(); QByteArray bytes(size, -1); char *data = bytes.data(); if (tempMeta.SerializeToArray(data, size)) { if (metaFile.resize(0)) return (metaFile.write(data, size) == size); } return false; } GtFTTemp::GtFTTemp(QObject *parent) : QIODevice(parent) , d_ptr(new GtFTTempPrivate(this)) { } GtFTTemp::GtFTTemp(const QString &dir, const QString &fileId, QObject *parent) : QIODevice(parent) , d_ptr(new GtFTTempPrivate(this)) { setPath(dir, fileId); } GtFTTemp::~GtFTTemp() { close(); } void GtFTTemp::setPath(const QString &dir, const QString &fileId) { Q_D(GtFTTemp); d->fileId = fileId; QDir path(dir); d->metaPath = path.filePath(fileId + ".meta"); d->dataPath = path.filePath(fileId + ".data"); d->metaFile.setFileName(d->metaPath); d->dataFile.setFileName(d->dataPath); } QString GtFTTemp::fileId() const { Q_D(const GtFTTemp); return d->fileId; } QString GtFTTemp::metaPath() const { Q_D(const GtFTTemp); return d->metaPath; } QString GtFTTemp::dataPath() const { Q_D(const GtFTTemp); return d->dataPath; } bool GtFTTemp::open(OpenMode mode) { Q_D(GtFTTemp); OpenMode metaMode = QIODevice::ReadWrite; if (mode & QIODevice::Truncate) metaMode |= QIODevice::Truncate; if (!d->metaFile.open(metaMode)) return false; if (d->metaFile.size() > 0) { QByteArray data = d->metaFile.readAll(); if (d->tempMeta.ParseFromArray(data.constData(), data.size()) && QString(d->tempMeta.file_id().c_str()) == d->fileId) { int count = d->tempMeta.datas_size(); for (int i = 0; i < count; ++i) { GtFTTempData *p = new GtFTTempData(d->tempMeta.datas(i)); d->tempDatas.push_back(p); } } else { mode |= QIODevice::Truncate; qWarning() << "invalid FTTemp meta file:" << d->metaPath; } } d->tempMeta.set_file_id(d->fileId.toUtf8()); if (d->dataFile.open(mode)) return QIODevice::open(mode); return false; } void GtFTTemp::close() { if (!isOpen()) return; Q_D(GtFTTemp); d->saveMeta(); QIODevice::close(); d->metaFile.close(); d->dataFile.close(); qDeleteAll(d->tempDatas); d->tempDatas.clear(); } bool GtFTTemp::flush() { Q_D(GtFTTemp); if (!d->saveMeta()) return false; return d->metaFile.flush() && d->dataFile.flush(); } qint64 GtFTTemp::size() const { Q_D(const GtFTTemp); return d->dataFile.size(); } bool GtFTTemp::seek(qint64 pos) { Q_D(GtFTTemp); if (!d->dataFile.seek(pos)) return false; return QIODevice::seek(pos); } int GtFTTemp::temps_size() const { Q_D(const GtFTTemp); return d->tempDatas.size(); } const GtFTTempData& GtFTTemp::temps(int index) const { Q_D(const GtFTTemp); return *d->tempDatas[index]; } qint64 GtFTTemp::complete(qint64 begin) const { Q_D(const GtFTTemp); return complete(d->tempDatas, begin); } bool GtFTTemp::exists() const { Q_D(const GtFTTemp); return d->metaFile.exists() && d->dataFile.exists(); } bool GtFTTemp::remove() { Q_D(GtFTTemp); return d->metaFile.remove() && d->dataFile.remove(); } qint64 GtFTTemp::readData(char *data, qint64 maxlen) { Q_D(GtFTTemp); return d->dataFile.read(data, maxlen); } qint64 GtFTTemp::writeData(const char *data, qint64 len) { Q_D(GtFTTemp); qint64 pos = d->dataFile.pos(); qint64 size = d->dataFile.write(data, len); append(d->tempDatas, pos, pos + size); return size; } qint64 GtFTTemp::complete(const QList<GtFTTempData*> &list, qint64 begin) { if (list.size() == 0) return begin; GtFTTempData *p = list[0]; if (p->offset() > begin) return begin; qint64 curPos; qint64 maxPos = p->size(); foreach(const GtFTTempData *it, list) { if (it->offset() > maxPos && it->offset() > begin) break; curPos = it->offset() + it->size(); maxPos = MAX(curPos, maxPos); } return maxPos; } void GtFTTemp::append(QList<GtFTTempData*> &list, qint64 begin, qint64 end) { qint64 begin0 = begin; qint64 end0 = end; bool done = false; foreach(GtFTTempData *p, list) { qint64 begin1 = p->offset(); qint64 end1 = begin1 + p->size(); if ((begin0 >= begin1 && begin0 <= end1) || (end0 >= begin1 && end0 <= end1) || (begin0 < begin1 && end0 > end1)) { qint64 begin2 = MIN(begin0, begin1); qint64 end2 = MAX(end0, end1); p->set_offset(begin2); p->set_size(end2 - begin2); done = true; break; } } if (!done) { GtFTTempData *p; int i, count = list.size(); for (i = 0; i < count; ++i) { p = list[i]; if (end < p->offset()) break; } p = new GtFTTempData(); p->set_offset(begin); p->set_size(end - begin); list.insert(i, p); } } GT_END_NAMESPACE
#undef UNICODE #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdlib.h> #include <stdio.h> #include <iostream> // Need to link with Ws2_32.lib #pragma comment (lib, "Ws2_32.lib") // #pragma comment (lib, "Mswsock.lib") #define DEFAULT_BUFLEN 3 #define DEFAULT_PORT "27015" int __cdecl main(void) { WSADATA wsaData; int iResult; SOCKET ListenSocket = INVALID_SOCKET; SOCKET ClientSockets = INVALID_SOCKET; SOCKET ClientSocketr = INVALID_SOCKET; struct addrinfo *result = NULL; struct addrinfo hints; int iSendResult; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } // Setup the TCP listening socket iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } freeaddrinfo(result); iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // Accept a client socket ClientSockets = accept(ListenSocket, NULL, NULL); if (ClientSockets == INVALID_SOCKET) { printf("accept s failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // Accept a client socket ClientSocketr = accept(ListenSocket, NULL, NULL); if (ClientSocketr == INVALID_SOCKET) { printf("accept r failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // Receive until the peer shuts down the connection int freq = 25; unsigned short int measurements[10] = { 0 }; int counter = 0; bool state = 1; recvbuf[0] = '1'; recvbuf[1] = '2'; recvbuf[2] = 0; do { recv(ClientSocketr, recvbuf, DEFAULT_BUFLEN, 0); std::cout << "Speed(Hz): " << recvbuf << std::endl; sscanf_s(recvbuf, "%d", &freq); if (freq == 0) break; if (freq > 50) freq = 50; Sleep(1000 / freq); if (measurements[0] == 0 || measurements[0] == 200) state = !state; for (int i = 0; i < 10; i++) { if (state) measurements[i]--; else measurements[i]++; std::cout << measurements[i] << '\t'; } std::cout << '\n'; send(ClientSockets, (char *)&measurements, 20, 0); } while (1); closesocket(ListenSocket); // shutdown the connection since we're done iResult = shutdown(ClientSockets, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ClientSockets); WSACleanup(); return 1; } // cleanup closesocket(ClientSockets); WSACleanup(); return 0; }
// // normal_esti_coarse2fine_ps.cpp // pm_stereo // // Created by KaiWu on Sep/9/16. // Copyright © 2016 KaiWu. All rights reserved. // #include "normal_esti_coarse2fine_ps.hpp" #include "mex.h" using Eigen::Matrix; using Eigen::Matrix2i; using Eigen::Matrix2d; using Eigen::MatrixXi; using Eigen::Vector2i; using Eigen::Vector2d; using Eigen::VectorXi; using Eigen::VectorXd; using Eigen::Map; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs != 10) { mexErrMsgIdAndTxt("MyToolbox:esti_norm:nrhs","Ten inputs required."); } double *pov_tar = mxGetPr(prhs[0]); int r = mxGetM(prhs[0]); int c = mxGetN(prhs[0]); MatrixXd ov_tar = Map<MatrixXd>(pov_tar, r, c); vector<MatrixXd> ov_ref(2); double *pov_ref_spec = mxGetPr(prhs[1]); r = mxGetM(prhs[1]); c = mxGetN(prhs[1]); ov_ref[0] = Map<MatrixXd>(pov_ref_spec, r, c); // ov_ref_spec double *pov_ref_diff = mxGetPr(prhs[2]); r = mxGetM(prhs[2]); c = mxGetN(prhs[2]); ov_ref[1] = Map<MatrixXd>(pov_ref_diff, r, c); // ov_ref_diff int *pov_tar_ind = (int *)mxGetData(prhs[3]); r = mxGetM(prhs[3]); c = mxGetN(prhs[3]); VectorXi ov_tar_ind = Map<VectorXi>(pov_tar_ind, r); vector<VectorXi> ov_ref_ind(2); int *pov_ref_spec_ind = (int *)mxGetData(prhs[4]); r = mxGetM(prhs[4]); c = mxGetN(prhs[4]); ov_ref_ind[0] = Map<VectorXi>(pov_ref_spec_ind, r); // ov_ref_spec_ind int *pov_ref_diff_ind = (int *)mxGetData(prhs[5]); r = mxGetM(prhs[5]); c = mxGetN(prhs[5]); ov_ref_ind[1] = Map<VectorXi>(pov_ref_diff_ind, r); // ov_ref_diff_ind int *psize_tar = (int *)mxGetData(prhs[6]); r = mxGetM(prhs[6]); c = mxGetN(prhs[6]); Vector2i size_tar = Map<Vector2i>(psize_tar); vector<Vector2i> size_ref(2); int *psize_ref = (int *)mxGetData(prhs[7]); r = mxGetM(prhs[7]); c = mxGetN(prhs[7]); Matrix2i size_ref_mat = Map<Matrix2i>(psize_ref, r, c); size_ref[0] = size_ref_mat.col(0); size_ref[1] = size_ref_mat.col(1); vector<Vector2d, Eigen::aligned_allocator<Vector2d> > center(2); double *pcenter = mxGetPr(prhs[8]); r = mxGetM(prhs[8]); c = mxGetN(prhs[8]); Matrix2d center_mat = Map<Matrix2d>(pcenter, r, c); center[0] = center_mat.col(0); center[1] = center_mat.col(1); vector<double> radius(2); double *pradius = mxGetPr(prhs[9]); r = mxGetM(prhs[9]); c = mxGetN(prhs[9]); Vector2d radius_mat = Map<Vector2d>(pradius, r, c); radius[0] = radius_mat(0); radius[1] = radius_mat(1); mwSize nrows = mxGetM(prhs[0]); plhs[0] = mxCreateDoubleMatrix(3, nrows, mxREAL); double* norm_map = mxGetPr(plhs[0]); esti_norm(ov_tar, ov_ref, ov_tar_ind, ov_ref_ind, size_tar, size_ref, center, radius, norm_map); }
/* * Copyright (c) 2016-2019 Morwenn * SPDX-License-Identifier: MIT */ #include <algorithm> #include <forward_list> #include <iterator> #include <list> #include <vector> #include <catch2/catch.hpp> #include <cpp-sort/sorters/counting_sorter.h> #include <testing-tools/distributions.h> TEST_CASE( "counting_sorter tests", "[counting_sorter]" ) { // Distribution used to generate the data to sort auto distribution = dist::shuffled{}; // Size of the collections to sort auto size = 100'000; SECTION( "sort with int iterable" ) { std::vector<int> vec; vec.reserve(size); distribution(std::back_inserter(vec), size, -1568); cppsort::counting_sort(vec); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); } SECTION( "sort with unsigned int iterators" ) { std::list<unsigned> li; distribution(std::back_inserter(li), size, 0u); cppsort::counting_sort(std::begin(li), std::end(li)); CHECK( std::is_sorted(std::begin(li), std::end(li)) ); } SECTION( "reverse sort with long long iterable" ) { std::vector<long long> vec; vec.reserve(size); distribution(std::back_inserter(vec), size, 1568); cppsort::counting_sort(vec); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); } SECTION( "reverse sort with unsigned long long iterators" ) { std::forward_list<unsigned long long> li; distribution(std::front_inserter(li), size, 0ULL); cppsort::counting_sort(std::begin(li), std::end(li)); CHECK( std::is_sorted(std::begin(li), std::end(li)) ); } #ifdef __SIZEOF_INT128__ SECTION( "sort with unsigned int128 iterators" ) { std::list<__uint128_t> li;; distribution(std::back_inserter(li), size, __uint128_t(0)); cppsort::counting_sort(std::begin(li), std::end(li)); CHECK( std::is_sorted(std::begin(li), std::end(li)) ); } #endif SECTION( "GitHub issue #103" ) { // Specific bug in counting_sort due to another specific bug in // minmax_element_and_is_sorted due to another specific bug in // minmax_element... found while investigating GitHub issue #103; // better have a test std::vector<int> vec = { -47, -46, -45, -44, -43, -42, -41, -39, -40, -38 }; cppsort::counting_sort(vec); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); } }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * 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 <skland/wayland/data-source.hpp> namespace skland { namespace wayland { const struct wl_data_source_listener DataSource::kListener = { OnTarget, OnSend, OnCancelled, OnDndDropPerformed, OnDndFinished, OnAction }; void DataSource::OnTarget(void *data, struct wl_data_source *wl_data_source, const char *mime_type) { DataSource *_this = static_cast<DataSource *>(data); if (_this->target_) _this->target_(mime_type); } void DataSource::OnSend(void *data, struct wl_data_source *wl_data_source, const char *mime_type, int32_t fd) { DataSource *_this = static_cast<DataSource *>(data); if (_this->send_) _this->send_(mime_type, fd); } void DataSource::OnCancelled(void *data, struct wl_data_source *wl_data_source) { DataSource *_this = static_cast<DataSource *>(data); if (_this->cancelled_) _this->cancelled_(); } void DataSource::OnDndDropPerformed(void *data, struct wl_data_source *wl_data_source) { DataSource *_this = static_cast<DataSource *>(data); if (_this->dnd_drop_performed_) _this->dnd_drop_performed_(); } void DataSource::OnDndFinished(void *data, struct wl_data_source *wl_data_source) { DataSource *_this = static_cast<DataSource *>(data); if (_this->dnd_finished_) _this->dnd_finished_(); } void DataSource::OnAction(void *data, struct wl_data_source *wl_data_source, uint32_t dnd_action) { DataSource *_this = static_cast<DataSource *>(data); if (_this->action_) _this->action_(dnd_action); } } }
#pragma once #include <PA9.h> #define PLAYER_PROFILE_MAX_NAMELENGTH 16 #define PLAYER_PROFILE_EXP_FOR_LVLUP 10 class PlayerProfile{ private: char m_name[PLAYER_PROFILE_MAX_NAMELENGTH+1]; //+1 for terminating 0 s8 m_nameLength; u8 m_level; u16 m_experience; //m_playtime; //m_lastsaved; public: PlayerProfile(); PlayerProfile(const PlayerProfile &pp); ~PlayerProfile(); void Copy(const PlayerProfile &pp); void Set(const char * const name, u8 level, u16 exp); void SetName(const char * const name); void SetLevel(u8 level); void SetExperience(u16 exp); void AddExperience(u16 exp); bool CheckLevelUp(); const char * const Name()const; u8 NameLength()const; u8 Level()const; u8 Experience()const; bool IsInitialized()const; void Read(FILE * f); void Write(FILE * f); }; void LoadPlayerProfiles(PlayerProfile * pp, u8 amount); void SavePlayerProfiles(PlayerProfile * pp, u8 amount);
#ifndef Shop_h #define Shop_h #include "DVD.h" #include "SaleableItem.h" #include <vector> #include <memory> using namespace std; class Shop { public: void AddBook(const char* pTitle, unsigned int unitPricePence, unsigned int noOfPages); void AddDVD(const char* pTitle, unsigned int unitPricePence, unsigned int runningTimeMins, DVD::DVDFormat format); void AddCD(const char* pTitle, unsigned int unitPricePence, unsigned int runningTimeMins, unsigned int noOfTracks); void ShowTaxedPrices() const; vector<shared_ptr<SaleableItem>> saleableItems_; }; #endif /* #ifndef Included_Shop_h */
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "ThirdPersonProyect.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, ThirdPersonProyect, "ThirdPersonProyect" );
// // Moon.hpp // w04_h01_moons // // Created by Kris Li on 9/29/16. // // #pragma once #include "ofMain.h" class Moon : public ofPoint { public: void set(float _dist, float _intAngle); void update(float _step, ofPoint _center); void draw(); float radius; float angle; };
#ifndef ASTNODE_H #define ASTNODE_H #include <vector> #include <string> #include <iostream> #include <tuple> #include <algorithm> #include <utility> #include <map> #include "ClassNode.hpp" #include "FieldNode.hpp" #include "Node.hpp" using namespace std; class StringNode { private: string s; StringNode *parent = nullptr; StringNode *son = nullptr; public: explicit StringNode(string value); string getValue(); StringNode *getSon(); StringNode *getParent(); void AddSon(StringNode *son); void AddParent(StringNode *parent); }; class PairTree { private: string s; StringNode *parent = nullptr; vector<StringNode *> sons; public: PairTree(); /** Checks that the current node has no parent with the same value. * * @param node the current node * @return true if node has no parent with the same value (consistent), false otherwise */ bool isNodeConsistent(StringNode *node); /** If a node with value arg1 is present in the tree, creates it a son node with value arg2. Otherwise, creates a * node with value arg1, creates it a son node with value arg2 and adds it to the sons vector. * * @param value = arg1 * @param son_value = arg2 */ void AddNode(string value, string son_value); /** Checks that no node in the tree has a parent with the same value. * * @return a vector of the parent-son pairs of nodes related to a cycle */ vector<pair<string, string>> CheckConsistency(); }; class AstNode : public Node { private: vector<ClassNode *> s; map<string, string> inheritances; public: string test = "test"; AstNode(); vector<ClassNode *> getClasses(); ClassNode *getClassNode(string className); vector<pair<int, int>> getRedefParentPos(string parentName); pair<int, int> getParentPos(string parentName); vector<pair<string, string>> checkCycle(vector<pair<string, string>> s); void addNode(ClassNode *node); /** Adds an inheritance relation to the list of the inheritance relations of the file. * * @param child * @param parent */ void addInheritance(string child, string parent); bool isParentDefined(string parentName, ClassNode **node); /** Checks whether a given parent class exits. * * @param parentName the name of the parent class * @return true if the parent class exists, false otherwise */ bool isParentExist(string parentName); vector<tuple<string, string, int, int>> containsCycle(); tuple<string, int, int> containsRedefFields(string nameRedef); tuple<string, int, int> containsRedefMethods(string nameRedef, string typeRedef); void printTree(); string printCheck(); }; #endif
#include "ai.h" #include <sstream> #include <iostream> #include <cstring> #include <cstdlib> #include "G_Global_IO.h" #include <fstream> using namespace std; // global variables for procedural string GIO_loadPath; float GIO_radius; int numPt; // recursive function that creates random cloud with fractal clumping static void initMyIo(g_global_io &io) { //char *path ="C:/Users/Administrator/Desktop/gp_cache/gpcache.0073.gp"; ifstream fin; fin.open(GIO_loadPath.c_str(),ios_base::binary); io.load(fin,(char*)GIO_loadPath.c_str()); fin.close(); } static void calNumPt(g_global_io &io) { vector <g_particles_io> flt_vecHandle=io.GIO_getFLTVecParticlesHandle(); numPt=flt_vecHandle[0].GIO_getFLTVecAttributeList().size(); } static void makecloud(g_global_io &io,AtArray *pointarr, AtArray *radarr,float rad) { vector <g_particles_io> flt_vecHandle=io.GIO_getFLTVecParticlesHandle(); // create points! // std::cout<<"has xxxxxxxx pt num is"<<numPt<<std::endl; int vecAttSize=flt_vecHandle.size(); // std::cout<<"flt_vecHandle size"<<flt_vecHandle.size()<<std::endl; for(int i=0;i<vecAttSize;i++) { string attname = flt_vecHandle[i].GIO_getCurrentAttributeName(); vector <per_float_vector> PtPosHandle = flt_vecHandle[i].GIO_getFLTVecAttributeList(); //std::cout<<"att name is"<<attname<<std::endl; if(attname =="P") // create points { std::cout<<"GIO_POINTS:Gearslogy.....Create the Points Num is .."<<PtPosHandle.size()<<std::endl; int eval_step=0; for(int k=0;k<PtPosHandle.size();k++) { per_float_vector vecPos = PtPosHandle[k]; AtVector vec; vec.x=vecPos.g_x; vec.y=vecPos.g_y; vec.z=vecPos.g_z; //std::cout<<vec.x<<" "<<vec.y<<" "<<vec.z<<std::endl; AiArraySetPnt(pointarr, k, vec); AiArraySetFlt(radarr, k, 0.02); } } } } static void forkTheVecFltAttribute(g_global_io &io,vector<AtArray*> ArFltVecList,AtNode *node) { vector <g_particles_io> flt_vecHandle=io.GIO_getFLTVecParticlesHandle(); ArFltVecList.resize(flt_vecHandle.size()); // sendAllocation for(int i=0;i<ArFltVecList.size();i++) { ArFltVecList[i]=AiArrayAllocate(numPt,1,AI_TYPE_RGBA); } //now set the attribute for each point for(int i=0;i<ArFltVecList.size();i++) { string attname = flt_vecHandle[i].GIO_getCurrentAttributeName(); vector <per_float_vector> PtPosHandle = flt_vecHandle[i].GIO_getFLTVecAttributeList(); AiNodeDeclare(node, attname.c_str(), "uniform RGBA"); // add attribute into arnold for user data color api for(int k=0;k<PtPosHandle.size();k++) { per_float_vector vecAtt = PtPosHandle[k]; AtRGBA vec; vec.r=vecAtt.g_x; vec.g=vecAtt.g_y; vec.b=vecAtt.g_z; vec.a=1.0f; AiArraySetRGBA(ArFltVecList[i], k, vec); } AiNodeSetArray(node, attname.c_str(), ArFltVecList[i]); } } static void forkTheVecIntAttribute(g_global_io&io,vector<AtArray*>arIntVecList,AtNode*node) { vector <g_particles_io> int_vecHandle=io.GIO_getINTVecParticlesHandle(); arIntVecList.resize(int_vecHandle.size()); // sendAllocation for(int i=0;i<arIntVecList.size();i++) { arIntVecList[i]=AiArrayAllocate(numPt,1,AI_TYPE_RGBA); } //now set the attribute for each point for(int i=0;i<arIntVecList.size();i++) { string attname = int_vecHandle[i].GIO_getCurrentAttributeName(); vector <per_int_vector> PtPosHandle = int_vecHandle[i].GIO_getINTVecAttributeList(); AiNodeDeclare(node, attname.c_str(), "uniform RGBA"); // add attribute into arnold for user data color api for(int k=0;k<PtPosHandle.size();k++) { per_int_vector vecAtt = PtPosHandle[k]; AtRGBA vec; vec.r=float(vecAtt.g_x); vec.g=float(vecAtt.g_y); vec.b=float(vecAtt.g_z); vec.a=1.0f; AiArraySetRGBA(arIntVecList[i], k, vec); } AiNodeSetArray(node, attname.c_str(), arIntVecList[i]); } } // we just wan't use the uesr data color,not the user the data float/int and so on static void forkTheIntAttribute(g_global_io&io,vector<AtArray*>arIntList,AtNode*node) { vector <g_particles_io> int_Handle=io.GIO_getINTParticlesHandle(); arIntList.resize(int_Handle.size()); for(int i=0;i<arIntList.size();i++) { arIntList[i]=AiArrayAllocate(numPt,1,AI_TYPE_RGBA); } for(int i=0;i<arIntList.size();i++) { string attname = int_Handle[i].GIO_getCurrentAttributeName(); vector <int> PtPosHandle = int_Handle[i].GIO_getINTAttributeList(); AiNodeDeclare(node, attname.c_str(), "uniform RGBA"); // add attribute into arnold for user data color api for(int k=0;k<PtPosHandle.size();k++) { int vecAtt = PtPosHandle[k]; AtRGBA vec; vec.r=float(vecAtt); vec.g=float(vecAtt); vec.b=float(vecAtt); vec.a=1.0f; AiArraySetRGBA(arIntList[i], k, vec); } AiNodeSetArray(node, attname.c_str(), arIntList[i]); } } static void forkTheFltAttribute(g_global_io&io,vector<AtArray*>arFltList,AtNode*node) { vector <g_particles_io> flt_Handle=io.GIO_getFLTParticlesHandle(); arFltList.resize(flt_Handle.size()); for(int i=0;i<arFltList.size();i++) { arFltList[i]=AiArrayAllocate(numPt,1,AI_TYPE_RGBA); } for(int i=0;i<arFltList.size();i++) { string attname = flt_Handle[i].GIO_getCurrentAttributeName(); vector <float> PtPosHandle = flt_Handle[i].GIO_getFLTAttributeList(); AiNodeDeclare(node, attname.c_str(), "uniform RGBA"); // add attribute into arnold for user data color api for(int k=0;k<PtPosHandle.size();k++) { float vecAtt = PtPosHandle[k]; AtRGBA vec; vec.r=vecAtt; vec.g=vecAtt; vec.b=vecAtt; vec.a=1.0f; AiArraySetRGBA(arFltList[i], k, vec); } AiNodeSetArray(node, attname.c_str(), arFltList[i]); } } static void forkTheSingleVec(g_global_io &io,AtArray *array) // this is just test one attribute for proc { vector <g_particles_io> flt_vecHandle=io.GIO_getFLTVecParticlesHandle(); for(int i=0;i<flt_vecHandle.size();i++) { string attname = flt_vecHandle[i].GIO_getCurrentAttributeName(); vector <per_float_vector> PtPosHandle = flt_vecHandle[i].GIO_getFLTVecAttributeList(); if(attname=="P") { AtRGBA vec; for(int k=0;k<PtPosHandle.size();k++) { per_float_vector vecAtt = PtPosHandle[k]; vec.r=vecAtt.g_x; vec.g=vecAtt.g_y; vec.b=vecAtt.g_z; vec.a = 1.0f; // std::cout<<"setting the rgb \n"; AiArraySetRGBA(array, k, vec); } } } } static int MyInit(AtNode *mynode, void **user_ptr) { //AiNodeDeclare(mynode, "aaa", "constant ARRAY RGB"); *user_ptr = mynode; // make a copy of the parent procedural GIO_loadPath = string(AiNodeGetStr(mynode,"GIO_loadPath")); std::cout<<"get load path is "<<GIO_loadPath<<std::endl; GIO_radius = AiNodeGetFlt(mynode,"GIO_radius"); return true; } static int MyCleanup(void *user_ptr) { return true; } static int MyNumNodes(void *user_ptr) { return 1; } static AtNode *MyGetNode(void *user_ptr, int i) { g_global_io io; initMyIo(io); calNumPt(io); AtArray *pointarray = AiArrayAllocate(numPt,1,AI_TYPE_POINT); AtArray *radiusarray=AiArrayAllocate(numPt,1,AI_TYPE_FLOAT); //AtArray *Parray=AiArrayAllocate(numPt,1,AI_TYPE_RGBA); //test att makecloud(io,pointarray, radiusarray,GIO_radius); AtNode *node = AiNode("points"); //AiNodeDeclare(node, "mycolor", "uniform RGBA"); AiNodeSetArray(node, "points", pointarray); AiNodeSetArray(node, "radius", radiusarray); //forkTheSingleVec(io,Parray); //AiNodeSetArray(node, "mycolor", Parray); //now set the flt vector attribute list std::vector <AtArray*> extraFLT_VecAttList; forkTheVecFltAttribute(io,extraFLT_VecAttList,node); // std::vector <AtArray*> extraINT_VecAttList; forkTheVecIntAttribute(io,extraINT_VecAttList,node); // std::vector <AtArray*> extraINT_AttList; forkTheIntAttribute(io,extraINT_AttList,node); // std::vector <AtArray*> extraFLT_AttList; forkTheFltAttribute(io,extraFLT_AttList,node); AiNodeSetStr(node, "mode", "sphere"); return node; } // vtable passed in by proc_loader macro define proc_loader { vtable->Init = MyInit; vtable->Cleanup = MyCleanup; vtable->NumNodes = MyNumNodes; vtable->GetNode = MyGetNode; strcpy(vtable->version, AI_VERSION); return true; }
// Created on: 1997-10-31 // Created by: Joelle CHAUVET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepFill_CurveConstraint_HeaderFile #define _BRepFill_CurveConstraint_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <GeomPlate_CurveConstraint.hxx> #include <Standard_Integer.hxx> class BRepFill_CurveConstraint; DEFINE_STANDARD_HANDLE(BRepFill_CurveConstraint, GeomPlate_CurveConstraint) //! same as CurveConstraint from GeomPlate //! with BRepAdaptor_Surface instead of //! GeomAdaptor_Surface class BRepFill_CurveConstraint : public GeomPlate_CurveConstraint { public: //! Create a constraint //! Order is the order of the constraint. The possible values for order are -1,0,1,2. //! Order i means constraints Gi //! Npt is the number of points associated with the constraint. //! TolDist is the maximum error to satisfy for G0 constraints //! TolAng is the maximum error to satisfy for G1 constraints //! TolCurv is the maximum error to satisfy for G2 constraints //! These errors can be replaced by laws of criterion. Standard_EXPORT BRepFill_CurveConstraint(const Handle(Adaptor3d_CurveOnSurface)& Boundary, const Standard_Integer Order, const Standard_Integer NPt = 10, const Standard_Real TolDist = 0.0001, const Standard_Real TolAng = 0.01, const Standard_Real TolCurv = 0.1); Standard_EXPORT BRepFill_CurveConstraint(const Handle(Adaptor3d_Curve)& Boundary, const Standard_Integer Tang, const Standard_Integer NPt = 10, const Standard_Real TolDist = 0.0001); DEFINE_STANDARD_RTTIEXT(BRepFill_CurveConstraint,GeomPlate_CurveConstraint) protected: private: }; #endif // _BRepFill_CurveConstraint_HeaderFile
#pragma once #include <stdexcept> namespace CCC { template<class T> class Expected { public: explicit Expected(T* _r) : result(_r), gotResult(_r) { if (!gotResult) ex = std::runtime_error("Object not found!"); } explicit Expected(T& _r) : Expected<T>(&_r) {} Expected() = delete; const bool isValid() const noexcept { return gotResult; } const T* operator->() const { return get(); } const T* get() const { if (!result) throw ex; return result; } private: const T* result; bool gotResult; std::exception ex; }; }
#include <iostream> #include <GL/glew.h> #include <GL/gl.h> #include "Display.hpp" #include "DisplaySettings.hpp" #include <imgui/imgui.h> #include <imgui/imgui_impl_opengl3.h> #include <imgui/imgui_impl_sdl.h> //////////////////////////////////////////////////////////////////////////////// Display::Display() { SDL_Init(SDL_INIT_EVERYTHING); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_DisplayMode display_mode; SDL_GetCurrentDisplayMode(0, &display_mode); width_ = DisplaySettings::WIDTH; height_ = DisplaySettings::HEIGHT; window_ = SDL_CreateWindow(DisplaySettings::TITLE.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width_, height_, SDL_WINDOW_OPENGL); context_ = SDL_GL_CreateContext(window_); glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) std::cout << "Error: Could not initialize glew" << std::endl; window_is_closed_ = false; /* Prevent faces behind other faces from being rendered */ glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Setup Dear ImGui binding IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls ImGui_ImplSDL2_InitForOpenGL(window_, context_); ImGui_ImplOpenGL3_Init("#version 130"); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glViewport(0, 0, width_, height_); } //////////////////////////////////////////////////////////////////////////////// Display::~Display() { SDL_GL_DeleteContext(context_); SDL_DestroyWindow(window_); SDL_Quit(); } //////////////////////////////////////////////////////////////////////////////// void Display::Update() { SDL_GL_SwapWindow(window_); } //////////////////////////////////////////////////////////////////////////////// bool Display::IsClosed() const { return window_is_closed_; } //////////////////////////////////////////////////////////////////////////////// void Display::Quit() { window_is_closed_ = true; } //////////////////////////////////////////////////////////////////////////////// SDL_Window* Display::WindowHandle() const { return window_; } /// @file
#include "bits/stdc++.h" using namespace std; // Program to check wheather a number is prime or not // T(n)=O(N) bool is_prime(int n){ if(n==1) return false; for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } // T(N)=O(sqrt(N)) bool is_prime_opt(int n){ if (n==1) return false; for (int i=2;i<=sqrt(n);i++){ if(n%i==0) return false; } return true; } /* Logic -> All divisor (that divides the number completely) occurs in pair eg 12=1,2,3,4,6,12 pair -> (1,12), (6,2) ,(3,4) Theorm -> (a,b) then a lies below sqrt(n) and b lies above sqrt(n) unless a==b lies on sqrt(n) */ int main() { int n; cin>>n; if(is_prime_opt(n)) cout<<"prime"; else cout<<"not prime"; return 0; }
#include <stdio.h> #define MAX_N 100 /* given an image represented by an N*N matrix, where each pixel in the image is 4 bytes.write an method to rotate the image by 90 degrees.can you do this in place? rotate the image clockwise my solution.swap the data in i line with the data in i row. after all data have been replace,reverse the data in each line. */ void my_swap(int *a,int *b){ int temp = *a; *a = *b; *b = temp; } void my_reverse(int matrix[][MAX_N], int length){ int i = 0; int j = 0; int half_len = (int) (length / 2); for(;i < length; i++){ for(j = 0;j < half_len; j++){ my_swap(&matrix[i][j], &matrix[i][length-j-1]); } } } void print_matrix(int matrix[][MAX_N], int length){ int i = 0; int j = 0; for(;i < length; i++){ for(j = 0;j < length; j++){ printf("%d ",matrix[i][j]); } printf("\n"); } } void my_rotate(int matrix[][MAX_N], int length){ int i = 0; int j = 0; for(;i < length; i++){ for(j = i; j < length; j++){ my_swap(&matrix[i][j], &matrix[j][i]); } } } //int main(){ // int my_matrix[MAX_N][MAX_N]; // int i = 0; // int j = 0; // int length = 0; // printf("input N:\n"); // scanf("%d", &length); // for(;i<length;i++){ // printf("input the %d line data\n",i); // for(j = 0;j < length;j++){ // scanf("%d", &my_matrix[i][j]); // } // } // printf("before rotate\n"); // print_matrix(my_matrix,length); // my_rotate(my_matrix,length); // //print_matrix(my_matrix,length); // my_reverse(my_matrix,length); // printf("after rotate\n"); // print_matrix(my_matrix,length); // return 0; //}
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <numeric> #include <stdio.h> #include <string.h> #define INF (1<<30) #define LINF (1e17) using namespace std; class DengklekMakingChains { public: int maxBeauty(vector <string> chains) { int N = (int)chains.size(); vector<int> prefix(2,0),suffix(2,0); int single = 0; int ans = 0; for (int i=0; i<N; ++i) { for (int j=0;j<3;++j) if (chains[i][j] != '.') single = max(single, chains[i][j]-'0'); int sum = 0; bool f = true; for (int j=0; j<3; ++j) { f = f && chains[i][j] != '.'; if (!f) break; sum += chains[i][j] - '0'; } if (f) { ans += sum; continue; } prefix.push_back(sum); sum = 0; for (int j=2; j>=0; --j) { if (chains[i][j] == '.') break; sum += chains[i][j] - '0'; } suffix.push_back(sum); } int M = (int)prefix.size(); for (int i=0;i<M;++i) for (int j=0;j<M;++j) if (i!=j) single = max(single,ans+prefix[i]+suffix[j]); return single; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {".15", "7..", "402", "..3"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 19; verify_case(0, Arg1, maxBeauty(Arg0)); } void test_case_1() { string Arr0[] = {"..1", "7..", "567", "24.", "8..", "234"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 36; verify_case(1, Arg1, maxBeauty(Arg0)); } void test_case_2() { string Arr0[] = {"...", "..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(2, Arg1, maxBeauty(Arg0)); } void test_case_3() { string Arr0[] = {"16.", "9.8", ".24", "52.", "3.1", "532", "4.4", "111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 28; verify_case(3, Arg1, maxBeauty(Arg0)); } void test_case_4() { string Arr0[] = {"..1", "3..", "2..", ".7."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; verify_case(4, Arg1, maxBeauty(Arg0)); } void test_case_5() { string Arr0[] = {"..1", "9.8", "567", "24.", "8.6", ".42"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 34; verify_case(5, Arg1, maxBeauty(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { DengklekMakingChains ___test; ___test.run_test(-1); } // END CUT HERE
#include<iostream> #include<stdio.h> #include "p1.cpp" using namespace std; int main() { FILE *f; int a,b,val,i f=fopen("testresults.txt","r"); if(f==NULL) { cout<<"error\n"; } else{ i=0; while(!feof(f)) { fscanf(f,"%d %d %d",&a,&b,&val); if(div(a,b)==val) cout<<"Test Case"<<i<<" Passed\n"; else cout<<"Test Case"<<i<<" Failed\n"; i++; } } return 0; }
#include "GnMainPCH.h" #include "GnRenderFrame.h" GnRenderFrame::GnRenderFrame() { } GnRenderFrame::~GnRenderFrame() { } void GnRenderFrame::Draw() { GnRenderer* renderer = GnRenderer::GetRenderer(); renderer->BeginFrame(); ElementIterator iter = mList.GetIterator(); GnRenderViewSet* step; while( iter.Valid() ) { step = iter.Item(); if( step && step->GetActive() ) step->Render(); iter.Forth(); } if( mList.GetCount() ) { renderer->EndRenderTarget(); } renderer->EndFrame(); } void GnRenderFrame::Render() { GnRenderer* renderer = GnRenderer::GetRenderer(); renderer->RenderFrame(); } void GnRenderFrame::Update(float fTime) { ElementIterator iter = mList.GetIterator(); GnRenderViewSet* step; while( iter.Valid() ) { step = iter.Item(); if( step && step->GetActive() ) { step->Update(fTime); } iter.Forth(); } }
#include "CComplex.h" CComplex::CComplex(double real, double image) :m_real(real) , m_image(image) { } double CComplex::Re() const { return m_real; } double CComplex::Im() const { return m_image; } double CComplex::GetMagnitude() const { return sqrt(pow(m_real, 2) + pow(m_image, 2)); } double CComplex::GetArgument() const { return atan(m_image / m_real); } CComplex const CComplex::operator+(CComplex const& complex2) const { return CComplex(m_real + complex2.m_real, m_image + complex2.m_image); } CComplex const CComplex::operator-(CComplex const& complex2) const { return CComplex(m_real - complex2.m_real, m_image - complex2.m_image); } CComplex const CComplex::operator*(CComplex const& complex2) const { return CComplex(m_real * complex2.m_real - m_image * complex2.m_image, m_real * complex2.m_image + complex2.m_real * m_image); } CComplex const CComplex::operator*(double scalar) const { return CComplex(m_real * scalar, m_image * scalar); } CComplex const CComplex::operator/(CComplex const& complex2) const { double powSum = pow(complex2.m_real, 2) + pow(complex2.m_image, 2); if (powSum == 0) { cout << ERROR_DIVIDE_ZERO << endl; return *this; } double real = (m_real * complex2.m_real + m_image * complex2.m_image) / powSum; double image = (m_image * complex2.m_real - m_real * complex2.m_image) / powSum; return CComplex(real, image); } CComplex const CComplex::operator/(double scalar) const { if (scalar == 0) { cout << ERROR_DIVIDE_ZERO << endl; return *this; } return CComplex(m_real / scalar, m_image / scalar); } CComplex const CComplex::operator-() const { return CComplex(-m_real, -m_image); } CComplex const CComplex::operator+() const { return *this; } CComplex& CComplex::operator+=(CComplex const& complex) { m_real += complex.m_real; m_image += complex.m_image; return *this; } CComplex& CComplex::operator-=(CComplex const& complex) { m_real -= complex.m_real; m_image -= complex.m_image; return *this; } CComplex& CComplex::operator*=(CComplex const& complex) { double newReal, newImage; newReal = m_real * complex.m_real - m_image * complex.m_image; newImage = m_real * complex.m_image + complex.m_real * m_image; m_real = newReal; m_image = newImage; return *this; } CComplex& CComplex::operator*=(double scalar) { m_real *= scalar; m_image *= scalar; return *this; } CComplex& CComplex::operator/=(CComplex const& complex) { double powSum = pow(complex.m_real, 2) + pow(complex.m_image, 2); if (powSum == 0) { cout << ERROR_DIVIDE_ZERO << endl; return *this; } double newReal, newImage; newReal = (m_real * complex.m_real + m_image * complex.m_image) / powSum; newImage = (m_image * complex.m_real - m_real * complex.m_image) / powSum; m_real = newReal; m_image = newImage; return *this; } CComplex& CComplex::operator/=(double scalar) { if (scalar == 0) { cout << ERROR_DIVIDE_ZERO << endl; return *this; } m_real /= scalar; m_image /= scalar; return *this; } bool CComplex::operator==(CComplex const& other) const { return (fabs(m_real - other.m_real) < DBL_EPSILON && fabs(m_image - other.m_image) < DBL_EPSILON); } bool CComplex::operator==(double scalar) const { return (fabs(m_real - scalar) < DBL_EPSILON && m_image == 0); } bool CComplex::operator!=(CComplex const& other) const { return !(*this == other); } bool CComplex::operator!=(double scalar) const { return !(*this == scalar); } CComplex const operator*(double scalar, CComplex const& complex) { return CComplex(scalar * complex.Re(), scalar * complex.Im()); } bool operator==(double scalar, CComplex const& complex) { return (fabs(scalar - complex.Re() < DBL_EPSILON) && complex.Im() == 0); } bool operator!=(double scalar, CComplex const& complex) { return !(scalar == complex); } ostream& operator<<(ostream& stream, CComplex const& complex) { if (complex.Re() == 0 && complex.Im() == 0) { stream << "0"; } else { if (complex.Re() != 0) { stream << complex.Re(); } if (complex.Im() != 0) { if (complex.Im() > 0 && complex.Re() != 0) { stream << "+"; } stream << complex.Im() << "i"; } } return stream; } istream& operator>>(istream& stream, CComplex& complex) { double real = 0, image = 0; string line; getline(stream, line); if (line.empty()) { complex = CComplex(real, image); return stream; } bool isFirstMinus = line[0] == '-'; if (isFirstMinus) { line = line.substr(1); } int minus = line.find("-"); int plus = line.find("+"); int i = line.find("i"); if (minus == -1 && plus == -1 && i == -1) { // только действительное отрицательное число real = stod(line); if (isFirstMinus) { real *= -1; } } if (minus != -1) { // идет отрицательное мнимое число real = stod(line.substr(0, minus)); if (isFirstMinus) { real *= -1; } line = line.substr(minus + 1); int i = line.find("i"); image = stod(line.substr(0, i)) * -1; } if (plus != -1) { // идет положительное мнимое число real = stod(line.substr(0, plus)); if (isFirstMinus) { real *= -1; } line = line.substr(plus + 1); int i = line.find("i"); image = stod(line.substr(0, i)); } if (minus == -1 && plus == -1 && i != -1) { image = stod(line); if (isFirstMinus) { image *= -1; } } complex = CComplex(real, image); return stream; }
#include <iostream> #include <vector> using ll=long long; using namespace std; const int maxn =200005; vector<int> v; int n,k; int main(){ cin>>n>>k; for(int i=1;i<=n;i++) v.emplace_back(i); int pos=0; for(int i=0;i<k;i++){ int x; cin>>x; pos=(pos+x)%n; cout<<v[pos]<<' '; v.erase(v.begin()+pos); n--; } return 0; }
#include<iostream> #include "windows.h" #include "cstdlib" #include <ctime> int main() { setlocale(LC_ALL, "Russian"); int i = 0; std::string loading = "#"; srand(time(NULL)); std::cout << "Взлом NASA"; Sleep(2000); do { if (i >= 100) { system("cls"); std::cout << "ИДЕТ ВЗЛОМ - "; std::cout << 100 << '%'; break; } system("cls"); std::cout << "ИДЕТ ВЗЛОМ - "; std::cout << i << '%'; i += rand() % 5 + 1; std::cout << '\n' << loading; loading = loading + '#'; Sleep(rand() % 1000 + 1); } while (true); std::cout << "\nВзлом завершен!"; }
#include <octomap/octomap.h> #include <octomap/ColorOcTree.h> #include "testing.h" using namespace std; using namespace octomap; void print_query_info(point3d query, ColorOcTreeNode* node) { if (node != NULL) { cout << "occupancy probability at " << query << ":\t " << node->getOccupancy() << endl; cout << "color of node is: " << node->getColor() << endl; } else cout << "occupancy probability at " << query << ":\t is unknown" << endl; } int main(int /*argc*/, char** /*argv*/) { double res = 0.05; // create empty tree with resolution 0.05 (different from default 0.1 for test) ColorOcTree tree (res); // insert some measurements of occupied cells for (int x=-20; x<20; x++) { for (int y=-20; y<20; y++) { for (int z=-20; z<20; z++) { point3d endpoint ((float) x*0.05f+0.01f, (float) y*0.05f+0.01f, (float) z*0.05f+0.01f); ColorOcTreeNode* n = tree.updateNode(endpoint, true); n->setColor(z*5+100,x*5+100,y*5+100); } } } // insert some measurements of free cells for (int x=-30; x<30; x++) { for (int y=-30; y<30; y++) { for (int z=-30; z<30; z++) { point3d endpoint ((float) x*0.02f+2.0f, (float) y*0.02f+2.0f, (float) z*0.02f+2.0f); ColorOcTreeNode* n = tree.updateNode(endpoint, false); n->setColor(255,255,0); // set color to yellow } } } // set inner node colors tree.updateInnerOccupancy(); // should already be pruned EXPECT_EQ(tree.size(), tree.calcNumNodes()); const size_t initialSize = tree.size(); EXPECT_EQ(initialSize, 1034); tree.prune(); EXPECT_EQ(tree.size(), tree.calcNumNodes()); EXPECT_EQ(initialSize, tree.size()); cout << endl; std::cout << "\nWriting to / from file\n===============================\n"; std::string filename ("simple_color_tree.ot"); std::cout << "Writing color tree to " << filename << std::endl; // write color tree EXPECT_TRUE(tree.write(filename)); // read tree file cout << "Reading color tree from "<< filename <<"\n"; AbstractOcTree* read_tree = AbstractOcTree::read(filename); EXPECT_TRUE(read_tree); EXPECT_EQ(read_tree->getTreeType().compare(tree.getTreeType()), 0); EXPECT_FLOAT_EQ(read_tree->getResolution(), tree.getResolution()); EXPECT_EQ(read_tree->size(), tree.size()); ColorOcTree* read_color_tree = dynamic_cast<ColorOcTree*>(read_tree); EXPECT_TRUE(read_color_tree); EXPECT_TRUE(tree == *read_color_tree); { cout << "Performing some queries:" << endl; // TODO: some more meaningful tests point3d query (0., 0., 0.); ColorOcTreeNode* result = tree.search (query); ColorOcTreeNode* result2 = read_color_tree->search (query); std::cout << "READ: "; print_query_info(query, result); std::cout << "WRITE: "; print_query_info(query, result2); EXPECT_TRUE(result); EXPECT_TRUE(result2); EXPECT_EQ(result->getColor(), result2->getColor()); EXPECT_EQ(result->getLogOdds(), result2->getLogOdds()); query = point3d(-1.,-1.,-1.); result = tree.search (query); result2 = read_color_tree->search (query); print_query_info(query, result); std::cout << "READ: "; print_query_info(query, result); std::cout << "WRITE: "; print_query_info(query, result2); EXPECT_TRUE(result); EXPECT_TRUE(result2); EXPECT_EQ(result->getColor(), result2->getColor()); EXPECT_EQ(result->getLogOdds(), result2->getLogOdds()); query = point3d(1.,1.,1.); result = tree.search (query); result2 = read_color_tree->search (query); print_query_info(query, result); std::cout << "READ: "; print_query_info(query, result); std::cout << "WRITE: "; print_query_info(query, result2); EXPECT_FALSE(result); EXPECT_FALSE(result2); } delete read_tree; read_tree = NULL; { std::cout << "\nPruning / expansion\n===============================\n"; EXPECT_EQ(initialSize, tree.size()); EXPECT_EQ(initialSize, tree.calcNumNodes()); std::cout << "Initial size: " << tree.size() << std::endl; // tree should already be pruned during insertion: tree.prune(); EXPECT_EQ(initialSize, tree.size()); EXPECT_EQ(initialSize, tree.calcNumNodes()); tree.expand(); std::cout << "Size after expansion: " << tree.size() << std::endl; EXPECT_EQ(tree.size(), tree.calcNumNodes()); // prune again, should be same as initial size tree.prune(); EXPECT_EQ(initialSize, tree.size()); EXPECT_EQ(initialSize, tree.calcNumNodes()); } // delete / create some nodes { std::cout << "\nCreating / deleting nodes\n===============================\n"; size_t initialSize = tree.size(); EXPECT_EQ(initialSize, tree.calcNumNodes()); std::cout << "Initial size: " << initialSize << std::endl; point3d newCoord(-2.0, -2.0, -2.0); ColorOcTreeNode* newNode = tree.updateNode(newCoord, true); newNode->setColor(255,0,0); EXPECT_TRUE(newNode != NULL); const size_t insertedSize = tree.size(); std::cout << "Size after one insertion: " << insertedSize << std::endl; EXPECT_EQ(insertedSize, initialSize+6); EXPECT_EQ(insertedSize, tree.calcNumNodes()); // find parent of newly inserted node: ColorOcTreeNode* parentNode = tree.search(newCoord, tree.getTreeDepth() -1); EXPECT_TRUE(parentNode); EXPECT_TRUE(tree.nodeHasChildren(parentNode)); // only one child exists: EXPECT_TRUE(tree.nodeChildExists(parentNode, 0)); for (size_t i = 1; i < 8; ++i){ EXPECT_FALSE(tree.nodeChildExists(parentNode, i)); } tree.deleteNodeChild(parentNode, 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); EXPECT_EQ(tree.size(), insertedSize - 1); tree.prune(); EXPECT_EQ(tree.size(), tree.calcNumNodes()); EXPECT_EQ(tree.size(), insertedSize - 1); tree.expandNode(parentNode); EXPECT_EQ(tree.size(), tree.calcNumNodes()); EXPECT_EQ(tree.size(), insertedSize + 7); EXPECT_TRUE(tree.pruneNode(parentNode)); EXPECT_EQ(tree.size(), tree.calcNumNodes()); EXPECT_EQ(tree.size(), insertedSize - 1); EXPECT_TRUE(tree.write("simple_color_tree_ed.ot")); } return 0; }
/*=============================================================== * Copyright (C) 2017 All rights reserved. * * FileName:HMMProbability.cpp * creator:yuliu1@microsoft.com * Time:12/02/2017 * Description: * Notice: * Updates: * ================================================================*/ #include "HMMProbability.h" #include "HMM.h" // please add your code here! #include<fstream> #include<stdlib.h> #include<iostream> std::vector<std::string> HMMProbability::StringSplit(std::string sstr, const char* delim) { std::vector<std::string> results; char *src = new char [sstr.length() + 1]; strncpy(src,sstr.c_str(),sstr.length()); src[sstr.length()] = 0; char *p = strtok(src,delim); if ( p!= NULL) { results.push_back(p); } while ( (p=strtok(NULL,delim)) != NULL ) { results.push_back(p); } if (src != NULL ) { delete [] src; src = NULL; } return results; } void HMMProbability::GetStatesInfo(const char * filename) { std::ifstream fin(filename); std::string line = ""; int id = 0; while (std::getline(fin,line)) { std::vector<std::string> lines = StringSplit(line,"\t"); states2Id.insert(std::make_pair(lines[0],id)); Id2States.push_back(lines[0]); id++; } statesNum=id; std::cerr << "statesNum="<<statesNum<<std::endl; fin.close(); } void HMMProbability::GetSymbolsInfo(const char * filename) { std::ifstream fin(filename); std::string line = ""; int id = 0; while (std::getline(fin,line)) { std::vector<std::string> lines = StringSplit(line,"\t"); symbols2Id.insert(std::make_pair(lines[0],id)); Id2Symbols.push_back(lines[0]); id++; } symbolsNum=id; std::cerr << "symbolsNum="<<symbolsNum<<std::endl; fin.close(); } void HMMProbability::InitializeProbabilities() { transits = new double* [statesNum]; for (int i = 0 ; i<statesNum;i++) { transits[i] = new double[statesNum]; memset(transits[i],0,sizeof(double)*statesNum); } states = new double [statesNum]; memset(states,0,sizeof(double)*statesNum); endstates = new double [statesNum]; memset(endstates,0,sizeof(double)*statesNum); emits = new double* [statesNum]; for (int i = 0; i< statesNum;i++) { emits[i] = new double[symbolsNum]; memset(emits[i],0, sizeof(double)*symbolsNum); } } void HMMProbability::BuildProbabilities(const char* filename) { InitializeProbabilities(); for (int i = 0; i < statesNum;i++) { states[i] = 1.0/double(statesNum); } for (int i = 0; i < statesNum;i++) { endstates[i] = 1.0/double(statesNum); } for (int i = 0; i < statesNum;i++) { for (int j = 0; j < statesNum;j++) { transits[i][j]=1.0/double(statesNum); } } for (int i = 0; i < statesNum;i++) { for (int j = 0; j < symbolsNum;j++) { emits[i][j] = 1.0/double(symbolsNum); } } std::cerr <<"initial"<<std::endl; PrintProbabilities(); Train(filename); } void HMMProbability::LoadProbabilities(const char *filename) { InitializeProbabilities(); std::ifstream fin(filename); std::string line = ""; int id = 0; while (std::getline(fin,line)) { if (line=="") { id = 0; continue; } std::vector<std::string> lines = StringSplit(line,"\t"); if (lines[0]=="states") { for (int i = 1; i < lines.size();i++) { states[i-1] = atof(lines[i].c_str()); } } if (lines[0]=="endstates") { for (int i = 1; i < lines.size();i++) { endstates[i-1] = atof(lines[i].c_str()); } } if (lines[0]=="transits") { for (int i = 1; i < lines.size();i++) { transits[id][i-1] = atof(lines[i].c_str()); } } if (lines[0]=="emits") { for(int i = 1; i < lines.size();i++) { emits[id][i-1] = atof(lines[i].c_str()); } } id++; } fin.close(); } void HMMProbability::clear() { if (states!= NULL) { delete [] states; states = NULL; } if (endstates!= NULL) { delete [] endstates; endstates = NULL; } if (transits != NULL) { for (int i = 0; i < statesNum;i++) { if (transits[i] != NULL) { delete [] transits[i]; transits[i] = NULL; } } delete [] transits; transits = NULL; } if (emits != NULL) { for (int i = 0; i < statesNum; i++) { if (emits[i] != NULL) { delete [] emits[i]; emits[i] = NULL; } } delete [] emits; emits = NULL; } } void HMMProbability:: Initialize(bool EMmode) { GetStatesInfo("Labels.txt"); GetSymbolsInfo("Symbols.txt"); if (!EMmode) { LoadProbabilities("hmm.model.txt"); } else { BuildProbabilities("train.txt"); } } void HMMProbability::PrintProbabilities() { std::cerr<<"states"; for (int i = 0; i < statesNum;i++) { std::cerr<<"\t"<<states[i]; } std::cerr<<std::endl; std::cerr<<"endstates"; for (int i = 0; i < statesNum;i++) { std::cerr<<"\t"<<endstates[i]; } std::cerr<<std::endl; for (int i = 0; i < statesNum;i++) { std::cerr<<"transits"; for (int j = 0; j < statesNum;j++) { std::cerr<<"\t"<<transits[i][j]; } std::cerr << std::endl; } for (int i = 0; i < statesNum;i++) { std::cerr<<"emits"; for (int j = 0; j < symbolsNum;j++) { std::cerr<<"\t"<<emits[i][j]; } std::cerr << std::endl; } } // notice here should has constraints void HMMProbability::Train(const char *filename) { std::ifstream fin(filename); std::string line = ""; int linecount = 0; while (std::getline(fin,line)) { std::vector<std::string> lines = StringSplit(line,"#"); if (lines.size()<=1) { continue; } linecount++; if (linecount%100==0) { std::cerr<<"EM training linecount="<<linecount<< std::endl; } HMM hmm(lines,this); hmm.Train(this); std::cerr << "training sample count="<<linecount<<std::endl; PrintProbabilities(); } fin.close(); } HMMProbability::~HMMProbability() { clear(); }
#include <iostream> #include <boost/mpl/int.hpp> /** * @brief static computation of factorial (compilation time) * @return the factorial of X */ template<int X> int factorial() { using namespace boost::mpl; return X * factorial< int_<X>::prior::value >(); } /** * @brief specialization for factorial<1>() * @return 1 */ template<> int factorial<1>() { return 1; } int main(int argc, char** argv) { std::cout << "Statically computed value of factorial<8> is:" << factorial<8>() << std::endl; return 0; }
// // main.cpp // DogAndGopher // // Created by Russell Lowry on 11/27/17. // Copyright © 2017 Russell Lowry. All rights reserved. // #include <iostream> #include <stdio.h> #include <math.h> #include <sstream> #include <iomanip> using namespace std; int main(int argc, const char * argv[]) { int number; double gopherX, gopherY, dogX, dogY; while(scanf("%d%lf%lf%lf%lf", &number, &gopherX, &gopherY, &dogX, &dogY) == 5) { bool hasEscaped = false; double x1, y1, x2, y2; int x; for (x = 1; x <= number; x++) { scanf("%lf%lf", &x1, &y1); double sqrtValGopher = sqrt((gopherX-x1) * (gopherX-x1) + (gopherY-y1) * (gopherY-y1)) * 2; double sqrtValDog = sqrt((dogX-x1) * (dogX-x1) + (dogY-y1) * (dogY-y1)); if (!hasEscaped && sqrtValGopher <= sqrtValDog) { hasEscaped = true; x2 = x1; y2 = y1; } } if (hasEscaped) { cout << "The gopher can escape through the hole at (" << setprecision(3) << fixed << x2 << "," << setprecision(3) << fixed << y2 << ").\n"; } else { cout << "The gopher cannot escape.\n"; } } return 0; }
// ComplexCalculator.h : main header file for the COMPLEXCALCULATOR application // #if !defined(AFX_COMPLEXCALCULATOR_H__26CAE571_198C_4BCB_B6F9_5B0D04FBD9A4__INCLUDED_) #define AFX_COMPLEXCALCULATOR_H__26CAE571_198C_4BCB_B6F9_5B0D04FBD9A4__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CComplexCalculatorApp: // See ComplexCalculator.cpp for the implementation of this class // class CComplexCalculatorApp : public CWinApp { public: CComplexCalculatorApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CComplexCalculatorApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CComplexCalculatorApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_COMPLEXCALCULATOR_H__26CAE571_198C_4BCB_B6F9_5B0D04FBD9A4__INCLUDED_)
#pragma once #include <iberbar/Poster/Elements/ElementBase.h> namespace iberbar { namespace Poster { class CElementImage; IBERBAR_UNKNOWN_PTR_DECLARE( CElementImage ); class __iberbarExports__ CElementImage : public CElementBase { public: CElementImage(); public: virtual void RenderSelf( CSurface* target ) override; public: void SetImage( CSurface* image ) { m_image = image; } void SetCorner( int radius ) { m_cornerRadius = radius; } protected: PTR_CSurface m_image; int m_cornerRadius; }; } }
// Copyright 2012 Yandex #ifndef LTR_LEARNERS_DECISION_TREE_CONDITIONS_LEARNER_H_ #define LTR_LEARNERS_DECISION_TREE_CONDITIONS_LEARNER_H_ #include <vector> #include "ltr/data/data_set.h" #include "ltr/interfaces/parameterized.h" #include "ltr/learners/decision_tree/condition.h" #include "ltr/utility/shared_ptr.h" using std::vector; namespace ltr { namespace decision_tree { class ConditionsLearner : public Parameterized { public: typedef ltr::utility::shared_ptr<ConditionsLearner> Ptr; typedef ltr::utility::shared_ptr<ConditionsLearner> BasePtr; /** * Function used to gen the next conditions set. * Returns 0 if can't generate or 1 if it could. * @param result - pointer to the vector to save result in. */ virtual int getNextConditions(vector<Condition::Ptr>* result) = 0; /** * Function used to set data set to generate conditions. */ void setDataSet(DataSet<Object> data) { data_ = data; init(); } /** Function used as a callback to tell ConditionsLearner * the quality of the last conditions set. */ virtual void setLastSplittingQuality(double quality) {} private: virtual void init() = 0; protected: DataSet<Object> data_; }; class FakeConditionsLearner : public ConditionsLearner { public: virtual int getNextConditions(vector<Condition::Ptr>* result) { return 0; } private: virtual void init() {} }; }; }; #endif // LTR_LEARNERS_DECISION_TREE_CONDITIONS_LEARNER_H_
/* Name: SquareWaveGen.ino Created: 30.07.2018 17:32:03 Author: Павел Unfortunately, timer approach can hardly provide ~200kHz, PWM can provide up to 8MHz but is too complex for this purpose. Better stick to arduino-based NOP bit-banger (see below). */ #define USE_TIMER_BASED 0 #if USE_TIMER_BASED #include <avr\interrupt.h> ISR(TIMER1_COMPA_vect) { TCNT1H = 0x00; TCNT1L = 0x00; PORTB ^= 0x01; } // the setup function runs once when you press reset or power the board void setup() { TIMSK0 &= ~_BV(TOIE0); //Disable millis interrupt pinMode(8, OUTPUT); // Timer/Counter 1 initialization // Clock source: System Clock // Clock value: 16000,000 kHz // Mode: Normal top=0xFFFF // OC1A output: Discon. // OC1B output: Discon. // Noise Canceler: Off // Input Capture on Falling Edge // Timer1 Overflow Interrupt: Off // Input Capture Interrupt: Off // Compare A Match Interrupt: On // Compare B Match Interrupt: Off TCCR1A = 0x00; TCCR1B = 0x01; TCNT1H = 0x00; TCNT1L = 0x00; ICR1H = 0x00; ICR1L = 0x00; OCR1AH = 0x00; OCR1AL = 0x0A; OCR1BH = 0x00; OCR1BL = 0x00; // Timer/Counter 1 Interrupt(s) initialization TIMSK1 = 0x02; sei(); } // the loop function runs over and over again until power down or reset void loop() { while (true); } #else //Bit-banger #define NOP __asm__ __volatile__ ("nop\n\t") #define MICROSECOND_DELAY NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; //Almost exactly 1uS half-period on Arduino Nano #define ADDITIONAL_DELAY NOP;NOP;NOP; void setup() { // put your setup code here, to run once: pinMode(8, OUTPUT); //TIMSK0 &= ~_BV(TOIE0); //Disable millis interrupt noInterrupts(); //Alternative } void loop() { // put your main code here, to run repeatedly: //digitalWrite(8, !digitalRead(8)); //About 5-7uS between transitions PORTB^=0x01; MICROSECOND_DELAY //MICROSECOND_DELAY //1uS, including PORT and jumps //ADDITIONAL_DELAY //Compensates time required for PORT instructions and jumps when half-period is more than 1uS } #endif // USE_TIMER_BASED
// Motor Y es el de los leds // Motor X es el del enfoque del portamuestras (eje z del portamuestras) #define Y_DIR_PIN 61 // poner número del pin de dirección #define Y_STEP_PIN 60 // poner número de pin de conexión al motor #define Y_ENABLE_PIN 56 // poner número de pin de poner en marcha #define FIN_CARRERA_1 3 // poner número de pin de final de carrera 1 #define FIN_CARRERA_2 2 // poner número de pin de final de carrera 2 #define FIN_CARRERA_3 14 // poner número de pin de final de carrera 3 #define X_DIR_PIN 54 // poner número del pin de dirección #define X_STEP_PIN 55 // poner número de pin de conexión al motor #define X_ENABLE_PIN 38 // poner número de pin de poner en marcha #define TRIGGER_FILTRO_LINEAL 16 // poner número de pin con el que leer el disparo de cada movimiento del filtro lineal int stepDelay = 100; // tiempo de parada para controlar la velocidad int num_trigger = 5; // poner el número de posiciones que tiene el filtro lineal para poder controlar cuando acaba el movimiento boolean pos_1 = false; boolean pos_2 = false; boolean pos_3 = false; boolean pos_final = false; boolean primer_arranque = true; boolean primera_conexion = true; int final_carrera_1 = 1; int final_carrera_2 = 1; int final_carrera_3 = 1; int cont_led = 0; int cont_filtro = 0; int trigger = 0; void setup() { // Marcar los pines como salida pinMode(Y_STEP_PIN, OUTPUT); pinMode(Y_DIR_PIN, OUTPUT); pinMode(Y_ENABLE_PIN, OUTPUT); digitalWrite(Y_ENABLE_PIN, LOW); pinMode(FIN_CARRERA_1, INPUT_PULLUP); pinMode(FIN_CARRERA_2, INPUT_PULLUP); pinMode(FIN_CARRERA_3, INPUT_PULLUP); pinMode(X_STEP_PIN, OUTPUT); pinMode(X_DIR_PIN, OUTPUT); pinMode(X_ENABLE_PIN, OUTPUT); pinMode(TRIGGER_FILTRO_LINEAL, INPUT); //digitalWrite(TRIGGER_FILTRO_LINEAL,LOW); Serial.begin(115200); } void loop() { if (primera_conexion == true) // cuando encendemos el puerto serie mandamos la comprobacion de que es nuestro programa el que busca { delayMicroseconds(500); Serial.print("a"); // codigo ascii 97 primera_conexion = false; } if (primer_arranque == true) // cuando encendemos el programa nos vamos a la posicion del final de carrera nº1 { posicion_1(); primer_arranque = false; pos_final = true; } leer_serial(); mover_led(); cont_led = 0; cont_filtro = 0; if (pos_final == true) { Serial.print("1"); pos_final = false; } } void comprobar_salto() // comprobamos si ha habido algún salto del filtro lineal y lo contabilizamos { int contador = 0; while (contador < cont_filtro) { trigger = digitalRead(TRIGGER_FILTRO_LINEAL); if (trigger == 1) { contador++; delay(250); } } } void mover_led() { switch (cont_led) { case 1: posicion_3(); comprobar_salto(); pos_final = true; break; case 2: posicion_2(); comprobar_salto(); pos_final = true; break; case 3: posicion_2(); comprobar_salto(); posicion_3(); comprobar_salto(); pos_final = true; break; case 4: posicion_1(); comprobar_salto(); pos_final = true; break; case 5: posicion_1(); comprobar_salto(); posicion_3(); comprobar_salto(); pos_final = true; break; case 6: posicion_1(); comprobar_salto(); posicion_2(); comprobar_salto(); pos_final = true; break; case 7: posicion_1(); comprobar_salto(); posicion_2(); comprobar_salto(); posicion_3(); comprobar_salto(); pos_final = true; break; } } void leer_serial() // nos carga los datos de la secuencia de movimiento y los saltos del filtro en sus variables { while (Serial.available()>0) { cont_led = Serial.parseInt(); cont_filtro = Serial.parseInt(); if (Serial.read() == '\n') { return; } } } void posicion_1() { final_carrera_1 = digitalRead(FIN_CARRERA_1); while ((final_carrera_1 == 1) && (pos_1 == false)) // vamos a ir hasta la posicion del led 1 { digitalWrite(Y_DIR_PIN, HIGH); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_1 = digitalRead(FIN_CARRERA_1); } final_carrera_1 = digitalRead(FIN_CARRERA_1); if (final_carrera_1 == 0) { pos_1 = true; pos_2 = false; pos_3 = false; } } void posicion_2() { final_carrera_2 = digitalRead(FIN_CARRERA_2); while ((final_carrera_2 == 1) && (pos_2 == false) && (pos_1 == true)) { digitalWrite(Y_DIR_PIN, LOW); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_2 = digitalRead(FIN_CARRERA_2); } while ((final_carrera_2 == 1) && (pos_2 == false) && (pos_3 == true)) { digitalWrite(Y_DIR_PIN, HIGH); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_2 = digitalRead(FIN_CARRERA_2); } if ((final_carrera_2 == 0) && (pos_3 == true)) { for (int x=0; x<3200; x++) { digitalWrite(Y_DIR_PIN, HIGH); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); } delay(100); final_carrera_2 = digitalRead(FIN_CARRERA_2); while ((final_carrera_2 == 1) && (pos_2 == false)) { digitalWrite(Y_DIR_PIN, LOW); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_2 = digitalRead(FIN_CARRERA_2); } } final_carrera_2 = digitalRead(FIN_CARRERA_2); if (final_carrera_2 == 0) { pos_1 = false; pos_3 = false; pos_2 = true; } } void posicion_3() { final_carrera_3 = digitalRead(FIN_CARRERA_3); while ((final_carrera_3 == 1) && (pos_3 == false)) { digitalWrite(Y_DIR_PIN, LOW); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_3 = digitalRead(FIN_CARRERA_3); } final_carrera_3 = digitalRead(FIN_CARRERA_3); if (final_carrera_3 == 0) { pos_1 = false; pos_2 = false; pos_3 = true; } } void motor_enfoque() { // falta saber cada cuantos pasos necesitamos mover el enfoque y como controlar el punto de inicio }
#include<bits/stdc++.h> using namespace std; const int maxn=10000; const double pi=acos(-1.0); const double eps=1e-8; //double类型的数,判断符号 int cmp(double x){ if(fabs(x)<eps) return 0; if(x>0) return 1; return -1; } //二维点类,可进行向量运算 //计算平方 inline double sqr(double x){ return x*x; } struct point{ double x,y; point(){} point(double a,double b):x(a),y(b){} void input(){ scanf("%lf%lf",&x,&y); } friend point operator + (const point &a,const point &b){ return point(a.x+b.x,a.y+b.y); } friend point operator - (const point &a,const point &b){ return point(a.x-b.x,a.y-b.y); } friend bool operator == (const point &a,const point &b){ return cmp(a.x-b.x)==0&&cmp(a.y-b.y)==0; } friend point operator * (const point &a,const double &b){ return point(a.x*b,a.y*b); } friend point operator * (const double &a,const point &b){ return point(a*b.x,a*b.y); } friend point operator / (const point &a,const double &b){ return point(a.x/b,a.y/b); } double norm(){ return sqrt(sqr(x)+sqr(y)); } }; //计算向量叉积 double det(const point &a,const point &b){ return a.x*b.y-a.y*b.x; } //计算向量点积 double dot(const point &a,const point &b){ return a.x*b.x+a.y*b.y; } //计算两点距离 double dist(const point &a,const point &b){ return (a-b).norm(); } //op绕原点逆时针旋转A弧度 point rotate_point(const point &p,double A){ double tx=p.x,ty=p.y; return point(tx*cos(A)-ty*sin(A),tx*sin(A)+ty*cos(A)); } struct polygon_convex{ vector<point> P; polygon_convex(int Size=0){ P.resize(Size); } double area(){ double sum=0; for(int i=0;i<P.size()-1;i++) sum+=det(P[i+1],P[i]); sum+=det(P[0],P[P.size()-1]); return sum/2.; } }; bool comp_less(const point &a,const point &b){ return cmp(a.x-b.x)<0||cmp(a.x-b.x)==0&&cmp(a.y-b.y)<0; } polygon_convex convex_hull(vector<point> a){ polygon_convex res(2*a.size()+5); sort(a.begin(),a.end(),comp_less); a.erase(unique(a.begin(),a.end()),a.end()); int m=0; for(int i=0;i<a.size();i++){ while(m>1&&cmp(det(res.P[m-1]-res.P[m-2],a[i]-res.P[m-2]))<=0) --m; res.P[m++]=a[i]; } int k=m; for(int i=int(a.size())-2;i>=0;--i){ while(m>k&&cmp(det(res.P[m-1]-res.P[m-2],a[i]-res.P[m-2]))<=0) --m; res.P[m++]=a[i]; } res.P.resize(m); if(a.size()>1) res.P.resize(m-1); return res; } typedef complex<double> Point; typedef pair<Point,Point> Halfplane; const double EPS=1e-10; const double INF=10000; inline int sgn(double n){ return fabs(n)<EPS ? 0 : (n<0 ? -1 : 1); } inline double cross(Point a,Point b){ return (conj(a)*b).imag(); } inline double dot(Point a,Point b){ return (conj(a)*b).real(); } inline double satisfy(Point a,Halfplane p){ return sgn(cross(a-p.first,p.second-p.first))<=0; } Point crosspoint(const Halfplane &a,const Halfplane &b){ double k=cross(b.first-b.second,a.first-b.second); k=k/(k-cross(b.first-b.second,a.second-b.second)); return a.first+(a.second-a.first)*k; } bool cmp1(const Halfplane &a,const Halfplane &b){ int res=sgn(arg(a.second-a.first)-arg(b.second-b.first)); return res==0 ? satisfy(a.first,b):res<0; } vector<Point> halfplaneIntersection(vector<Halfplane> v){ sort(v.begin(),v.end(),cmp1); deque<Halfplane> q; deque<Point> ans; q.push_back(v[0]); for(int i=1;i<int(v.size());i++){ if(sgn(arg(v[i].second-v[i].first)-arg(v[i-1].second-v[i-1].first))==0) continue; while(ans.size()>0&&!satisfy(ans.back(),v[i])){ ans.pop_back(); q.pop_back(); } while(ans.size()>0&&!satisfy(ans.front(),v[i])){ ans.pop_front(); q.pop_front(); } ans.push_back(crosspoint(q.back(),v[i])); q.push_back(v[i]); } while(ans.size()>0&&!satisfy(ans.back(),q.front())){ ans.pop_back(); q.pop_back(); } while(ans.size()>0&&!satisfy(ans.front(),q.back())){ ans.pop_front(); q.pop_front(); } ans.push_back(crosspoint(q.back(),q.front())); return vector<Point>(ans.begin(),ans.end()); } struct polygon{ int n; point a[maxn]; polygon(){} }; struct halfplane{ double a,b,c; halfplane(point p,point q){ a=p.y-q.y; b=q.x-p.x; c=det(p,q); } halfplane (double aa,double bb,double cc){ a=aa; b=bb; c=cc; } }; double calc(halfplane &L,point &a){ return a.x*L.a+a.y*L.b+L.c; } point Intersect(point &a,point &b,halfplane &L){ point res; double t1=calc(L,a),t2=calc(L,b); res.x=(t2*a.x-t1*b.x)/(t2-t1); res.y=(t2*a.y-t1*b.y)/(t2-t1); return res; } polygon_convex cut(polygon_convex &a,halfplane &L){ int n=a.P.size(); polygon_convex res; for(int i=0;i<n;i++){ if(calc(L,a.P[i])<-eps) res.P.push_back(a.P[i]); else{ int j; j=i-1; if(j<0) j=n-1; if(calc(L,a.P[j])>-eps){ res.P.push_back(Intersect(a.P[j],a.P[i],L)); } j=i+1; if(j==n) j=0; if(calc(L,a.P[j])<-eps) res.P.push_back(Intersect(a.P[i],a.P[j],L)); } } return res; } polygon_convex core(polygon &a){ polygon_convex res; res.P.push_back(point(-INF,-INF)); res.P.push_back(point(INF,-INF)); res.P.push_back(point(INF,INF)); res.P.push_back(point(-INF,INF)); int n=a.n; for(int i=0;i<n;i++){ halfplane L(a.a[i],a.a[(i+1)%n]); res=cut(res,L); } return res; }
class EpochDeathBoardDialog { idd = -1; movingenable = 0; class Controls { class RscText_1000: RscText { idc = -1; x = 0.283659 * safezoneW + safezoneX; y = 0.224978 * safezoneH + safezoneY; w = 0.432681 * safezoneW; h = 0.550044 * safezoneH; colorBackground[] = {0,0,0,0.7}; }; class RscText_1001: RscText { idc = -1; text = $STR_EPOCH_PLAYER_302; x = 0.283659 * safezoneW + safezoneX; y = 0.224978 * safezoneH + safezoneY; w = 0.432681 * safezoneW; h = 0.0550044 * safezoneH; colorBackground[] = {0,0,0,0.7}; }; class RscListbox_1500: RscListbox { idc = 21000; x = 0.297181 * safezoneW + safezoneX; y = 0.334987 * safezoneH + safezoneY; w = 0.148734 * safezoneW; h = 0.412533 * safezoneH; onMouseButtonClick = "[(lbCurSel 21000), ((ctrlParent (_this select 0)) displayCtrl 21001)] spawn EpochDeathBoardClick;"; }; class RscText_1002: RscText { idc = -1; text = $STR_EPOCH_PLAYER_303; x = 0.29042 * safezoneW + safezoneX; y = 0.293733 * safezoneH + safezoneY; w = 0.0540852 * safezoneW; h = 0.0275022 * safezoneH; colorText[] = {1,1,1,1}; }; class RscShortcutButton_1700: RscShortcutButton { idc = -1; text = $STR_UI_CLOSE; x = 0.628452 * safezoneW + safezoneX; y = 0.706267 * safezoneH + safezoneY; w = 0.0743671 * safezoneW; h = 0.0550044 * safezoneH; onButtonClick = "PVDZE_plr_DeathBResult = nil; ((ctrlParent (_this select 0)) closeDisplay 2);"; }; class RscStructuredText_1100: RscStructuredText { idc = 21001; text = ""; x = 0.452114 * safezoneW + safezoneX; y = 0.307485 * safezoneH + safezoneY; w = 0.250144 * safezoneW; h = 0.398782 * safezoneH; colorBackground[] = {0,0,0,0}; }; }; };
#include<iostream> #include<conio.h> using namespace std; main() { int x=89; cout<<x; }
/* Given a string S, find and return all the possible permutations of the input string. Note 1 : The order of permutations is not important. Note 2 : If original string contains duplicate characters, permutations will also be duplicates. Input Format : String S Output Format : All permutations (in different lines) Sample Input : abc Sample Output : abc acb bac bca cab cba */ #include<bits/stdc++.h> using namespace std; int returnPermutation(string input,string output[]){ if(input.empty()){ output[0] = ""; return 1; } int k = 0; for(int i=0;i<input.size();i++){ string smallOutput[1000]; int ans = returnPermutation(input.substr(0,i) + input.substr(i+1,input.size()-i-1),smallOutput); for(int j=0;j<ans;j++){ output[k] = input[i] + smallOutput[j]; k++; } } return k; } int main(){ string input; cin >> input; string output[10000]; int count = returnPermutation(input,output); for(int i=0;i<count;i++){ cout << output[i] << endl; } return 0; }
#include <bits/stdc++.h> #define ll long long #define ull unsigned long long #define FOR(i,n) for(ll i=0;i<n;i++) #define FOR1(i,n) for(ll i=1;i<n;i++) #define FORn1(i,n) for(ll i=1;i<=n;i++) #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define mod 1000000007; using namespace std; int main() { // your code goes here fast; ll t; cin>>t; while(t--) { ll n,past=0; cin>>n; ll a[n]; FOR(i,n) { cin>>a[i]; } sort(a,a+n); FOR(i,n) { if(past>=a[i]) past++; } cout<<past<<endl; } return 0; }
#include <bits/stdc++.h> #include <bitset> #include <assert.h> #include <stdint.h> #include <unistd.h> #include <iostream> #include <algorithm> #include <stdlib.h> #include <cmath> #include <assert.h> #include <omp.h> #include "kvec.h" typedef struct { int n; int m; int *a; //id of points } group; class Trail { public: char *file_name; std::vector<group *> groups; int n; //number of points float **dist_matrix; float **w_matrix; float e = 1.3; float w_threshold, dist_threshold; void Run(); int FindMax(int id, int *trail_set); int FindMin(int id, int *trail_set); void WriteResult(char *file_name); void Split(group *g); Trail(int _n, float **_dist_matrix, float _e = 1.3) { e = _e; n = _n; dist_matrix = _dist_matrix; // w_matrix = (float **)malloc(sizeof(float *) *n); // w_matrix[0] = (float *)malloc(sizeof(float) *n*n); // for(int i = 1; i < n; i++) // w_matrix[i] = w_matrix[0] + n * i; // for(int i = 0; i < n; i++) // { // w_matrix[i][i] = 1.0; // for(int j = i+1; j < n; j++) // { // //printf("%.4f %.4f\n",dist_matrix[i][j],exp(-0.1*dist_matrix[i][j])); // w_matrix[i][j] = 0.01+exp(-0.01*dist_matrix[i][j]); // w_matrix[j][i] = w_matrix[i][j]; // } // } printf("dimension %d\n",n); } ~Trail() { //for(int i = 0; i < n; i++) // free(w_matrix[i]); //free(w_matrix); for(int i = 0; i < n; i++) free(dist_matrix[i]); free(dist_matrix); for(int i = 0; i < groups.size(); i++) free(groups[i]); } };