text
stringlengths
8
6.88M
#pragma once #include <iostream> #include <boost/log/sinks/syslog_backend.hpp> //Here we define our application severity levels. enum class SysLogSeverity { slEMERGENCY = boost::log::sinks::syslog::emergency, slALERT = boost::log::sinks::syslog::alert, slCRITICAL = boost::log::sinks::syslog::critical, slERROR = boost::log::sinks::syslog::error, slWARN = boost::log::sinks::syslog::warning, slNOTICE = boost::log::sinks::syslog::notice, slINFO = boost::log::sinks::syslog::info, slDEBUG = boost::log::sinks::syslog::debug }; // The operator is used for regular stream formatting std::ostream& operator<< (std::ostream& strm, SysLogSeverity level); std::istream& operator>>(std::istream& i, SysLogSeverity &level);
/* * Process.cpp * * Created on: 26 Apr 2013 * Author: william */ #include "pb_process.h" namespace Popbal { namespace Processes { Process::Process(): mA(1.0), mDelta(0) {} Process::~Process() {} //! Basic implementation of rate function double Process::Rate(double t, const Background &bg) const { return mA; } //! Basic application of rate terms double Process::ApplyRateTerms(double t, Background &bg, dvec &ydot) const { return Rate(t, bg); } /*! * @param dx The change in component number */ void Process::SetComponentChange(signed int dx) { mDelta = dx; } } } /* namespace Popbal */
/* * LocMQTT.h * * Created on: Oct 17, 2019 * Author: annuar */ #ifndef OURS_LOCMQTT_H_ #define OURS_LOCMQTT_H_ #include "Arduino.h" #include <PubSubClient.h> #include <WiFiClient.h> #include <TimeLib.h> #include <WiFi.h> class LocMQTT { private: String *_MAC; public: LocMQTT(String *mac); void update(); void hantar(String t, String m); static void callback(char* topic, byte* message, unsigned int length); static void reconnect(); }; #endif /* OURS_LOCMQTT_H_ */
#include <iostream> using namespace std; int main() { char a; cout << "문자형 입력(%c) : "; cin >> a; cout << endl << "문자로 출력(%c): " << a << endl; cout << "정수로 출력(%d): " << (int)a-48 << endl; }
#include "substringstatistics.h" SubstringStatistics::SubstringStatistics(QString str1,QString str2) { this->str1=str1; this->str2=str2; len1=str1.length(); len2=str2.length(); count=0; } SubstringStatistics::~SubstringStatistics(){ } void SubstringStatistics::calculate(){ for (int i = 0; i <= len1-len2; i++) { if (str1[i] == str2[0]) { int sum = 0; for (int j = 0; j < len2; j++) { if (str1[i + j] == str2[j]) { sum++; } } if (sum == len2) { count++; } } } } int SubstringStatistics::getcount(){ return count; }
//minimum no of no of sq required to get an number #include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 5; int main() { int n; cin >> n; vector<int> dp(n + 1, MOD); dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; for (int i = 1; i * i <= n; i++) { for (int j = 0; i * i + j <= n; j++) { dp[i * i + j] = min(dp[i * i + j], 1 + dp[j]); } } cout << dp[n] << endl; }
#include "Arduino.h" #include "LiquidCrystal.h" #include "gtest/gtest.h" TEST(ApplicationTest, setup_initializesLogger) { uint8_t backLightPin = 13; ArduinoMock *pArduinoMock = arduinoMockInstance(); LiquidCrystalMock *pLiquidCrystalMock = liquidCrystalMockInstance(); SerialMock *pSerialMock = serialMockInstance(); EXPECT_CALL(*pSerialMock, begin(testing::Eq(9600))).Times(testing::Exactly(1)); EXPECT_CALL(*pArduinoMock, pinMode(testing::Eq(backLightPin), testing::Eq(OUTPUT))); EXPECT_CALL(*pLiquidCrystalMock, begin(testing::Eq(16), testing::Eq(2), testing::Eq(LCD_5x8DOTS))).Times(testing::Exactly(1)); EXPECT_CALL(*pLiquidCrystalMock, clear()); EXPECT_CALL(*pArduinoMock, analogWrite(testing::Eq(backLightPin), testing::Eq(HIGH))); setup(); releaseSerialMock(); releaseLiquidCrystalMock(); releaseArduinoMock(); } TEST(ApplicationTest, loop_readsTemperatureAndWaits1Seconds) { ArduinoMock *pArduinoMock = arduinoMockInstance(); SerialMock *pSerialMock = serialMockInstance(); LiquidCrystalMock *pLiquidCrystalMock = liquidCrystalMockInstance(); EXPECT_CALL(*pArduinoMock, analogRead(testing::Eq(A0))).WillOnce(testing::Return(124)); EXPECT_CALL(*pSerialMock, println(testing::SafeMatcherCast<const char *>(testing::StrEq("10.5C. degrees")))); EXPECT_CALL(*pLiquidCrystalMock, clear()); EXPECT_CALL(*pLiquidCrystalMock, print(testing::SafeMatcherCast<const char *>(testing::StrEq("10.5C. degrees")))); EXPECT_CALL(*pArduinoMock, delay(testing::Eq(1000))); loop(); releaseArduinoMock(); releaseSerialMock(); releaseLiquidCrystalMock(); }
#include <bits/stdc++.h> #include <time.h> using namespace std; #define ll long long #define ld long double #define uint unsigned int #define ull unsigned long long const ll INF = 1e18; struct pnt { int place, val; pnt() {} pnt(int p, int v) { place = p; val = v; } }; void print(vector<pnt> t) { for (pnt x : t) cout << "(" << x.val << " " << x.place << ") "; cout << endl; } class Heap { public: vector<pnt> heap; vector<int> acts; void sw(int x, int y) { acts[heap[x].place] = y; acts[heap[y].place] = x; pnt tx = heap[x], ty = heap[y]; heap[x] = ty; heap[y] = tx; } void siftUp(int x) { if (heap[x].val < heap[(x - 1) / 2].val) { sw(x, (x - 1) / 2); siftUp((x - 1) / 2); } } void siftDown(int x) { int l = x * 2 + 1, r = x * 2 + 2; if ((int)heap.size() <= l) return; int next_; if (r < (int)heap.size() && heap[r].val < heap[l].val) next_ = r; else next_ = l; if (heap[next_].val < heap[x].val) { sw(x, next_); siftDown(next_); } } void push(int x) { acts.push_back((int)heap.size()); heap.push_back(pnt((int)acts.size() - 1, x)); siftUp((int)heap.size() - 1); } pnt extractMin() { acts.push_back(-1); if (heap.empty()) return pnt(2e9, 2e9); pnt ans = heap[0]; sw(0, (int)heap.size() - 1); heap.pop_back(); siftDown(0); return ans; } void decreaseKey(int x, int new_val) { acts.push_back(-1); if (heap[acts[x]].val <= new_val) return; heap[acts[x]].val = new_val; siftUp(acts[x]); } }; int main() { // freopen("file.in", "r", stdin); freopen("priorityqueue2.in", "r", stdin); freopen("priorityqueue2.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(); int a, b; Heap h; pnt ans; string s; while (cin >> s) { if (s == "push") { cin >> a; h.push(a); } if (s == "extract-min") { ans = h.extractMin(); if (ans.val == 2e9) cout << "*\n"; else cout << ans.val << " " << ans.place + 1 << "\n"; } if (s == "decrease-key") { cin >> a >> b; a--; h.decreaseKey(a, b); } // print(h.heap); } return 0; }
/************************************************************************************* Daniel Stokes 1331134 **************************************************************************************/ #include <iostream> #include "LargeNeighbourhoodSearch.h" #include "Block.h" #include <chrono> #include <fstream> #include <thread> #include "DestroyFunctions/DistintegrationRay.h" #include "DestroyFunctions/SimpleRemove.h" #include "DestroyFunctions/RowElimination.h" #include "DestroyFunctions/Jitter.h" #include "DestroyFunctions/HoleExpansion.h" #include "RepairFunctions/Tetris.h" #include "RepairFunctions/FitPolicy.h" #include "RepairFunctions/Shake.h" using namespace std::chrono_literals; int main(int argc, char** argv) { if (argc != 7) { std::cerr << "Usage: " << argv[0] << " <input csv file> <output_prefix> <object width> <degree of destruction> <acceptance temperature> <seconds to run for>" << std::endl; return -1; } std::string input_file = argv[1]; std::string out_name = argv[2]; std::fstream myfile; myfile.open(input_file, std::ios::in); if (!myfile.is_open()) { std::cerr << "Invalid test file: " << input_file << std::endl; return -1; } std::vector<Block> blocks; while (!myfile.fail() && !myfile.eof()) { uint64_t width = 0; uint64_t height = 0; char comma = '\0'; myfile >> width >> comma >> height; if (comma != ',' || width == 0 || height == 0) { std::cerr << "Invalid file format" << std::endl; return -1; } blocks.emplace_back(width, height); } const uint64_t grid_width = std::strtoul(argv[3], nullptr, 0); if (grid_width == 0) { std::cout << "Invalid grid width" << std::endl; return -1; } const double degree_of_destruction = std::strtod(argv[4], nullptr); if (degree_of_destruction <= 0 || degree_of_destruction > 1.0) { std::cout << "Invalid degree of destruction" << std::endl; return -1; } const double temperature = std::strtod(argv[5], nullptr); if (temperature <= 0) { std::cout << "Invalid temperature" << std::endl; return -1; } const uint64_t runtime = std::strtoul(argv[6], nullptr, 0); if (runtime == 0) { std::cout << "Invalid runtime" << std::endl; return -1; } IDestroy::setDegreeOfDestruction(degree_of_destruction); const uint64_t num_threads = std::thread::hardware_concurrency(); std::vector<std::thread> threads; std::vector<std::array<Grid, 3>> best_results; std::vector<std::unique_ptr<LargeNeighbourhoodSearch>> searches(num_threads); for (uint64_t i = 0; i < num_threads; i++) { best_results.emplace_back(); threads.emplace_back([&, i]() { std::vector<Block> local_blocks(blocks.begin(), blocks.end()); std::vector<IDestroy*> destroyers = {new DistintegrationRay(), new SimpleRemove(), new RowElimination(), new Jitter(), new HoleExpansion(), }; std::vector<IRepair*> repairers = {new Tetris(SOUTHEAST), new Tetris(SOUTHWEST), new Tetris(SOUTH), new Tetris(EAST), new Tetris(WEST), new FitPolicy(FitPolicy::Policy::BEST), new FitPolicy(FitPolicy::Policy::FIRST), new FitPolicy(FitPolicy::Policy::TIGHTEST), new FitPolicy(FitPolicy::Policy::LOWEST), new Shake<Tetris, GravityDir>(SOUTH), new Shake<FitPolicy, FitPolicy::Policy>(FitPolicy::Policy::BEST), new Shake<FitPolicy, FitPolicy::Policy>(FitPolicy::Policy::FIRST), new Shake<FitPolicy, FitPolicy::Policy>(FitPolicy::Policy::TIGHTEST), new Shake<FitPolicy, FitPolicy::Policy>(FitPolicy::Policy::LOWEST), }; searches[i] = std::make_unique<LargeNeighbourhoodSearch>(local_blocks, grid_width, destroyers, repairers, temperature); const uint64_t seed = std::random_device()(); searches[i]->initRun(seed); searches[i]->run(std::chrono::seconds(runtime)); for (auto destroyer : destroyers) delete destroyer; for (auto repairer : repairers) delete repairer; }); } for (auto& thread : threads) thread.join(); LargeNeighbourhoodSearch::reportStats(searches); std::cout << "************************** Best solutions: *******************************" << std::endl; auto winners = LargeNeighbourhoodSearch::mergeResults(searches); uint64_t index = 0; std::string extension = ".jpg"; for (auto& grid : winners) grid.display(out_name + "_" + std::to_string(++index) + extension); return 0; }
/* Name: Mohit Kishorbhai Sheladiya Student ID: 117979203 Student Email: mksheladiya@myseneca.ca Date: 21/02/14 */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <istream> #include <iomanip> #include <cstring> #include "Label.h" using namespace std; namespace sdds { void Label::setFrameArg(const char* frameArg) { strcpy(m_frameArg, frameArg); m_frameArg[8] = '\0'; } void Label::setName(const char* labelArg) { m_labelArg = nullptr; m_labelArg = new char[strlen(labelArg) + 1]; strcpy(m_labelArg, labelArg); } void Label::setToDefault() { m_labelArg = nullptr; m_frameArg[0] = '\0'; } Label::Label() { setToDefault(); setFrameArg("+-+|+-+|"); } Label::Label(const char* frameArg) { setToDefault(); setFrameArg(frameArg); } Label::Label(const char* frameArg, const char* content) { setToDefault(); setName(content); setFrameArg(frameArg); } Label::~Label() { delete[] m_labelArg; m_labelArg = nullptr; } void Label::readLabel() { char readlabel[71]; cin.getline(readlabel, 71); setName(readlabel); } std::ostream& Label::printLabel() const { /* if (m_labelArg != nullptr) { int c = 0; while (m_labelArg[c] != '\0') { c++; } c = c + 3; cout << m_frameArg[0] << setw(c) << setfill(m_frameArg[1]); cout << m_frameArg[2] << endl; cout << m_frameArg[7] << setw(c) << setfill(' '); cout << m_frameArg[3] << endl; cout << m_frameArg[7] << ' ' << m_labelArg << ' '; cout << m_frameArg[3] << endl; cout << m_frameArg[7] << setw(c) << setfill(' '); cout << m_frameArg[3] << endl; cout << m_frameArg[6] << setw(c) << setfill(m_frameArg[5]); cout << m_frameArg[4] << endl; } */ int l = 0; if (m_labelArg != '\0') { l = strlen(m_labelArg); cout << m_frameArg[0]; for (int i = 0; i < l + 2; i++) { cout << m_frameArg[1]; } cout << m_frameArg[2] << endl; cout << m_frameArg[7]; for (int i = 0; i < l + 2; i++) { cout << " "; } cout << m_frameArg[3] << endl; cout << m_frameArg[7] << " "; cout << m_labelArg << " "; cout << m_frameArg[3] << endl; cout << m_frameArg[7]; for (int i = 0; i < l + 2; i++) { cout << " "; } cout << m_frameArg[3] << endl; cout << m_frameArg[6]; for (int i = 0; i < l + 2; i++) { cout << m_frameArg[5]; } cout << m_frameArg[4]; } return cout; } }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.Devices.Perception.Provider.0.h" #include "Windows.Devices.Perception.0.h" #include "Windows.Foundation.0.h" #include "Windows.Foundation.Collections.0.h" #include "Windows.Graphics.Imaging.0.h" #include "Windows.Media.0.h" #include "Windows.Foundation.Collections.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Devices::Perception::Provider { struct __declspec(uuid("3ae651d6-9669-4106-9fae-4835c1b96104")) __declspec(novtable) IKnownPerceptionFrameKindStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Color(hstring * value) = 0; virtual HRESULT __stdcall get_Depth(hstring * value) = 0; virtual HRESULT __stdcall get_Infrared(hstring * value) = 0; }; struct __declspec(uuid("172c4882-2fd9-4c4e-ba34-fdf20a73dde5")) __declspec(novtable) IPerceptionControlGroup : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_FrameProviderIds(Windows::Foundation::Collections::IVectorView<hstring> ** value) = 0; }; struct __declspec(uuid("2f1af2e0-baf1-453b-bed4-cd9d4619154c")) __declspec(novtable) IPerceptionControlGroupFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Create(Windows::Foundation::Collections::IIterable<hstring> * ids, Windows::Devices::Perception::Provider::IPerceptionControlGroup ** result) = 0; }; struct __declspec(uuid("b4131a82-dff5-4047-8a19-3b4d805f7176")) __declspec(novtable) IPerceptionCorrelation : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_TargetId(hstring * value) = 0; virtual HRESULT __stdcall get_Position(Windows::Foundation::Numerics::float3 * value) = 0; virtual HRESULT __stdcall get_Orientation(Windows::Foundation::Numerics::quaternion * value) = 0; }; struct __declspec(uuid("d4a6c425-2884-4a8f-8134-2835d7286cbf")) __declspec(novtable) IPerceptionCorrelationFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Create(hstring targetId, Windows::Foundation::Numerics::float3 position, Windows::Foundation::Numerics::quaternion orientation, Windows::Devices::Perception::Provider::IPerceptionCorrelation ** result) = 0; }; struct __declspec(uuid("752a0906-36a7-47bb-9b79-56cc6b746770")) __declspec(novtable) IPerceptionCorrelationGroup : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RelativeLocations(Windows::Foundation::Collections::IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation> ** value) = 0; }; struct __declspec(uuid("7dfe2088-63df-48ed-83b1-4ab829132995")) __declspec(novtable) IPerceptionCorrelationGroupFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Create(Windows::Foundation::Collections::IIterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> * relativeLocations, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup ** result) = 0; }; struct __declspec(uuid("e8019814-4a91-41b0-83a6-881a1775353e")) __declspec(novtable) IPerceptionFaceAuthenticationGroup : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_FrameProviderIds(Windows::Foundation::Collections::IVectorView<hstring> ** value) = 0; }; struct __declspec(uuid("e68a05d4-b60c-40f4-bcb9-f24d46467320")) __declspec(novtable) IPerceptionFaceAuthenticationGroupFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Create(Windows::Foundation::Collections::IIterable<hstring> * ids, Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler * startHandler, Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler * stopHandler, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup ** result) = 0; }; struct __declspec(uuid("7cfe7825-54bb-4d9d-bec5-8ef66151d2ac")) __declspec(novtable) IPerceptionFrame : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RelativeTime(Windows::Foundation::TimeSpan * value) = 0; virtual HRESULT __stdcall put_RelativeTime(Windows::Foundation::TimeSpan value) = 0; virtual HRESULT __stdcall get_Properties(Windows::Foundation::Collections::IPropertySet ** value) = 0; virtual HRESULT __stdcall get_FrameData(Windows::Foundation::IMemoryBuffer ** value) = 0; }; struct __declspec(uuid("794f7ab9-b37d-3b33-a10d-30626419ce65")) __declspec(novtable) IPerceptionFrameProvider : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_FrameProviderInfo(Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo ** result) = 0; virtual HRESULT __stdcall get_Available(bool * value) = 0; virtual HRESULT __stdcall get_Properties(Windows::Foundation::Collections::IPropertySet ** value) = 0; virtual HRESULT __stdcall abi_Start() = 0; virtual HRESULT __stdcall abi_Stop() = 0; virtual HRESULT __stdcall abi_SetProperty(Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest * value) = 0; }; struct __declspec(uuid("cca959e8-797e-4e83-9b87-036a74142fc4")) __declspec(novtable) IPerceptionFrameProviderInfo : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Id(hstring * value) = 0; virtual HRESULT __stdcall put_Id(hstring value) = 0; virtual HRESULT __stdcall get_DisplayName(hstring * value) = 0; virtual HRESULT __stdcall put_DisplayName(hstring value) = 0; virtual HRESULT __stdcall get_DeviceKind(hstring * value) = 0; virtual HRESULT __stdcall put_DeviceKind(hstring value) = 0; virtual HRESULT __stdcall get_FrameKind(hstring * value) = 0; virtual HRESULT __stdcall put_FrameKind(hstring value) = 0; virtual HRESULT __stdcall get_Hidden(bool * value) = 0; virtual HRESULT __stdcall put_Hidden(bool value) = 0; }; struct __declspec(uuid("a959ce07-ead3-33df-8ec1-b924abe019c4")) __declspec(novtable) IPerceptionFrameProviderManager : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_GetFrameProvider(Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo * frameProviderInfo, Windows::Devices::Perception::Provider::IPerceptionFrameProvider ** result) = 0; }; struct __declspec(uuid("ae8386e6-cad9-4359-8f96-8eae51810526")) __declspec(novtable) IPerceptionFrameProviderManagerServiceStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_RegisterFrameProviderInfo(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo * frameProviderInfo) = 0; virtual HRESULT __stdcall abi_UnregisterFrameProviderInfo(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo * frameProviderInfo) = 0; virtual HRESULT __stdcall abi_RegisterFaceAuthenticationGroup(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup * faceAuthenticationGroup) = 0; virtual HRESULT __stdcall abi_UnregisterFaceAuthenticationGroup(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup * faceAuthenticationGroup) = 0; virtual HRESULT __stdcall abi_RegisterControlGroup(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionControlGroup * controlGroup) = 0; virtual HRESULT __stdcall abi_UnregisterControlGroup(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionControlGroup * controlGroup) = 0; virtual HRESULT __stdcall abi_RegisterCorrelationGroup(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup * correlationGroup) = 0; virtual HRESULT __stdcall abi_UnregisterCorrelationGroup(Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager * manager, Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup * correlationGroup) = 0; virtual HRESULT __stdcall abi_UpdateAvailabilityForProvider(Windows::Devices::Perception::Provider::IPerceptionFrameProvider * provider, bool available) = 0; virtual HRESULT __stdcall abi_PublishFrameForProvider(Windows::Devices::Perception::Provider::IPerceptionFrameProvider * provider, Windows::Devices::Perception::Provider::IPerceptionFrame * frame) = 0; }; struct __declspec(uuid("3c5aeb51-350b-4df8-9414-59e09815510b")) __declspec(novtable) IPerceptionPropertyChangeRequest : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Name(hstring * value) = 0; virtual HRESULT __stdcall get_Value(Windows::Foundation::IInspectable ** value) = 0; virtual HRESULT __stdcall get_Status(winrt::Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus * value) = 0; virtual HRESULT __stdcall put_Status(winrt::Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus value) = 0; virtual HRESULT __stdcall abi_GetDeferral(Windows::Foundation::IDeferral ** result) = 0; }; struct __declspec(uuid("4c38a7da-fdd8-4ed4-a039-2a6f9b235038")) __declspec(novtable) IPerceptionVideoFrameAllocator : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_AllocateFrame(Windows::Devices::Perception::Provider::IPerceptionFrame ** value) = 0; virtual HRESULT __stdcall abi_CopyFromVideoFrame(Windows::Media::IVideoFrame * frame, Windows::Devices::Perception::Provider::IPerceptionFrame ** value) = 0; }; struct __declspec(uuid("1a58b0e1-e91a-481e-b876-a89e2bbc6b33")) __declspec(novtable) IPerceptionVideoFrameAllocatorFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Create(uint32_t maxOutstandingFrameCountForWrite, winrt::Windows::Graphics::Imaging::BitmapPixelFormat format, Windows::Foundation::Size resolution, winrt::Windows::Graphics::Imaging::BitmapAlphaMode alpha, Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator ** result) = 0; }; struct __declspec(uuid("74816d2a-2090-4670-8c48-ef39e7ff7c26")) __declspec(novtable) PerceptionStartFaceAuthenticationHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup * sender, bool * result) = 0; }; struct __declspec(uuid("387ee6aa-89cd-481e-aade-dd92f70b2ad7")) __declspec(novtable) PerceptionStopFaceAuthenticationHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup * sender) = 0; }; } namespace ABI { template <> struct traits<Windows::Devices::Perception::Provider::PerceptionControlGroup> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionControlGroup; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionCorrelation> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionCorrelation; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionCorrelationGroup> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFrame> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionFrame; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator> { using default_interface = Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator; }; } namespace Windows::Devices::Perception::Provider { template <typename D> struct WINRT_EBO impl_IKnownPerceptionFrameKindStatics { [[deprecated("KnownPerceptionFrameKind may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring Color() const; [[deprecated("KnownPerceptionFrameKind may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring Depth() const; [[deprecated("KnownPerceptionFrameKind may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring Infrared() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionControlGroup { [[deprecated("PerceptionControlGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Collections::IVectorView<hstring> FrameProviderIds() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionControlGroupFactory { [[deprecated("PerceptionControlGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionControlGroup Create(iterable<hstring> ids) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionCorrelation { [[deprecated("PerceptionCorrelation may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring TargetId() const; [[deprecated("PerceptionCorrelation may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Numerics::float3 Position() const; [[deprecated("PerceptionCorrelation may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Numerics::quaternion Orientation() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionCorrelationFactory { [[deprecated("PerceptionCorrelation may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionCorrelation Create(hstring_view targetId, const Windows::Foundation::Numerics::float3 & position, const Windows::Foundation::Numerics::quaternion & orientation) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionCorrelationGroup { [[deprecated("PerceptionCorrelationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Collections::IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation> RelativeLocations() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionCorrelationGroupFactory { [[deprecated("PerceptionCorrelationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionCorrelationGroup Create(iterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> relativeLocations) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFaceAuthenticationGroup { [[deprecated("PerceptionFaceAuthenticationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Collections::IVectorView<hstring> FrameProviderIds() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFaceAuthenticationGroupFactory { [[deprecated("PerceptionFaceAuthenticationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup Create(iterable<hstring> ids, const Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler & startHandler, const Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler & stopHandler) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFrame { [[deprecated("PerceptionFrame may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::TimeSpan RelativeTime() const; [[deprecated("PerceptionFrame may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void RelativeTime(const Windows::Foundation::TimeSpan & value) const; [[deprecated("PerceptionFrame may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Collections::ValueSet Properties() const; [[deprecated("PerceptionFrame may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::IMemoryBuffer FrameData() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFrameProvider { [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo FrameProviderInfo() const; [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] bool Available() const; [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Collections::IPropertySet Properties() const; [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void Start() const; [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void Stop() const; [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void SetProperty(const Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest & value) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFrameProviderInfo { [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring Id() const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void Id(hstring_view value) const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring DisplayName() const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void DisplayName(hstring_view value) const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring DeviceKind() const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void DeviceKind(hstring_view value) const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring FrameKind() const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void FrameKind(hstring_view value) const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] bool Hidden() const; [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void Hidden(bool value) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFrameProviderManager { [[deprecated("IPerceptionFrameProviderManager may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::IPerceptionFrameProvider GetFrameProvider(const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionFrameProviderManagerServiceStatics { [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void RegisterFrameProviderInfo(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void UnregisterFrameProviderInfo(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo & frameProviderInfo) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void RegisterFaceAuthenticationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & faceAuthenticationGroup) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void UnregisterFaceAuthenticationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & faceAuthenticationGroup) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void RegisterControlGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionControlGroup & controlGroup) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void UnregisterControlGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionControlGroup & controlGroup) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void RegisterCorrelationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & correlationGroup) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void UnregisterCorrelationGroup(const Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager & manager, const Windows::Devices::Perception::Provider::PerceptionCorrelationGroup & correlationGroup) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void UpdateAvailabilityForProvider(const Windows::Devices::Perception::Provider::IPerceptionFrameProvider & provider, bool available) const; [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void PublishFrameForProvider(const Windows::Devices::Perception::Provider::IPerceptionFrameProvider & provider, const Windows::Devices::Perception::Provider::PerceptionFrame & frame) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionPropertyChangeRequest { [[deprecated("PerceptionPropertyChangeRequest may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] hstring Name() const; [[deprecated("PerceptionPropertyChangeRequest may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::IInspectable Value() const; [[deprecated("PerceptionPropertyChangeRequest may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus Status() const; [[deprecated("PerceptionPropertyChangeRequest may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] void Status(Windows::Devices::Perception::PerceptionFrameSourcePropertyChangeStatus value) const; [[deprecated("PerceptionPropertyChangeRequest may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Foundation::Deferral GetDeferral() const; }; template <typename D> struct WINRT_EBO impl_IPerceptionVideoFrameAllocator { [[deprecated("PerceptionVideoFrameAllocator may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionFrame AllocateFrame() const; [[deprecated("PerceptionVideoFrameAllocator may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionFrame CopyFromVideoFrame(const Windows::Media::VideoFrame & frame) const; }; template <typename D> struct WINRT_EBO impl_IPerceptionVideoFrameAllocatorFactory { [[deprecated("PerceptionVideoFrameAllocator may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator Create(uint32_t maxOutstandingFrameCountForWrite, Windows::Graphics::Imaging::BitmapPixelFormat format, const Windows::Foundation::Size & resolution, Windows::Graphics::Imaging::BitmapAlphaMode alpha) const; }; } namespace impl { template <> struct traits<Windows::Devices::Perception::Provider::IKnownPerceptionFrameKindStatics> { using abi = ABI::Windows::Devices::Perception::Provider::IKnownPerceptionFrameKindStatics; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IKnownPerceptionFrameKindStatics<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionControlGroup> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionControlGroup; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionControlGroup<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionControlGroupFactory> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionControlGroupFactory; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionControlGroupFactory<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionCorrelation> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionCorrelation; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionCorrelation<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionCorrelationFactory> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionCorrelationFactory; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionCorrelationFactory<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionCorrelationGroup; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionCorrelationGroup<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionCorrelationGroupFactory> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionCorrelationGroupFactory; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionCorrelationGroupFactory<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroup; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFaceAuthenticationGroup<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroupFactory> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFaceAuthenticationGroupFactory; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFaceAuthenticationGroupFactory<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFrame> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFrame; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFrame<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFrameProvider> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFrameProvider; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFrameProvider<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFrameProviderInfo; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFrameProviderInfo<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFrameProviderManager; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFrameProviderManager<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionFrameProviderManagerServiceStatics> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionFrameProviderManagerServiceStatics; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionFrameProviderManagerServiceStatics<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionPropertyChangeRequest; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionPropertyChangeRequest<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocator; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionVideoFrameAllocator<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocatorFactory> { using abi = ABI::Windows::Devices::Perception::Provider::IPerceptionVideoFrameAllocatorFactory; template <typename D> using consume = Windows::Devices::Perception::Provider::impl_IPerceptionVideoFrameAllocatorFactory<D>; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionStartFaceAuthenticationHandler; }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionStopFaceAuthenticationHandler; }; template <> struct traits<Windows::Devices::Perception::Provider::KnownPerceptionFrameKind> { static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.KnownPerceptionFrameKind"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionControlGroup> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionControlGroup; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionControlGroup"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionCorrelation> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionCorrelation; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionCorrelation"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionCorrelationGroup> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionCorrelationGroup; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionCorrelationGroup"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionFaceAuthenticationGroup"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFrame> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionFrame; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionFrame"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionFrameProviderInfo; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionFrameProviderInfo"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionFrameProviderManagerService> { static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionFrameProviderManagerService"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionPropertyChangeRequest; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionPropertyChangeRequest"; } }; template <> struct traits<Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator> { using abi = ABI::Windows::Devices::Perception::Provider::PerceptionVideoFrameAllocator; static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.Perception.Provider.PerceptionVideoFrameAllocator"; } }; } }
#ifndef RANK_DEP_ANALYSIS_H #define RANK_DEP_ANALYSIS_H #include "genericDataflowCommon.h" #include "cfgUtils.h" #include "VirtualCFGIterator.h" #include "cfgUtils.h" #include "CFGRewrite.h" #include "CallGraphTraverse.h" #include "analysisCommon.h" #include "analysis.h" #include "dataflow.h" #include "latticeFull.h" #include "printAnalysisStates.h" #include "liveDeadVarAnalysis.h" extern int MPIRankDepAnalysisDebugLevel; // Maintains information about a variable's dependence on MPI rank or number of ranks class MPIRankNProcsDepLattice : public FiniteLattice { public: /* <true, true> / \ -- <true, false> <false, true> \ / <false, false> | uninitialized */ private: bool initialized; bool rankDep; bool nprocsDep; /* // Variables that are equal to the process rank varIDSet rankVars; // Variables that are equal to the number of processes varIDSet nprocsVars;*/ public: MPIRankNProcsDepLattice() { initialized = false; rankDep = false; nprocsDep = false; } MPIRankNProcsDepLattice(const MPIRankNProcsDepLattice& that) { this->initialized = that.initialized; this->rankDep = that.rankDep; this->nprocsDep = that.nprocsDep; } // initializes this Lattice to its default state, if it is not already initialized void initialize() { if(!initialized) { initialized = true; rankDep = false; nprocsDep = false; } //printf("MPIRankNProcsDepLattice::initialize() : %s\n", str().c_str()); } // returns a copy of this lattice Lattice* copy() const; // overwrites the state of this Lattice with that of that Lattice void copy(Lattice* that); // overwrites the state of this Lattice with that of that Lattice // returns true if this causes this lattice to change and false otherwise //bool copyMod(Lattice* that_arg); // computes the meet of this and that and saves the result in this // returns true if this causes this to change and false otherwise bool meetUpdate(Lattice* that); bool operator==(Lattice* that); // returns the current state of this object bool getRankDep() const; bool getNprocsDep() const; // set the current state of this object, returning true if it causes // the object to change and false otherwise bool setRankDep(bool rankDep); bool setNprocsDep(bool nprocsDep); // Sets the state of this lattice to bottom (false, false) // returns true if this causes the lattice's state to change, false otherwise bool setToBottom(); // Sets the state of this lattice to bottom (true, true) // returns true if this causes the lattice's state to change, false otherwise bool setToTop(); string str(string indent=""); }; class MPIRankDepAnalysis : public IntraFWDataflow { public: MPIRankDepAnalysis(): IntraFWDataflow() { } // generates the initial lattice state for the given dataflow node, in the given function, with the given NodeState //vector<Lattice*> genInitState(const Function& func, const DataflowNode& n, const NodeState& state); void genInitState(const Function& func, const DataflowNode& n, const NodeState& state, vector<Lattice*>& initLattices, vector<NodeFact*>& initFacts); bool transfer(const Function& func, const DataflowNode& n, NodeState& state, const vector<Lattice*>& dfInfo); }; MPIRankDepAnalysis* runMPIRankDepAnalysis(SgIncidenceDirectedGraph* graph, string indent=""); // Prints the Lattices set by the given MPIRankDepAnalysis void printMPIRankDepAnalysisStates(string indent=""); void printMPIRankDepAnalysisStates(MPIRankDepAnalysis* rankDepAnal, string indent=""); // Returns whether the given variable at the given DataflowNode depends on the process' rank bool isMPIRankVarDep(const Function& func, const DataflowNode& n, varID var); // Returns whether the given variable at the given DataflowNode depends on the number of processes bool isMPINprocsVarDep(const Function& func, const DataflowNode& n, varID var); // Sets rankDep and nprocsDep to true if some variable in the expression depends on the process' rank or // the number of processes, respectively. False otherwise. bool isMPIDep(const Function& func, const DataflowNode& n, bool& rankDep, bool& nprocsDep); // Returns whether some variable at the given DataflowNode depends on the process' rank bool isMPIRankDep(const Function& func, const DataflowNode& n); // Returns whether some variable at the given DataflowNode depends on the number of processes bool isMPINprocsDep(const Function& func, const DataflowNode& n); #endif
// // Created by twome on 11/05/2020. // #ifndef GAMEOFLIFE_OPENGL_FBO_H #define GAMEOFLIFE_OPENGL_FBO_H #include <glad/glad.h> class Fbo { private: int width; int height; GLuint frameBuffer = 0; GLuint colorBuffer = 0; GLuint colorTexture = 0; public: Fbo(int width, int height); ~Fbo(); void bind() const; static void unbind(); GLuint get_color_texture() const; int get_width() const; int get_height() const; private: void create_framebuffer(); void create_tex_attachment(); }; #endif //GAMEOFLIFE_OPENGL_FBO_H
#include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 ll util(vector<ll> &arr,vector<vector<ll> > &dp,ll i,ll sum){ if(sum==0) return 0; ll n=arr.size(); if(i>=n || sum<0) return INT_MAX; if(sum==arr[i]) return 1; if(dp[sum][i]!=INT_MAX) return dp[sum][i]; return dp[sum][i]=min(1+util(arr,dp,i,sum-arr[i]),util(arr,dp,i+1,sum)); } int main(){ ll n,target;cin>>n>>target; vector<ll> arr(n); vector<vector<ll> > dp(target+1,vector<ll>(n,INT_MAX)); for(int i=0;i<n;i++) { cin>>arr[i]; } ll ans=util(arr,dp,0,target); if(ans==INT_MAX) cout<<-1<<endl; else cout<<ans<<endl; }
#include "coverageobject.h" #include <Cutelyst/Application> #include <Cutelyst/Controller> #include <Cutelyst/Plugins/CSRFProtection/CSRFProtection> #include <QObject> #include <QTest> #include <QNetworkCookie> using namespace Cutelyst; class TestCsrfProtection : public CoverageObject { Q_OBJECT public: explicit TestCsrfProtection(QObject *parent = nullptr) : CoverageObject(parent) {} void initTest(); void cleanupTest(); private Q_SLOTS: void initTestCase(); void doTest_data(); void doTest(); void detachToOnArgument(); void csrfIgnorArgument(); void ignoreNamespace(); void ignoreNamespaceRequired(); void csrfRedirect(); void cleanupTestCase(); private: TestEngine *m_engine; QNetworkCookie m_cookie; const QString m_cookieName = QStringLiteral("xsrftoken"); const QString m_fieldName = QStringLiteral("xsrfprotect"); const QString m_headerName = QStringLiteral("X-MY-CSRF"); QString m_fieldValue; TestEngine *getEngine(); void performTest(); }; class CsrfprotectionTest : public Controller { Q_OBJECT public: explicit CsrfprotectionTest(QObject *parent) : Controller(parent) {} C_ATTR(testCsrf, :Local :AutoArgs) void testCsrf(Context *c) { c->res()->setContentType(QStringLiteral("text/plain")); if (c->req()->isGet()) { c->res()->setBody(CSRFProtection::getToken(c)); } else { c->res()->setBody(QByteArrayLiteral("allowed")); } } C_ATTR(testCsrfIgnore, :Local :AutoArgs :CSRFIgnore) void testCsrfIgnore(Context *c) { c->res()->setContentType(QStringLiteral("text/plain")); c->res()->setBody(QByteArrayLiteral("allowed")); } C_ATTR(testCsrfRedirect, :Local :AutoArgs) void testCsrfRedirect(Context *c) { c->res()->redirect(QStringLiteral("http//www.example.com")); } C_ATTR(testCsrfDetachTo, :Local :AutoArgs :CSRFDetachTo(csrfdenied)) void testCsrfDetachTo(Context *c) { c->res()->setContentType(QStringLiteral("text/plain")); c->res()->setBody(QByteArrayLiteral("allowed")); } C_ATTR(csrfdenied, :Private :AutoArgs) void csrfdenied(Context *c) { c->res()->setContentType(QStringLiteral("text/plain")); c->res()->setBody(QByteArrayLiteral("detachdenied")); c->detach(); } }; class CsrfprotectionNsTest : public Controller { Q_OBJECT C_NAMESPACE("testns") public: explicit CsrfprotectionNsTest(QObject *parent) : Controller(parent) {} C_ATTR(testCsrf, :Local :AutoArgs) void testCsrf(Context *c) { c->res()->setContentType(QStringLiteral("text/plain")); c->res()->setBody(QByteArrayLiteral("allowed")); } C_ATTR(testCsrfRequired, :Local :AutoArgs :CSRFRequire) void testCsrfRequired(Context *c) { c->res()->setContentType(QStringLiteral("text/plain")); c->res()->setBody(QByteArrayLiteral("allowed")); } }; void TestCsrfProtection::initTestCase() { m_engine = getEngine(); QVERIFY(m_engine); if (m_cookie.value().isEmpty()) { const QVariantMap result = m_engine->createRequest(QStringLiteral("GET"), QStringLiteral("csrfprotection/test/testCsrf"), QByteArray(), Headers(), nullptr); const QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(result.value(QStringLiteral("headers")).value<Headers>().header(QStringLiteral("Set-Cookie")).toLatin1()); QVERIFY(!cookies.empty()); for (const QNetworkCookie &cookie : cookies) { if (cookie.name() == m_cookieName.toLatin1()) { m_cookie = cookie; break; } } QVERIFY(!m_cookie.value().isEmpty()); initTest(); } } TestEngine* TestCsrfProtection::getEngine() { qputenv("RECURSION", QByteArrayLiteral("100")); auto app = new TestApplication; auto engine = new TestEngine(app, QVariantMap()); auto csrf = new CSRFProtection(app); csrf->setCookieName(m_cookieName); csrf->setGenericErrorMessage(QStringLiteral("denied")); csrf->setFormFieldName(m_fieldName); csrf->setHeaderName(m_headerName); csrf->setIgnoredNamespaces(QStringList(QStringLiteral("testns"))); new CsrfprotectionTest(app); new CsrfprotectionNsTest(app); if (!engine->init()) { delete engine; return nullptr; } return engine; } void TestCsrfProtection::cleanupTestCase() { delete m_engine; } void TestCsrfProtection::initTest() { Headers headers; headers.setHeader(QStringLiteral("Cookie"), QString::fromLatin1(m_cookie.toRawForm(QNetworkCookie::NameAndValueOnly))); m_fieldValue = m_engine->createRequest(QStringLiteral("GET"), QStringLiteral("csrfprotection/test/testCsrf"), QByteArray(), headers, nullptr).value(QStringLiteral("body")).toString(); } void TestCsrfProtection::cleanupTest() { m_fieldValue.clear(); } void TestCsrfProtection::doTest() { QFETCH(QString, method); QFETCH(Headers, headers); QFETCH(QByteArray, body); QFETCH(int, status); QFETCH(QByteArray, output); const QVariantMap result = m_engine->createRequest(method, QStringLiteral("csrfprotection/test/testCsrf"), QByteArray(), headers, &body); QCOMPARE(result.value(QStringLiteral("statusCode")).value<int>(), status); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), output); } void TestCsrfProtection::doTest_data() { QTest::addColumn<QString>("method"); QTest::addColumn<Headers>("headers"); QTest::addColumn<QByteArray>("body"); QTest::addColumn<int>("status"); QTest::addColumn<QByteArray>("output"); for (const QString &method : {QStringLiteral("POST"), QStringLiteral("PUT"), QStringLiteral("PATCH"), QStringLiteral("DELETE")}) { const QString cookieValid = QString::fromLatin1(m_cookie.toRawForm(QNetworkCookie::NameAndValueOnly)); QString cookieInvalid = cookieValid; #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) auto& cookieLast = cookieInvalid[cookieInvalid.size() - 1]; #else QCharRef cookieLast = cookieInvalid[cookieInvalid.size() - 1]; #endif if (cookieLast.isDigit()) { if (cookieLast.unicode() < 57) { cookieLast.unicode()++; } else { cookieLast.unicode()--; } } else { if (cookieLast.isUpper()) { cookieLast = cookieLast.toLower(); } else { cookieLast = cookieLast.toUpper(); } } QString fieldValueInvalid = m_fieldValue; #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) auto& fieldLast = fieldValueInvalid[fieldValueInvalid.size() - 2]; #else QCharRef fieldLast = fieldValueInvalid[fieldValueInvalid.size() - 2]; #endif if (fieldLast.isDigit()) { if (fieldLast.unicode() < 57) { fieldLast.unicode()++; } else { fieldLast.unicode()--; } } else { if (fieldLast.isUpper()) { fieldLast = fieldLast.toLower(); } else { fieldLast = fieldLast.toUpper(); } } const QString fieldValid = m_fieldName + QLatin1Char('=') + m_fieldValue; const QString fieldInvalid = m_fieldName + QLatin1Char('=') + fieldValueInvalid; Headers headers; headers.setContentType(QStringLiteral("application/x-www-form-urlencoded")); QByteArray body; QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(absent), header(absent), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.setHeader(QStringLiteral("Cookie"), cookieValid); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(valid), header(absent), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.setHeader(QStringLiteral("Cookie"), cookieInvalid); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(invalid), header(absent), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.removeHeader(QStringLiteral("Cookie")); headers.setHeader(m_headerName, m_fieldValue); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(absent), header(valid), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.setHeader(QStringLiteral("Cookie"), cookieValid); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(valid), header(valid), field(absent)").arg(method))) << method << headers << body << 200 << QByteArrayLiteral("allowed"); headers.setHeader(QStringLiteral("Cookie"), cookieInvalid); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(invalid), header(valid), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.setHeader(m_headerName, fieldValueInvalid); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(invalid), header(invalid), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.setHeader(QStringLiteral("Cookie"), cookieValid); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(valid), header(invalid), field(absent)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); body = method != u"DELETE" ? fieldValid.toLatin1() : QByteArray(); int status = (method != u"DELETE") ? 200 : 403; QByteArray result = (method != u"DELETE") ? QByteArrayLiteral("allowed") : QByteArrayLiteral("denied"); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(valid), header(invalid), field(valid)").arg(method))) << method << headers << body << status << result; body = fieldInvalid.toLatin1(); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(valid), header(invalid), field(invalid)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); headers.setHeader(m_headerName, m_fieldValue); status = method == u"DELETE" ? 200 : 403; result = method == u"DELETE" ? QByteArrayLiteral("allowed") : QByteArrayLiteral("denied"); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(valid), header(valid), field(invalid)").arg(method))) << method << headers << body << status << result; headers.setHeader(QStringLiteral("Cookie"), cookieInvalid); body = fieldValid.toLatin1(); QTest::newRow(qUtf8Printable(QStringLiteral("%1: cookie(invalid), header(valid), field(valid)").arg(method))) << method << headers << body << 403 << QByteArrayLiteral("denied"); } } void TestCsrfProtection::detachToOnArgument() { const QVariantMap result = m_engine->createRequest(QStringLiteral("POST"), QStringLiteral("csrfprotection/test/testCsrfDetachTo"), QByteArray(), Headers(), nullptr); QCOMPARE(result.value(QStringLiteral("statusCode")).value<int>(), 403); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), QByteArrayLiteral("detachdenied")); } void TestCsrfProtection::csrfIgnorArgument() { const QVariantMap result = m_engine->createRequest(QStringLiteral("POST"), QStringLiteral("csrfprotection/test/testCsrfIgnore"), QByteArray(), Headers(), nullptr); QCOMPARE(result.value(QStringLiteral("statusCode")).value<int>(), 200); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), QByteArrayLiteral("allowed")); } void TestCsrfProtection::ignoreNamespace() { const QVariantMap result = m_engine->createRequest(QStringLiteral("POST"), QStringLiteral("testns/testCsrf"), QByteArray(), Headers(), nullptr); QCOMPARE(result.value(QStringLiteral("statusCode")).value<int>(), 200); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), QByteArrayLiteral("allowed")); } void TestCsrfProtection::ignoreNamespaceRequired() { const QVariantMap result = m_engine->createRequest(QStringLiteral("POST"), QStringLiteral("testns/testCsrfRequired"), QByteArray(), Headers(), nullptr); QCOMPARE(result.value(QStringLiteral("statusCode")).value<int>(), 403); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), QByteArrayLiteral("denied")); } void TestCsrfProtection::csrfRedirect() { const QVariantMap result = m_engine->createRequest(QStringLiteral("POST"), QStringLiteral("csrfprotection/test/testCsrfRedirect"), QByteArray(), Headers(), nullptr); QCOMPARE(result.value(QStringLiteral("statusCode")).value<int>(), 403); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), QByteArrayLiteral("denied")); } QTEST_MAIN(TestCsrfProtection) #include "testcsrfprotection.moc"
#pragma once #include "shape.h" class Bomb : public Shape { public: Bomb(Point & _head, const char _c); void takeShapeUp() override; virtual bool canMoveShapeDown(Board & playBoard, bool & bombWasActivated, int & bombScore); virtual void moveAllWayDown(Board & playBoard, int & bombScore, int & bombHeight); virtual bool canMoveShapeRightOrLeft(Board & playBoard, char keyPressed, bool & bombWasActivatedRL, int & bombScore) override; int updateAfterBombing(Board & playBoard, int x1, int y1); virtual int dropScore(int hardDrop, int softDrop, int heightBomb); void cleanBomb(); virtual string type() const override { return "bomb"; } };
#include "component/light/DirectionalLight.h" #include "component/Camera.h" #include "renderer/Renderer.h" #include "core/GameObject.h" #include "core/Helpers.h" using namespace de; using namespace de::component; using namespace de::data; COMPONENT_DEF_TYPE(DirectionalLight); de::Material* DirectionalLight::sDiretionalLightMat = nullptr; DirectionalLight::DirectionalLight() : Light(1) { if(sDiretionalLightMat == nullptr) { sDiretionalLightMat = AssetDatabase::load<Material>("data/internals/lights/directional/DirectionalLight.mat"); } } //------------------------- void DirectionalLight::init() { mShadowmapBuffer.init(1024, 1024, false); mShadowmap.create(1024, 1024); mShadowmap.init(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_FLOAT); mShadowmap.setParameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); mShadowmap.setParameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); mShadowmapBuffer.addTexture(&mShadowmap, GL_DEPTH_ATTACHMENT); mLightGameobject = new GameObject(); mLightCamera = (Camera*)mLightGameobject->addComponent(new Camera()); mLightCamera->setOrtho(true); mLightCamera->setClipPlane(glm::vec2(0.1f, 500.0f)); mLightCamera->setOrthoHalfSize(100); mLightCamera->setAspect(1.0f); } //----------------------- void DirectionalLight::setupLightType(de::data::Texture* pAlbedo, de::data::Texture* pNormal, de::data::Texture* pDepth) { sDiretionalLightMat->addTexture("_Albedo", pAlbedo); sDiretionalLightMat->addTexture("_Normal", pNormal); sDiretionalLightMat->addTexture("_Depth", pDepth); sDiretionalLightMat->setup(false); sDiretionalLightMat->program()->setMatrix("_InvertVP", glm::inverse(component::Camera::current()->projectionMatrix() * component::Camera::current()->viewMatrix())); sDiretionalLightMat->program()->setVector4("_CamPos", glm::vec4(component::Camera::current()->owner()->transform()->position(), 1.0f)); } ///----------------------- void DirectionalLight::setup() { Light::internalSetup(sDiretionalLightMat->program()); sDiretionalLightMat->program()->setVector4("_LightDirection", glm::vec4(mOwner->transform()->forward(), 0.0f)); sDiretionalLightMat->addTexture("_ShadowMap", &mShadowmap, true); sDiretionalLightMat->program()->setMatrix("_VPLight", mCurrentMat/*mLightCamera->projectionMatrix() * mLightCamera->viewMatrix()*/); Helpers::drawQuad(); } //------------------------------ void DirectionalLight::renderShadowmap() { Camera* pPrevious = Camera::current(); mLightGameobject->transform()->setRotation(mOwner->transform()->rotation()); //mLightGameobject->transform()->setPosition(Camera::current()->owner()->transform()->position() - mLightGameobject->transform()->forward() * 30.0f); mLightGameobject->transform()->setPosition(glm::vec3(50,0,50) - mLightGameobject->transform()->forward() * 30.0f); mLightCamera->setup(); mCurrentMat = component::Camera::current()->projectionMatrix() * component::Camera::current()->viewMatrix(); mShadowmapBuffer.bind(); glClear(GL_DEPTH_BUFFER_BIT); Camera::current()->setReplacementMaterial(AssetDatabase::load<Material>("data/internals/depthOnly/depth.mat")); renderer::Renderer::current()->sortRenderList(); renderer::Renderer::current()->renderOpaque(); Camera::current()->setReplacementMaterial(nullptr); mShadowmapBuffer.unbind(); pPrevious->setup(); }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef _FEMLABMESHREADER_H_ #define _FEMLABMESHREADER_H_ #include "AbstractCachedMeshReader.hpp" /** * Concrete version of the AbstractCachedMeshReader class. * A FemlabMeshReader takes the file names of a set of Femlab mesh files. * Once constructed the public methods of the AbstractCachedMeshReader * (std::vector<double> GetNextNode(); etc) can be called to interrogate the * data */ template <unsigned ELEMENT_DIM, unsigned SPACE_DIM> class FemlabMeshReader : public AbstractCachedMeshReader<ELEMENT_DIM, SPACE_DIM> { private: /** * TokenizeStringsToDoubles is specific to reading node data which came from * a Femlab or Matlab PDE toolbox file. * * Each string is expected to be a series of doubles. * @return a vector where each item is a vector of double which represents * position. Indices are implicit in the vector. * * @param rRawData the node data to be read */ std::vector<std::vector<double> > TokenizeStringsToDoubles(const std::vector<std::string>& rRawData); /** * TokenizeStringsToInts is for reading element, face or edge data which came from * a Femlab or Matlab PDE toolbox file. * Each string is expected to be a series of unsigned which represent: * The first several lines denote the indices of nodes * The rest contains extra information which are ignored currently. * ( In 2-D: 2 indices for an edge, 3 for a triangle) * ( In 3-D: 3 indices for a face, 4 for a tetrahedron) * @return a vector where each item is a vector of ints which represents * indices of nodes. * * @param rRawData the element, face or edge data to be read * @param dimensionOfObject the number of lines of data to be read */ std::vector<std::vector<unsigned> > TokenizeStringsToInts(const std::vector<std::string>& rRawData, unsigned dimensionOfObject); public: /** * The constructor takes the path to and names of a set of Femlab mesh files * (ie. the nodes, elements and faces files (in that order) and allows the data to * be queried. * Typical use: * AbstractMeshReader* pMeshReader = new FemlabMeshReader("pdes/tests/meshdata/", * "femlab_lshape_nodes.dat", * "femlab_lshape_elements.dat", * "femlab_lshape_edges.dat",); * * @param rPathBaseName the base name of the files from which to read the mesh data * @param rNodeFileName the name of the nodes file * @param rElementFileName the name of the elements file * @param rEdgeFileName the name of the edges file */ FemlabMeshReader(const std::string& rPathBaseName, const std::string& rNodeFileName, const std::string& rElementFileName, const std::string& rEdgeFileName); /** * Destructor */ virtual ~FemlabMeshReader(); }; #endif //_FEMLABMESHREADER_H_
//题目:给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。 //遍历数组,遇到零,重写一个零,不是零,保留下来 #include<stdio.h> int main(){ int arry[9]={0,1,0,7,0,4,0,2,3}; int destination[9]; int d = 0; for(int i = 0; i < 9; i++) { if (arry[i] == 0) {// Copy zero twice. destination[d] = 0; d += 1; destination[d] = 0;} else destination[d] = arry[i]; d += 1; if(d >= sizeof(arry)) break; } for(int i = 0;i < 9;i++) printf("%d\n",destination[i]); }
#pragma once #ifndef _CONSTANTS_HPP_ #define _CONSTANTS_HPP_ #include <vector> struct Data { Data(std::string in, std::string out) : input(in), output(out) { } std::string input; std::string output; }; namespace NConstants { // The linkage between input and output files const std::vector<Data> FILES { { "input\\1.in", "output\\1.out"}, { "input\\2.in", "output\\2.out"}, }; }; // NConstants #endif // _CONSTANTS_HPP_
/************************************************************* * > File Name : P2764.cpp * > Author : Tony * > Created Time : 2019年04月08日 星期一 12时51分25秒 **************************************************************/ #include <bits/stdc++.h> using namespace std; const int maxn = 1010; const int inf = 0x3f3f3f3f; bool vis[maxn], vst[maxn]; int n, m, s, t; int d[maxn], cur[maxn], to[maxn]; struct Edge { int from, to, cap, flow; Edge(int u, int v, int c, int f) : from(u), to(v), cap(c), flow(f) {} }; vector<Edge> edges; vector<int> G[maxn]; void add(int u, int v, int c) { edges.push_back(Edge(u, v, c, 0)); edges.push_back(Edge(v, u, 0, 0)); int mm = edges.size(); G[u].push_back(mm - 2); G[v].push_back(mm - 1); } bool bfs() { memset(vis, 0, sizeof(vis)); queue<int> Q; Q.push(s); d[s] = 0; vis[s] = true; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i = 0; i < G[x].size(); ++i) { Edge& e = edges[G[x][i]]; if (!vis[e.to] && e.cap > e.flow) { vis[e.to] = true; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vis[t]; } int dfs(int x, int a) { if (x == t || a == 0) return a; int flow = 0, f; for (int& i = cur[x]; i < G[x].size(); ++i) { Edge& e = edges[G[x][i]]; if (d[x] + 1 == d[e.to] && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0) { to[x] = e.to; e.flow += f; edges[G[x][i] ^ 1].flow -= f; flow += f; a -= f; if (a == 0) break; } } return flow; } int maxflow(int s, int t) { int flow = 0; while (bfs()) { memset(cur, 0, sizeof(cur)); flow += dfs(s, inf); } return flow; } int main() { scanf("%d %d", &n, &m); s = 0; t = 2 * n + 1; for (int i = 1; i <= m; ++i) { int u, v; scanf("%d %d", &u, &v); add(u, v + n, 1); } for (int i = 1; i <= n; ++i) add(s, i, 1); for (int i = 1; i <= n; ++i) add(i + n, t, 1); int ans = maxflow(s, t); for (int i = 1; i <= n; ++i) { if (!vst[i]) { int x = i; vst[x] = true; printf("%d ", x); while (to[x] && to[x] != t) { x = to[x] - n; printf("%d ", x); vst[x] = true; } printf("\n"); } } printf("%d\n", n - ans); return 0; }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include "tensorflow/core/framework/op_kernel.h" #include "./layer_norm_fused_op.h" namespace tensorflow { typedef Eigen::GpuDevice GPUDevice; template <typename Device, typename T> struct LaunchLayerNormOp; template <typename T> struct LayerNormGPULaunch { static void Run(const GPUDevice& d, const LayerNormFusedArgs args, const T* input, T* output); }; template <typename T> struct LaunchLayerNormOp<GPUDevice, T> { static void launch(OpKernelContext* ctx, const LayerNormFusedArgs args, const T* input, T* output ) { const GPUDevice& d = ctx->eigen_device<GPUDevice>(); LayerNormGPULaunch<T>().Run(d, args, input, output); } }; template <typename Device, typename T> class LayerNormOp : public OpKernel { public: explicit LayerNormOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("epsilon", &epsilon_)); } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); OP_REQUIRES(context, input.dims() >= 2, errors::InvalidArgument("input dimensions must be larger than 2D", input.shape().DebugString())); const int32 last_dim = input.dims()-1; const int32 depth = input.dim_size(last_dim); int32 n_slices = 1; for (int i = 0; i < last_dim; ++i) { n_slices *= input.dim_size(i); } Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, input.shape(), &output)); VLOG(2) << "LayerNormCustom: " << "depth:"<<depth << ", " <<"n_slices:"<<n_slices; //temporarily hard-coding warp_size for CUDA kernel. const int warp_size = 32; LayerNormFusedArgs args; args.depth = depth; args.n_slices = n_slices; args.n_inputs = n_slices*depth; args.epsilon = epsilon_; if (depth<=warp_size) { int tmp_depth = depth; int slice_size = 1; while(tmp_depth >>=1)slice_size*=2; args.slice_size = slice_size>=depth?slice_size:slice_size*2; }else{ int slice_size = (depth/warp_size)*warp_size; args.slice_size = slice_size>=depth?slice_size:slice_size+warp_size; } auto input_ptr = input.template flat<T>().data(); auto output_ptr = output->template flat<T>().data(); LaunchLayerNormOp<Device, T>::launch(context, args, input_ptr,output_ptr); } private: float epsilon_; TF_DISALLOW_COPY_AND_ASSIGN(LayerNormOp); }; template <typename Device, typename T> struct LaunchLayerNormBiasAddOp; template <typename T> struct LayerNormBiasAddGPULaunch { static void Run(const GPUDevice& d, const LayerNormFusedArgs args, const T* input, const T* beta,T* output); }; template <typename T> struct LaunchLayerNormBiasAddOp<GPUDevice, T> { static void launch(OpKernelContext* ctx, const LayerNormFusedArgs args, const T* input,const T* beta, T* output ) { const GPUDevice& d = ctx->eigen_device<GPUDevice>(); LayerNormBiasAddGPULaunch<T>().Run(d, args, input,beta, output); } }; template <typename Device, typename T> class LayerNormBiasAddOp : public OpKernel { public: explicit LayerNormBiasAddOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("epsilon", &epsilon_)); } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& beta = context->input(1); OP_REQUIRES(context, input.dims() >= 2, errors::InvalidArgument("input dimensions must be larger than 2D", input.shape().DebugString())); OP_REQUIRES(context, beta.dims() == 1, errors::InvalidArgument("beta dimension must be 1D", beta.shape().DebugString())); const int32 last_dim = input.dims()-1; const int32 depth = input.dim_size(last_dim); OP_REQUIRES( context, depth == beta.dim_size(0), errors::InvalidArgument("input depth and beta must have the same size: ", depth, " vs ", beta.dim_size(0))); int32 n_slices = 1; for (int i = 0; i < last_dim; ++i) { n_slices *= input.dim_size(i); } Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, input.shape(), &output)); VLOG(2) << "LayerNormBiasAddCustom: " << "depth:"<<depth << ", " <<"n_slices:"<<n_slices; //temporarily hard-coding warp_size for CUDA kernel. const int warp_size = 32; LayerNormFusedArgs args; args.depth = depth; args.n_slices = n_slices; args.n_inputs = n_slices*depth; args.epsilon = epsilon_; if (depth<=warp_size) { int tmp_depth = depth; int slice_size = 1; while(tmp_depth >>=1)slice_size*=2; args.slice_size = slice_size>=depth?slice_size:slice_size*2; }else{ int slice_size = (depth/warp_size)*warp_size; args.slice_size = slice_size>=depth?slice_size:slice_size+warp_size; } auto input_ptr = input.template flat<T>().data(); auto beta_ptr = beta.template flat<T>().data(); auto output_ptr = output->template flat<T>().data(); LaunchLayerNormBiasAddOp<Device, T>::launch(context, args, input_ptr,beta_ptr, output_ptr ); } private: float epsilon_; TF_DISALLOW_COPY_AND_ASSIGN(LayerNormBiasAddOp); }; template <typename Device, typename T> struct LaunchLayerNormFusedOp; template <typename T> struct LayerNormFusedGPULaunch { static void Run(const GPUDevice& d, const LayerNormFusedArgs args, const T* input, const T* gamma,const T* beta,T* output); }; template <typename T> struct LaunchLayerNormFusedOp<GPUDevice, T> { static void launch(OpKernelContext* ctx, const LayerNormFusedArgs args, const T* input,const T* gamma,const T* beta, T* output ) { const GPUDevice& d = ctx->eigen_device<GPUDevice>(); LayerNormFusedGPULaunch<T>().Run(d, args, input,gamma,beta, output); } }; template <typename Device, typename T> class LayerNormFusedOp : public OpKernel { public: explicit LayerNormFusedOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("epsilon", &epsilon_)); } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& gamma = context->input(1); const Tensor& beta = context->input(2); OP_REQUIRES(context, input.dims() >= 2, errors::InvalidArgument("input dimensions must be larger than 2D", input.shape().DebugString())); OP_REQUIRES(context, gamma.dims() == 1, errors::InvalidArgument("gamma dimension must be 1D", gamma.shape().DebugString())); OP_REQUIRES(context, beta.dims() == 1, errors::InvalidArgument("beta dimension must be 1D", beta.shape().DebugString())); const int32 last_dim = input.dims()-1; const int32 depth = input.dim_size(last_dim); OP_REQUIRES( context, depth == gamma.dim_size(0), errors::InvalidArgument("input depth and gamma must have the same size: ", depth, " vs ", gamma.dim_size(0))); OP_REQUIRES( context, depth == beta.dim_size(0), errors::InvalidArgument("input depth and beta must have the same size: ", depth, " vs ", beta.dim_size(0))); int32 n_slices = 1; for (int i = 0; i < last_dim; ++i) { n_slices *= input.dim_size(i); } Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, input.shape(), &output)); VLOG(2) << "LayerNormFusedCustom: " << "depth:"<<depth << ", " <<"n_slices:"<<n_slices; //temporarily hard-coding warp_size for CUDA kernel. const int warp_size = 32; LayerNormFusedArgs args; args.depth = depth; args.n_slices = n_slices; args.n_inputs = n_slices*depth; args.epsilon = epsilon_; if (depth<=warp_size) { int tmp_depth = depth; int slice_size = 1; while(tmp_depth >>=1)slice_size*=2; args.slice_size = slice_size>=depth?slice_size:slice_size*2; }else{ int slice_size = (depth/warp_size)*warp_size; args.slice_size = slice_size>=depth?slice_size:slice_size+warp_size; } auto input_ptr = input.template flat<T>().data(); auto gamma_ptr = gamma.template flat<T>().data(); auto beta_ptr = beta.template flat<T>().data(); auto output_ptr = output->template flat<T>().data(); LaunchLayerNormFusedOp<Device, T>::launch(context, args, input_ptr,gamma_ptr,beta_ptr, output_ptr ); } private: float epsilon_; TF_DISALLOW_COPY_AND_ASSIGN(LayerNormFusedOp); }; REGISTER_KERNEL_BUILDER( Name("LayerNormCustom").Device(DEVICE_GPU).TypeConstraint<float>("T"), LayerNormOp<GPUDevice, float>); REGISTER_KERNEL_BUILDER(Name("LayerNormCustom") .Device(DEVICE_GPU) .TypeConstraint<double>("T"), LayerNormOp<GPUDevice, double>); REGISTER_KERNEL_BUILDER( Name("LayerNormBiasAddCustom").Device(DEVICE_GPU).TypeConstraint<float>("T"), LayerNormBiasAddOp<GPUDevice, float>); REGISTER_KERNEL_BUILDER(Name("LayerNormBiasAddCustom") .Device(DEVICE_GPU) .TypeConstraint<double>("T"), LayerNormBiasAddOp<GPUDevice, double>); REGISTER_KERNEL_BUILDER( Name("LayerNormFusedCustom").Device(DEVICE_GPU).TypeConstraint<float>("T"), LayerNormFusedOp<GPUDevice, float>); REGISTER_KERNEL_BUILDER(Name("LayerNormFusedCustom") .Device(DEVICE_GPU) .TypeConstraint<double>("T"), LayerNormFusedOp<GPUDevice, double>); } // namespace tensorflow
//This is the implementation of the Tournament class. Please see the... //corresponding header file for details about its interface. #include "Tournament.hpp" Tournament::Tournament(std::mt19937& generator) { this->p1Wins = 0; this->p2Losses = 0; this->p2Wins = 0; this->p1Losses = 0; this->currentRound = 0; this->generator = &generator; std::cout << "*******************************************\n"; std::cout << "* Tournament Creature Pool Creation Phase *\n"; std::cout << "*******************************************\n\n"; std::cout << "* Each player will choose creatures from a pool to fill their respective lineups.\n"; std::cout << "* How many creatures will each line up have?\n"; this->lineupLength = validatePosInteger(); this->Losers = new LoserStack; this->lineupPool = new LineupPool; this->p1Lineup = new LineupQueue; this->p2Lineup = new LineupQueue; bool continueAddingCreatures = true; int numInPool = 0; std::string name; std::cout << "\n* Ok, each lineup will have " << lineupLength << " creature(s) in it.\n"; std::cout << "* You will now fill the pool with creatures.\n"; std::cout << "* The pool needs at least as many creatures"; std::cout << " as the number of creatures in both lineups.\n\n"; do { std::cout << "*********************************************************\n"; std::cout << "* Choose the type of creature to add to the lineup pool.\n"; std::cout << "* (Select option 6 when you are done adding to the pool).\n"; std::cout << "1. Barbarian\n2. Blue Men\n3. Harry Potter\n4. Medusa\n"; std::cout << "5. Vampire\n6. Done adding creatures.\n"; std::cout << "*********************************************************\n"; int option = 0; while (option < 1 || option > 6) { option = validatePosInteger(); if (option < 1 || option > 6) { std::cout << "* Enter one of the options above.\n"; } } if (option >= 1 && option < 6) { do { std::cout << "* Enter a name for this creature: "; std::getline(std::cin, name); } while (name.empty()); } switch (option) { case 1: this->lineupPool->addNode(BARBARIAN, name); ++numInPool; break; case 2: this->lineupPool->addNode(BLUE_MEN, name); ++numInPool; break; case 3: this->lineupPool->addNode(HARRY_POTTER, name); ++numInPool; break; case 4: this->lineupPool->addNode(MEDUSA, name); ++numInPool; break; case 5: this->lineupPool->addNode(VAMPIRE, name); ++numInPool; break; case 6: if (numInPool < lineupLength * 2) { std::cout << "* There are not enough creatures in the pool to fill both lineups. "; std::cout << "\n* Please enter at least " << (lineupLength * 2) - numInPool << " more.\n"; continueAddingCreatures = true; } else { continueAddingCreatures = false; } break; } if(option != 6) { std::cout << "* " << name << " was added to the lineup pool.\n\n"; } } while (continueAddingCreatures); } void Tournament::createLineups() { std::cout << "\n*******************************************\n"; std::cout << "* Tournament Player Lineup Creation Phase *\n"; std::cout << "*******************************************\n\n"; std::cout << "* Player 1 will now choose their lineup from the pool of available creatures.\n"; for (int i = 0; i < this->lineupLength; ++i) { std::string creatureName; std::cout << "\n* Enter the name of the creature you want to add to your team"; std::cout << " from the creatures below:\n"; this->lineupPool->printPool(); Creature* searchResults; do { std::getline(std::cin, creatureName); searchResults = this->lineupPool->searchPool(creatureName); if (searchResults == nullptr) { std::cout << "* There is no creature with that name. "; std::cout << "Enter another name.\n"; } } while (searchResults == nullptr); this->p1Lineup->enqueue(searchResults, "P1"); } std::cout << "\n* Player 2 will now choose their lineup from the pool of available creatures.\n"; for (int i = 0; i < this->lineupLength; ++i) { std::string creatureName; std::cout << "* Enter the name of the creature you want to add to your team"; std::cout << " from the creatures below:\n\n"; this->lineupPool->printPool(); Creature* searchResults; do { std::getline(std::cin, creatureName); searchResults = this->lineupPool->searchPool(creatureName); if (searchResults == nullptr) { std::cout << "* There is no creature with that name. "; std::cout << "Enter another name.\n"; } } while (searchResults == nullptr); this->p2Lineup->enqueue(searchResults, "P2"); } } void Tournament::game() { std::cout << "\n* Show updated score tally after each round? (y/n). "; char showRound; do { std::cin >> showRound; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (showRound != 'y' && showRound != 'n') { std::cout << "Enter y or n.\n"; } } while (showRound != 'y' && showRound != 'n'); while (!this->p1Lineup->isEmpty() && !this->p2Lineup->isEmpty()) { ++this->currentRound; Creature* p1Fighter = this->p1Lineup->getFront(); Creature* p2Fighter = this->p2Lineup->getFront(); Creature* loser = nullptr; Creature* winner = this->fight(*p1Fighter, *p2Fighter, *this->generator); if (winner == p1Fighter) { loser = p2Fighter; } else { loser = p1Fighter; } this->printRound(winner, loser); if (winner->getPlayer() == "P1") { ++this->p1Wins; ++this->p2Losses; this->p1Lineup->frontToBack(); //front to back calls healing function this->p2Lineup->dequeue(); this->Losers->pushBack(loser); } else { ++this->p2Wins; ++this->p1Losses; this->p2Lineup->frontToBack(); this->p1Lineup->dequeue(); this->Losers->pushBack(loser); } if (showRound == 'y') { std::cout << "* Round " << currentRound << " winner: " << winner->getName(); std::cout << "\n* P1 Wins: " << p1Wins; std::cout << ".\n* P1 Losses: " << p1Losses; std::cout << ".\n* P2 Wins: " << p2Wins; std::cout << ".\n* P2 Losses: " << p2Losses << ".\n"; } } } void Tournament::printTournamentResults() { std::cout << "\n****************************\n"; std::cout << "* TOURNAMENT RESULTS *\n"; std::cout << "****************************\n\n"; if (this->p1Wins > this->p2Wins) { std::cout << "* Player 1's lineup won the tournament.\n"; } else { std::cout << "* Player 2's lineup won the tournament.\n"; } std::cout << "* The final tally of points is as follows: *\n"; std::cout << "********************************************\n"; std::cout << "* P1 wins: " << this->p1Wins << ".\n"; std::cout << "* P1 losses: " << this->p1Losses << ".\n"; std::cout << "* P2 wins: " << this->p2Wins << ".\n"; std::cout << "* P2 losses: " << this->p2Losses << ".\n"; std::cout << "********************************************\n\n"; std::cout << "* Would you like to see the defeated creatures? (y/n)\n"; char seeLosers; do { std::cin >> seeLosers; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (seeLosers != 'y' && seeLosers != 'n') { std::cout << "Enter y or n.\n"; } } while (seeLosers != 'y' && seeLosers != 'n'); if (seeLosers == 'y') { this->Losers->printStack(); } } Creature* Tournament::fight(Creature& attacker, Creature& defender, std::mt19937& generator) { //simulate a coin flip (or roll of 2-sided die) to choose who will attack first int roll = Die(1, 2).rollDie(generator); int turn; if (roll == 1) { turn = 0; } else { turn = 1; } int defenderStr = defender.getStrength(), attackerStr = attacker.getStrength(); int atk = 0; //have fighters take turn attacking and defending do { if (turn % 2 == 0) { atk = attacker.attack(defender, generator); defenderStr = defender.defend(atk, attacker, generator); ++turn; } else { atk = defender.attack(attacker, generator); attackerStr = attacker.defend(atk, defender, generator); ++turn; } } while (defenderStr > 0 && attackerStr > 0); //return winner if (attacker.getStrength() <= 0) { return &defender; } else { return &attacker; } } void Tournament::printRound(Creature* winner, Creature* loser) const { std::cout << "\n* Round " << this->currentRound << " Results *\n"; std::cout << "**********************************************\n"; std::cout << "* " << loser->getPlayer() << "\'s " << loser->getType() << ", " << loser->getName(); std::cout << ", fought " << winner->getPlayer() << "\'s " << winner->getType() << ", " << winner->getName(); std::cout << ". " << winner->getName() << " won the round.\n"; } Tournament::~Tournament() { delete this->Losers; delete this->lineupPool; delete this->p1Lineup; delete this->p2Lineup; }
//Dutch National Flag Algorithm #include<iostream> #include<vector> using namespace std; class Solution{ public: void sortColors(vector<int> nums) { int l = 0; int m = 0; int h = nums.size()-1; while(m<=h){ switch(nums[m]){ case 0: swap(nums[l++],nums[m++]); break; case 1: m++; break; case 2: swap(nums[m],nums[h--]); break; } } cout<<"Number after arranging...."<<endl; for(int i=0;i<nums.size();i++){ cout<<nums[i]<<" "; } } }; int main(){ int n; vector<int> arr; cout<<"Enter the number of element you want to enter : "<<endl; cin>>n; for(int i=0;i<n;i++){ cout<<"Enter number: "; int input; cin>>input; arr.push_back(input); } Solution s1; s1.sortColors(arr); return 0; }
// ====================================== // filename: project2_carter_slc0070.cpp // author: Sydney Carter // project: Duel Simulator // sources: I used the Project2_hints.pdf as my source code // stack overflow links from Piazza // compile: compiled with g++ // ====================================== #include <iostream> #include <stdlib.h> #include <assert.h> #include <ctime> #include <cassert> using namespace std; bool at_least_two_alive(bool aaronAlive, bool bobAlive, bool charlieAlive); void Aaron_shoots1(bool& B_abobAlivelive, bool& charlieAlive); void Bob_shoots(bool& aaronAlive, bool& charlieAlive); void Charlie_shoots(bool& aaronAlive, bool& bobAlive); void Aaron_shoots2(bool& bobAlive, bool& charlieAlive); void Press_any_key(void); bool shoot_target_result(int probability); //TEST PROTOTYPES void test_at_least_two_alive(void); void test_Aaron_shoots1(void); void test_Bob_shoots(void); void test_Charlie_shoots(void); void test_Aaron_shoots2(void); //VARIABLES const int TOTAL_RUNS = 10000; const int aaronHitChance = 33; const int bobHitChance = 50; string target; int aaronWins1 = 0; int bobWins = 0; int charlieWins = 0; int aaronWins2 = 0; bool aaronAlive = true; bool bobAlive = true; bool charlieAlive = true; int main() { //Initializes Random number generator's seed and calls test functions cout << "*** Welcome to Sydney's Duel Simulator*** "; srand(time(0)); test_at_least_two_alive(); Press_any_key(); test_Aaron_shoots1(); Press_any_key(); test_Bob_shoots(); Press_any_key(); test_Charlie_shoots(); Press_any_key(); test_Aaron_shoots2(); Press_any_key(); //Starts strategy 1 and runs 10,000 times cout << "Ready to test strategy 1 (run 10000 times):\n"; Press_any_key(); for (int i = 0; i < TOTAL_RUNS; i++ ){ // setup duel aaronAlive = true; bobAlive = true; charlieAlive = true; while (at_least_two_alive(aaronAlive, bobAlive, charlieAlive)) { // Duel if (aaronAlive) { Aaron_shoots1(bobAlive, charlieAlive); } if (bobAlive) { Bob_shoots(aaronAlive, charlieAlive); } if (charlieAlive) { Charlie_shoots(aaronAlive, bobAlive); } } // add 1 to winner if (aaronAlive) { aaronWins1++; } if (bobAlive) { bobWins++; } if (charlieAlive) { charlieWins++; } } cout << "Aaron won " << aaronWins1 << "/10000 duels or " << static_cast<double>(aaronWins1) / TOTAL_RUNS * 100 << "%\n" << "Bob won " << bobWins << "/10000 duels or " << static_cast<double>(bobWins) / TOTAL_RUNS * 100 << "%\n" << "Charlie won " << charlieWins << "/10000 duels or " << static_cast<double>(charlieWins) / TOTAL_RUNS * 100 << "%\n" << endl; //Reinitializes variables and starts strategy 2 to run 10,000 times cout << "Ready to test strategy 2 (run 10000 times):\n"; bobWins = 0, charlieWins = 0; Press_any_key(); for (int i = 0; i < TOTAL_RUNS; i++) { // setup duel aaronAlive = true; bobAlive = true; charlieAlive = true; while(at_least_two_alive(aaronAlive, bobAlive, charlieAlive)) { // duel if (aaronAlive) { Aaron_shoots2(bobAlive, charlieAlive); } if (bobAlive) { Bob_shoots(aaronAlive, charlieAlive); } if (charlieAlive) { Charlie_shoots(aaronAlive, bobAlive); } } if (aaronAlive) { aaronWins2++; } if (bobAlive) { bobWins++; } if (charlieAlive) { charlieWins++; } } cout << "Aaron won " << aaronWins2 << "/10000 duels or " << static_cast<double>(aaronWins2)/TOTAL_RUNS * 100 << "%\n" << "Bob won " << bobWins << "/10000 duels or " << static_cast<double>(bobWins)/TOTAL_RUNS * 100 << "%\n" << "Charlie won " << charlieWins << "/10000 duels or " << static_cast<double>(charlieWins)/TOTAL_RUNS * 100 << "%\n" << endl; if (aaronWins1 > aaronWins2) { cout << "Strategy 1 is better than strategy 2.\n"; } else { cout << "Strategy 2 is better than strategy 1.\n"; } Press_any_key(); return 0; } //Implementation of functions bool at_least_two_alive(bool aaronAlive, bool bobAlive, bool charlieAlive) { if ((aaronAlive && bobAlive) | (bobAlive && charlieAlive) | (aaronAlive && charlieAlive)) { return true; } else { return false; } } void test_at_least_two_alive(void) { cout << "Unit Testing 1: Function - at_least_two_alive()\n"; cout << "\tCase 1: Aaron alive, Bob alive, Charlie alive\n"; assert(true == at_least_two_alive(true, true, true)); cout << "\tCase passed ...\n"; cout << "\tCase 2: Aaron dead, Bob alive, Charlie alive\n"; assert(true == at_least_two_alive(false, true, true)); cout << "\tCase passed ...\n"; cout << "\tCase 3: Aaron alive, Bob dead, Charlie alive\n"; assert(true == at_least_two_alive(true, false, true)); cout << "\tCase passed ...\n"; cout << "\tCase 4: Aaron alive, Bob alive, Charlie dead\n"; assert(true == at_least_two_alive(true, true, false)); cout << "\tCase passed ...\n"; cout << "\tCase 5: Aaron dead, Bob dead, Charlie alive\n"; assert(false == at_least_two_alive(false, false, true)); cout << "\tCase passed ...\n"; cout << "\tCase 6: Aaron dead, Bob alive, Charlie dead\n"; assert(false == at_least_two_alive(false, true, false)); cout << "\tCase passed ...\n"; cout << "\tCase 7: Aaron alive, Bob dead, Charlie dead\n"; assert(false == at_least_two_alive(true, false, false)); cout << "\tCase passed ...\n"; cout << "\tCase 8: Aaron dead, Bob dead, Charlie dead\n"; assert(false == at_least_two_alive(false, false, false)); cout << "\tCase passed ...\n"; } void Aaron_shoots1(bool& bobAlive, bool& charlieAlive) { assert(true == (bobAlive || charlieAlive)); int shootResult = rand() % 100; if (charlieAlive) { target = "Charlie"; } else { target = "Bob"; } if (shootResult <= aaronHitChance) { if (target == "Bob") { bobAlive = false; return; } else { charlieAlive = false; return; } } else { return; } } void test_Aaron_shoots1(void) { cout << "Init Testing 2: Function Aaron_shoots1(Bob_alive, Charlie_alive)\n"; bool bob_a = false; bool charlie_a = true; cout << "\tCase 1: Bob alive, Charlie alive\n" << "\t\tAaron is shooting at Charlie\n"; Aaron_shoots1(bob_a, charlie_a); bob_a = false; charlie_a = true; cout << "\tCase 2: Bob dead, Charlie alive\n" << "\t\tAaron is shooting at Charlie\n"; Aaron_shoots1(bob_a, charlie_a); bob_a = false; charlie_a = true; cout << "\tCase 3: Bob alive, Charlie dead\n" << "\t\tAaron is shooting at Bob\n"; Aaron_shoots1(bob_a, charlie_a); } void Bob_shoots(bool& aaronAlive, bool& charlieAlive) { assert(true == (aaronAlive || charlieAlive)); int shootResult = rand() % 100; if (charlieAlive) { target = "Charlie"; } else { target = "Aaron"; } if (shootResult <= bobHitChance) { if (target == "Charlie") { charlieAlive = false; return; } if (target == "Aaron") { aaronAlive = false; return; } } else { return; } } void test_Bob_shoots(void) { cout << "Unit Testing 3: Function Bob_shoots1(Aaron_alive, Charlie_alive)\n"; bool aaron_a = true; bool charlie_a = true; cout << "\tCase 1: Aaron alive, Charlie alive\n" << "\t\tBob is shooting at Charlie\n"; Bob_shoots(aaron_a, charlie_a); aaron_a = false; charlie_a = true; cout << "\tCase 2: Aaron dead, Charlie alive\n" << "\t\tBob is shooting at Charlie\n"; Bob_shoots(aaron_a, charlie_a); aaron_a = true; charlie_a = false; cout << "\tCase 3: Aaron alive, Charlie dead\n" << "\t\tBob is shooting at Aaron\n"; Bob_shoots(aaron_a, charlie_a); } void Charlie_shoots(bool& aaronAlive, bool& bobAlive) { assert(true == (aaronAlive || bobAlive)); if (bobAlive) { bobAlive = false; } else { aaronAlive = false; } return; } void test_Charlie_shoots(void) { cout << "Unit Testing 4: Function Charlie_shoots(aaronAlive, bobAlive)\n"; bool aaron_a = true; bool bob_a = true; cout << "\tCase 1: Aaron alive, Bob alive\n" << "\t\tCharlie is shooting at Bob\n"; Charlie_shoots(aaron_a, bob_a); aaron_a = false; bob_a = true; cout << "\tCase 2: Aaron dead, Bob alive\n" << "\t\tCharlie is shooting at Bob\n"; Charlie_shoots(aaron_a, bob_a); aaron_a = true; bob_a = false; cout << "\tCase 3: Aaron alive, Bob dead\n" << "\t\tCharlie is shooting at Aaron\n"; Charlie_shoots(aaron_a, bob_a); } void Aaron_shoots2(bool& bobAlive, bool& charlieAlive) { assert(true == (bobAlive || charlieAlive)); int shootResult = rand() % 100; if (bobAlive && charlieAlive) { return; } if(charlieAlive) { target = "Charlie"; } else { target = "Bob"; } if (shootResult <= aaronHitChance) { if (target == "Charlie") { charlieAlive = false; return; } else { bobAlive = false; return; } } return; } void test_Aaron_shoots2(void) { cout << "Unit Testing 5: Function Aaron_shoots2(Bob_alive, Charlie_alive)\n"; bool bob_a = true; bool charlie_a = true; cout << "\tCase 1: Bob alive, Charlie alive\n" << "\t\tAaron intentionally misses his first shot\n" << "\t\tBoth Bob and Charlie are alive.\n"; Aaron_shoots2(bob_a, charlie_a); bob_a = false; charlie_a = true; cout << "\tCase 2: Bob dead, Charlie alive\n" << "\t\tAaron is shooting at Charlie\n"; Aaron_shoots2(bob_a, charlie_a); bob_a = true; charlie_a = false; cout << "\tCase 3: Bob alive, Charlie dead\n" << "\t\tAaron is shooting at Bob\n"; Aaron_shoots2(bob_a, charlie_a); } void Press_any_key(void) { cout << "Press any key to continue..."; cin.ignore().get(); } bool shoot_target_result(int probability) { int result = rand()%100; return result <= probability; }
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; int* arr = new int[n]; int* check = new int[n](); for(int i=0;i<n-1;i++) { cin >> arr[i]; check[arr[i]-1]=-1; } for(int i=0;i<n;i++) { if(check[i]==0) { cout << i+1 << endl; break; } } delete[] arr; delete[] check; } return 0; }
#ifndef ARRAY_ANNOT_H #define ARRAY_ANNOT_H #include <AnnotExpr.h> #include <AnnotCollect.h> #include <OperatorDescriptors.h> #include <CPPAnnotation.h> #include <ValuePropagate.h> #include <list> class ArrayShapeDescriptor { SymbolicValDescriptor dimension; SymbolicFunctionDeclarationGroup length; public: void push_back( const ReadSymbolicFunctionDeclaration& cur); void write(std::ostream& out) const; void Dump() const; bool read( std::istream& in); const SymbolicValDescriptor& get_dimension() const { return dimension; } SymbolicValDescriptor& get_dimension() { return dimension; } bool get_dimension( int& val) const ; void set_length( const SymbolicFunctionDeclarationGroup v) { length = v; } SymbolicFunctionDeclarationGroup get_length() const { return length; } bool get_length( int dim, SymbolicVal& result) const { std::vector<SymbolicVal> args; args.push_back( SymbolicConst(dim)); return length.get_val(args, result); } void replace_var( const std::string& varname, const SymbolicVal& repl) { dimension.replace_var( varname, repl); length.replace_var(varname, repl); } void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl) { dimension.replace_val(repl); length.replace_val(repl); } }; class ArrayElemDescriptor { SymbolicFunctionDeclarationGroup elem; public: void push_back( const ReadSymbolicFunctionDeclaration& cur); void Dump() const; void write(std::ostream& out) const; bool read(std::istream& in); void replace_var( const std::string& varname, const SymbolicVal& repl) { elem.replace_var( varname, repl); } void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl) { elem.replace_val(repl); } const SymbolicFunctionDeclarationGroup& get_elem() const { return elem; } }; class ArrayDescriptor : public ArrayShapeDescriptor, public ArrayElemDescriptor { public: void push_back( const ReadSymbolicFunctionDeclaration& cur); bool read( std::istream& in) ; void write(std::ostream& out) const; void Dump() const; void replace_var( const std::string& varname, const SymbolicVal& repl) { ArrayShapeDescriptor::replace_var( varname, repl); ArrayElemDescriptor::replace_var( varname, repl); } void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl) { ArrayShapeDescriptor :: replace_val(repl); ArrayElemDescriptor :: replace_val(repl); } }; class ArrayDefineDescriptor : public ArrayDescriptor { SymbolicFunctionDeclarationGroup reshape; public: void push_back( const ReadSymbolicFunctionDeclaration& cur); bool read( std::istream& in) ; void write(std::ostream& out) const; void Dump() const; void replace_var( const std::string& varname, const SymbolicVal& repl); void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl); SymbolicFunctionDeclarationGroup get_reshape() const { return reshape; } }; class ArrayOptDescriptor : public ArrayDescriptor { typedef ContainerDescriptor <std::list<DefineVariableDescriptor>, DefineVariableDescriptor, ';', '{', '}'> DefContainer; DefContainer defs; public: typedef std::list<DefineVariableDescriptor>::iterator InitVarIterator; InitVarIterator init_var_begin() { return defs.begin(); } InitVarIterator init_var_end() { return defs.end(); } bool read( std::istream& in) ; void write(std::ostream& out) const; void Dump() const; void replace_var( const std::string& varname, const SymbolicVal& repl); void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl); }; class ArrayConstructDescriptor : public OPDescriptorTemp < CollectPair< ContainerDescriptor<std::list<SymbolicValDescriptor>, SymbolicValDescriptor, ',', '(', ')'>, ArrayDescriptor, 0 > > { typedef OPDescriptorTemp < CollectPair< ContainerDescriptor<std::list<SymbolicValDescriptor>, SymbolicValDescriptor, ',', '(', ')'>, ArrayDescriptor, 0 > > BaseClass; public: void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl) { for (std::list<SymbolicValDescriptor>::iterator p = first.begin(); p != first.end(); ++p) { (*p).replace_val(repl); } second.replace_val(repl); } }; class ArrayModifyDescriptor : public OPDescriptorTemp < CollectPair< CloseDescriptor<SymbolicValDescriptor, '(', ')'>, ArrayDescriptor,0> > { typedef OPDescriptorTemp < CollectPair< CloseDescriptor<NameDescriptor, '(', ')'>, ArrayDescriptor,0> > BaseClass; public: void replace_val(MapObject<SymbolicVal, SymbolicVal>& repl) { first.replace_val(repl); second.replace_val(repl); } }; class ArrayCollection : public TypeAnnotCollection< ArrayDefineDescriptor>, public CPPTypeCollection< ArrayDefineDescriptor> { typedef TypeAnnotCollection< ArrayDefineDescriptor > BaseClass; virtual bool read_annot_name( const std::string& annotName) const { return annotName == "array"; } public: ArrayCollection() : CPPTypeCollection<ArrayDefineDescriptor>(this) {} void Dump() const { std::cerr << "arrays: \n"; BaseClass::Dump(); } }; class ArrayOptCollection : public TypeAnnotCollection< ArrayOptDescriptor> { typedef TypeAnnotCollection< ArrayOptDescriptor > BaseClass; virtual bool read_annot_name( const std::string& annotName) const { return annotName == "array_optimize"; } public: void Dump() const { std::cerr << "array optimizations: \n"; BaseClass::Dump(); } }; class ArrayConstructOpCollection : public OperatorAnnotCollection<ArrayConstructDescriptor> { virtual bool read_annot_name( const std::string& annotName) const { return annotName == "construct_array"; } public: void Dump() const { std::cerr << "construct_array: \n"; OperatorAnnotCollection<ArrayConstructDescriptor>::Dump(); } }; class ArrayModifyOpCollection : public OperatorAnnotCollection<ArrayModifyDescriptor> { virtual bool read_annot_name( const std::string& annotName) const { return annotName == "modify_array"; } public: void Dump() const { std::cerr << "modify_array: \n"; OperatorAnnotCollection<ArrayModifyDescriptor>::Dump(); } }; class ArrayAnnotation : public FunctionSideEffectInterface, public FunctionAliasInterface { //map <std::string, OperatorDeclaration> decl; ArrayCollection arrays; ArrayOptCollection arrayopt; ArrayModifyOpCollection arrayModify; ArrayConstructOpCollection arrayConstruct; static ArrayAnnotation* inst; virtual bool may_alias(AstInterface& fa, const AstNodePtr& fc, const AstNodePtr& result, CollectObject< std::pair<AstNodePtr, int> >& collectalias); virtual bool allow_alias(AstInterface& fa, const AstNodePtr& fc, CollectObject< std::pair<AstNodePtr, int> >& collectalias); virtual bool get_modify(AstInterface& fa, const AstNodePtr& fc, CollectObject<AstNodePtr>* collect = 0); virtual bool get_read(AstInterface& fa, const AstNodePtr& fc, CollectObject<AstNodePtr>* collect = 0); ArrayAnnotation() {} public: static ArrayAnnotation* get_inst(); void register_annot(); void Dump() const; bool known_array( CPPAstInterface& fa, const AstNodePtr& array, ArrayDefineDescriptor* d = 0); bool known_array_type(CPPAstInterface& fa, const AstNodeType& array, ArrayDefineDescriptor* d = 0); bool has_array_opt( CPPAstInterface& fa, const AstNodePtr array, ArrayOptDescriptor* d = 0); bool is_array_mod_op( CPPAstInterface& fa, const AstNodePtr& arrayExp, AstNodePtr* modArray = 0, ArrayDescriptor* desc = 0, bool* reshapeArray = 0, ReplaceParams* repl = 0); bool is_array_construct_op( CPPAstInterface& fa, const AstNodePtr& arrayExp, CPPAstInterface::AstNodeList* alias = 0, ArrayDescriptor* desc = 0, ReplaceParams* repl = 0); bool is_access_array_elem( CPPAstInterface& fa, const AstNodePtr& orig, AstNodePtr* array=0, CPPAstInterface::AstNodeList* args=0); bool is_access_array_length( CPPAstInterface& fa, const AstNodePtr& orig, AstNodePtr* array=0, AstNodePtr* dimast = 0, int* dim =0); bool is_access_array_elem( CPPAstInterface& fa, const SymbolicVal& orig, AstNodePtr* array=0, SymbolicFunction::Arguments* args=0); bool is_access_array_length( CPPAstInterface& fa, const SymbolicVal& orig, AstNodePtr* array=0, SymbolicVal *dim = 0); SymbolicVal create_access_array_elem( const AstNodePtr& array, const SymbolicFunction::Arguments& args); SymbolicVal create_access_array_length( const AstNodePtr& array, const SymbolicVal& dim); AstNodePtr create_access_array_elem( CPPAstInterface& fa, const AstNodePtr& array, const CPPAstInterface::AstNodeList& args); AstNodePtr create_access_array_length( CPPAstInterface& fa, const AstNodePtr& array, int dim); bool is_reshape_array( CPPAstInterface& fa, const AstNodePtr& orig, AstNodePtr* array=0, CPPAstInterface::AstNodeList* args=0); AstNodePtr create_reshape_array( CPPAstInterface& fa, const AstNodePtr& array, const CPPAstInterface::AstNodeList& args); }; #endif
// // Management.cpp // Homework6 // // Created by HeeCheol Kim on 2018. 10. 12.. // Copyright © 2018년 HeeCheol Kim. All rights reserved. // #include "Management.h" double Management::calcScore(double subject[], int subjectCount) { double sumScore = 0; for(int i = 0; i < subjectCount; i++) { sumScore += subject[i]; } return sumScore; } double Management::calcAvrg(double subject[], int subjectCount) { double sumScore = 0; for(int i = 0; i < subjectCount; i++) { sumScore += subject[i]; } return sumScore / this->subjectCount; } void Management::sortRank(Student student[]) { for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX - i - 1; j++) { if (student[j].sumScore < student[j + 1].sumScore) { Student temp = student[j]; student[j] = student[j + 1]; student[j + 1] = temp; } } } for (int i = 0; i < MAX; i++) { student[i].rank = i + 1; } } void Management::initSubject(Student student[], int subjectCount) { for(int i = 0; i < MAX; i++) { student[i].initSubjectList(subjectCount); } }
#include "header.h" int main() { int M = 0;//¿­ int N = 0;//Çà string filename; int X; int Y; int X1, X2, Y1, Y2; char gpp; char** gparr = nullptr; char color; char tmpcolor; while (1) { cin >> gpp; if (gpp == 'I' || gpp == 'i') { if (gparr != nullptr) { delete gparr; } cin >> M; cin >> N; gparr = new char* [N]; for (int i = 0; i < N; i++) { gparr[i] = new char[M]; } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { gparr[i][j] = 'O'; } } } else if (gpp == 'C'|| gpp == 'c') { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { gparr[i][j] = 'O'; } } } else if (gpp == 'L'|| gpp == 'l') { cin >> X; cin >> Y; cin >> color; gparr[Y - 1][X - 1] = color; } else if (gpp == 'V' || gpp == 'v') { cin >> X; cin >> Y1; cin >> Y2; cin >> color; for (int i = Y1; i <= Y2; i++) { gparr[i-1][X-1] = color; } } else if (gpp == 'H' || gpp == 'h') { cin >> X1; cin >> X2; cin >> Y; cin >> color; for (int i = X1; i <= X2; i++) { gparr[Y-1][i-1] = color; } } else if (gpp == 'S' || gpp == 's') { cin >> filename; cout << filename << endl; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << gparr[i][j]; } cout << endl; } } else if (gpp == 'K' || gpp == 'k') { while (1) { cin >> X1; cin >> Y1; cin >> X2; cin >> Y2; if (X1 > X2 || Y1 > Y2) { cout << "size error" << endl; continue; } else break; } cin >> color; for (int i = Y1; i <= Y2; i++) { for (int j = X1; j <= X2; j++) { gparr[i - 1][j - 1] = color; } } } else if (gpp == 'F' || gpp == 'f') { cin >> X; cin >> Y; cin >> color; tmpcolor = gparr[Y][X]; gparr[Y][X] = color; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (gparr[i][j] == tmpcolor && gparr[i][j] != color) { gparr[i][j] = color; } } } } else if (gpp == 'X' || gpp == 'x') { exit(1); } else exit(0); } }
#include<bits/stdc++.h> using namespace std; main() { int n; cin >> n; int p1 = 100, p2 = 100; int a,b; for(int i = 0; i < n; i++) { cin >> a >> b; if(a == b) continue; else if(a > b) p2 -= a; else if(b > a) p1 -= b; } cout << p1 << "\n" << p2 << '\n'; }
/* LICENSE ------- Copyright 2005-2013 Nullsoft, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nullsoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "plugin.h" #include "render/context.h" #include "render/DrawBuffer.h" using namespace render; //#define CosineInterp(x) (0.5f - 0.5f*cosf((x) * M_PI)) inline float CosineInterp(float x) { return (0.5f - 0.5f*cosf((x) * M_PI)); } //#define COLOR_RGBA_01(r,g,b,a) COLOR_RGBA(((int)(r*255)),((int)(g*255)),((int)(b*255)),((int)(a*255))) #define COLOR_RGBA_01(r,g,b,a) Color4F::ToU32(r,g,b,a) #define FRAND frand() // // //static CommonVars GetCommonVars(CPlugin *plugin) //{ // CommonVars common; // common.time = (double)plugin->GetTime(); // common.frame = (double)plugin->GetFrame(); // common.fps = (double)plugin->GetFps(); // common.progress = (double)plugin->GetPresetProgress(); // common.bass = (double)plugin->GetImmRel(BAND_BASS); // common.mid = (double)plugin->GetImmRel(BAND_MID); // common.treb = (double)plugin->GetImmRel(BAND_TREBLE); // common.bass_att = (double)plugin->GetAvgRel(BAND_BASS); // common.mid_att = (double)plugin->GetAvgRel(BAND_MID); // common.treb_att = (double)plugin->GetAvgRel(BAND_TREBLE); // return common; //} float CPlugin::GetPresetProgress() { return m_PresetDuration / m_NextPresetDuration; } void CState::LoadPerFrameEvallibVars() { float time = m_plugin->GetTime(); // load the 'var_pf_*' variables in this CState object with the correct values. // for vars that affect pixel motion, that means evaluating them at time==-1, // (i.e. no blending w/blendto value); the blending of the file dx/dy // will be done *after* execution of the per-vertex code. // for vars that do NOT affect pixel motion, evaluate them at the current time, // so that if they're blending, both states see the blended value. // 1. vars that affect pixel motion: (eval at time==-1) var_pf_zoom = (double)m_fZoom.eval(-1);//GetTime()); var_pf_zoomexp = (double)m_fZoomExponent.eval(-1);//GetTime()); var_pf_rot = (double)m_fRot.eval(-1);//GetTime()); var_pf_warp = (double)m_fWarpAmount.eval(-1);//GetTime()); var_pf_cxy.x = (double)m_fRotCX.eval(-1);//GetTime()); var_pf_cxy.y = (double)m_fRotCY.eval(-1);//GetTime()); var_pf_dxy.x = (double)m_fXPush.eval(-1);//GetTime()); var_pf_dxy.y = (double)m_fYPush.eval(-1);//GetTime()); var_pf_sxy.x = (double)m_fStretchX.eval(-1);//GetTime()); var_pf_sxy.y = (double)m_fStretchY.eval(-1);//GetTime()); // read-only: var_pf_common = m_plugin->GetCommonVars(); //var_pf_monitor = 0; -leave this as it was set in the per-frame INIT code! for (int vi=0; vi<NUM_Q_VAR; vi++) var_pf_q[vi] = q_values_after_init_code[vi];//0.0f; var_pf_monitor = monitor_after_init_code; // 2. vars that do NOT affect pixel motion: (eval at time==now) var_pf_decay = (double)m_fDecay.eval(time); var_pf_wave_rgba.a = (double)m_fWaveAlpha.eval(time); var_pf_wave_rgba.r = (double)m_fWaveR.eval(time); var_pf_wave_rgba.g = (double)m_fWaveG.eval(time); var_pf_wave_rgba.b = (double)m_fWaveB.eval(time); var_pf_wave_x = (double)m_fWaveX.eval(time); var_pf_wave_y = (double)m_fWaveY.eval(time); var_pf_wave_mystery= (double)m_fWaveParam.eval(time); var_pf_wave_mode = (double)m_nWaveMode; //?!?! -why won't it work if set to m_nWaveMode??? var_pf_ob_size = (double)m_fOuterBorderSize.eval(time); var_pf_ob_rgba.r = (double)m_fOuterBorderR.eval(time); var_pf_ob_rgba.g = (double)m_fOuterBorderG.eval(time); var_pf_ob_rgba.b = (double)m_fOuterBorderB.eval(time); var_pf_ob_rgba.a = (double)m_fOuterBorderA.eval(time); var_pf_ib_size = (double)m_fInnerBorderSize.eval(time); var_pf_ib_rgba.r = (double)m_fInnerBorderR.eval(time); var_pf_ib_rgba.g = (double)m_fInnerBorderG.eval(time); var_pf_ib_rgba.b = (double)m_fInnerBorderB.eval(time); var_pf_ib_rgba.a = (double)m_fInnerBorderA.eval(time); var_pf_mv_xy.x = (double)m_fMvX.eval(time); var_pf_mv_xy.y = (double)m_fMvY.eval(time); var_pf_mv_dxy.x = (double)m_fMvDX.eval(time); var_pf_mv_dxy.y = (double)m_fMvDY.eval(time); var_pf_mv_l = (double)m_fMvL.eval(time); var_pf_mv_rgba.r = (double)m_fMvR.eval(time); var_pf_mv_rgba.g = (double)m_fMvG.eval(time); var_pf_mv_rgba.b = (double)m_fMvB.eval(time); var_pf_mv_rgba.a = (double)m_fMvA.eval(time); var_pf_echo_zoom = (double)m_fVideoEchoZoom.eval(time); var_pf_echo_alpha = (double)m_fVideoEchoAlpha.eval(time); var_pf_echo_orient = (double)m_nVideoEchoOrientation; // new in v1.04: var_pf_wave_usedots = (double)m_bWaveDots; var_pf_wave_thick = (double)m_bWaveThick; var_pf_wave_additive = (double)m_bAdditiveWaves; var_pf_wave_brighten = (double)m_bMaximizeWaveColor; var_pf_darken_center = (double)m_bDarkenCenter; var_pf_gamma = (double)m_fGammaAdj.eval(time); var_pf_wrap = (double)m_bTexWrap; var_pf_invert = (double)m_bInvert; var_pf_brighten = (double)m_bBrighten; var_pf_darken = (double)m_bDarken; var_pf_solarize = (double)m_bSolarize; // new in v2.0: var_pf_blur1min = (double)m_fBlur1Min.eval(time); var_pf_blur2min = (double)m_fBlur2Min.eval(time); var_pf_blur3min = (double)m_fBlur3Min.eval(time); var_pf_blur1max = (double)m_fBlur1Max.eval(time); var_pf_blur2max = (double)m_fBlur2Max.eval(time); var_pf_blur3max = (double)m_fBlur3Max.eval(time); var_pf_blur1_edge_darken = (double)m_fBlur1EdgeDarken.eval(time); } static void BlendState(CStatePtr m_pState, CStatePtr m_pOldState, float m_fBlendProgress, float m_fSnapPoint) { // For all variables that do NOT affect pixel motion, blend them NOW, // so later the user can just access m_pState->m_pf_whatever. double mix = (double)CosineInterp(m_fBlendProgress); double mix2 = 1.0 - mix; m_pState->var_pf_decay = mix*(m_pState->var_pf_decay ) + mix2*(m_pOldState->var_pf_decay ); m_pState->var_pf_wave_rgba.a = mix*(m_pState->var_pf_wave_rgba.a ) + mix2*(m_pOldState->var_pf_wave_rgba.a ); m_pState->var_pf_wave_rgba.r = mix*(m_pState->var_pf_wave_rgba.r ) + mix2*(m_pOldState->var_pf_wave_rgba.r ); m_pState->var_pf_wave_rgba.g = mix*(m_pState->var_pf_wave_rgba.g ) + mix2*(m_pOldState->var_pf_wave_rgba.g ); m_pState->var_pf_wave_rgba.b = mix*(m_pState->var_pf_wave_rgba.b ) + mix2*(m_pOldState->var_pf_wave_rgba.b ); m_pState->var_pf_wave_x = mix*(m_pState->var_pf_wave_x ) + mix2*(m_pOldState->var_pf_wave_x ); m_pState->var_pf_wave_y = mix*(m_pState->var_pf_wave_y ) + mix2*(m_pOldState->var_pf_wave_y ); m_pState->var_pf_wave_mystery = mix*(m_pState->var_pf_wave_mystery) + mix2*(m_pOldState->var_pf_wave_mystery); // wave_mode: exempt (integer) m_pState->var_pf_ob_size = mix*(m_pState->var_pf_ob_size ) + mix2*(m_pOldState->var_pf_ob_size ); m_pState->var_pf_ob_rgba.r = mix*(m_pState->var_pf_ob_rgba.r ) + mix2*(m_pOldState->var_pf_ob_rgba.r ); m_pState->var_pf_ob_rgba.g = mix*(m_pState->var_pf_ob_rgba.g ) + mix2*(m_pOldState->var_pf_ob_rgba.g ); m_pState->var_pf_ob_rgba.b = mix*(m_pState->var_pf_ob_rgba.b ) + mix2*(m_pOldState->var_pf_ob_rgba.b ); m_pState->var_pf_ob_rgba.a = mix*(m_pState->var_pf_ob_rgba.a ) + mix2*(m_pOldState->var_pf_ob_rgba.a ); m_pState->var_pf_ib_size = mix*(m_pState->var_pf_ib_size ) + mix2*(m_pOldState->var_pf_ib_size ); m_pState->var_pf_ib_rgba.r = mix*(m_pState->var_pf_ib_rgba.r ) + mix2*(m_pOldState->var_pf_ib_rgba.r ); m_pState->var_pf_ib_rgba.g = mix*(m_pState->var_pf_ib_rgba.g ) + mix2*(m_pOldState->var_pf_ib_rgba.g ); m_pState->var_pf_ib_rgba.b = mix*(m_pState->var_pf_ib_rgba.b ) + mix2*(m_pOldState->var_pf_ib_rgba.b ); m_pState->var_pf_ib_rgba.a = mix*(m_pState->var_pf_ib_rgba.a ) + mix2*(m_pOldState->var_pf_ib_rgba.a ); m_pState->var_pf_mv_xy.x = mix*(m_pState->var_pf_mv_xy.x ) + mix2*(m_pOldState->var_pf_mv_xy.x ); m_pState->var_pf_mv_xy.y = mix*(m_pState->var_pf_mv_xy.y ) + mix2*(m_pOldState->var_pf_mv_xy.y ); m_pState->var_pf_mv_dxy.x = mix*(m_pState->var_pf_mv_dxy.x ) + mix2*(m_pOldState->var_pf_mv_dxy.x ); m_pState->var_pf_mv_dxy.y = mix*(m_pState->var_pf_mv_dxy.y ) + mix2*(m_pOldState->var_pf_mv_dxy.y ); m_pState->var_pf_mv_l = mix*(m_pState->var_pf_mv_l ) + mix2*(m_pOldState->var_pf_mv_l ); m_pState->var_pf_mv_rgba.r = mix*(m_pState->var_pf_mv_rgba.r ) + mix2*(m_pOldState->var_pf_mv_rgba.r ); m_pState->var_pf_mv_rgba.g = mix*(m_pState->var_pf_mv_rgba.g ) + mix2*(m_pOldState->var_pf_mv_rgba.g ); m_pState->var_pf_mv_rgba.b = mix*(m_pState->var_pf_mv_rgba.b ) + mix2*(m_pOldState->var_pf_mv_rgba.b ); m_pState->var_pf_mv_rgba.a = mix*(m_pState->var_pf_mv_rgba.a ) + mix2*(m_pOldState->var_pf_mv_rgba.a ); m_pState->var_pf_echo_zoom = mix*(m_pState->var_pf_echo_zoom ) + mix2*(m_pOldState->var_pf_echo_zoom ); m_pState->var_pf_echo_alpha = mix*(m_pState->var_pf_echo_alpha ) + mix2*(m_pOldState->var_pf_echo_alpha ); m_pState->var_pf_echo_orient = (mix < m_fSnapPoint) ? m_pOldState->var_pf_echo_orient : m_pState->var_pf_echo_orient; // added in v1.04: m_pState->var_pf_wave_usedots = (mix < m_fSnapPoint) ? m_pOldState->var_pf_wave_usedots : m_pState->var_pf_wave_usedots ; m_pState->var_pf_wave_thick = (mix < m_fSnapPoint) ? m_pOldState->var_pf_wave_thick : m_pState->var_pf_wave_thick ; m_pState->var_pf_wave_additive= (mix < m_fSnapPoint) ? m_pOldState->var_pf_wave_additive : m_pState->var_pf_wave_additive; m_pState->var_pf_wave_brighten= (mix < m_fSnapPoint) ? m_pOldState->var_pf_wave_brighten : m_pState->var_pf_wave_brighten; m_pState->var_pf_darken_center= (mix < m_fSnapPoint) ? m_pOldState->var_pf_darken_center : m_pState->var_pf_darken_center; m_pState->var_pf_gamma = mix*(m_pState->var_pf_gamma ) + mix2*(m_pOldState->var_pf_gamma ); m_pState->var_pf_wrap = (mix < m_fSnapPoint) ? m_pOldState->var_pf_wrap : m_pState->var_pf_wrap ; m_pState->var_pf_invert = (mix < m_fSnapPoint) ? m_pOldState->var_pf_invert : m_pState->var_pf_invert ; m_pState->var_pf_brighten = (mix < m_fSnapPoint) ? m_pOldState->var_pf_brighten : m_pState->var_pf_brighten ; m_pState->var_pf_darken = (mix < m_fSnapPoint) ? m_pOldState->var_pf_darken : m_pState->var_pf_darken ; m_pState->var_pf_solarize = (mix < m_fSnapPoint) ? m_pOldState->var_pf_solarize : m_pState->var_pf_solarize ; // added in v2.0: m_pState->var_pf_blur1min = mix*(m_pState->var_pf_blur1min ) + mix2*(m_pOldState->var_pf_blur1min ); m_pState->var_pf_blur2min = mix*(m_pState->var_pf_blur2min ) + mix2*(m_pOldState->var_pf_blur2min ); m_pState->var_pf_blur3min = mix*(m_pState->var_pf_blur3min ) + mix2*(m_pOldState->var_pf_blur3min ); m_pState->var_pf_blur1max = mix*(m_pState->var_pf_blur1max ) + mix2*(m_pOldState->var_pf_blur1max ); m_pState->var_pf_blur2max = mix*(m_pState->var_pf_blur2max ) + mix2*(m_pOldState->var_pf_blur2max ); m_pState->var_pf_blur3max = mix*(m_pState->var_pf_blur3max ) + mix2*(m_pOldState->var_pf_blur3max ); m_pState->var_pf_blur1_edge_darken = mix*(m_pState->var_pf_blur1_edge_darken) + mix2*(m_pOldState->var_pf_blur1_edge_darken); } void CState::RunPerFrameEquations() { // values that will affect the pixel motion (and will be automatically blended // LATER, when the results of 2 sets of these params creates 2 different U/V // meshes that get blended together.) LoadPerFrameEvallibVars(); // also do just a once-per-frame init for the *per-**VERTEX*** *READ-ONLY* variables // (the non-read-only ones will be reset/restored at the start of each vertex) var_pv_common = var_pf_common; //var_pv_monitor = var_pf_monitor; // execute once-per-frame expressions: if (m_perframe_expression) { m_perframe_expression->Execute(); } // save some things for next frame: monitor_after_init_code = var_pf_monitor; // save some things for per-vertex code: for (int vi=0; vi<NUM_Q_VAR; vi++) var_pv_q[vi] = var_pf_q[vi]; // (a few range checks:) var_pf_gamma = std::max(0.0 , std::min( 8.0, var_pf_gamma )); var_pf_echo_zoom = std::max(0.001, std::min( 1000.0, var_pf_echo_zoom)); } void CPlugin::RunPerFrameEquations() { PROFILE_FUNCTION() // run per-frame calculations /* code is only valid when blending. OLDcomp ~ blend-from preset has a composite shader; NEWwarp ~ blend-to preset has a warp shader; etc. code OLDcomp NEWcomp OLDwarp NEWwarp 0 1 1 2 1 3 1 1 4 1 5 1 1 6 1 1 7 1 1 1 8 1 9 1 1 10 1 1 11 1 1 1 12 1 1 13 1 1 1 14 1 1 1 15 1 1 1 1 */ // when blending booleans (like darken, invert, etc) for pre-shader presets, // if blending to/from a pixel-shader preset, we can tune the snap point // (when it changes during the blend) for a less jumpy transition: m_fSnapPoint = 0.5f; if (m_bBlending) { bool bOldPresetUsesWarpShader = (m_pOldState->m_nWarpPSVersion > 0); bool bNewPresetUsesWarpShader = (m_pState->m_nWarpPSVersion > 0); bool bOldPresetUsesCompShader = (m_pOldState->m_nCompPSVersion > 0); bool bNewPresetUsesCompShader = (m_pState->m_nCompPSVersion > 0); // note: 'code' is only meaningful if we are BLENDING. int code = (bOldPresetUsesWarpShader ? 8 : 0) | (bOldPresetUsesCompShader ? 4 : 0) | (bNewPresetUsesWarpShader ? 2 : 0) | (bNewPresetUsesCompShader ? 1 : 0); switch(code) { case 4: case 6: case 12: case 14: // old preset (only) had a comp shader m_fSnapPoint = -0.01f; break; case 1: case 3: case 9: case 11: // new preset (only) has a comp shader m_fSnapPoint = 1.01f; break; case 0: case 2: case 8: case 10: // neither old or new preset had a comp shader m_fSnapPoint = 0.5f; break; case 5: case 7: case 13: case 15: // both old and new presets use a comp shader - so it won't matter m_fSnapPoint = 0.5f; break; } } if (!m_bBlending) { m_pState->RunPerFrameEquations(); } else { m_pState->RunPerFrameEquations(); m_pOldState->RunPerFrameEquations(); BlendState(m_pState, m_pOldState, m_fBlendProgress, m_fSnapPoint); } } //static int RoundUp(int size, int align) //{ // return (size + (align -1)) & ~(align-1); //} void CPlugin::TestLineDraw() { { Vertex v[2]; v[0].Clear(); v[1].Clear(); v[0].x = -0.25; v[0].y = -0.25; v[1].x = 0.25; v[1].y = 0.25; v[0].Diffuse = v[1].Diffuse = Color4F::ToU32(1,1,1,1); SetFixedShader(nullptr); m_context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); GetDrawBuffer()->DrawLineListAA(2, v, 128, 64); GetDrawBuffer()->Flush(); } } void CPlugin::ClearTargets() { PROFILE_FUNCTION() m_context->SetRenderTarget(m_lpVS[1], "lpVS[1]", LoadAction::Clear ); m_context->SetRenderTarget(m_lpVS[0], "lpVS[0]", LoadAction::Clear ); for (auto texture : m_blur_textures) { m_context->SetRenderTarget(texture, "blur_texture_clear", LoadAction::Clear ); } for (auto texture : m_blurtemp_textures) { m_context->SetRenderTarget(texture, "blur_texture_clear", LoadAction::Clear ); } } void CPlugin::RenderFrame() { PROFILE_FUNCTION() // note that this transform only affects the fixed function shader, not any custom shaders Matrix44 ortho = MatrixOrthoLH(2.0f, -2.0f, 0.0f, 1.0f); m_context->SetTransform(ortho); m_context->SetDepthEnable(false); m_context->SetBlendDisable(); { m_rand_frame = Vector4(FRAND, FRAND, FRAND, FRAND); // update m_fBlendProgress; if (m_bBlending) { m_fBlendProgress = (GetTime() - m_fBlendStartTime) / m_fBlendDuration; if (m_fBlendProgress > 1.0f) { m_bBlending = false; } } } m_fAspectX = (m_nTexSizeY > m_nTexSizeX) ? m_nTexSizeX/(float)m_nTexSizeY : 1.0f; m_fAspectY = (m_nTexSizeX > m_nTexSizeY) ? m_nTexSizeY/(float)m_nTexSizeX : 1.0f; m_fInvAspectX = 1.0f/m_fAspectX; m_fInvAspectY = 1.0f/m_fAspectY; // setup common vars that everthing else uses m_commonVars.time = (double)GetTime(); m_commonVars.frame = (double)GetFrame(); m_commonVars.fps = (double)GetFps(); m_commonVars.progress = (double)GetPresetProgress(); m_commonVars.bass = (double)GetImmRel(BAND_BASS); m_commonVars.mid = (double)GetImmRel(BAND_MID); m_commonVars.treb = (double)GetImmRel(BAND_TREBLE); m_commonVars.bass_att = (double)GetAvgRel(BAND_BASS); m_commonVars.mid_att = (double)GetAvgRel(BAND_MID); m_commonVars.treb_att = (double)GetAvgRel(BAND_TREBLE); m_commonVars.meshxy.x = (double)m_nGridX; m_commonVars.meshxy.y = (double)m_nGridY; m_commonVars.pixelsxy.x = (double)GetWidth(); m_commonVars.pixelsxy.y = (double)GetHeight(); m_commonVars.aspectxy.x = (double)m_fInvAspectX; m_commonVars.aspectxy.y = (double)m_fInvAspectY; RunPerFrameEquations(); { // draw motion vectors to VS0 m_context->SetRenderTarget(m_lpVS[0], "MotionVectors", LoadAction::Load); m_pState->DrawMotionVectors(); } if (m_clearTargets) { ClearTargets(); m_clearTargets = false; } { ComputeGridAlphaValues_ComputeBegin(); DrawCustomShapes_ComputeBegin(); // draw these first; better for feedback if the waves draw *over* them. DrawCustomWaves_ComputeBegin(); } { ComputeGridAlphaValues_ComputeEnd(); } // blend grid vertices together BlendGrid(); // warp from vs0 + blur123 -> vs1 WarpedBlit(); // blur passes vs0 -> blur123 BlurPasses(0); // draw audio data { m_context->SetRenderTarget(m_lpVS[1], "DrawCustomShapes", LoadAction::Load); DrawCustomShapes_ComputeEnd(); } { m_context->SetRenderTarget(m_lpVS[1], "DrawCustomWaves", LoadAction::Load); DrawCustomWaves_ComputeEnd(); } { m_context->SetRenderTarget(m_lpVS[1], "DrawWave", LoadAction::Load); DrawWave(); } { m_context->SetRenderTarget(m_lpVS[1], "DrawSprites", LoadAction::Load); DrawSprites(); } // vs0 + blur123 - > output texture CompositeBlit(); // flip buffers std::swap(m_lpVS[0], m_lpVS[1]); } void CPlugin::CaptureScreenshot(render::TexturePtr texture, Vector2 pos, Size2D size) { // update screenshot m_context->SetRenderTarget(texture, "Screenshot", LoadAction::Load); m_context->SetBlendDisable(); // setup ortho projections float sw = texture->GetWidth(); float sh = texture->GetHeight(); Matrix44 m = MatrixOrthoLH(0, sw, sh, 0, 0, 1); m_context->SetTransform(m); DrawQuad(m_outputTexture, pos.x, pos.y, size.width, size.height, Color4F(1,1,1,1)); m_context->SetRenderTarget(nullptr); } void CPlugin::BlendGrid() { PROFILE_FUNCTION() int total = (int)m_vertinfo.size(); const std::vector<WarpVertex> &va = m_pState->m_verts; if (!m_bBlending) { for (int i=0; i < total; i++) { Vertex &ov = m_verts[i]; ov.x = m_vertinfo[i].vx; ov.y = m_vertinfo[i].vy; ov.z = 0.0; ov.rad = m_vertinfo[i].rad; ov.ang = m_vertinfo[i].ang; ov.tu = va[i].tu; ov.tv = va[i].tv; ov.Diffuse = 0xFFFFFFFF; } return; } float fBlend = m_fBlendProgress; const std::vector<WarpVertex> &vb = m_pOldState->m_verts; // blend verts between states for (int i=0; i < total; i++) { const td_vertinfo &vi = m_vertinfo[i]; Vertex &ov = m_verts[i]; ov.x = vi.vx; ov.y = vi.vy; ov.z = 0.0; ov.rad = m_vertinfo[i].rad; ov.ang = m_vertinfo[i].ang; // blend to UV's for m_pOldState float mix2 = vi.a*fBlend + vi.c;//fCosineBlend2; mix2 = std::max(0.0f,std::min(1.0f,mix2)); // if fBlend un-flipped, then mix2 is 0 at the beginning of a blend, 1 at the end... // and alphas are 0 at the beginning, 1 at the end. ov.tu = va[i].tu*(mix2) + vb[i].tu*(1-mix2); ov.tv = va[i].tv*(mix2) + vb[i].tv*(1-mix2); // this sets the alpha values for blending between two presets: ov.Diffuse = Color4F::ToU32(1,1,1, mix2); } } void CPlugin::WarpedBlit() { PROFILE_FUNCTION() bool bOldPresetUsesWarpShader = (m_pOldState->UsesWarpShader()); bool bNewPresetUsesWarpShader = (m_pState->UsesWarpShader()); // set up to render [from VS0] to VS1. m_context->SetRenderTarget(m_lpVS[1], "WarpedBlit", LoadAction::Clear); // do the warping for this frame [warp shader] if (!m_bBlending) { // no blend if (bNewPresetUsesWarpShader) WarpedBlit_Shaders(1, false, false); else WarpedBlit_NoShaders(1, false, false); } else { // blending // WarpedBlit( nPass, bAlphaBlend, bFlipAlpha, bCullTiles, bFlipCulling ) // note: alpha values go from 0..1 during a blend. // note: bFlipCulling==false means tiles with alpha>0 will draw. // bFlipCulling==true means tiles with alpha<255 will draw. if (bOldPresetUsesWarpShader && bNewPresetUsesWarpShader) { WarpedBlit_Shaders (0, false, false); WarpedBlit_Shaders (1, true, false); } else if (!bOldPresetUsesWarpShader && bNewPresetUsesWarpShader) { WarpedBlit_NoShaders(0, false, false); WarpedBlit_Shaders (1, true, false); } else if (bOldPresetUsesWarpShader && !bNewPresetUsesWarpShader) { WarpedBlit_Shaders (0, false, false); WarpedBlit_NoShaders(1, true, false); } else if (!bOldPresetUsesWarpShader && !bNewPresetUsesWarpShader) { //WarpedBlit_NoShaders(0, false, false, true, true); //WarpedBlit_NoShaders(1, true, false, true, false); // special case - all the blending just happens in the vertex UV's, so just pretend there's no blend. WarpedBlit_NoShaders(1, false, false); } } } void CPlugin::CompositeBlit() { PROFILE_FUNCTION() bool bOldPresetUsesCompShader = (m_pOldState->UsesCompShader()); bool bNewPresetUsesCompShader = (m_pState->UsesCompShader()); m_context->SetRenderTarget(m_outputTexture, "CompositeBlit", LoadAction::Clear); // show it to the user [composite shader] if (!m_bBlending) { // no blend if (bNewPresetUsesCompShader) ShowToUser_Shaders(1, false, false); else ShowToUser_NoShaders();//1, false, false, false, false); } else { // blending // ShowToUser( nPass, bAlphaBlend, bFlipAlpha) // note: alpha values go from 0..1 during a blend. // NOTE: ShowToUser_NoShaders() must always come before ShowToUser_Shaders(), // because it always draws the full quad (it can't do tile culling or alpha blending). // [third case here] if (bOldPresetUsesCompShader && bNewPresetUsesCompShader) { ShowToUser_Shaders (0, false, false); ShowToUser_Shaders (1, true, false); } else if (!bOldPresetUsesCompShader && bNewPresetUsesCompShader) { ShowToUser_NoShaders(); ShowToUser_Shaders (1, true, false); } else if (bOldPresetUsesCompShader && !bNewPresetUsesCompShader) { // THA FUNKY REVERSAL //ShowToUser_Shaders (0); //ShowToUser_NoShaders(1); ShowToUser_NoShaders(); ShowToUser_Shaders (0, true, true); } else if (!bOldPresetUsesCompShader && !bNewPresetUsesCompShader) { // special case - all the blending just happens in the blended state vars, so just pretend there's no blend. ShowToUser_NoShaders();//1, false, false, false, false); } } } void CState::DrawMotionVectors() { // FLEXIBLE MOTION VECTOR FIELD if ((float)var_pf_mv_rgba.a >= 0.001f) { PROFILE_FUNCTION(); ContextPtr context = m_plugin->m_context; IDrawBufferPtr draw = m_plugin->GetDrawBuffer(); // set up to render [from NULL] to VS0 (for motion vectors). { context->SetDepthEnable(false); context->SetBlendDisable(); m_plugin->SetFixedShader(nullptr); } //------------------------------------------------------- m_plugin->SetFixedShader(nullptr); //------------------------------------------------------- int x,y; int nX = (int)(var_pf_mv_xy.x);// + 0.999f); int nY = (int)(var_pf_mv_xy.y);// + 0.999f); float dx = (float)var_pf_mv_xy.x - nX; float dy = (float)var_pf_mv_xy.y - nY; if (nX > 64) { nX = 64; dx = 0; } if (nY > 48) { nY = 48; dy = 0; } if (nX > 0 && nY > 0) { /* float dx2 = m_fMotionVectorsTempDx;//(var_pf_mv_dx) * 0.05f*GetTime(); // 0..1 range float dy2 = m_fMotionVectorsTempDy;//(var_pf_mv_dy) * 0.05f*GetTime(); // 0..1 range if (GetFps() > 2.0f && GetFps() < 300.0f) { dx2 += (float)(var_pf_mv_dx) * 0.05f / GetFps(); dy2 += (float)(var_pf_mv_dy) * 0.05f / GetFps(); } if (dx2 > 1.0f) dx2 -= (int)dx2; if (dy2 > 1.0f) dy2 -= (int)dy2; if (dx2 < 0.0f) dx2 = 1.0f - (-dx2 - (int)(-dx2)); if (dy2 < 0.0f) dy2 = 1.0f - (-dy2 - (int)(-dy2)); // hack: when there is only 1 motion vector on the screem, to keep it in // the center, we gradually migrate it toward 0.5. dx2 = dx2*0.995f + 0.5f*0.005f; dy2 = dy2*0.995f + 0.5f*0.005f; // safety catch if (dx2 < 0 || dx2 > 1 || dy2 < 0 || dy2 > 1) { dx2 = 0.5f; dy2 = 0.5f; } m_fMotionVectorsTempDx = dx2; m_fMotionVectorsTempDy = dy2;*/ float dx2 = (float)(var_pf_mv_dxy.x); float dy2 = (float)(var_pf_mv_dxy.y); float len_mult = (float)var_pf_mv_l; if (dx < 0) dx = 0; if (dy < 0) dy = 0; if (dx > 1) dx = 1; if (dy > 1) dy = 1; //dx = dx * 1.0f/(float)nX; //dy = dy * 1.0f/(float)nY; float inv_texsize = 1.0f/(float)m_plugin->m_nTexSizeX; float min_len = 1.0f*inv_texsize; Vertex v[(64+1)*2]; memset(v, 0, sizeof(v)); v[0].Diffuse = COLOR_RGBA_01((float)var_pf_mv_rgba.r,(float)var_pf_mv_rgba.g,(float)var_pf_mv_rgba.b,(float)var_pf_mv_rgba.a); for (x=1; x<(nX+1)*2; x++) v[x].Diffuse = v[0].Diffuse; context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); for (y=0; y<nY; y++) { float fy = (y + 0.25f)/(float)(nY + dy + 0.25f - 1.0f); // now move by offset fy -= dy2; if (fy > 0.0001f && fy < 0.9999f) { int n = 0; for (x=0; x<nX; x++) { //float fx = (x + 0.25f)/(float)(nX + dx + 0.25f - 1.0f); float fx = (x + 0.25f)/(float)(nX + dx + 0.25f - 1.0f); // now move by offset fx += dx2; if (fx > 0.0001f && fx < 0.9999f) { float fx2 = 0.0f, fy2 = 0.0f; m_plugin->ReversePropagatePoint(fx, fy, &fx2, &fy2); // NOTE: THIS IS REALLY A REVERSE-PROPAGATION //fx2 = fx*2 - fx2; //fy2 = fy*2 - fy2; //fx2 = fx + 1.0f/(float)m_nTexSize; //fy2 = 1-(fy + 1.0f/(float)m_nTexSize); // enforce minimum trail lengths: { float dx = (fx2 - fx); float dy = (fy2 - fy); dx *= len_mult; dy *= len_mult; float len = sqrtf(dx*dx + dy*dy); if (len > min_len) { } else if (len > 0.00000001f) { len = min_len/len; dx *= len; dy *= len; } else { dx = min_len; dy = min_len; } fx2 = fx + dx; fy2 = fy + dy; } /**/ v[n].x = fx * 2.0f - 1.0f; v[n].y = fy * 2.0f - 1.0f; v[n+1].x = fx2 * 2.0f - 1.0f; v[n+1].y = fy2 * 2.0f - 1.0f; // actually, project it in the reverse direction //v[n+1].x = v[n].x*2.0f - v[n+1].x;// + dx*2; //v[n+1].y = v[n].y*2.0f - v[n+1].y;// + dy*2; //v[n].x += dx*2; //v[n].y += dy*2; n += 2; } } // draw it draw->DrawLineList(n, v); } } draw->Flush(); context->SetBlendDisable(); } } } bool CPlugin::ReversePropagatePoint(float fx, float fy, float *fx2, float *fy2) { //float fy = y/(float)nMotionVectorsY; int y0 = (int)(fy*m_nGridY); float dy = fy*m_nGridY - y0; //float fx = x/(float)nMotionVectorsX; int x0 = (int)(fx*m_nGridX); float dx = fx*m_nGridX - x0; int x1 = x0 + 1; int y1 = y0 + 1; if (x0 < 0) return false; if (y0 < 0) return false; //if (x1 < 0) return false; //if (y1 < 0) return false; //if (x0 > m_nGridX) return false; //if (y0 > m_nGridY) return false; if (x1 > m_nGridX) return false; if (y1 > m_nGridY) return false; float tu, tv; tu = m_verts[y0*(m_nGridX+1)+x0].tu * (1-dx)*(1-dy); tv = m_verts[y0*(m_nGridX+1)+x0].tv * (1-dx)*(1-dy); tu += m_verts[y0*(m_nGridX+1)+x1].tu * (dx)*(1-dy); tv += m_verts[y0*(m_nGridX+1)+x1].tv * (dx)*(1-dy); tu += m_verts[y1*(m_nGridX+1)+x0].tu * (1-dx)*(dy); tv += m_verts[y1*(m_nGridX+1)+x0].tv * (1-dx)*(dy); tu += m_verts[y1*(m_nGridX+1)+x1].tu * (dx)*(dy); tv += m_verts[y1*(m_nGridX+1)+x1].tv * (dx)*(dy); *fx2 = tu; *fy2 = 1.0f - tv; return true; } void CState::GetSafeBlurMinMax(float* blur_min, float* blur_max) { blur_min[0] = (float)var_pf_blur1min; blur_min[1] = (float)var_pf_blur2min; blur_min[2] = (float)var_pf_blur3min; blur_max[0] = (float)var_pf_blur1max; blur_max[1] = (float)var_pf_blur2max; blur_max[2] = (float)var_pf_blur3max; // check that precision isn't wasted in later blur passes [...min-max gap can't grow!] // also, if min-max are close to each other, push them apart: const float fMinDist = 0.1f; if (blur_max[0] - blur_min[0] < fMinDist) { float avg = (blur_min[0] + blur_max[0])*0.5f; blur_min[0] = avg - fMinDist*0.5f; blur_max[0] = avg - fMinDist*0.5f; } blur_max[1] = std::min(blur_max[0], blur_max[1]); blur_min[1] = std::max(blur_min[0], blur_min[1]); if (blur_max[1] - blur_min[1] < fMinDist) { float avg = (blur_min[1] + blur_max[1])*0.5f; blur_min[1] = avg - fMinDist*0.5f; blur_max[1] = avg - fMinDist*0.5f; } blur_max[2] = std::min(blur_max[1], blur_max[2]); blur_min[2] = std::max(blur_min[1], blur_min[2]); if (blur_max[2] - blur_min[2] < fMinDist) { float avg = (blur_min[2] + blur_max[2])*0.5f; blur_min[2] = avg - fMinDist*0.5f; blur_max[2] = avg - fMinDist*0.5f; } } void CPlugin::DrawImageWithShader(ShaderPtr shader, TexturePtr source, TexturePtr dest) { m_context->SetBlendDisable(); m_context->SetShader(shader); m_context->SetRenderTarget(dest, dest->GetName().c_str(), LoadAction::Clear ); auto sampler = shader->GetSampler(0); if (sampler) { sampler->SetTexture(source, SAMPLER_CLAMP, SAMPLER_LINEAR); } // set up fullscreen quad Vertex v[4]; memset(v, 0, sizeof(v)); v[0].x = -1; v[0].y = -1; v[1].x = 1; v[1].y = -1; v[2].x = -1; v[2].y = 1; v[3].x = 1; v[3].y = 1; v[0].tu = 0; v[0].tv = 0; v[1].tu = 1; v[1].tv = 0; v[2].tu = 0; v[2].tv = 1; v[3].tu = 1; v[3].tv = 1; for (int i=0; i < 4; i++) { v[i].Diffuse = 0xFFFFFFFF; v[i].ang = v[i].rad = 0; } m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v); } void CPlugin::BlurPasses(int source_index) { // Note: Blur is currently a little funky. It blurs the *current* frame after warp; // this way, it lines up well with the composite pass. However, if you switch // presets instantly, to one whose *warp* shader uses the blur texture, // it will be outdated (just for one frame). Oh well. // This also means that when sampling the blurred textures in the warp shader, // they are one frame old. This isn't too big a deal. Getting them to match // up for the composite pass is probably more important. int m_nHighestBlurTexUsedThisFrame = m_pState->GetHighestBlurTexUsed(); if (m_bBlending) m_nHighestBlurTexUsedThisFrame = std::max(m_nHighestBlurTexUsedThisFrame, m_pOldState->GetHighestBlurTexUsed()); int passes = std::min( (int)m_blur_textures.size(), m_nHighestBlurTexUsedThisFrame); //passes = (int)m_blur_textures.size(); if (passes==0) return; PROFILE_FUNCTION() m_context->PushLabel("BlurPasses"); const float w[8] = { 4.0f, 3.8f, 3.5f, 2.9f, 1.9f, 1.2f, 0.7f, 0.3f }; //<- user can specify these float edge_darken = (float)m_pState->var_pf_blur1_edge_darken; float blur_min[3], blur_max[3]; m_pState->GetSafeBlurMinMax(blur_min, blur_max); float fscale[3]; float fbias[3]; // figure out the progressive scale & bias needed, at each step, // to go from one [min..max] range to the next. float temp_min, temp_max; fscale[0] = 1.0f / (blur_max[0] - blur_min[0]); fbias [0] = -blur_min[0] * fscale[0]; temp_min = (blur_min[1] - blur_min[0]) / (blur_max[0] - blur_min[0]); temp_max = (blur_max[1] - blur_min[0]) / (blur_max[0] - blur_min[0]); fscale[1] = 1.0f / (temp_max - temp_min); fbias [1] = -temp_min * fscale[1]; temp_min = (blur_min[2] - blur_min[1]) / (blur_max[1] - blur_min[1]); temp_max = (blur_max[2] - blur_min[1]) / (blur_max[1] - blur_min[1]); fscale[2] = 1.0f / (temp_max - temp_min); fbias [2] = -temp_min * fscale[2]; TexturePtr source = m_lpVS[source_index]; for (int pass=0; pass < passes; pass++) { TexturePtr dest = m_blurtemp_textures[pass]; { // pass 1 (long horizontal pass) //------------------------------------- float fscale_now = fscale[pass]; float fbias_now = fbias[pass]; int srcw = source->GetWidth(); int srch = source->GetHeight(); Vector4 srctexsize = Vector4( (float)srcw, (float)srch, 1.0f/(float)srcw, 1.0f/(float)srch ); const float w1 = w[0] + w[1]; const float w2 = w[2] + w[3]; const float w3 = w[4] + w[5]; const float w4 = w[6] + w[7]; const float d1 = 0 + 2*w[1]/w1; const float d2 = 2 + 2*w[3]/w2; const float d3 = 4 + 2*w[5]/w3; const float d4 = 6 + 2*w[7]/w4; const float w_div = 0.5f/(w1+w2+w3+w4); //------------------------------------- //float4 _c0; // source texsize (.xy), and inverse (.zw) //float4 _c1; // w1..w4 //float4 _c2; // d1..d4 //float4 _c3; // scale, bias, w_div, 0 //------------------------------------- #if 1 ShaderPtr shader = m_shader_blur1; auto _srctexsize = shader->GetConstant("srctexsize"); auto _wv = shader->GetConstant("wv"); auto _dv = shader->GetConstant("dv"); auto _fscale = shader->GetConstant("fscale"); auto _fbias = shader->GetConstant("fbias"); auto _w_div = shader->GetConstant("w_div"); // set constants _srctexsize->SetVector( srctexsize ); _wv->SetVector( Vector4( w1,w2,w3,w4 )); _dv->SetVector( Vector4( d1,d2,d3,d4 )); _fscale->SetFloat(fscale_now); _fbias->SetFloat(fbias_now); _w_div->SetFloat(w_div); DrawImageWithShader(shader, source, dest); #else ShaderInfoPtr si = m_BlurShaders[0]; ShaderConstantPtr* h = si->const_handles; if (h[0]) h[0]->SetVector( srctexsize ); if (h[1]) h[1]->SetVector( Vector4( w1,w2,w3,w4 )); if (h[2]) h[2]->SetVector( Vector4( d1,d2,d3,d4 )); if (h[3]) h[3]->SetVector( Vector4( fscale_now,fbias_now,w_div,0)); DrawImageWithShader(si->shader, source, dest); #endif } { // pass 2 (short vertical pass) //------------------------------------- source = dest; dest = m_blur_textures[pass]; int srcw = source->GetWidth(); int srch = source->GetHeight(); Vector4 srctexsize = Vector4( (float)srcw, (float)srch, 1.0f/(float)srcw, 1.0f/(float)srch ); const float w1 = w[0]+w[1] + w[2]+w[3]; const float w2 = w[4]+w[5] + w[6]+w[7]; const float d1 = 0 + 2*((w[2]+w[3])/w1); const float d2 = 2 + 2*((w[6]+w[7])/w2); const float w_div = 1.0f/((w1+w2)*2); //------------------------------------- //float4 _c0; // source texsize (.xy), and inverse (.zw) //float4 _c5; // w1,w2,d1,d2 //float4 _c6; // w_div, edge_darken_c1, edge_darken_c2, edge_darken_c3 //------------------------------------- #if 1 ShaderPtr shader = m_shader_blur2; auto _srctexsize = shader->GetConstant("srctexsize"); auto _wv = shader->GetConstant("wv"); auto _dv = shader->GetConstant("dv"); auto _edge_darken = shader->GetConstant("edge_darken"); auto _w_div = shader->GetConstant("w_div"); _srctexsize->SetVector( srctexsize ); _wv->SetVector(Vector4(w1,w2,0,0) ); _dv->SetVector(Vector4(d1,d2,0,0) ); { // note: only do this first time; if you do it many times, // then the super-blurred levels will have big black lines along the top & left sides. if (pass==0) _edge_darken->SetVector(Vector4((1-edge_darken),edge_darken,5.0f,0.0f)); //darken edges else _edge_darken->SetVector(Vector4(1.0f,0.0f,5.0f,0.0f)); // don't darken } _w_div->SetFloat(w_div); DrawImageWithShader(shader, source, dest); #else ShaderInfoPtr si = m_BlurShaders[1]; ShaderConstantPtr* h = si->const_handles; if (h[0]) h[0]->SetVector( srctexsize ); if (h[5]) h[5]->SetVector(Vector4(w1,w2,d1,d2) ); if (h[6]) { // note: only do this first time; if you do it many times, // then the super-blurred levels will have big black lines along the top & left sides. if (pass==0) h[6]->SetVector(Vector4(w_div,(1-edge_darken),edge_darken,5.0f)); //darken edges else h[6]->SetVector(Vector4(w_div,1.0f,0.0f,5.0f )); // don't darken } DrawImageWithShader(si->shader, source, dest); #endif } source = dest; } m_context->PopLabel(); } void CPlugin::ComputeGridAlphaValues_ComputeBegin() { PROFILE_FUNCTION() m_pState->ComputeGridAlphaValues_ComputeBegin(); if (m_bBlending) m_pOldState->ComputeGridAlphaValues_ComputeBegin(); } void CPlugin::ComputeGridAlphaValues_ComputeEnd() { PROFILE_FUNCTION() m_pState->ComputeGridAlphaValues_ComputeEnd(); if (m_bBlending) m_pOldState->ComputeGridAlphaValues_ComputeEnd(); } void CState::ComputeGridAlphaValues_ComputeBegin() { PROFILE_FUNCTION(); const std::vector<td_vertinfo> &m_vertinfo = m_plugin->m_vertinfo; float fAspectX = m_plugin->m_fAspectX; float fAspectY = m_plugin->m_fAspectY; int gridX = m_plugin->m_nGridX; int gridY = m_plugin->m_nGridY; int total = (gridY+1) * (gridX+1); m_verts.resize(total); m_pervertex_buffer->Resize(total); for (int n=0; n < total; n++) { float vx = m_vertinfo[n].vx; float vy = m_vertinfo[n].vy; float rad = m_vertinfo[n].rad; float ang = m_vertinfo[n].ang; // restore all the variables to their original states, // run the user-defined equations, // then move the results into local vars for computation as floats var_pv_xy.x = (double)(vx* 0.5f*fAspectX + 0.5f); var_pv_xy.y = (double)(vy*-0.5f*fAspectY + 0.5f); var_pv_rad = (double)rad; var_pv_ang = (double)ang; var_pv_zoom = var_pf_zoom; var_pv_zoomexp = var_pf_zoomexp; var_pv_rot = var_pf_rot; var_pv_warp = var_pf_warp; var_pv_cxy = var_pf_cxy; var_pv_dxy = var_pf_dxy; var_pv_sxy = var_pf_sxy; m_pervertex_buffer->StoreJob(n); } // execute all kernels m_pervertex_buffer->ExecuteAsync(); } void CState::ComputeGridAlphaValues_ComputeEnd() { PROFILE_FUNCTION(); float fAspectX = m_plugin->m_fAspectX; float fAspectY = m_plugin->m_fAspectY; float fInvAspectX = m_plugin->m_fInvAspectX; float fInvAspectY = m_plugin->m_fInvAspectY; const std::vector<td_vertinfo> &m_vertinfo = m_plugin->m_vertinfo; // warp stuff float fWarpTime = m_plugin->GetTime() * m_fWarpAnimSpeed; float fWarpScaleInv = 1.0f / m_fWarpScale.eval(m_plugin->GetTime()); float f[4]; f[0] = 11.68f + 4.0f*cosf(fWarpTime*1.413f + 10); f[1] = 8.77f + 3.0f*cosf(fWarpTime*1.113f + 7); f[2] = 10.54f + 3.0f*cosf(fWarpTime*1.233f + 3); f[3] = 11.49f + 4.0f*cosf(fWarpTime*0.933f + 5); // texel alignment // float texel_offset_x = m_plugin->m_context->GetTexelOffset() / (float)m_plugin->m_nTexSizeX; // float texel_offset_y = m_plugin->m_context->GetTexelOffset() / (float)m_plugin->m_nTexSizeY; // wait for end m_pervertex_buffer->Sync(); // complete // int n = 0; // for (int y=0; y<=m_plugin->m_nGridY; y++) int total = m_pervertex_buffer->GetSize(); for (int n=0; n < total; n++) { // for (int x=0; x<=m_plugin->m_nGridX; x++) { float vx = m_vertinfo[n].vx; float vy = m_vertinfo[n].vy; float rad = m_vertinfo[n].rad; // float ang = m_vertinfo[n].ang; // // var_pv_xy.x = (double)(vx* 0.5f*fAspectX + 0.5f); // var_pv_xy.y = (double)(vy*-0.5f*fAspectY + 0.5f); // var_pv_rad = (double)rad; // var_pv_ang = (double)ang; // var_pv_zoom = var_pf_zoom; // var_pv_zoomexp = var_pf_zoomexp; // var_pv_rot = var_pf_rot; // var_pv_warp = var_pf_warp; // var_pv_cxy = var_pf_cxy; // var_pv_dxy = var_pf_dxy; // var_pv_sxy = var_pf_sxy; m_pervertex_buffer->ReadJob(n); float fZoom = (float)(var_pv_zoom); float fZoomExp = (float)(var_pv_zoomexp); float fRot = (float)(var_pv_rot); float fWarp = (float)(var_pv_warp); float fCX = (float)(var_pv_cxy.x); float fCY = (float)(var_pv_cxy.y); float fDX = (float)(var_pv_dxy.x); float fDY = (float)(var_pv_dxy.y); float fSX = (float)(var_pv_sxy.x); float fSY = (float)(var_pv_sxy.y); float fZoom2 = powf(fZoom, powf(fZoomExp, rad*2.0f - 1.0f)); // initial texcoords, w/built-in zoom factor float fZoom2Inv = 1.0f/fZoom2; float u = vx*fAspectX*0.5f*fZoom2Inv + 0.5f; float v = -vy*fAspectY*0.5f*fZoom2Inv + 0.5f; //float u_orig = u; //float v_orig = v; //m_verts[n].tr = u_orig + texel_offset_x; //m_verts[n].ts = v_orig + texel_offset_y; // stretch on X, Y: u = (u - fCX)/fSX + fCX; v = (v - fCY)/fSY + fCY; // warping: //if (fWarp > 0.001f || fWarp < -0.001f) //{ u += fWarp*0.0035f*sinf(fWarpTime*0.333f + fWarpScaleInv*(vx*f[0] - vy*f[3])); v += fWarp*0.0035f*cosf(fWarpTime*0.375f - fWarpScaleInv*(vx*f[2] + vy*f[1])); u += fWarp*0.0035f*cosf(fWarpTime*0.753f - fWarpScaleInv*(vx*f[1] - vy*f[2])); v += fWarp*0.0035f*sinf(fWarpTime*0.825f + fWarpScaleInv*(vx*f[0] + vy*f[3])); //} // rotation: float u2 = u - fCX; float v2 = v - fCY; float cos_rot = cosf(fRot); float sin_rot = sinf(fRot); u = u2*cos_rot - v2*sin_rot + fCX; v = u2*sin_rot + v2*cos_rot + fCY; // translation: u -= fDX; v -= fDY; // undo aspect ratio fix: u = (u-0.5f)*fInvAspectX + 0.5f; v = (v-0.5f)*fInvAspectY + 0.5f; // final half-texel-offset translation: // u += texel_offset_x; // v += texel_offset_y; // write texcoords m_verts[n].tu = u; m_verts[n].tv = v; // n++; } } } void CPlugin::WarpedBlit_NoShaders(int nPass, bool bAlphaBlend, bool bFlipAlpha) { PROFILE_FUNCTION() SamplerAddress texaddr = (m_pState->var_pf_wrap > m_fSnapPoint) ? SAMPLER_WRAP : SAMPLER_CLAMP; float fDecay = (float)(m_pState->var_pf_decay); // decay //if (m_pState->m_bBlending) // fDecay = fDecay*(fCosineBlend) + (1.0f-fCosineBlend)*((float)(m_pOldState->var_pf_decay)); #if 0 Color4F cDecay = COLOR_RGBA_01(fDecay,fDecay,fDecay,1); SetFixedShader(m_lpVS[0], texaddr, SAMPLER_LINEAR); #else auto shader = m_shader_warp_fixed; auto sampler = shader->GetSampler(0); m_context->SetShader(shader); ShaderConstantPtr uniform_fdecay = shader->GetConstant("fDecay"); if (uniform_fdecay) uniform_fdecay->SetFloat(fDecay); if (sampler) sampler->SetTexture(m_lpVS[0], texaddr, SAMPLER_LINEAR); #endif if (bAlphaBlend) { if (bFlipAlpha) { m_context->SetBlend(BLEND_INVSRCALPHA, BLEND_SRCALPHA); } else { m_context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); } } else m_context->SetBlendDisable(); // Hurl the triangles at the video card. // We're going to un-index it, so that we don't stress any crappy (AHEM intel g33) // drivers out there. // If we're blending, we'll skip any polygon that is all alpha-blended out. // This also respects the MaxPrimCount limit of the video card. int primCount = m_nGridX*m_nGridY*2; #if 0 { Vertex tempv[1024 * 16]; int i=0; int src_idx = 0; for (int prim = 0; prim < primCount; prim++) { // copy 3 verts for (int j=0; j<3; j++) { tempv[i++] = m_verts[ m_indices_list[src_idx++] ]; // don't forget to flip sign on Y and factor in the decay color!: tempv[i-1].y *= -1; // tempv[i-1].Diffuse = (cDecay & 0x00FFFFFF) | (tempv[i-1].Diffuse & 0xFF000000); tempv[i - 1].Diffuse.r = cDecay.r; tempv[i - 1].Diffuse.g = cDecay.g; tempv[i - 1].Diffuse.b = cDecay.b; } } m_context->Draw(PRIMTYPE_TRIANGLELIST, primCount, tempv ); } #elif 0 { Vertex tempv[1024 * 16]; for (size_t i=0; i < m_verts.size(); i++) { tempv[i] = m_verts[i]; tempv[i].y *= -1; tempv[i].Diffuse.r = cDecay.r; tempv[i].Diffuse.g = cDecay.g; tempv[i].Diffuse.b = cDecay.b; } m_context->UploadIndexData(m_indices_list); m_context->UploadVertexData((int)m_verts.size(), tempv); m_context->DrawIndexed(PRIMTYPE_TRIANGLELIST, 0, primCount * 3 ); } #else { m_context->UploadIndexData(m_indices_list); m_context->UploadVertexData(m_verts); m_context->DrawIndexed(PRIMTYPE_TRIANGLELIST, 0, primCount * 3 ); } #endif m_context->SetBlendDisable(); } void CPlugin::WarpedBlit_Shaders(int nPass, bool bAlphaBlend, bool bFlipAlpha) { PROFILE_FUNCTION() // if nPass==0, it draws old preset (blending 1 of 2). // if nPass==1, it draws new preset (blending 2 of 2, OR done blending) if (bAlphaBlend) { if (bFlipAlpha) { m_context->SetBlend(BLEND_INVSRCALPHA, BLEND_SRCALPHA); } else { m_context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); } } else m_context->SetBlendDisable(); int pass = nPass; { // PASS 0: draw using *blended per-vertex motion vectors*, but with the OLD warp shader. // PASS 1: draw using *blended per-vertex motion vectors*, but with the NEW warp shader. CStatePtr state = (pass==0) ? m_pOldState : m_pState; ApplyShaderParams(state->m_shader_warp, state ); // Hurl the triangles at the video card. // We're going to un-index it, so that we don't stress any crappy (AHEM intel g33) // drivers out there. // We divide it into the two halves of the screen (top/bottom) so we can hack // the 'ang' values along the angle-wrap seam, halfway through the draw. // If we're blending, we'll skip any polygon that is all alpha-blended out. // This also respects the MaxPrimCount limit of the video card. #if 0 Vertex tempv[1024 * 16]; for (int half=0; half<2; half++) { // hack / restore the ang values along the angle-wrap [0 <-> 2pi] seam... float new_ang = half ? M_PI : -M_PI; int y_offset = (m_nGridY/2) * (m_nGridX + 1); for (int x=0; x<m_nGridX/2; x++) m_verts[y_offset + x].ang = new_ang; // send half of the polys int primCount = m_nGridX*m_nGridY*2 / 2; // in this case, to draw HALF the polys int src_idx_offset = half * primCount*3; { int i=0; for (int prim = 0; prim < primCount; prim++) { // copy 3 verts for (int j=0; j<3; j++) { tempv[i++] = m_verts[ m_indices_list[src_idx_offset++] ]; } } m_context->Draw(PRIMTYPE_TRIANGLELIST, primCount, tempv ); } } #elif 0 for (int half=0; half<2; half++) { // hack / restore the ang values along the angle-wrap [0 <-> 2pi] seam... float new_ang = half ? M_PI : -M_PI; int y_offset = (m_nGridY/2) * (m_nGridX + 1); for (int x=0; x<m_nGridX/2; x++) m_verts[y_offset + x].ang = new_ang; // send half of the polys int primCount = m_nGridX*m_nGridY*2 / 2; // in this case, to draw HALF the polys int src_idx_offset = half * primCount*3; m_context->UploadIndexData((int)m_indices_list.size(), m_indices_list.data()); m_context->UploadVertexData((int)m_verts.size(), m_verts.data()); m_context->DrawIndexed(PRIMTYPE_TRIANGLELIST, src_idx_offset, primCount * 3 ); } #else { int y_offset_neg = (m_nGridY/2) * (m_nGridX + 1); int width = m_nGridX / 2; int y_offset_pos = (int)m_verts.size() - width; // mirror ang across seam for (int x=0; x < width; x++) { Vertex v = m_verts[y_offset_neg + x]; v.ang = -M_PI; m_verts[y_offset_neg + x] = v; v.ang = M_PI; m_verts[y_offset_pos + x] = v; } m_context->UploadIndexData(m_indices_list_wrapped); m_context->UploadVertexData(m_verts); m_context->DrawIndexed(PRIMTYPE_TRIANGLELIST, 0, (int)m_indices_list_wrapped.size() ); } #endif } m_context->SetBlendDisable(); SetFixedShader(nullptr); } void CPlugin::DrawCustomShapes_ComputeBegin() { if (!m_bBlending) { m_pState->DrawCustomShapes_ComputeBegin(); } else { m_pState->DrawCustomShapes_ComputeBegin(); m_pOldState->DrawCustomShapes_ComputeBegin(); } } void CPlugin::DrawCustomShapes_ComputeEnd() { if (!m_bBlending) { m_pState->DrawCustomShapes_ComputeEnd(1.0f); } else { m_pState->DrawCustomShapes_ComputeEnd(m_fBlendProgress); m_pOldState->DrawCustomShapes_ComputeEnd( (1-m_fBlendProgress)); } } #define SHAPE_BUFFER 1 void CShape::Draw_ComputeBegin(CState *pState) { PROFILE_FUNCTION(); #if SHAPE_BUFFER m_perframe_buffer->Resize(instances); for (int instance=0; instance<instances; instance++) { // 1. execute per-frame code LoadCustomShapePerFrameEvallibVars(pState); // set instance var_pf_instance = instance; m_perframe_buffer->StoreJob(instance); } m_perframe_buffer->ExecuteAsync(); #endif } void CShape::Draw_ComputeEnd(class CPlugin *plugin, CState * pState, float alpha_mult) { PROFILE_FUNCTION(); float fAspectY = plugin->m_fAspectY; m_perframe_buffer->Sync(); // all shapes use the same shader... auto context = plugin->m_context; auto shader = plugin->m_shader_custom_shapes; auto sampler = shader->GetSampler(0); context->SetShader(shader); IDrawBufferPtr draw = plugin->GetDrawBuffer(); bool is_textured = false; if (sampler) sampler->SetTexture(nullptr); for (int instance=0; instance<instances; instance++) { #if !SHAPE_BUFFER // 1. execute per-frame code LoadCustomShapePerFrameEvallibVars(pState); // set instance var_pf_instance = instance; if (m_perframe_expression) { m_perframe_expression->Execute(); } #else m_perframe_buffer->ReadJob(instance); #endif int sides = (int)(var_pf_sides); if (sides<3) sides=3; if (sides>100) sides=100; bool additive = ((int)(var_pf_additive) != 0); context->SetBlend(BLEND_SRCALPHA, additive ? BLEND_ONE : BLEND_INVSRCALPHA); float x0 = (float)(var_pf_x* 2-1);// * ASPECT; float y0 = (float)(var_pf_y*-2+1); auto rgba = COLOR_ARGB( var_pf_rgba.a* alpha_mult, var_pf_rgba.r, var_pf_rgba.g, var_pf_rgba.b); auto rgba2 = COLOR_ARGB( var_pf_rgba2.a * alpha_mult, var_pf_rgba2.r, var_pf_rgba2.g, var_pf_rgba2.b ); Vertex v[512]; // for textured shapes (has texcoords) // setup first vertex v[0].x = x0; v[0].y = y0; v[0].z = 0; v[0].tu = 0.5f; v[0].tv = 0.5f; v[0].rad = v[0].ang = 0.0f; v[0].Diffuse = rgba; float rad = (float)var_pf_rad; float ang = (float)var_pf_ang; float tex_ang = (float)var_pf_tex_ang; float tex_zoom = (float)var_pf_tex_zoom; for (int j=1; j<sides+1; j++) { float t = (j-1)/(float)sides; v[j].x = x0 + rad*cosf(t*M_PI *2 + ang + M_PI *0.25f)* fAspectY; // DON'T TOUCH! v[j].y = y0 + rad*sinf(t*M_PI *2 + ang + M_PI *0.25f); // DON'T TOUCH! v[j].z = 0; v[j].tu = 0.5f + 0.5f*cosf(t*M_PI *2 + tex_ang + M_PI *0.25f)/(tex_zoom) * fAspectY; // DON'T TOUCH! v[j].tv = 0.5f + 0.5f*sinf(t*M_PI *2 + tex_ang + M_PI *0.25f)/(tex_zoom); // DON'T TOUCH! v[j].rad = v[j].ang = 0.0f; v[j].Diffuse = rgba2; } v[sides+1] = v[1]; // did textured state change? if ((int)(var_pf_textured) != 0) { if (!is_textured) { draw->Flush(); // draw textured version if (sampler) sampler->SetTexture(plugin->m_lpVS[0]); is_textured = true; } } else { if (is_textured) { draw->Flush(); // no texture if (sampler) sampler->SetTexture(nullptr); is_textured = false; } } draw->DrawTriangleFan(v, sides + 2); // DRAW BORDER if (var_pf_border.a > 0) { if (is_textured) { draw->Flush(); // no texture if (sampler) sampler->SetTexture(nullptr); is_textured = false; } v[0].Diffuse = COLOR_ARGB( var_pf_border.a * alpha_mult, var_pf_border.r, var_pf_border.g, var_pf_border.b ); for (int j=1; j<sides+2; j++) { v[j].Diffuse = v[0].Diffuse; } bool thick = ((int)(var_pf_thick) != 0); draw->DrawLineStrip(sides + 1, &v[1], thick); } } draw->Flush(); plugin->SetFixedShader(nullptr); } void CState::DrawCustomShapes_ComputeBegin() { for (auto shape : m_shapes) { StopWatch sw = StopWatch::StartNew(); if (shape->enabled) { shape->Draw_ComputeBegin(this); } shape->time_compute_begin = sw.GetElapsedMilliSeconds(); } } void CState::DrawCustomShapes_ComputeEnd(float alpha_mult) { for (auto shape : m_shapes) { StopWatch sw = StopWatch::StartNew(); if (shape->enabled) { shape->Draw_ComputeEnd(m_plugin, this, alpha_mult); } shape->time_compute_end = sw.GetElapsedMilliSeconds(); } m_plugin->SetFixedShader(nullptr); m_plugin->m_context->SetBlendDisable(); } void CShape::LoadCustomShapePerFrameEvallibVars(CState *pState) { var_pf_common = pState->GetCommonVars(); for (int vi=0; vi<NUM_Q_VAR; vi++) var_pf_q[vi] = pState->var_pf_q[vi]; for (int vi=0; vi<NUM_T_VAR; vi++) var_pf_t[vi] = t_values_after_init_code[vi]; var_pf_x = x; var_pf_y = y; var_pf_rad = rad; var_pf_ang = ang; var_pf_tex_zoom = tex_zoom; var_pf_tex_ang = tex_ang; var_pf_sides = sides; var_pf_additive = additive; var_pf_textured = textured; var_pf_instances = instances; var_pf_instance = 0; var_pf_thick = thickOutline; var_pf_rgba.r = rgba.r; var_pf_rgba.g = rgba.g; var_pf_rgba.b = rgba.b; var_pf_rgba.a = rgba.a; var_pf_rgba2.r = rgba2.r; var_pf_rgba2.g = rgba2.g; var_pf_rgba2.b = rgba2.b; var_pf_rgba2.a = rgba2.a; var_pf_border.r = border.r; var_pf_border.g = border.g; var_pf_border.b = border.b; var_pf_border.a = border.a; } void CWave::LoadCustomWavePerFrameEvallibVars(CState * pState) { var_pf_common = pState->GetCommonVars(); for (int vi=0; vi<NUM_Q_VAR; vi++) var_pf_q[vi] = pState->var_pf_q[vi]; for (int vi=0; vi<NUM_T_VAR; vi++) var_pf_t[vi] = t_values_after_init_code[vi]; var_pf_rgba.r = rgba.r; var_pf_rgba.g = rgba.g; var_pf_rgba.b = rgba.b; var_pf_rgba.a = rgba.a; var_pf_samples = samples; } // does a better-than-linear smooth on a wave. Roughly doubles the # of points. #if 0 static int SmoothWave(const Vertex* vi, int nVertsIn, Vertex* vo) { const float c1 = -0.15f; const float c2 = 1.15f; const float c3 = 1.15f; const float c4 = -0.15f; const float inv_sum = 1.0f/(c1+c2+c3+c4); int j = 0; int i_below = 0; int i_above; int i_above2 = 1; for (int i=0; i<nVertsIn-1; i++) { i_above = i_above2; i_above2 = std::min(nVertsIn-1,i+2); vo[j] = vi[i]; vo[j+1].x = (c1*vi[i_below].x + c2*vi[i].x + c3*vi[i_above].x + c4*vi[i_above2].x)*inv_sum; vo[j+1].y = (c1*vi[i_below].y + c2*vi[i].y + c3*vi[i_above].y + c4*vi[i_above2].y)*inv_sum; vo[j+1].z = 0; vo[j+1].Diffuse = vi[i].Diffuse;//0xFFFF0080; i_below = i; j += 2; } vo[j++] = vi[nVertsIn-1]; return j; } #endif static void SmoothWave(const Vertex* vi, int nVertsIn, std::vector<Vertex> &vo) { if (nVertsIn <= 0) return; const float c1 = -0.15f; const float c2 = 1.15f; const float c3 = 1.15f; const float c4 = -0.15f; const float inv_sum = 1.0f/(c1+c2+c3+c4); vo.reserve(nVertsIn * 2 + 8); int i_below = 0; int i_above; int i_above2 = 1; for (int i=0; i<nVertsIn-1; i++) { i_above = i_above2; i_above2 = std::min(nVertsIn-1,i+2); Vertex v1 = vi[i]; vo.push_back(v1); Vertex v2 = v1; v2.x = (c1*vi[i_below].x + c2*vi[i].x + c3*vi[i_above].x + c4*vi[i_above2].x)*inv_sum; v2.y = (c1*vi[i_below].y + c2*vi[i].y + c3*vi[i_above].y + c4*vi[i_above2].y)*inv_sum; vo.push_back(v2); i_below = i; } vo.push_back(vi[nVertsIn-1]); } void CPlugin::DrawCustomWaves_ComputeBegin() { PROFILE_FUNCTION(); m_pState->DrawCustomWaves_ComputeBegin(); if (m_bBlending) { m_pOldState->DrawCustomWaves_ComputeBegin(); } } void CPlugin::DrawCustomWaves_ComputeEnd() { PROFILE_FUNCTION(); if (!m_bBlending) { m_pState->DrawCustomWaves_ComputeEnd(1.0f); } else { m_pState->DrawCustomWaves_ComputeEnd(m_fBlendProgress); m_pOldState->DrawCustomWaves_ComputeEnd((1-m_fBlendProgress)); } } void CWave::Draw_ComputeBegin(class CPlugin *plugin, CState *pState) { PROFILE_FUNCTION(); // 1. execute per-frame code LoadCustomWavePerFrameEvallibVars(pState); // 2.a. do just a once-per-frame init for the *per-point* *READ-ONLY* variables // (the non-read-only ones will be reset/restored at the start of each vertex) var_pp_common = var_pf_common; if (m_perframe_expression) m_perframe_expression->Execute(); for (int vi=0; vi<NUM_Q_VAR; vi++) var_pp_q[vi] = var_pf_q[vi]; for (int vi=0; vi<NUM_T_VAR; vi++) var_pp_t[vi] = var_pf_t[vi]; int nSamples = (int)var_pf_samples; nSamples = std::min(512, nSamples); if ((nSamples >= 2) || (bUseDots && nSamples >= 1)) { } else { return; } float tempdata[2][512]; int max_samples = bSpectrum ? NUM_FREQUENCIES : NUM_WAVEFORM_SAMPLES; float mult = ((bSpectrum) ? 0.15f : 0.004f) * scaling * pState->m_fWaveScale.eval(-1); SampleBuffer<float> pdata1; SampleBuffer<float> pdata2; if (bSpectrum) { plugin->m_audio->RenderSpectrum(max_samples, pdata1, pdata2); } else { plugin->m_audio->RenderWaveForm(max_samples, pdata1, pdata2); } // initialize tempdata[2][512] { int j0 = (bSpectrum) ? 0 : (max_samples - nSamples)/2/**(1-bSpectrum)*/ - sep/2; int j1 = (bSpectrum) ? 0 : (max_samples - nSamples)/2/**(1-bSpectrum)*/ + sep/2; if (j0 < 0) j0 = 0; if (j1 < 0) j1 = 0; float t = (bSpectrum) ? (max_samples - sep)/(float)nSamples : 1; float mix1 = powf(smoothing*0.98f, 0.5f); // lower exponent -> more default smoothing float mix2 = 1-mix1; // SMOOTHING: tempdata[0][0] = pdata1[j0]; tempdata[1][0] = pdata2[j1]; for (int j=1; j<nSamples; j++) { tempdata[0][j] = pdata1[(int)(j*t)+j0]*mix2 + tempdata[0][j-1]*mix1; tempdata[1][j] = pdata2[(int)(j*t)+j1]*mix2 + tempdata[1][j-1]*mix1; } // smooth again, backwards: [this fixes the asymmetry of the beginning & end..] for (int j=nSamples-2; j>=0; j--) { tempdata[0][j] = tempdata[0][j]*mix2 + tempdata[0][j+1]*mix1; tempdata[1][j] = tempdata[1][j]*mix2 + tempdata[1][j+1]*mix1; } // finally, scale to final size: for (int j=0; j<nSamples; j++) { tempdata[0][j] *= mult; tempdata[1][j] *= mult; } } // 2. for each point, execute per-point code m_perpoint_buffer->Resize(nSamples); // to do: // -add any of the m_wave[i].xxx menu-accessible vars to the code? float j_mult = 1.0f/(float)(nSamples-1); for (int j=0; j<nSamples; j++) { float t = j*j_mult; float value1 = tempdata[0][j]; float value2 = tempdata[1][j]; var_pp_sample = t; var_pp_value1 = value1; var_pp_value2 = value2; var_pp_x = 0.5f + value1; var_pp_y = 0.5f + value2; var_pp_rgba = var_pf_rgba; m_perpoint_buffer->StoreJob(j); } m_perpoint_buffer->ExecuteAsync(); } void CWave::Draw_ComputeEnd(class CPlugin *plugin, CState * pState, float alpha_mult) { PROFILE_FUNCTION(); auto context = plugin->m_context; auto shader = plugin->m_shader_custom_waves; auto sampler = shader->GetSampler(0); float fInvAspectX = plugin->m_fInvAspectX; float fInvAspectY = plugin->m_fInvAspectY; float nTexSizeX = (float)plugin->m_nTexSizeX; // float nTexSizeY = (float)plugin->m_nTexSizeY; // wait for end m_perpoint_buffer->Sync(); int nSamples = m_perpoint_buffer->GetSize(); std::vector<Vertex> verts; verts.reserve(nSamples); for (int j=0; j<nSamples; j++) { m_perpoint_buffer->ReadJob(j); Vertex v; v.Clear(); v.x = (float)(var_pp_x* 2-1)*fInvAspectX; v.y = (float)(var_pp_y*-2+1)*fInvAspectY; v.z = 0; v.Diffuse = COLOR_ARGB( var_pp_rgba.a * alpha_mult, var_pp_rgba.r, var_pp_rgba.g, var_pp_rgba.b ); verts.push_back(v); } // 3. smooth it if (!bUseDots) { std::vector<Vertex> v2; SmoothWave(verts.data(), (int)verts.size(), v2); verts.swap(v2); } context->SetShader(shader); if (sampler) sampler->SetTexture(nullptr); // 4. draw it context->SetBlend(BLEND_SRCALPHA, bAdditive ? BLEND_ONE : BLEND_INVSRCALPHA); IDrawBufferPtr draw = plugin->GetDrawBuffer(); if (bUseDots) { float ptsize = (float)((nTexSizeX >= 1024) ? 2 : 1) + (bDrawThick ? 1 : 0); draw->DrawPointsWithSize((int)verts.size(), verts.data(), ptsize); } else { draw->DrawLineStrip((int)verts.size(), verts.data(), bDrawThick); } draw->Flush(); context->SetBlendDisable(); } void CState::DrawCustomWaves_ComputeBegin() { for (auto wave : m_waves) { StopWatch wave_sw = StopWatch::StartNew(); if (wave->enabled) { wave->Draw_ComputeBegin(m_plugin, this); } wave->time_compute_begin = wave_sw.GetElapsedMilliSeconds(); } } void CState::DrawCustomWaves_ComputeEnd(float alpha_mult) { for (auto wave : m_waves) { StopWatch wave_sw = StopWatch::StartNew(); if (wave->enabled) { wave->Draw_ComputeEnd(m_plugin, this, alpha_mult); } wave->time_compute_end = wave_sw.GetElapsedMilliSeconds(); } } void CPlugin::RenderWaveForm( int sampleCount, SampleBuffer<Sample> &samples ) { m_audio->RenderWaveForm( sampleCount, samples ); float fWaveScale = m_pState->m_fWaveScale.eval(GetTime()); samples.Modulate(fWaveScale); float fWaveSmoothing = m_pState->m_fWaveSmoothing.eval(GetTime());; samples.Smooth(fWaveSmoothing); } void CPlugin::RenderSpectrum( int sampleCount, SampleBuffer<float> &fSpectrum ) { m_audio->RenderSpectrum(sampleCount, fSpectrum); } void CPlugin::DrawWave() { PROFILE_FUNCTION(); SetFixedShader(nullptr); Vertex v1[MAX_SAMPLES+1], v2[MAX_SAMPLES+1]; m_context->SetBlend(BLEND_SRCALPHA, (m_pState->var_pf_wave_additive) ? BLEND_ONE : BLEND_INVSRCALPHA); //float cr = m_pState->m_waveR.eval(GetTime()); //float cg = m_pState->m_waveG.eval(GetTime()); //float cb = m_pState->m_waveB.eval(GetTime()); float cr = (float)(m_pState->var_pf_wave_rgba.r); float cg = (float)(m_pState->var_pf_wave_rgba.g); float cb = (float)(m_pState->var_pf_wave_rgba.b); float cx = (float)(m_pState->var_pf_wave_x); float cy = (float)(m_pState->var_pf_wave_y); // note: it was backwards (top==1) in the original milkdrop, so we keep it that way! float fWaveParam = (float)(m_pState->var_pf_wave_mystery); /*if (m_pState->m_bBlending) { cr = cr*(m_pState->m_fBlendProgress) + (1.0f-m_pState->m_fBlendProgress)*((float)(m_pOldState->var_pf_wave_r)); cg = cg*(m_pState->m_fBlendProgress) + (1.0f-m_pState->m_fBlendProgress)*((float)(m_pOldState->var_pf_wave_g)); cb = cb*(m_pState->m_fBlendProgress) + (1.0f-m_pState->m_fBlendProgress)*((float)(m_pOldState->var_pf_wave_b)); cx = cx*(m_pState->m_fBlendProgress) + (1.0f-m_pState->m_fBlendProgress)*((float)(m_pOldState->var_pf_wave_x)); cy = cy*(m_pState->m_fBlendProgress) + (1.0f-m_pState->m_fBlendProgress)*((float)(m_pOldState->var_pf_wave_y)); fWaveParam = fWaveParam*(m_pState->m_fBlendProgress) + (1.0f-m_pState->m_fBlendProgress)*((float)(m_pOldState->var_pf_wave_mystery)); }*/ if (cr < 0) cr = 0; if (cg < 0) cg = 0; if (cb < 0) cb = 0; if (cr > 1) cr = 1; if (cg > 1) cg = 1; if (cb > 1) cb = 1; // maximize color: if (m_pState->var_pf_wave_brighten) { float fMaximizeWaveColorAmount = 1.0f; float max = cr; if (max < cg) max = cg; if (max < cb) max = cb; if (max > 0.01f) { cr = cr/max*fMaximizeWaveColorAmount + cr*(1.0f - fMaximizeWaveColorAmount); cg = cg/max*fMaximizeWaveColorAmount + cg*(1.0f - fMaximizeWaveColorAmount); cb = cb/max*fMaximizeWaveColorAmount + cb*(1.0f - fMaximizeWaveColorAmount); } } float fWavePosX = cx*2.0f - 1.0f; // go from 0..1 user-range to -1..1 D3D range float fWavePosY = cy*2.0f - 1.0f; // float bass_rel = GetImmRel(0); // float mid_rel = GetImmRel(1); float treble_rel = GetImmRel(BAND_TREBLE); // int sample_offset = 0; int new_wavemode = (int)(m_pState->var_pf_wave_mode) % NUM_WAVES; // since it can be changed from per-frame code! int its = (m_bBlending && (new_wavemode != m_pState->m_nOldWaveMode)) ? 2 : 1; int nVerts1 = 0; int nVerts2 = 0; int nBreak1 = -1; int nBreak2 = -1; float alpha1=0, alpha2=0; for (int it=0; it<its; it++) { int wave = (it==0) ? new_wavemode : m_pState->m_nOldWaveMode; int nVerts = NUM_WAVEFORM_SAMPLES; // allowed to peek ahead 64 (i.e. left is [i], right is [i+64]) int nBreak = -1; // nVerts = 16; // nVerts = 32; float fWaveParam2 = fWaveParam; //std::string fWaveParam; // kill its scope if ((wave==0 || wave==1 || wave==4) && (fWaveParam2 < -1 || fWaveParam2 > 1)) { //fWaveParam2 = max(fWaveParam2, -1.0f); //fWaveParam2 = min(fWaveParam2, 1.0f); fWaveParam2 = fWaveParam2*0.5f + 0.5f; fWaveParam2 -= floorf(fWaveParam2); fWaveParam2 = fabsf(fWaveParam2); fWaveParam2 = fWaveParam2*2-1; } Vertex *v = (it==0) ? v1 : v2; memset(v, 0, sizeof(v[0])*nVerts); float alpha = (float)(m_pState->var_pf_wave_rgba.a);//m_pState->m_fWaveAlpha.eval(GetTime()); if (m_pState->m_bModWaveAlphaByVolume) alpha *= (GetImmRelTotal() - m_pState->m_fModWaveAlphaStart.eval(GetTime()))/(m_pState->m_fModWaveAlphaEnd.eval(GetTime()) - m_pState->m_fModWaveAlphaStart.eval(GetTime())); //wave = 4; switch(wave) { case 0: // circular wave nVerts /= 2; // sample_offset = (NUM_WAVEFORM_SAMPLES-nVerts)/2;//mysound.GoGoAlignatron(nVerts * 12/10); // only call this once nVerts is final! { SampleBuffer<Sample> samples; int pad = nVerts / 10; RenderWaveForm(nVerts + pad, samples); float inv_nverts_minus_one = 1.0f/(float)(nVerts-1); for (int i=0; i<nVerts; i++) { float rad = 0.5f + 0.4f*samples[i].volume() + fWaveParam2; float ang = (i)*inv_nverts_minus_one*6.28f + GetTime()*0.2f; if (i < pad) { float mix = (float)i / (float)(pad); mix = 0.5f - 0.5f*cosf(mix * M_PI); float rad_2 = 0.5f + 0.4f*samples[i + nVerts].volume() + fWaveParam2; rad = rad_2*(1.0f-mix) + rad*(mix); } v[i].x = rad*cosf(ang) *m_fAspectY + fWavePosX; // 0.75 = adj. for aspect ratio v[i].y = rad*sinf(ang) *m_fAspectX + fWavePosY; //v[i].Diffuse = color; } } // dupe last vertex to connect the lines; skip if blending if (!m_bBlending) { // nVerts++; v[nVerts-1] = v[0]; } break; case 1: // x-y osc. that goes around in a spiral, in time { alpha *= 1.25f; nVerts /= 2; SampleBuffer<Sample> samples; RenderWaveForm(nVerts + 32, samples); for (int i=0; i<nVerts; i++) { float rad = 0.53f + 0.43f*samples[i].right() + fWaveParam2; float ang = samples[i+32].left() * 1.57f + GetTime()*2.3f; v[i].x = rad*cosf(ang) *m_fAspectY + fWavePosX; // 0.75 = adj. for aspect ratio v[i].y = rad*sinf(ang) *m_fAspectX + fWavePosY; //v[i].Diffuse = color;//(COLOR_RGBA_01(cr, cg, cb, alpha*min(1, max(0, fL[i]))); } } break; case 2: // centered spiro (alpha constant) // aimed at not being so sound-responsive, but being very "nebula-like" // difference is that alpha is constant (and faint), and waves a scaled way up switch(m_nTexSizeX) { case 256: alpha *= 0.07f; break; case 512: alpha *= 0.09f; break; case 1024: alpha *= 0.11f; break; case 2048: alpha *= 0.13f; break; case 4096: alpha *= 0.15f; break; } { SampleBuffer<Sample> samples; RenderWaveForm(nVerts + 32, samples); for (int i=0; i<nVerts; i++) { v[i].x = samples[i ].left() *m_fAspectY + fWavePosX;//((pR[i] ^ 128) - 128)/90.0f * ASPECT; // 0.75 = adj. for aspect ratio v[i].y = samples[i+32].right() *m_fAspectX + fWavePosY;//((pL[i+32] ^ 128) - 128)/90.0f; //v[i].Diffuse = color; } } break; case 3: // centered spiro (alpha tied to volume) // aimed at having a strong audio-visual tie-in // colors are always bright (no darks) switch(m_nTexSizeX) { case 256: alpha = 0.075f; break; case 512: alpha = 0.150f; break; case 1024: alpha = 0.220f; break; case 2048: alpha = 0.330f; break; case 4096: alpha = 0.400f; break; } alpha *= 1.3f; alpha *= powf(treble_rel, 2.0f); { SampleBuffer<Sample> samples; RenderWaveForm(nVerts + 32, samples); for (int i=0; i<nVerts; i++) { v[i].x = samples[i ].left() *m_fAspectY + fWavePosX;//((pR[i] ^ 128) - 128)/90.0f * ASPECT; // 0.75 = adj. for aspect ratio v[i].y = samples[i+32].right() *m_fAspectX + fWavePosY;//((pL[i+32] ^ 128) - 128)/90.0f; //v[i].Diffuse = color; } } break; case 4: // horizontal "script", left channel //sample_offset = (NUM_WAVEFORM_SAMPLES-nVerts)/2;//mysound.GoGoAlignatron(nVerts + 25); // only call this once nVerts is final! { SampleBuffer<Sample> samples; RenderWaveForm(nVerts + 25, samples); float w1 = 0.45f + 0.5f*(fWaveParam2*0.5f + 0.5f); // 0.1 - 0.9 float w2 = 1.0f - w1; float inv_nverts = 1.0f/(float)(nVerts-1); for (int i=0; i<nVerts; i++) { v[i].x = -1.0f + 2.0f*(i*inv_nverts) + fWavePosX; v[i].y = samples[i].left() *0.47f + fWavePosY;//((pL[i] ^ 128) - 128)/270.0f; v[i].x += samples[i+25].right() *0.44f;//((pR[i+25] ^ 128) - 128)/290.0f; //v[i].Diffuse = color; // momentum if (i>1) { v[i].x = v[i].x*w2 + w1*(v[i-1].x*2.0f - v[i-2].x); v[i].y = v[i].y*w2 + w1*(v[i-1].y*2.0f - v[i-2].y); } } /* // center on Y float avg_y = 0; for (i=0; i<nVerts; i++) avg_y += v[i].y; avg_y /= (float)nVerts; avg_y *= 0.5f; // damp the movement for (i=0; i<nVerts; i++) v[i].y -= avg_y; */ } break; case 5: // weird explosive complex # thingy switch(m_nTexSizeX) { case 256: alpha *= 0.07f; break; case 512: alpha *= 0.09f; break; case 1024: alpha *= 0.11f; break; case 2048: alpha *= 0.13f; break; case 4096: alpha *= 0.15f; break; } { SampleBuffer<Sample> samples; RenderWaveForm(nVerts + 32, samples); float cos_rot = cosf(GetTime()*0.3f); float sin_rot = sinf(GetTime()*0.3f); for (int i=0; i<nVerts; i++) { float l0 = samples[i].left(); float r0 = samples[i].right(); float l1 = samples[i+32].left(); float r1 = samples[i+32].right(); float x0 = (r0*l1 + l0*r1); float y0 = (r0*r0 - l1*l1); v[i].x = (x0*cos_rot - y0*sin_rot)*m_fAspectY + fWavePosX; v[i].y = (x0*sin_rot + y0*cos_rot)*m_fAspectX + fWavePosY; //v[i].Diffuse = color; } } break; case 6: case 7: case 8: // 6: angle-adjustable left channel, with temporal wave alignment; // fWaveParam2 controls the angle at which it's drawn // fWavePosX slides the wave away from the center, transversely. // fWavePosY does nothing // // 7: same, except there are two channels shown, and // fWavePosY determines the separation distance. // // 8: same as 6, except using the spectrum analyzer (UNFINISHED) // nVerts /= 2; if (wave==8) nVerts = 256; // else // sample_offset = (NUM_WAVEFORM_SAMPLES-nVerts)/2;//mysound.GoGoAlignatron(nVerts); // only call this once nVerts is final! { float ang = 1.57f*fWaveParam2; // from -PI/2 to PI/2 float dx = cosf(ang); float dy = sinf(ang); float edge_x[2], edge_y[2]; //edge_x[0] = fWavePosX - dx*3.0f; //edge_y[0] = fWavePosY - dy*3.0f; //edge_x[1] = fWavePosX + dx*3.0f; //edge_y[1] = fWavePosY + dy*3.0f; edge_x[0] = fWavePosX*cosf(ang + 1.57f) - dx*3.0f; edge_y[0] = fWavePosX*sinf(ang + 1.57f) - dy*3.0f; edge_x[1] = fWavePosX*cosf(ang + 1.57f) + dx*3.0f; edge_y[1] = fWavePosX*sinf(ang + 1.57f) + dy*3.0f; for (int i=0; i<2; i++) // for each point defining the line { // clip the point against 4 edges of screen // be a bit lenient (use +/-1.1 instead of +/-1.0) // so the dual-wave doesn't end too soon, after the channels are moved apart for (int j=0; j<4; j++) { float t = 0; bool bClip = false; switch(j) { case 0: if (edge_x[i] > 1.1f) { t = (1.1f - edge_x[1-i]) / (edge_x[i] - edge_x[1-i]); bClip = true; } break; case 1: if (edge_x[i] < -1.1f) { t = (-1.1f - edge_x[1-i]) / (edge_x[i] - edge_x[1-i]); bClip = true; } break; case 2: if (edge_y[i] > 1.1f) { t = (1.1f - edge_y[1-i]) / (edge_y[i] - edge_y[1-i]); bClip = true; } break; case 3: if (edge_y[i] < -1.1f) { t = (-1.1f - edge_y[1-i]) / (edge_y[i] - edge_y[1-i]); bClip = true; } break; } if (bClip) { float dx = edge_x[i] - edge_x[1-i]; float dy = edge_y[i] - edge_y[1-i]; edge_x[i] = edge_x[1-i] + dx*t; edge_y[i] = edge_y[1-i] + dy*t; } } } dx = (edge_x[1] - edge_x[0]) / (float)(nVerts-1); dy = (edge_y[1] - edge_y[0]) / (float)(nVerts-1); float ang2 = atan2f(dy,dx); float perp_dx = cosf(ang2 + 1.57f); float perp_dy = sinf(ang2 + 1.57f); if (wave == 6) { SampleBuffer<Sample> samples; RenderWaveForm(nVerts, samples); for (int i=0; i<nVerts; i++) { float s = samples[i].volume(); v[i].x = edge_x[0] + dx*i + perp_dx*0.25f*s; v[i].y = edge_y[0] + dy*i + perp_dy*0.25f*s; //v[i].Diffuse = color; } } else if (wave == 8) { SampleBuffer<float> fSpectrum; RenderSpectrum(nVerts, fSpectrum); //256 verts for (int i=0; i<nVerts; i++) { float f = 0.1f*logf(fSpectrum[i]); v[i].x = edge_x[0] + dx*i + perp_dx*f; v[i].y = edge_y[0] + dy*i + perp_dy*f; //v[i].Diffuse = color; } } else { SampleBuffer<Sample> samples; RenderWaveForm(nVerts, samples); float sep = powf(fWavePosY*0.5f + 0.5f, 2.0f); for (int i=0; i<nVerts; i++) { float s = samples[i].left(); v[i].x = edge_x[0] + dx*i + perp_dx*(0.25f*s + sep); v[i].y = edge_y[0] + dy*i + perp_dy*(0.25f*s + sep); //v[i].Diffuse = color; } //D3DPRIMITIVETYPE primtype = (m_pState->var_pf_wave_usedots) ? D3DPT_POINTLIST : D3DPT_LINESTRIP; //m_lpD3DDev->DrawPrimitive(primtype, D3DFVF_LVERTEX, (LPVOID)v, nVerts, NULL); for (int i=0; i<nVerts; i++) { float s = samples[i].right(); v[i+nVerts].x = edge_x[0] + dx*i + perp_dx*(0.25f*s - sep); v[i+nVerts].y = edge_y[0] + dy*i + perp_dy*(0.25f*s - sep); //v[i+nVerts].Diffuse = color; } nBreak = nVerts; nVerts *= 2; } } break; case 9: // horizontal "script", left channel { SampleBuffer<Sample> samples; RenderWaveForm(nVerts, samples); float inv_nverts = 1.0f / (float)(nVerts-1); for (int i = 0; i < nVerts; i++) { v[i].x = -1.0f + 2.0f*(i*inv_nverts) + fWavePosX; v[i].y = samples[i].volume() * 1 + fWavePosY; } } break; } // clamp alpha if (alpha < 0) alpha = 0; if (alpha > 1) alpha = 1; if (it==0) { nVerts1 = nVerts; nBreak1 = nBreak; alpha1 = alpha; } else { nVerts2 = nVerts; nBreak2 = nBreak; alpha2 = alpha; } } // v1[] is for the current waveform // v2[] is for the old waveform (from prev. preset - only used if blending) // nVerts1 is the # of vertices in v1 // nVerts2 is the # of vertices in v2 // nBreak1 is the index of the point at which to break the solid line in v1[] (-1 if no break) // nBreak2 is the index of the point at which to break the solid line in v2[] (-1 if no break) float mix = CosineInterp(m_fBlendProgress); float mix2 = 1.0f - mix; // blend 2 waveforms if (nVerts2 > 0) { // note: this won't yet handle the case where (nBreak1 > 0 && nBreak2 > 0) // in this case, code must break wave into THREE segments float m = (nVerts2-1)/(float)nVerts1; float x,y; for (int i=0; i<nVerts1; i++) { float fIdx = i*m; int nIdx = (int)fIdx; float t = fIdx - nIdx; if (nIdx == nBreak2-1) { x = v2[nIdx].x; y = v2[nIdx].y; nBreak1 = i+1; } else { x = v2[nIdx].x*(1-t) + v2[nIdx+1].x*(t); y = v2[nIdx].y*(1-t) + v2[nIdx+1].y*(t); } v1[i].x = v1[i].x*(mix) + x*(mix2); v1[i].y = v1[i].y*(mix) + y*(mix2); } } // determine alpha if (nVerts2 > 0) { alpha1 = alpha1*(mix) + alpha2*(1.0f-mix); } // apply color & alpha // ALSO reverse all y values, to stay consistent with the pre-VMS milkdrop, // which DIDN'T: v1[0].Diffuse = COLOR_RGBA_01(cr, cg, cb, alpha1); for (int i=0; i<nVerts1; i++) { v1[i].Diffuse = v1[0].Diffuse; v1[i].y = -v1[i].y; } // don't draw wave if (possibly blended) alpha is less than zero. if (alpha1 < 0.004f) { m_context->SetBlendDisable(); return; } // TESSELLATE - smooth the wave, one time. std::vector<Vertex> vTess; std::vector<Vertex> vTess2; if (1) { if (nBreak1==-1) { SmoothWave(v1, nVerts1, vTess); } else { SmoothWave(v1, nBreak1, vTess); SmoothWave(&v1[nBreak1], nVerts1-nBreak1, vTess2); } } // draw primitives IDrawBufferPtr draw = GetDrawBuffer(); { //D3DPRIMITIVETYPE primtype = (m_pState->var_pf_wave_usedots) ? D3DPT_POINTLIST : D3DPT_LINESTRIP; bool thick = ((m_pState->var_pf_wave_thick || m_pState->var_pf_wave_usedots) && (m_nTexSizeX >= 512)); if (m_pState->var_pf_wave_usedots) { draw->DrawPoints((int)vTess.size(), vTess.data(), thick); if (!vTess2.empty()) draw->DrawPoints((int)vTess2.size(), vTess2.data(), thick); } else { draw->DrawLineStrip((int)vTess.size(), vTess.data(), thick); if (!vTess2.empty()) draw->DrawLineStrip((int)vTess2.size(), vTess2.data(), thick); } } draw->Flush(); m_context->SetBlendDisable(); } void CPlugin::DrawSprites() { PROFILE_FUNCTION() SetFixedShader(nullptr); if (m_pState->var_pf_darken_center) { m_context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); Vertex v3[6]; memset(v3, 0, sizeof(v3)); // colors: v3[0].Diffuse = COLOR_RGBA_01(0, 0, 0, 3.0f/32.0f); v3[1].Diffuse = COLOR_RGBA_01(0, 0, 0, 0.0f/32.0f); v3[2].Diffuse = v3[1].Diffuse; v3[3].Diffuse = v3[1].Diffuse; v3[4].Diffuse = v3[1].Diffuse; v3[5].Diffuse = v3[1].Diffuse; // positioning: float fHalfSize = 0.05f; v3[0].x = 0.0f; v3[1].x = 0.0f - fHalfSize*m_fAspectY; v3[2].x = 0.0f; v3[3].x = 0.0f + fHalfSize*m_fAspectY; v3[4].x = 0.0f; v3[5].x = v3[1].x; v3[0].y = 0.0f; v3[1].y = 0.0f; v3[2].y = 0.0f - fHalfSize; v3[3].y = 0.0f; v3[4].y = 0.0f + fHalfSize; v3[5].y = v3[1].y; //v3[0].tu = 0; v3[1].tu = 1; v3[2].tu = 0; v3[3].tu = 1; //v3[0].tv = 1; v3[1].tv = 1; v3[2].tv = 0; v3[3].tv = 0; m_context->DrawArrays(PRIMTYPE_TRIANGLEFAN, 6, v3); m_context->SetBlendDisable(); } // do borders { float fOuterBorderSize = (float)m_pState->var_pf_ob_size; float fInnerBorderSize = (float)m_pState->var_pf_ib_size; m_context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); for (int it=0; it<2; it++) { Vertex v3[4]; memset(v3, 0, sizeof(v3)); // colors: float r = (it==0) ? (float)m_pState->var_pf_ob_rgba.r : (float)m_pState->var_pf_ib_rgba.r; float g = (it==0) ? (float)m_pState->var_pf_ob_rgba.g : (float)m_pState->var_pf_ib_rgba.g; float b = (it==0) ? (float)m_pState->var_pf_ob_rgba.b : (float)m_pState->var_pf_ib_rgba.b; float a = (it==0) ? (float)m_pState->var_pf_ob_rgba.a : (float)m_pState->var_pf_ib_rgba.a; if (a > 0.001f) { v3[0].Diffuse = COLOR_RGBA_01(r,g,b,a); v3[1].Diffuse = v3[0].Diffuse; v3[2].Diffuse = v3[0].Diffuse; v3[3].Diffuse = v3[0].Diffuse; // positioning: float fInnerRad = (it==0) ? 1.0f - fOuterBorderSize : 1.0f - fOuterBorderSize - fInnerBorderSize; float fOuterRad = (it==0) ? 1.0f : 1.0f - fOuterBorderSize; v3[0].x = fInnerRad; v3[1].x = fOuterRad; v3[2].x = fOuterRad; v3[3].x = fInnerRad; v3[0].y = fInnerRad; v3[1].y = fOuterRad; v3[2].y = -fOuterRad; v3[3].y = -fInnerRad; for (int rot=0; rot<4; rot++) { m_context->DrawArrays(PRIMTYPE_TRIANGLEFAN, 4, v3); // rotate by 90 degrees for (int v=0; v<4; v++) { float t = 1.570796327f; float x = v3[v].x; float y = v3[v].y; v3[v].x = x*cosf(t) - y*sinf(t); v3[v].y = x*sinf(t) + y*cosf(t); } } } } m_context->SetBlendDisable(); } } void CPlugin::UvToMathSpace(float u, float v, float* rad, float* ang) { // (screen space = -1..1 on both axes; corresponds to UV space) // uv space = [0..1] on both axes // "math" space = what the preset authors are used to: // upper left = [0,0] // bottom right = [1,1] // rad == 1 at corners of screen // ang == 0 at three o'clock, and increases counter-clockwise (to 6.28). float px = (u*2-1) * m_fAspectX; // probably 1.0 float py = (v*2-1) * m_fAspectY; // probably <1 *rad = sqrtf(px*px + py*py) / sqrtf(m_fAspectX*m_fAspectX + m_fAspectY*m_fAspectY); *ang = atan2f(py, px); if (*ang < 0) *ang += M_PI * 2; } void CPlugin::ApplyShaderParams(ShaderInfoPtr p, CStatePtr pState) { PROFILE_FUNCTION(); m_context->SetShader(p->shader); // bind textures for (const auto &tb : p->_texture_bindings) { if (!tb.shader_sampler) continue; tex_code texcode = tb.texcode; TexturePtr texture; switch (texcode) { case TEX_VS: texture = m_lpVS[0]; break; case TEX_BLUR1: texture = m_blur_textures[0]; break; case TEX_BLUR2: texture = m_blur_textures[1]; break; case TEX_BLUR3: texture = m_blur_textures[2]; break; case TEX_DISK: texture = tb.texptr; break; default: assert(0); texture= nullptr; break; } // also set up sampler stage, if anything is bound here... { bool bAniso = false; SamplerFilter HQFilter = bAniso ? SAMPLER_ANISOTROPIC : SAMPLER_LINEAR; SamplerAddress wrap = tb.bWrap ? SAMPLER_WRAP : SAMPLER_CLAMP; SamplerFilter filter = tb.bBilinear ? HQFilter : SAMPLER_POINT; if (tb.shader_sampler) tb.shader_sampler->SetTexture(texture, wrap, filter); } } // bind "texsize_XYZ" params for (const auto &q : p->texsize_params) { q.texsize_param->SetVector(Vector4((float)q.w,(float)q.h,1.0f/q.w,1.0f/q.h)); } float time_since_preset_start = m_PresetDuration; float time_since_preset_start_wrapped = time_since_preset_start - (int)(time_since_preset_start/10000)*10000; float time = GetTime(); float progress = GetPresetProgress(); float mip_x = logf((float)GetWidth())/logf(2.0f); float mip_y = logf((float)GetWidth())/logf(2.0f); float mip_avg = 0.5f*(mip_x + mip_y); float aspect_x = 1; float aspect_y = 1; if (GetWidth() > GetHeight()) aspect_y = GetHeight()/(float)GetWidth(); else aspect_x = GetWidth()/(float)GetHeight(); float blur_min[3], blur_max[3]; pState->GetSafeBlurMinMax(blur_min, blur_max); // bind float4's if (p->rand_frame ) p->rand_frame->SetVector( m_rand_frame ); if (p->rand_preset) p->rand_preset->SetVector( pState->m_rand_preset ); ShaderConstantPtr* h = p->const_handles; if (h[0]) h[0]->SetVector( Vector4( aspect_x, aspect_y, 1.0f/aspect_x, 1.0f/aspect_y )); if (h[1]) h[1]->SetVector( Vector4(0, 0, 0, 0 )); if (h[2]) h[2]->SetVector( Vector4(time_since_preset_start_wrapped, GetFps(), (float)GetFrame(), progress)); if (h[3]) h[3]->SetVector( Vector4(GetImmRel(BAND_BASS), GetImmRel(BAND_MID), GetImmRel(BAND_TREBLE), GetImmRelTotal() )); if (h[4]) h[4]->SetVector( Vector4(GetAvgRel(BAND_BASS), GetAvgRel(BAND_MID), GetAvgRel(BAND_TREBLE), GetAvgRelTotal() )); if (h[5]) h[5]->SetVector( Vector4( blur_max[0]-blur_min[0], blur_min[0], blur_max[1]-blur_min[1], blur_min[1] )); if (h[6]) h[6]->SetVector( Vector4( blur_max[2]-blur_min[2], blur_min[2], blur_min[0], blur_max[0] )); if (h[7]) h[7]->SetVector( Vector4((float)m_nTexSizeX, (float)m_nTexSizeY, 1.0f/(float)m_nTexSizeX, 1.0f/(float)m_nTexSizeY )); if (h[8]) h[8]->SetVector( Vector4( 0.5f+0.5f*cosf(time* 0.329f+1.2f), 0.5f+0.5f*cosf(time* 1.293f+3.9f), 0.5f+0.5f*cosf(time* 5.070f+2.5f), 0.5f+0.5f*cosf(time*20.051f+5.4f) )); if (h[9]) h[9]->SetVector( Vector4( 0.5f+0.5f*sinf(time* 0.329f+1.2f), 0.5f+0.5f*sinf(time* 1.293f+3.9f), 0.5f+0.5f*sinf(time* 5.070f+2.5f), 0.5f+0.5f*sinf(time*20.051f+5.4f) )); if (h[10]) h[10]->SetVector( Vector4( 0.5f+0.5f*cosf(time*0.0050f+2.7f), 0.5f+0.5f*cosf(time*0.0085f+5.3f), 0.5f+0.5f*cosf(time*0.0133f+4.5f), 0.5f+0.5f*cosf(time*0.0217f+3.8f) )); if (h[11]) h[11]->SetVector( Vector4( 0.5f+0.5f*sinf(time*0.0050f+2.7f), 0.5f+0.5f*sinf(time*0.0085f+5.3f), 0.5f+0.5f*sinf(time*0.0133f+4.5f), 0.5f+0.5f*sinf(time*0.0217f+3.8f) )); if (h[12]) h[12]->SetVector( Vector4( mip_x, mip_y, mip_avg, 0 )); if (h[13]) h[13]->SetVector( Vector4( blur_min[1], blur_max[1], blur_min[2], blur_max[2] )); // write q vars int num_q_float4s = sizeof(p->q_const_handles)/sizeof(p->q_const_handles[0]); for (int i=0; i<num_q_float4s; i++) { if (p->q_const_handles[i]) p->q_const_handles[i]->SetVector( Vector4( (float)pState->var_pf_q[i*4+0], (float)pState->var_pf_q[i*4+1], (float)pState->var_pf_q[i*4+2], (float)pState->var_pf_q[i*4+3] )); } // write matrices for (int i=0; i<20; i++) { if (p->rot_mat[i]) { Matrix44 mx,my,mz,mxlate,temp; mx = MatrixRotationX(pState->m_rot_base[i].x + pState->m_rot_speed[i].x*time); my = MatrixRotationY(pState->m_rot_base[i].y + pState->m_rot_speed[i].y*time); mz = MatrixRotationZ(pState->m_rot_base[i].z + pState->m_rot_speed[i].z*time); mxlate = MatrixTranslation(pState->m_xlate[i]); temp = MatrixMultiply(mx, mxlate); temp = MatrixMultiply(temp, mz); temp = MatrixMultiply(temp, my); p->rot_mat[i]->SetMatrix(temp); } } // the last 4 are totally random, each frame for (int i=20; i<24; i++) { if (p->rot_mat[i]) { Matrix44 mx,my,mz,mxlate,temp; mx = MatrixRotationX(FRAND * 6.28f); my = MatrixRotationY(FRAND * 6.28f); mz = MatrixRotationZ(FRAND * 6.28f); mxlate = MatrixTranslation(FRAND, FRAND, FRAND); temp = MatrixMultiply(mx, mxlate); temp = MatrixMultiply(temp, mz); temp = MatrixMultiply(temp, my); p->rot_mat[i]->SetMatrix(temp); } } } void CPlugin::ShowToUser_NoShaders()//int bRedraw, int nPassOverride) { // note: this one has to draw the whole screen! (one big quad) SetFixedShader(m_lpVS[1]); float fZoom = 1.0f; Vertex v3[4]; memset(v3, 0, sizeof(v3)); // extend the poly we draw by 1 pixel around the viewable image area, // in case the video card wraps u/v coords with a +0.5-texel offset // (otherwise, a 1-pixel-wide line of the image would wrap at the top and left edges). v3[0].x = -1.0f; v3[1].x = 1.0f; v3[2].x = -1.0f; v3[3].x = 1.0f; v3[0].y = 1.0f; v3[1].y = 1.0f; v3[2].y = -1.0f; v3[3].y = -1.0f; //float aspect = GetWidth() / (float)(GetHeight()/(ASPECT)/**4.0f/3.0f*/); float aspect = GetWidth() / (float)(GetHeight()*m_fInvAspectY/**4.0f/3.0f*/); float x_aspect_mult = 1.0f; float y_aspect_mult = 1.0f; if (aspect>1) y_aspect_mult = aspect; else x_aspect_mult = 1.0f/aspect; for (int n=0; n<4; n++) { v3[n].x *= x_aspect_mult; v3[n].y *= y_aspect_mult; } { float shade[4][3] = { { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f } }; // for each vertex, then each comp. float fShaderAmount = m_pState->m_fShader.eval(GetTime()); if (fShaderAmount > 0.001f) { for (int i=0; i<4; i++) { shade[i][0] = 0.6f + 0.3f*sinf(GetTime()*30.0f*0.0143f + 3 + i*21 + m_fRandStart[3]); shade[i][1] = 0.6f + 0.3f*sinf(GetTime()*30.0f*0.0107f + 1 + i*13 + m_fRandStart[1]); shade[i][2] = 0.6f + 0.3f*sinf(GetTime()*30.0f*0.0129f + 6 + i*9 + m_fRandStart[2]); float max = ((shade[i][0] > shade[i][1]) ? shade[i][0] : shade[i][1]); if (shade[i][2] > max) max = shade[i][2]; for (int k=0; k<3; k++) { shade[i][k] /= max; shade[i][k] = 0.5f + 0.5f*shade[i][k]; } for (int k=0; k<3; k++) { shade[i][k] = shade[i][k]*(fShaderAmount) + 1.0f*(1.0f - fShaderAmount); } v3[i].Diffuse = COLOR_RGBA_01(shade[i][0],shade[i][1],shade[i][2],1); } } float fVideoEchoZoom = (float)(m_pState->var_pf_echo_zoom);//m_pState->m_fVideoEchoZoom.eval(GetTime()); float fVideoEchoAlpha = (float)(m_pState->var_pf_echo_alpha);//m_pState->m_fVideoEchoAlpha.eval(GetTime()); int nVideoEchoOrientation = (int) (m_pState->var_pf_echo_orient) % 4;//m_pState->m_nVideoEchoOrientation; float fGammaAdj = (float)(m_pState->var_pf_gamma);//m_pState->m_fGammaAdj.eval(GetTime()); if (m_bBlending && m_pState->m_fVideoEchoAlpha.eval(GetTime()) > 0.01f && m_pState->m_fVideoEchoAlphaOld > 0.01f && m_pState->m_nVideoEchoOrientation != m_pState->m_nVideoEchoOrientationOld) { if (m_fBlendProgress < m_fSnapPoint) { nVideoEchoOrientation = m_pState->m_nVideoEchoOrientationOld; fVideoEchoAlpha *= 1.0f - 2.0f*CosineInterp(m_fBlendProgress); } else { fVideoEchoAlpha *= 2.0f*CosineInterp(m_fBlendProgress) - 1.0f; } } if (fVideoEchoAlpha > 0.001f) { // video echo m_context->SetBlendDisable(); for (int i=0; i<2; i++) { fZoom = (i==0) ? 1.0f : fVideoEchoZoom; float temp_lo = 0.5f - 0.5f/fZoom; float temp_hi = 0.5f + 0.5f/fZoom; v3[0].tu = temp_lo; v3[0].tv = temp_hi; v3[1].tu = temp_hi; v3[1].tv = temp_hi; v3[2].tu = temp_lo; v3[2].tv = temp_lo; v3[3].tu = temp_hi; v3[3].tv = temp_lo; // flipping if (i==1) { for (int j=0; j<4; j++) { if (nVideoEchoOrientation % 2) v3[j].tu = 1.0f - v3[j].tu; if (nVideoEchoOrientation >= 2) v3[j].tv = 1.0f - v3[j].tv; } } float mix = (i==1) ? fVideoEchoAlpha : 1.0f - fVideoEchoAlpha; for (int k=0; k<4; k++) v3[k].Diffuse = COLOR_RGBA_01(mix*shade[k][0],mix*shade[k][1],mix*shade[k][2],1); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); if (i==0) { m_context->SetBlend(BLEND_ONE, BLEND_ONE); } if (fGammaAdj > 0.001f) { // draw layer 'i' a 2nd (or 3rd, or 4th...) time, additively int nRedraws = (int)(fGammaAdj - 0.0001f); float gamma; for (int nRedraw=0; nRedraw < nRedraws; nRedraw++) { if (nRedraw == nRedraws-1) gamma = fGammaAdj - (int)(fGammaAdj - 0.0001f); else gamma = 1.0f; for (int k=0; k<4; k++) v3[k].Diffuse = COLOR_RGBA_01(gamma*mix*shade[k][0],gamma*mix*shade[k][1],gamma*mix*shade[k][2],1); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); } } } } else { // no video echo v3[0].tu = 0; v3[1].tu = 1; v3[2].tu = 0; v3[3].tu = 1; v3[0].tv = 1; v3[1].tv = 1; v3[2].tv = 0; v3[3].tv = 0; m_context->SetBlendDisable(); // draw it iteratively, solid the first time, and additively after that int nPasses = (int)(fGammaAdj - 0.001f) + 1; float gamma; for (int nPass=0; nPass < nPasses; nPass++) { if (nPass == nPasses - 1) gamma = fGammaAdj - (float)nPass; else gamma = 1.0f; for (int k=0; k<4; k++) v3[k].Diffuse = COLOR_RGBA_01(gamma*shade[k][0],gamma*shade[k][1],gamma*shade[k][2],1); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); if (nPass==0) { m_context->SetBlend(BLEND_ONE, BLEND_ONE); } } } Vertex v3[4]; memset(v3, 0, sizeof(v3)); v3[0].x = -1.0f; v3[1].x = 1.0f; v3[2].x = -1.0f; v3[3].x = 1.0f; v3[0].y = 1.0f; v3[1].y = 1.0f; v3[2].y = -1.0f; v3[3].y = -1.0f; for (int i=0; i<4; i++) v3[i].Diffuse = COLOR_RGBA_01(1,1,1,1); if (m_pState->var_pf_brighten) { // square root filter SetFixedShader(nullptr); // first, a perfect invert m_context->SetBlend(BLEND_INVDESTCOLOR, BLEND_ZERO); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); // then modulate by self (square it) m_context->SetBlend(BLEND_ZERO, BLEND_DESTCOLOR); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); // then another perfect invert m_context->SetBlend(BLEND_INVDESTCOLOR, BLEND_ZERO); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); } if (m_pState->var_pf_darken) { // squaring filter SetFixedShader(nullptr); m_context->SetBlend(BLEND_ZERO, BLEND_DESTCOLOR); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); } if (m_pState->var_pf_solarize) { SetFixedShader(nullptr); m_context->SetBlend(BLEND_ZERO, BLEND_INVDESTCOLOR); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); m_context->SetBlend(BLEND_DESTCOLOR, BLEND_ONE); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); } if (m_pState->var_pf_invert) { SetFixedShader(nullptr); m_context->SetBlend(BLEND_INVDESTCOLOR, BLEND_ZERO); m_context->DrawArrays(PRIMTYPE_TRIANGLESTRIP, 4, v3); } m_context->SetBlendDisable(); } } void CPlugin::ShowToUser_Shaders(int nPass, bool bAlphaBlend, bool bFlipAlpha)//int bRedraw, int nPassOverride, bool bFlipAlpha) { //SetFixedShader(nullptr); //m_context->SetBlendDisable(); // float fZoom = 1.0f; float aspect = GetWidth() / (float)(GetHeight()*m_fInvAspectY/**4.0f/3.0f*/); float x_aspect_mult = 1.0f; float y_aspect_mult = 1.0f; if (aspect>1) y_aspect_mult = aspect; else x_aspect_mult = 1.0f/aspect; // hue shader float shade[4][3] = { { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f } }; // for each vertex, then each comp. float fShaderAmount = 1;//since we don't know if shader uses it or not! m_pState->m_fShader.eval(GetTime()); if (fShaderAmount > 0.001f || m_bBlending) { // pick 4 colors for the 4 corners for (int i=0; i<4; i++) { shade[i][0] = 0.6f + 0.3f*sinf(GetTime()*30.0f*0.0143f + 3 + i*21 + m_fRandStart[3]); shade[i][1] = 0.6f + 0.3f*sinf(GetTime()*30.0f*0.0107f + 1 + i*13 + m_fRandStart[1]); shade[i][2] = 0.6f + 0.3f*sinf(GetTime()*30.0f*0.0129f + 6 + i*9 + m_fRandStart[2]); float max = ((shade[i][0] > shade[i][1]) ? shade[i][0] : shade[i][1]); if (shade[i][2] > max) max = shade[i][2]; for (int k=0; k<3; k++) { shade[i][k] /= max; shade[i][k] = 0.5f + 0.5f*shade[i][k]; } // note: we now pass the raw hue shader colors down; the shader can only use a certain % if it wants. //for (k=0; k<3; k++) // shade[i][k] = shade[i][k]*(fShaderAmount) + 1.0f*(1.0f - fShaderAmount); //m_comp_verts[i].Diffuse = COLOR_RGBA_01(shade[i][0],shade[i][1],shade[i][2],1); } // interpolate the 4 colors & apply to all the verts for (int j=0; j<FCGSY; j++) { for (int i=0; i<FCGSX; i++) { Vertex* p = &m_comp_verts[i + j*FCGSX]; float x = p->x*0.5f + 0.5f; float y = p->y*0.5f + 0.5f; float col[3] = { 1, 1, 1 }; if (fShaderAmount > 0.001f) { for (int c=0; c<3; c++) col[c] = shade[0][c]*( x)*( y) + shade[1][c]*(1-x)*( y) + shade[2][c]*( x)*(1-y) + shade[3][c]*(1-x)*(1-y); } // TO DO: improve interp here? // TO DO: during blend, only send the triangles needed // if blending, also set up the alpha values - pull them from the alphas used for the Warped Blit double alpha = 1; if (m_bBlending) { x *= (m_nGridX + 1); y *= (m_nGridY + 1); x = std::max(std::min(x,(float)m_nGridX-1),0.0f); y = std::max(std::min(y,(float)m_nGridY-1),0.0f); int nx = (int)x; int ny = (int)y; double dx = x - nx; double dy = y - ny; double alpha00 = (m_verts[(ny )*(m_nGridX+1) + (nx )].Diffuse >> 24); double alpha01 = (m_verts[(ny )*(m_nGridX+1) + (nx+1)].Diffuse >> 24); double alpha10 = (m_verts[(ny+1)*(m_nGridX+1) + (nx )].Diffuse >> 24); double alpha11 = (m_verts[(ny+1)*(m_nGridX+1) + (nx+1)].Diffuse >> 24); alpha = alpha00*(1-dx)*(1-dy) + alpha01*( dx)*(1-dy) + alpha10*(1-dx)*( dy) + alpha11*( dx)*( dy); alpha /= 255.0f; //if (bFlipAlpha) // alpha = 1-alpha; //alpha = (m_verts[y*(m_nGridX+1) + x].Diffuse >> 24) / 255.0f; } p->Diffuse = COLOR_RGBA_01(col[0],col[1],col[2],alpha); } } } if (bAlphaBlend) { if (bFlipAlpha) { m_context->SetBlend(BLEND_INVSRCALPHA, BLEND_SRCALPHA); } else { m_context->SetBlend(BLEND_SRCALPHA, BLEND_INVSRCALPHA); } } else m_context->SetBlendDisable(); // Now do the final composite blit, fullscreen; // or do it twice, alpha-blending, if we're blending between two sets of shaders. int pass = nPass; { // PASS 0: draw using *blended per-vertex motion vectors*, but with the OLD comp shader. // PASS 1: draw using *blended per-vertex motion vectors*, but with the NEW comp shader. CStatePtr state = (pass==0) ? m_pOldState : m_pState; ApplyShaderParams(state->m_shader_comp, state ); // Hurl the triangles at the video card. // We're going to un-index it, so that we don't stress any crappy (AHEM intel g33) // drivers out there. Not a big deal - only ~800 polys / 24kb of data. // If we're blending, we'll skip any polygon that is all alpha-blended out. // This also respects the MaxPrimCount limit of the video card. m_context->UploadIndexData(m_comp_indices); m_context->UploadVertexData(m_comp_verts); m_context->DrawIndexed(PRIMTYPE_TRIANGLELIST, 0, (int)m_comp_indices.size() ); } m_context->SetBlendDisable(); SetFixedShader(nullptr); }
// // Created by twome on 10/05/2020. // #ifndef GAMEOFLIFE_OPENGL_TEXTUREMANAGER_H #define GAMEOFLIFE_OPENGL_TEXTUREMANAGER_H #include <string> #include <map> #include "Texture.h" class TextureManager { private: static std::map<std::string, Texture> textures; public: static Texture *load(std::string id); }; #endif //GAMEOFLIFE_OPENGL_TEXTUREMANAGER_H
#include <iostream> #include <set> #include <vector> #include <map> #include <algorithm> #include <sstream> using namespace std; template <class T> vector<T> input_split() { cin >> ws; string line; getline(cin, line); stringstream ss(line); T buf; vector<T> tokens; while (ss >> buf) tokens.push_back(buf); return tokens; } template <class T> void print(vector<T> v) { cout << "["; for (auto it=v.begin(); it!=v.end();) { cout << *it; if (++it != v.end()) cout << ", "; } cout << "]\n"; } int main() { int n; cin >> n; map<string,vector<string>> data; for (int i = 0; i < n; i++){ vector<string> data_split; data_split = input_split<string>(); vector<string> data_2_to_end; for ( unsigned i = 1; i < data_split.size(); i++ ){ data_2_to_end.push_back(data_split[i]); } data[data_split[0]] = data_2_to_end; } vector<string> f; f = input_split<string>(); vector<vector<string>> out; for (auto k : data){ bool is_subset = true; for (string c : f){ if (find(k.second.begin(), k.second.end(), c) == k.second.end()){ is_subset = false; break; } } if (is_subset == true){ vector<string> temp; temp.push_back(k.first); for (auto e : k.second){ temp.push_back(e); } out.push_back(temp); } } if ( out.size() == 0 ){ cout << "Not Found" << "\n"; } else { sort(out.begin(), out.end()); for (auto c1 : out){ for (auto c2 : c1 ){ cout << c2 << " "; } cout << "\n"; } } return 0; }
#include <iostream> #include "freckle/capp.h" using namespace std; int main() { CApp app; cout << "Game ON! :D" << endl; return app.onExecute(); }
#include <iostream> #include <fstream> #include <sstream> int main(int argc, char **argv) { if (argc != 2) { return 0; } std::ifstream f(argv[1]); // first argument is the test file while (true) { std::string line; std::getline(f, line); if (f.fail()) { break; } size_t n1 = line.find_last_of(' '); std::string s = line.substr(0, n1); size_t n2 = s.find_last_of(' '); if (n2 == std::string::npos) { std::cout << s << '\n'; } else { std::cout << s.substr(n2+1) << '\n'; } } return 0; }
#ifndef GPURESOURCE_H_ #define GPURESOURCE_H_ #include "Types.h" #include <GL/glew.h> #include "GpuException.h" #include "Log.h" namespace revel { namespace renderer { class GpuObject { public: GpuObject(); virtual ~GpuObject(); u32 get_id() const; bool is_valid() const; protected: u32 m_Identifier; }; } // ::revel::renderer } // ::revel #endif // GPURESOURCE_H_
/** * author : Wang Shaotong * email : wangshaotongsydemon@gmail.com * date : 2020-04-26 * * id : poj 1328 * name : Radar Installation * url : http://poj.org/problem?id=1328 * level : 1 * tag : 贪心 */ #include <cmath> #include <vector> #include <iostream> #include <algorithm> using namespace std; vector<pair<double, double> > v; bool cmp(pair<double, double> p1, pair<double, double> p2) { return p1.first < p2.first; } int main() { int n, d, t = 0; while (cin >> n >> d && (n != 0 || d != 0)) { t++; v.clear(); for (int i = 0; i < n; i++) { int a, b; double len; pair<double, double> temp; cin >> a >> b; if (b <= d) { len = sqrt(1.0 * d * d - b * b); temp.first = a - len; temp.second = a + len; v.push_back(temp); } } cout << "Case " << t << ": "; if (v.size() != n) { cout << "-1" << endl; } else { sort(v.begin(), v.end(), cmp); int ans = 1; double cur = v.begin()->second; for (vector<pair<double, double> >::iterator it = v.begin(); it != v.end(); it++) { if (cur < it->first) { ans++; cur = it->second; } else { cur = min(cur, it->second); } } cout << ans << endl; } } return 0; }
vector<vector<int>> v; int st=-1; for(int i=0;i<n;i++) { int flag=-1; if(i==0 && A[i]<A[i+1])flag=0; else if(i>0 && i<n && A[i]>=A[i+1] && A[i]>A[i-1])flag=1; else if(i>0 && i<n && A[i]<=A[i-1] && A[i]<A[i+1])flag=0; else if(i==n-1 && A[i]>A[i-1])flag=1; if(flag==0) { st=i; } else if(flag==1) { vector<int> temp; temp.push_back(st); temp.push_back(i); v.push_back(temp); st=-1; } } return v;
#include "i2c_master.h" void I2C_Master::init() { RCC->AHBENR |= RCC_AHBENR_GPIOBEN_Msk; GPIOB->MODER &= ~GPIO_MODER_MODER8_0; GPIOB->MODER |= GPIO_MODER_MODER8_1; GPIOB->OTYPER |= GPIO_OTYPER_OT_8; GPIOB->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR8_Msk; GPIOB->PUPDR &= ~GPIO_PUPDR_PUPDR8_Msk; GPIOB->MODER &= ~GPIO_MODER_MODER9_0; GPIOB->MODER |= GPIO_MODER_MODER9_1; GPIOB->OTYPER |= GPIO_OTYPER_OT_9; GPIOB->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR9_Msk; GPIOB->PUPDR &= ~GPIO_PUPDR_PUPDR9_Msk; GPIOB->AFR[1] = GPIOB->AFR[1] & ~GPIO_AFRH_AFSEL8 | (4UL << GPIO_AFRH_AFSEL8_Pos); GPIOB->AFR[1] = GPIOB->AFR[1] & ~GPIO_AFRH_AFSEL9 | (4UL << GPIO_AFRH_AFSEL9_Pos); RCC->APB1ENR |= RCC_APB1ENR_I2C1EN_Msk; I2C1->CR2 |= I2C_CR2_ITEVTEN_Msk | I2C_CR2_ITERREN_Msk | I2C_CR2_ITBUFEN_Msk | 0x02; I2C1->CCR = 0x50; //I2C Frequenz = 100kHz I2C1->TRISE = 0x65; //Berechnung: siehe Datasheet I2C1->CR1 |= I2C_CR1_PE_Msk; } void I2C_Master::write(uint8_t addr, uint8_t* data, uint32_t len, bool repeated_start) { uint32_t sr1 = 0; uint32_t sr2 = 0; uint32_t i = 0; I2C1->CR1 |= I2C_CR1_START_Msk; while(!(I2C1->SR1 & I2C_SR1_SB_Msk)); I2C1->DR = addr << 1; while(!(I2C1->SR1 & I2C_SR1_ADDR_Msk)); sr2 = I2C1->SR2; while(i++ < len) { I2C1->DR = data[i - 1]; while(!(I2C1->SR1 & I2C_SR1_TXE_Msk)); if(I2C1->SR1 & I2C_SR1_BTF_Msk) { I2C1->DR; } } if(repeated_start) { I2C1->CR1 |= I2C_CR1_START_Msk; while(!(I2C1->SR1 & I2C_SR1_SB_Msk)); } else { I2C1->CR1 |= I2C_CR1_STOP_Msk; } } void I2C_Master::read(uint8_t addr, uint8_t* data, uint32_t len, bool stop_cond) { uint32_t sr1 = 0; uint32_t sr2 = 0; uint32_t i = 0; if(len > 1) { I2C1->CR1 |= I2C_CR1_ACK_Msk; } else { I2C1->CR1 &= ~I2C_CR1_ACK_Msk; } if(!stop_cond) { I2C1->CR1 |= I2C_CR1_START_Msk; } while(!(I2C1->SR1 & I2C_SR1_SB_Msk)); I2C1->DR = addr << 1 | 1; while(!(I2C1->SR1 & I2C_SR1_ADDR_Msk)); I2C1->SR1; I2C1->SR2; while(i++ < len) { while(!(I2C1->SR1 & I2C_SR1_RXNE_Msk)); if(i == len - 1) { I2C1->CR1 &= ~I2C_CR1_ACK_Msk; } data[i - 1] = I2C1->DR; if(I2C1->SR1 & I2C_SR1_BTF_Msk) { I2C1->DR; } } if(stop_cond) { I2C1->CR1 |= I2C_CR1_STOP_Msk; } }
/*************************************************************************** Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. 2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD FileName: MyAssert.h Description: Provide a assert class in C++ or some assert Macroes in C. Comment: copy from Darwin Streaming Server 5.5.5 Author: taoyunxing@dadimedia.com Version: v1.0.0.1 CreateDate: 2010-08-16 LastUpdate: 2010-08-19 ****************************************************************************/ #ifndef _MYASSERT_H_ #define _MYASSERT_H_ #include <stdio.h> #include "SafeStdLib.h" #ifdef __cplusplus class AssertLogger { public: // An interface so the MyAssert function can write a message virtual void LogAssert(char* inMessage) = 0; virtual ~AssertLogger(){} }; // If a logger is provided, asserts will be logged. Otherwise, asserts will cause a bus error void SetAssertLogger(AssertLogger* theLogger); #endif #if ASSERT void MyAssert(char *s); #define kAssertBuffSize 256 #define Assert(condition) { \ \ if (!(condition)) \ { \ char s[kAssertBuffSize]; \ s[kAssertBuffSize -1] = 0; \ qtss_snprintf (s,kAssertBuffSize -1, "_Assert: %s, %d",__FILE__, __LINE__ ); \ MyAssert(s); \ } } #define AssertV(condition,errNo) { \ if (!(condition)) \ { \ char s[kAssertBuffSize]; \ s[kAssertBuffSize -1] = 0; \ qtss_snprintf( s,kAssertBuffSize -1, "_AssertV: %s, %d (%d)",__FILE__, __LINE__, errNo ); \ MyAssert(s); \ } } #define Warn(condition) { \ if (!(condition)) \ qtss_printf( "_Warn: %s, %d\n",__FILE__, __LINE__ ); } #define WarnV(condition,msg) { \ if (!(condition)) \ qtss_printf ("_WarnV: %s, %d (%s)\n",__FILE__, __LINE__, msg ); } #define WarnVE(condition,msg,err) { \ if (!(condition)) \ { char buffer[kAssertBuffSize]; \ buffer[kAssertBuffSize -1] = 0; \ qtss_printf ("_WarnV: %s, %d (%s, %s [err=%d])\n",__FILE__, __LINE__, msg, qtss_strerror(err,buffer,sizeof(buffer) -1), err ); \ } } #else #define Assert(condition) ((void) 0) #define AssertV(condition,errNo) ((void) 0) #define Warn(condition) ((void) 0) #define WarnV(condition,msg) ((void) 0) #endif #endif //_MY_ASSERT_H_
/* How to pass outer scope elements inside lambda functions Case 1: Using [=] [=](int &x) { // All outer scope elements has been passed by value } Case 2: Using [&] [&](int &x) { // All outer scope elements has been passed by reference } $g++ -o lambda_func lambda_func.cpp --std=c++11 */ #include <iostream> #include <algorithm> int main() { int arr[] = { 1, 2, 3, 4, 5 }; int mul = 5; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [&](int x) { std::cout<<x<<" "; // Can modify the mul inside this lambda function because // all outer scope elements has write access here. mul = 3; }); std::cout << std::endl; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [=](int &x) { x= x*mul; // Can not modify the mul inside this lambda function because // all outer scope elements has read only access here. // mul = 9; }); std::cout << std::endl; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) { // No access to mul inside this lambda function because // all outer scope elements are not visible here. //std::cout<<mul<<" "; }); std::cout << std::endl; }
#include "AssetTreeHandler.h" Ui::AssetTreeHandler::AssetTreeHandler() { } void Ui::AssetTreeHandler::AddSubCategories(QTreeWidgetItem * topLevel) { QTreeWidgetItem* brick = new QTreeWidgetItem(); brick->setText(0, "Bricks"); brick->setTextAlignment(0, Qt::AlignCenter); topLevel->addChild(brick); topLevel->insertChild(BRICK, brick); QTreeWidgetItem* stone = new QTreeWidgetItem(); stone->setText(0, "Stones"); stone->setTextAlignment(0, Qt::AlignCenter); topLevel->addChild(stone); topLevel->insertChild(STONE, stone); QTreeWidgetItem* plaster = new QTreeWidgetItem(); plaster->setText(0, "Plaster"); plaster->setTextAlignment(0, Qt::AlignCenter); topLevel->addChild(plaster); topLevel->insertChild(PLASTER, plaster); QTreeWidgetItem* iron = new QTreeWidgetItem(); iron->setText(0, "Iron"); iron->setTextAlignment(0, Qt::AlignCenter); topLevel->addChild(iron); topLevel->insertChild(IRON, iron); } bool Ui::AssetTreeHandler::IsValidItem() { if (m_tree->currentItem()->parent() == NULL) //If a category window is clicked return false; if (m_tree->currentItem()->text(0) == QString("Bricks")) return false; if (m_tree->currentItem()->text(0) == QString("Stones")) return false; if (m_tree->currentItem()->text(0) == QString("Plaster")) return false; if (m_tree->currentItem()->text(0) == QString("Iron")) return false; return true; } Ui::AssetTreeHandler::AssetTreeHandler(QTreeWidget * tree) { /*Defining m_tree and disabling sorting for manual sorting*/ this->m_tree = tree; m_tree->setSortingEnabled(false); /*Creating the "General Assets" tab*/ QTreeWidgetItem* g_Assets = new QTreeWidgetItem(tree); g_Assets->setText(0, "General Assets"); g_Assets->setTextAlignment(0, Qt::AlignCenter); m_tree->addTopLevelItem(g_Assets); m_tree->insertTopLevelItem(GENERAL_ASSETS, g_Assets); /*Creating the "Floors" tab also adding subcategories to this category*/ QTreeWidgetItem* floors = new QTreeWidgetItem(tree); floors->setText(0, "Floors"); floors->setTextAlignment(0, Qt::AlignCenter); this->AddSubCategories(floors); m_tree->addTopLevelItem(floors); m_tree->insertTopLevelItem(FLOORS, floors); m_tree->setHeaderLabels(QStringList() << "Resources"); /*Creating the "Ceilings" tab also adding subcategories to this category*/ QTreeWidgetItem* ceilings = new QTreeWidgetItem(tree); ceilings->setText(0, "Ceilings"); ceilings->setTextAlignment(0, Qt::AlignCenter); this->AddSubCategories(ceilings); m_tree->addTopLevelItem(ceilings); m_tree->insertTopLevelItem(CEILINGS, ceilings); /*Creating the "Walls" tab also adding subcategories to this category*/ QTreeWidgetItem* walls = new QTreeWidgetItem(tree); walls->setText(0, "Walls"); walls->setTextAlignment(0, Qt::AlignCenter); this->AddSubCategories(walls); m_tree->addTopLevelItem(walls); m_tree->insertTopLevelItem(WALLS, walls); /*Creating the "Interactable" tab*/ QTreeWidgetItem* interactable = new QTreeWidgetItem(tree); interactable->setText(0, "Interactable"); interactable->setTextAlignment(0, Qt::AlignCenter); m_tree->addTopLevelItem(interactable); m_tree->insertTopLevelItem(INTERACTABLE, interactable); /*connecting the doubleclicked signal to the "on_treeview_doubleclicked function*/ connect(m_tree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_treeView_doubleClicked())); } Ui::AssetTreeHandler::~AssetTreeHandler() { } bool Ui::AssetTreeHandler::AddItem(AssetCategories type, std::string name, QVariant itemData) { QTreeWidgetItem *itm = new QTreeWidgetItem(); itm->setData(0, Qt::ItemDataRole::UserRole, itemData); itm->setText(0, name.substr(0, name.rfind(".")).c_str()); m_tree->topLevelItem((int)type)->addChild(itm); return true; } bool Ui::AssetTreeHandler::AddItem(AssetCategories type, std::string name, QVariant itemData, AssetSubCategories subType) { QTreeWidgetItem *itm = new QTreeWidgetItem(); itm->setData(0, Qt::ItemDataRole::UserRole, itemData); itm->setText(0, name.substr(0, name.rfind(".")).c_str()); m_tree->topLevelItem((int)type)->child((int)subType)->addChild(itm); return true; } bool Ui::AssetTreeHandler::AddItem(AssetCategories type, QTreeWidgetItem * item) { m_tree->topLevelItem((int)type)->addChild(item); return true; } void Ui::AssetTreeHandler::on_treeView_doubleClicked() { //Qt::ItemFlag::ItemIsDropEnabled if (!this->IsValidItem()) return; //If a category window is clicked QModelIndex index = m_tree->currentIndex(); //use index.r to get the right mesh /*checking to see if the selected object is valid*/ if (!index.isValid()) return; int modelIndex = m_tree->currentItem()->data(0, Qt::ItemDataRole::UserRole).toInt(); std::vector<Resources::Model*>* test = DataHandler::GetInstance()->GetModels(); DirectX::XMVECTOR pos = { 0.0f,0.0f,0.0f }; DirectX::XMVECTOR rot = { 0.0f,0.0f,0.0f }; LevelHandler::GetInstance()->GetCurrentLevel()->AddModelEntity(test->at(modelIndex)->GetId(), pos, rot); //QFileInfo fileInfo = this->m_model->fileInfo(index); //QString filePath = fileInfo.filePath(); /*send the filepath to the importer*/ }
#include "boardpart.h" BoardPart::BoardPart(QGraphicsItem *parent) : QGraphicsObject(parent), color(Qt::lightGray), dragOver(false) { setAcceptDrops(true); } BoardPart::~BoardPart() { } void BoardPart::dragEnterEvent(QGraphicsSceneDragDropEvent *event) { if(event->mimeData()->hasColor()) { event->setAccepted(true); dragOver = true; update(); } else { event->setAccepted(false); } } void BoardPart::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) { Q_UNUSED(event); dragOver = false; update(); } void BoardPart::dropEvent(QGraphicsSceneDragDropEvent *event) { dragOver = false; if(event->mimeData()->hasColor()) { color = qvariant_cast<QColor>(event->mimeData()->colorData()); } update(); }
// // Created by wqy on 19-11-28. // #ifndef VERIFIER_VERTEX_H #define VERIFIER_VERTEX_H #include <string> #include <list> using std::string; using std::list; namespace esc { class Edge; class Vertex{ private: string name; //list<Edge*> nexts; public: Vertex() : name("") {} Vertex(string _name) : name(_name) {} string getName(){return this->name;} void setName(string _name); }; } #endif //VERIFIER_VERTEX_H
#include "ESPDevice.h" #include "EEPROMManager.h" #include <ESP8266WiFi.h> #include <DNSServer.h> #include "ESP8266mDNS.h" //defines - mapeamento de pinos do NodeMCU #define D0 16 #define D1 5 #define D2 4 #define D3 0 #define D4 2 #define D5 14 // WiFi Reset Button #define D6 12 // Antigo DebugManager #define D7 13 #define D8 15 #define D9 3 #define D10 1 #define HOST_NAME "remotedebug-sample" #define WEBAPI_HOST "192.168.1.12" #define WEBAPI_PORT 80 #define WEBAPI_URI "/ART.Domotica.WebApi/" struct config_t { String hardwaresInApplicationId; String hardwareId; } configuration; int configurationEEPROMAddr = 0; using namespace ART; ESPDevice espDevice(WEBAPI_HOST, WEBAPI_PORT, WEBAPI_URI); void setup() { Serial.begin(9600); // Buzzer pinMode(D6, OUTPUT); pinMode(D4, INPUT); pinMode(D5, INPUT); Serial.println("Iniciando..."); initConfiguration(); espDevice.begin(); String hostNameWifi = HOST_NAME; hostNameWifi.concat(".local"); if (MDNS.begin(HOST_NAME)) { Serial.print("* MDNS responder started. Hostname -> "); Serial.println(HOST_NAME); } WiFi.hostname(hostNameWifi); } void initConfiguration() { EEPROM_readAnything(0, configuration); //EEPROM_writeAnything(configurationEEPROMAddr, configuration); } void loop() { espDevice.loop(); DeviceInApplication* deviceInApplication = espDevice.getDeviceInApplication(); if (deviceInApplication->inApplication()) { loopInApplication(); } else{ espDevice.getDeviceDisplay()->getDeviceDisplayWiFiAccess()->loop(); } //keep-alive da comunicação com broker MQTT espDevice.getDeviceMQ()->loop(); //using include ESP8266WiFi.h the following core cmds work for me.. /*Serial.print(F("ESP.getBootMode(); ")); Serial.println(ESP.getBootMode()); Serial.print(F("ESP.getSdkVersion(); ")); Serial.println(ESP.getSdkVersion()); Serial.print(F("ESP.getBootVersion(); ")); Serial.println(ESP.getBootVersion()); Serial.print(F("ESP.getChipId(); ")); Serial.println(ESP.getChipId()); Serial.print(F("ESP.getFlashChipSize(); ")); Serial.println(ESP.getFlashChipSize()); Serial.print(F("ESP.getFlashChipRealSize(); ")); Serial.println(ESP.getFlashChipRealSize()); Serial.print(F("ESP.getFlashChipSizeByChipId(); ")); Serial.println(ESP.getFlashChipSizeByChipId()); Serial.print(F("ESP.getFlashChipId(); ")); Serial.println(ESP.getFlashChipId());*/ Serial.print(F("ESP.getFreeHeap(); ")); Serial.println(ESP.getFreeHeap()); } void loopInApplication() { espDevice.getDeviceDisplay()->display.clearDisplay(); espDevice.getDeviceNTP()->update(); if(espDevice.hasDeviceSensor()){ DeviceSensor* deviceSensor = espDevice.getDeviceSensor(); bool deviceSensorReaded = deviceSensor->read(); espDevice.getDeviceDisplay()->getDeviceDisplaySensor()->printUpdate(deviceSensorReaded); } // MQTT if(espDevice.getDeviceMQ()->connected()){ loopMQQTConnected(); } // Wifi espDevice.getDeviceDisplay()->getDeviceDisplayWiFi()->printSignal(); espDevice.getDeviceDisplay()->display.display(); } void loopMQQTConnected() { Serial.println(F("[loopMQQTConnected] begin")); espDevice.getDeviceDisplay()->getDeviceDisplayMQ()->printConnected(); espDevice.getDeviceDisplay()->getDeviceDisplayMQ()->printReceived(false); bool mqqtPrintSent = false; // Wifi DeviceWiFi* deviceWiFi = espDevice.getDeviceWiFi(); bool deviceWiFiPublished = deviceWiFi->publish(); if(deviceWiFiPublished){ mqqtPrintSent = true; } Serial.printf("deviceWiFi->publish: %s\n", deviceWiFiPublished ? "true" : "false"); // DeviceSerial if(espDevice.hasDeviceSerial()){ DeviceSerial* deviceSerial = espDevice.getDeviceSerial(); if (deviceSerial->initialized()) { } } // DeviceDebug if(espDevice.hasDeviceDebug()){ DeviceDebug* deviceDebug = espDevice.getDeviceDebug(); if (deviceDebug->initialized()) { } } // Sensor if(espDevice.hasDeviceSensor()){ DeviceSensor* deviceSensor = espDevice.getDeviceSensor(); if (deviceSensor->initialized()) { espDevice.getDeviceDisplay()->getDeviceDisplaySensor()->printSensors(); bool deviceSensorPublished = deviceSensor->publish(); if(deviceSensorPublished){ mqqtPrintSent = true; } Serial.printf("deviceSensor->publish: %s\n", deviceSensorPublished ? "true" : "false"); } } espDevice.getDeviceDisplay()->getDeviceDisplayMQ()->printSent(mqqtPrintSent); Serial.println(F("[loopMQQTConnected] end")); }
#ifndef WBPENULL_H #define WBPENULL_H #include "wbpe.h" class WBPENull : public WBPE { public: WBPENull(); virtual ~WBPENull(); DEFINE_WBPE_FACTORY( Null ); virtual void Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const; }; #endif // WBPENULL_H
/** * @file Factor.h * @brief Graph factor for iSAM. * @author Michael Kaess * @version $Id: Factor.h 7610 2012-10-25 10:21:12Z hordurj $ * * Copyright (C) 2009-2013 Massachusetts Institute of Technology. * Michael Kaess, Hordur Johannsson, David Rosen, * Nicholas Carlevaris-Bianco and John. J. Leonard * * This file is part of iSAM. * * iSAM is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * iSAM is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with iSAM. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #include <vector> #include <string> #include <math.h> // for sqrt #include <Eigen/Dense> #include "util.h" #include "Jacobian.h" #include "Element.h" #include "Node.h" #include "Noise.h" #include "numericalDiff.h" namespace isam { //typedef double (*cost_func_t)(double); // Factor of the graph of measurements between Nodes. class Factor : public Element, Function { friend std::ostream& operator<<(std::ostream& output, const Factor& e) { e.write(output); return output; } cost_func_t *ptr_cost_func; static int _next_id; bool _deleted; protected: const Noise _noise; std::vector<Node*> _nodes; // list of nodes affected by measurement public: virtual Eigen::VectorXd error(Selector s = ESTIMATE) const { Eigen::VectorXd err = _noise.sqrtinf() * basic_error(s); // optional modified cost function if (*ptr_cost_func) { for (int i=0; i<err.size(); i++) { double val = err(i); err(i) = ((val>=0)?1.:(-1.)) * sqrt((*ptr_cost_func)(val)); } } return err; } std::vector<Node*>& nodes() {return _nodes;} Factor(const char* name, int dim, const Noise& noise) : Element(name, dim), ptr_cost_func(NULL), _deleted(false), _noise(noise) { #ifndef NDEBUG // all lower triagular entries below the diagonal must be 0 for (int r=0; r<_noise.sqrtinf().rows(); r++) { for (int c=0; c<r; c++) { requireDebug(_noise.sqrtinf()(r,c)==0, "Factor::Factor: sqrtinf must be upper triangular!"); } } #endif _id = _next_id++; } virtual ~Factor() {} virtual void initialize() = 0; virtual void initialize_internal() { for (unsigned int i=0; i<_nodes.size(); i++) { _nodes[i]->add_factor(this); } initialize(); } virtual void set_cost_function(cost_func_t* ptr) {ptr_cost_func = ptr;} virtual Eigen::VectorXd basic_error(Selector s = ESTIMATE) const = 0; virtual const Eigen::MatrixXd& sqrtinf() const {return _noise.sqrtinf();} Eigen::VectorXd evaluate() const { return error(LINPOINT); } virtual Jacobian jacobian_internal(bool force_numerical) { if (force_numerical) { // ignore any symbolic derivative provided by user return Factor::jacobian(); } else { return jacobian(); } } // can be replaced by symbolic derivative by user virtual Jacobian jacobian() { Eigen::MatrixXd H = numerical_jacobian(); Eigen::VectorXd r = error(LINPOINT); Jacobian jac(r); int position = 0; int n_measure = dim(); for (unsigned int i=0; i<_nodes.size(); i++) { int n_var = _nodes[i]->dim(); Eigen::MatrixXd Hi = H.block(0, position, n_measure, n_var); position += n_var; jac.add_term(_nodes[i], Hi); } return jac; } int num_measurements() const { return dim(); } void mark_deleted() { _deleted = true; } bool deleted() const { return _deleted; } virtual void write(std::ostream &out) const { Element::write(out); for (unsigned int i=0; i<_nodes.size(); i++) { if (_nodes[i]) { out << " " << _nodes[i]->unique_id(); } } } private: virtual Eigen::MatrixXd numerical_jacobian() { return numericalDiff(*this); } }; /** * Convert upper triangular square root information matrix to string. * @param sqrtinf Upper triangular square matrix. */ inline std::string noise_to_string(const Noise& noise) { int nrows = noise.sqrtinf().rows(); int ncols = noise.sqrtinf().cols(); require(nrows==ncols, "slam2d::sqrtinf_to_string: matrix must be square"); std::stringstream s; s << "{"; bool first = true; for (int r=0; r<nrows; r++) { for (int c=r; c<ncols; c++) { if (first) { first = false; } else { s << ","; } s << noise.sqrtinf()(r,c); } } s << "}"; return s.str(); } // Generic template for easy instantiation(实例化) of new factors template <class T> class FactorT : public Factor { protected: const T _measure; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW FactorT(const char* name, int dim, const Noise& noise, const T& measure) : Factor(name, dim, noise), _measure(measure) {} const T& measurement() const {return _measure;} void write(std::ostream &out) const { Factor::write(out); out << " " << _measure << " " << noise_to_string(_noise); } }; }
/** * @brief Lab3: Geometry (part 2) * * In this lab we do some basic geometry stuff. * * @author Romain Maffina * @date 26.02.2016 * @file main.cpp */ #include "point.h" #include "segment.h" #include "geometrydrawing.h" #include <iostream> using namespace std; int main(void) { // create a new square drawing surface with default PPCM const size_t surface_side = 10; GeometryDrawing drawing(surface_side, surface_side); cout << "Lab3 - Geometry (part 2)" << endl; /* main part code */ // declare some geometry elements Segment s1(Point{6,5},Point{4,2}); Segment s2({2,3},{4,5}); Segment s3(1,6,4,7); cout << "s1 length=" << s1.length() << endl; // translate using offset x/y s1.translate(-0.5,-1); cout << "s1.a = " << s1.getA() << endl; // rotate given a rotation point and an offset angle in degrees s2.rotate(s2.getB(), 87); cout << "s2 is " << s2 << endl; // draw elements drawing.draw(s1); drawing.draw(s2); drawing.draw(s3); /* output */ drawing.saveToBmp("geometry.bmp"); return EXIT_SUCCESS; }
// // Utils.hpp // alfrid // // Created by Yi-Wen Lin on 2016/5/29. // // #ifndef Utils_hpp #define Utils_hpp #include <stdio.h> #include "cinder/gl/Texture.h" using namespace ci; using namespace std; namespace alfrid { class Utils { public: static gl::TextureRef createTexture(string); }; } #endif /* Utils_hpp */
#define NOMINMAX #include "ArchiveReader.h" #ifndef WIN32 #include "../external/minizip/zip.h" #include "../external/minizip/unzip.h" #include "../external/minizip/ioapi_mem.h" #endif #include "../external/lzma1801/C/7z.h" #include "../external/lzma1801/C/7zAlloc.h" #include "../external/lzma1801/C/7zFile.h" #include "../external/lzma1801/C/7zBuf.h" #include "../external/lzma1801/C/7zCrc.h" #include "../external/lzma1801/C/7zFile.h" #include "../external/lzma1801/C/7zVersion.h" #include "path.h" #include "platform.h" #include <stdint.h> #include <memory> #include <algorithm> namespace Archive { #ifndef WIN32 class ZipReader : public ArchiveReader { private: std::vector<uint8_t> _archiveData; zlib_filefunc_def _filefunc = {}; ourmemory_t _memory = {}; zipFile _zf = {}; unz_file_info64 _file_info = {}; bool _firstFile = true; public: ZipReader() { } virtual ~ZipReader() { if (_zf) unzClose(_zf); } bool OpenArchive(std::string path) { if (!FileReadAllBytes(path, _archiveData)) { return false; } // setup memory stream _memory.base = (char *)_archiveData.data(); _memory.size = (uLong)_archiveData.size(); _memory.limit = _memory.size ; _memory.cur_offset = 0; _memory.grow = 0; fill_memory_filefunc(&_filefunc, &_memory); _zf = unzOpen2(path.c_str(), &_filefunc); if (!_zf) return false; return true; } virtual void Rewind() override { _firstFile = true; } virtual bool NextFile(ArchiveFileInfo &fi) override { char buffer[4096]; buffer[0] = 0; int result; if (_firstFile) { result = unzGoToFirstFile2 (_zf, &_file_info, buffer, sizeof(buffer), NULL, 0, NULL, 0 ); _firstFile = false; } else { result = unzGoToNextFile2 (_zf, &_file_info, buffer, sizeof(buffer), NULL, 0, NULL, 0 ); } if (result != UNZ_OK) return false; fi.name = buffer; fi.compressedSize = _file_info.compressed_size; fi.uncompressedSize = _file_info.uncompressed_size; fi.is_directory = !fi.name.empty() && fi.name.back() == '/'; return true; } virtual bool ExtractBinary(std::vector<uint8_t> &buffer) override { int err = unzOpenCurrentFile(_zf); if (err != UNZ_OK) { return false; } buffer.resize( _file_info.uncompressed_size ); int read = unzReadCurrentFile(_zf, buffer.data(), (unsigned int)buffer.size()); if (read != buffer.size()) { return false; } unzCloseCurrentFile(_zf); return true; } }; #endif static const ISzAlloc g_Alloc = { SzAlloc, SzFree }; class SevenZipReader : public ArchiveReader { public: struct MemoryLookInStream : public ILookInStream { std::vector<uint8_t> _data; size_t _offset = 0; size_t _length = 0; MemoryLookInStream() { Look = MemoryLookInStream::DoLook; Skip = MemoryLookInStream::DoSkip; Read = MemoryLookInStream::DoRead; Seek = MemoryLookInStream::DoSeek; } SRes DoRead(void *buf, size_t *size) { if (_offset >= _length) { return SZ_ERROR_READ; } auto avail = _length - _offset; *size = std::min(avail, *size); memcpy( ((uint8_t *)buf), &_data[_offset], *size ); return SZ_OK; } SRes DoSeek(Int64 *pos, ESzSeek origin) { switch (origin) { case SZ_SEEK_SET: _offset = (size_t)*pos; break; case SZ_SEEK_CUR: _offset += (size_t)*pos; break; case SZ_SEEK_END: _offset = (size_t)(_length - *pos); break; } *pos = _offset; return SZ_OK; } SRes DoLook(const void **buf, size_t *size) { auto avail = _length - _offset; *buf = &_data[_offset]; *size = std::min(avail, *size); return SZ_OK; } SRes DoSkip(size_t offset) { _offset += offset; return SZ_OK; } static SRes DoLook(const ILookInStream *pp, const void **buf, size_t *size) { return ((MemoryLookInStream *)(pp))->DoLook(buf, size); } static SRes DoSkip(const ILookInStream *pp, size_t offset) { return ((MemoryLookInStream *)(pp))->DoSkip(offset); } static SRes DoRead(const ILookInStream *pp, void *buf, size_t *size) { return ((MemoryLookInStream *)(pp))->DoRead(buf, size); } static SRes DoSeek(const ILookInStream *pp, Int64 *pos, ESzSeek origin) { return ((MemoryLookInStream *)(pp))->DoSeek(pos, origin); } }; SevenZipReader() { _db.NumFiles = 0; } virtual ~SevenZipReader() { if (_outBuffer) { ISzAlloc_Free(&_allocImp, _outBuffer); } SzArEx_Free(&_db, &_allocImp); } bool OpenArchive(std::string path) { if (!FileReadAllBytes(path, _lookStream._data)) { return false; } _lookStream._offset = 0; _lookStream._length = _lookStream._data.size(); CrcGenerateTable(); SzArEx_Init(&_db); auto res = SzArEx_Open(&_db, &_lookStream, &_allocImp, &_allocTempImp); if (res != SZ_OK) { return false; } return true; } static void ConvertString(std::string &dest, const std::vector<uint16_t> &source) { dest.clear(); dest.reserve(source.size()); for (int j=0; source[j]; j++) { dest += (char)source[j]; } } virtual void Rewind() override { _fileIndex = -1; } virtual bool NextFile(ArchiveFileInfo &fi) override { ++_fileIndex; if (_fileIndex >= (int)_db.NumFiles) return false; size_t len = SzArEx_GetFileNameUtf16(&_db, _fileIndex, NULL); _filename.resize(len); SzArEx_GetFileNameUtf16(&_db, _fileIndex, _filename.data()); fi.is_directory = SzArEx_IsDir(&_db, _fileIndex); fi.compressedSize = 0; fi.uncompressedSize = (long)SzArEx_GetFileSize(&_db, _fileIndex); ConvertString(fi.name, _filename); return true; } virtual bool ExtractBinary(std::vector<uint8_t> &buffer) override { if (_fileIndex >= (int)_db.NumFiles) return false; size_t offset = 0; size_t outSizeProcessed = 0; auto res = SzArEx_Extract(&_db, &_lookStream, _fileIndex, &_blockIndex, &_outBuffer, &_outBufferSize, &offset, &outSizeProcessed, &_allocImp, &_allocTempImp); if (res != SZ_OK) { buffer.clear(); return false; } // copy data into buffer buffer.resize(outSizeProcessed); buffer.assign(_outBuffer + offset, _outBuffer + offset + outSizeProcessed); return true; } private: ISzAlloc _allocImp = g_Alloc; ISzAlloc _allocTempImp = g_Alloc; MemoryLookInStream _lookStream = {}; CSzArEx _db = {}; int _fileIndex = -1; std::vector<UInt16> _filename; Byte *_outBuffer = nullptr; UInt32 _blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */ size_t _outBufferSize = 0; /* it can have any value before first call (if outBuffer = 0) */ }; ArchiveReaderPtr OpenArchive(std::string path) { std::string ext = PathGetExtensionLower(path); #ifndef WIN32 if (ext == ".zip") { auto reader = std::make_shared<ZipReader>(); if (!reader->OpenArchive(path)) { return nullptr; } return reader; } #endif if (ext == ".7z") { auto reader = std::make_shared<SevenZipReader>(); if (!reader->OpenArchive(path)) { return nullptr; } return reader; } return nullptr; } } // namespace
#include <iostream> #include <vector> using namespace std; int n, m; int *chain; vector<pair<int, int>> v; int main() { // freopen("a.txt", "r", stdin); scanf("%d %d", &n, &m); chain = new int[n]; for(int i = 0; i < n; i++) scanf("%d", &chain[i]); int curSum = 0; int nSum = 0; //for(int i = 0; i < n; i++) //{ // int nSum = 0; // for(int j = i; j < n; j++) // { // nSum += chain[j]; // if(nSum >= m) // { // if(nSum - m < abs(curSum - m)) // { // v.clear(); // v.push_back(make_pair(i, j)); // curSum = nSum; // } // else if(nSum - m == abs(curSum - m)) // { // v.push_back(make_pair(i, j)); // } // break; // } // } //} int i = 0, j = 0; while (i < n && j < n) { nSum += chain[j]; if(nSum < m) { j++; continue; } if(nSum >= m) { if(nSum - m < abs(curSum - m)) { v.clear(); v.push_back(make_pair(i, j)); curSum = nSum; } else if(nSum - m == abs(curSum - m)) v.push_back(make_pair(i, j)); nSum -= chain[i]; nSum -= chain[j]; i++; continue; } } for(int i = 0; i < v.size(); i++) printf("%d-%d\n", v[i].first + 1, v[i].second + 1); }
#ifndef _ScreenGameMainMenu_H_ #define _ScreenGameMainMenu_H_ #include <iostream> #include "BaseGoods.h" #include "GameView.h" #include "Global.h" #include "Player.h" #include "TextRender.h" #include "Util.h" #include "BaseMagic.h" #include "MagicAttack.h" #include "MagicRestore.h" #include "ScreenMagic.h" #include "ScreenMainGame.h" #include "BaseScreen.h" #include "Bitmap.h" #include "Canvas.h" #include "Rect.h" struct OnMainMenuItemSelectedListener :public OnItemSelectedListener { int id; OnMainMenuItemSelectedListener(int id); virtual ~OnMainMenuItemSelectedListener(); virtual void onItemSelected(BaseMagic *magic); }; class _screenSelectActor : public BaseScreen { private: int mIndex; Rect mFrameRect; Bitmap *bmpFrame; std::vector<std::string> mNames; int mSum; public: _screenSelectActor(); virtual ~_screenSelectActor(); virtual void update(long delta){} virtual void draw(Canvas *canvas); virtual void onKeyDown(int key); virtual void onKeyUp(int key); virtual bool isPopup(){ return true; } }; class ScreenGameMainMenu: public BaseScreen { public : ScreenGameMainMenu(); virtual ~ScreenGameMainMenu(); virtual void update(long delta){} virtual void draw(Canvas *canvas); virtual void onKeyDown(int key); virtual void onKeyUp(int key); /** * * @param id 0 1 2 * @return */ static ScreenMagic *getScreenMagic(const int id); private: virtual bool isPopup() { return true; } private: Bitmap *bmpFrame1; Bitmap *bmpFrame2; Rect menuItemsRect; char *menuItems; std::string menuItemsS[4]; int mSelIndex; BaseScreen *screenSelectActor; }; #endif
#include "Celestial.h" Celestial::Celestial() { celestialName = "Blank"; } Celestial::~Celestial() { //dtor }
/** MIT License Copyright (c) 2019 mpomaranski at gmail Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "m2m_controller_tester.hpp" #include "granada/http/session/map_session.h" #include "m2m_controller.hpp" #include <catch/catch.hpp> #include <cpprest/filestream.h> #include <cpprest/http_client.h> #include <string> using namespace utility; using namespace web::http; using namespace web::http::client; using namespace concurrency::streams; using namespace std; using namespace cleric::http::controller; using namespace web; using namespace utility; TEST_CASE("GET controller is invoked", "[rest_controller]") { CHECK(cleric::http::controller::test::isGetInvoked == false); cleric::http::controller::test::M2MControllerTester::callGet(); CHECK(cleric::http::controller::test::isGetInvoked == true); } TEST_CASE("POST controller is invoked", "[rest_controller]") { CHECK(cleric::http::controller::test::isPostInvoked == false); cleric::http::controller::test::M2MControllerTester::callPost(); CHECK(cleric::http::controller::test::isPostInvoked == true); }
#include <iostream> #include <vector> #include <string> #include <opencv2/opencv.hpp> #include "../HSVImage.hpp" std::string window = "Threshold Picker"; int hue_upper_threshold; std::string hue_upper_trackbar = "Hue Upper Threshold:"; int hue_lower_threshold; std::string hue_lower_trackbar = "Hue Lower Threshold"; int canny_threshold; std::string canny_trackbar = "Canny Threshold:"; HSVImage img; void trackbar_callback(int param, void *obj) { cv::Mat input; img.rgb.copyTo(input); cv::Mat hsv_thresh_hue_upper; cv::Mat hsv_thresh_hue_lower; cv::Mat thresholded; cv::threshold(img.hsv, hsv_thresh_hue_lower, hue_lower_threshold, 255, cv::THRESH_BINARY); cv::threshold(img.hsv, hsv_thresh_hue_upper, hue_upper_threshold, 255, cv::THRESH_BINARY_INV); thresholded = hsv_thresh_hue_lower & hsv_thresh_hue_upper; cv::imshow(window, thresholded); /*cv::Mat gray0; thresholded.copyTo(gray0); cv::Mat gray; cv::Canny(gray0, gray, 0, canny_threshold, 5); cv::dilate(gray, gray, cv::Mat(), cv::Point(-1, -1)); std::vector < std::vector < cv::Point > >contours; cv::findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); // This is for contour display for (uint i = 0; i < contours.size(); i++) { cv::Scalar color(0, 0, 0); cv::drawContours(input, contours, i, color, 1, 8); } // This is for bounding rectangle displaye std::vector<cv::RotatedRect> boundingRects; for (uint i = 0; i < contours.size(); i++) boundingRects.push_back(cv::minAreaRect(contours.at(i))); for (uint i = 0; i < contours.size(); i++) { cv::Point2f boundingPoints[4]; boundingRects.at(i).points(boundingPoints); for (int i = 0; i < 4; i++) cv::line(input, boundingPoints[i], boundingPoints[(i + 1) % 4], cv::Scalar(0, 0, 0)); } cv::imshow(window, input); */ } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " [INPUT FILE]" << std::endl; return EXIT_FAILURE; } cv::Mat raw_image = cv::imread(argv[1]); img = HSVImage(raw_image); cv::namedWindow(window, 0); cv::createTrackbar(hue_lower_trackbar, window, &hue_lower_threshold, 255, trackbar_callback); cv::createTrackbar(hue_upper_trackbar, window, &hue_upper_threshold, 255, trackbar_callback); cv::createTrackbar(canny_trackbar, window, &canny_threshold, 255, trackbar_callback); cv::imshow(window, raw_image); while (true) { cv::waitKey(0); } return EXIT_SUCCESS; }
#include <iostream> #include "afx.h" #include <winsock2.h> #include <process.h> /* _beginthread, _endthread */ #include <string.h> #include <time.h> using namespace std; CFile f; CFileException ex; clock_t start, finish; // удалить сообщение с номером void del(wchar_t* p, int n) { wchar_t tel[200]; int j = 0; for (int i = n; (p[i] != L' ') && (p[i] != L'\0'); i++) { tel[j] = p[i]; j++; } tel[j] = L'\0'; wchar_t fName[200]; fName[0] = '\0'; wcscat(fName, tel); if (!f.Open(fName, CFile::modeReadWrite, &ex)) { cerr << "SMS storage error. Try again\n"; exit(EXIT_FAILURE); } ULONGLONG lastLineEndPosition = 0LL; wchar_t buf; while (f.Read(&buf, sizeof(buf)) != 0) { ULONGLONG position = f.GetPosition(); if (position == f.GetLength()) { break; } if (buf == L'\n') { lastLineEndPosition = f.GetPosition(); } } f.SetLength(lastLineEndPosition); f.Close(); cout << "SMS is removed" << endl; } //Отослать сообщение на SMS-центр для номера void sms(wchar_t* p, int n) { wchar_t tel[200]; wchar_t str[200]; int j = 0; for (int i = n; p[i] != ' '; i++) { tel[j] = p[i]; j++; } tel[j] = L'\0'; n += j + 1; j = 0; for (int i = n; p[i]; i++) { str[j] = p[i]; j++; } str[j] = L'\0'; wchar_t fName[200]; fName[0] = L'\0'; wcscat(fName, tel); cout << "sms processing..."; if (!f.Open(fName, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &ex)) { cerr << "SMS storage error. Try again\n"; exit(EXIT_FAILURE); } f.SeekToEnd(); f.Write(str, wcslen(str) * sizeof(wchar_t)); f.Write(L"\n", 2); f.Close(); cout << "sent successfully" << endl; } void SMSworking(void* newS) { int c; wchar_t p[200], com[200]; com[0] = '\0'; p[0] = '\0'; wcscat(p, L"SMS center connected...\n"); send((SOCKET)newS, (char*)p, sizeof(p), 0); while ((c = recv((SOCKET)newS, (char*)p, sizeof(p), 0) != 0)) { int i = 0; while ((p[i] != ' ') && (p[i] != L'\0')) { com[i] = p[i]; i++; } com[i] = L'\0'; i++; if (!wcscmp(com, L"sms")) { start = clock(); sms(p, i); com[0] = L'\0'; } if (!wcscmp(com, L"del")) { finish = clock(); // если с отправки сообщения прошло больше минуты if ((double)(finish - start) / CLOCKS_PER_SEC > 60) cout << "Cannot be canceled" << endl; else del(p, i); com[0] = L'\0'; } if (!wcscmp(com, L"quit")) { closesocket((SOCKET)newS); exit(EXIT_SUCCESS); com[0] = L'\0'; } } } int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) return -1; sockaddr_in local; local.sin_family = AF_INET; local.sin_port = htons(1280); local.sin_addr.s_addr = htonl(INADDR_ANY); SOCKET s = socket(AF_INET, SOCK_STREAM, 0); int c = bind(s, (struct sockaddr*)&local, sizeof(local)); int r = listen(s, 5); while (true) { sockaddr_in remote; int j = sizeof(remote); SOCKET newS = accept(s, (struct sockaddr*) &remote, &j); _beginthread(SMSworking, 0, (void*)newS); } WSACleanup(); return 0; }
// Copyright 2020-2021 Russ 'trdwll' Treadwell <trdwll.com>. All Rights Reserved. #include "Core/SteamUserStats.h" #include "SteamBridgeUtils.h" USteamUserStats::USteamUserStats() { OnGlobalAchievementPercentagesReadyCallback.Register(this, &USteamUserStats::OnGlobalAchievementPercentagesReady); OnGlobalStatsReceivedCallback.Register(this, &USteamUserStats::OnGlobalStatsReceived); OnLeaderboardFindResultCallback.Register(this, &USteamUserStats::OnLeaderboardFindResult); OnLeaderboardScoresDownloadedCallback.Register(this, &USteamUserStats::OnLeaderboardScoresDownloaded); OnLeaderboardScoreUploadedCallback.Register(this, &USteamUserStats::OnLeaderboardScoreUploaded); OnLeaderboardUGCSetCallback.Register(this, &USteamUserStats::OnLeaderboardUGCSet); OnNumberOfCurrentPlayersCallback.Register(this, &USteamUserStats::OnNumberOfCurrentPlayers); OnUserAchievementIconFetchedCallback.Register(this, &USteamUserStats::OnUserAchievementIconFetched); OnUserAchievementStoredCallback.Register(this, &USteamUserStats::OnUserAchievementStored); OnUserStatsReceivedCallback.Register(this, &USteamUserStats::OnUserStatsReceived); OnUserStatsStoredCallback.Register(this, &USteamUserStats::OnUserStatsStored); OnUserStatsUnloadedCallback.Register(this, &USteamUserStats::OnUserStatsUnloaded); } USteamUserStats::~USteamUserStats() { OnGlobalAchievementPercentagesReadyCallback.Unregister(); OnGlobalStatsReceivedCallback.Unregister(); OnLeaderboardFindResultCallback.Unregister(); OnLeaderboardScoresDownloadedCallback.Unregister(); OnLeaderboardScoreUploadedCallback.Unregister(); OnLeaderboardUGCSetCallback.Unregister(); OnNumberOfCurrentPlayersCallback.Unregister(); OnUserAchievementIconFetchedCallback.Unregister(); OnUserAchievementStoredCallback.Unregister(); OnUserStatsReceivedCallback.Unregister(); OnUserStatsStoredCallback.Unregister(); OnUserStatsUnloadedCallback.Unregister(); } FSteamAPICall USteamUserStats::DownloadLeaderboardEntries(FSteamLeaderboard SteamLeaderboard, ESteamLeaderboardDataRequest LeaderboardDataRequest, int32 RangeStart, int32 RangeEnd) const { return SteamUserStats()->DownloadLeaderboardEntries(SteamLeaderboard, (ELeaderboardDataRequest)LeaderboardDataRequest, RangeStart, RangeEnd); } FSteamAPICall USteamUserStats::FindOrCreateLeaderboard(const FString& LeaderboardName, ESteamLeaderboardSortMethod LeaderboardSortMethod, ESteamLeaderboardDisplayType LeaderboardDisplayType) const { return SteamUserStats()->FindOrCreateLeaderboard(TCHAR_TO_UTF8(*LeaderboardName), (ELeaderboardSortMethod)LeaderboardSortMethod, (ELeaderboardDisplayType)LeaderboardDisplayType); } bool USteamUserStats::GetDownloadedLeaderboardEntry(FSteamLeaderboardEntries SteamLeaderboardEntries, int32 index, FSteamLeaderboardEntry& LeaderboardEntry, TArray<int32>& Details, int32 DetailsMax) const { Details.SetNum(DetailsMax); LeaderboardEntry_t TmpEntry; bool bResult = SteamUserStats()->GetDownloadedLeaderboardEntry(SteamLeaderboardEntries, index, &TmpEntry, Details.GetData(), DetailsMax); LeaderboardEntry = TmpEntry; return bResult; } int32 USteamUserStats::GetGlobalStatHistoryFloat(const FString& StatName, TArray<float>& Data, int32 Size) const { TArray<double> TmpData; int32 result = SteamUserStats()->GetGlobalStatHistory(TCHAR_TO_UTF8(*StatName), TmpData.GetData(), Size); for (int32 i = 0; i < TmpData.Num(); i++) { Data.Add((float)TmpData[i]); } return result; } int32 USteamUserStats::GetMostAchievedAchievementInfo(FString& Name, float& Percent, bool& bAchieved) const { TArray<char> TmpName; int32 result = SteamUserStats()->GetMostAchievedAchievementInfo(TmpName.GetData(), 1024, &Percent, &bAchieved); Name = UTF8_TO_TCHAR(TmpName.GetData()); return result; } int32 USteamUserStats::GetNextMostAchievedAchievementInfo(int32 IteratorPrevious, FString& Name, float& Percent, bool& bAchieved) const { TArray<char> TmpName; int32 result = SteamUserStats()->GetNextMostAchievedAchievementInfo(IteratorPrevious, TmpName.GetData(), 1024, &Percent, &bAchieved); Name = UTF8_TO_TCHAR(TmpName.GetData()); return result; } FSteamAPICall USteamUserStats::UploadLeaderboardScore(FSteamLeaderboard SteamLeaderboard, ESteamLeaderboardUploadScoreMethod LeaderboardUploadScoreMethod, int32 Score, const TArray<int32>& ScoreDetails) const { return SteamUserStats()->UploadLeaderboardScore(SteamLeaderboard, (ELeaderboardUploadScoreMethod)LeaderboardUploadScoreMethod, Score, ScoreDetails.GetData(), ScoreDetails.Num()); } void USteamUserStats::OnGlobalAchievementPercentagesReady(GlobalAchievementPercentagesReady_t* pParam) { m_OnGlobalAchievementPercentagesReady.Broadcast(pParam->m_nGameID, (ESteamResult)pParam->m_eResult); } void USteamUserStats::OnGlobalStatsReceived(GlobalStatsReceived_t* pParam) { m_OnGlobalStatsReceived.Broadcast(pParam->m_nGameID, (ESteamResult)pParam->m_eResult); } void USteamUserStats::OnLeaderboardFindResult(LeaderboardFindResult_t* pParam) { m_OnLeaderboardFindResult.Broadcast(pParam->m_hSteamLeaderboard, pParam->m_bLeaderboardFound == 1); } void USteamUserStats::OnLeaderboardScoresDownloaded(LeaderboardScoresDownloaded_t* pParam) { m_OnLeaderboardScoresDownloaded.Broadcast(pParam->m_hSteamLeaderboard, pParam->m_hSteamLeaderboardEntries, pParam->m_cEntryCount); } void USteamUserStats::OnLeaderboardScoreUploaded(LeaderboardScoreUploaded_t* pParam) { m_OnLeaderboardScoreUploaded.Broadcast(pParam->m_bSuccess == 1, pParam->m_hSteamLeaderboard, pParam->m_nScore, pParam->m_bScoreChanged == 1, pParam->m_nGlobalRankNew, pParam->m_nGlobalRankPrevious); } void USteamUserStats::OnLeaderboardUGCSet(LeaderboardUGCSet_t* pParam) { m_OnLeaderboardUGCSet.Broadcast((ESteamResult)pParam->m_eResult, pParam->m_hSteamLeaderboard); } void USteamUserStats::OnNumberOfCurrentPlayers(NumberOfCurrentPlayers_t* pParam) { m_OnNumberOfCurrentPlayers.Broadcast(pParam->m_bSuccess == 1, pParam->m_cPlayers); } void USteamUserStats::OnUserAchievementIconFetched(UserAchievementIconFetched_t* pParam) { m_OnUserAchievementIconFetched.Broadcast(pParam->m_nGameID.ToUint64(), UTF8_TO_TCHAR(pParam->m_rgchAchievementName), pParam->m_bAchieved, pParam->m_nIconHandle); } void USteamUserStats::OnUserAchievementStored(UserAchievementStored_t* pParam) { m_OnUserAchievementStored.Broadcast(pParam->m_nGameID, pParam->m_bGroupAchievement, UTF8_TO_TCHAR(pParam->m_rgchAchievementName), pParam->m_nCurProgress, pParam->m_nMaxProgress); } void USteamUserStats::OnUserStatsReceived(UserStatsReceived_t* pParam) { m_OnUserStatsReceived.Broadcast(pParam->m_nGameID, (ESteamResult)pParam->m_eResult, pParam->m_steamIDUser.ConvertToUint64()); } void USteamUserStats::OnUserStatsStored(UserStatsStored_t* pParam) { m_OnUserStatsStored.Broadcast(pParam->m_nGameID, (ESteamResult)pParam->m_eResult); } void USteamUserStats::OnUserStatsUnloaded(UserStatsUnloaded_t* pParam) { m_OnUserStatsUnloaded.Broadcast(pParam->m_steamIDUser.ConvertToUint64()); }
// // Created by BramboraSK on 24. 9. 2021. // // Generujte čísla od -10 do 10. Spočítajte 6 čísel, ktoré sú >0 a zároveň deliteľné tromi. #include <iostream> #include <random> using namespace std; int main() { int sucet = 0, i = 0, random = 0; // Dala by sa pouzit aj funkcia rand z kniznice stdlib, ale nie je tak spolahliva a neodporuca sa na opakovane generovanie cisel. random_device device; mt19937 mt(device()); uniform_int_distribution<int> dist(-10, 10); while(i < 6) { random = dist(mt); if(random > 0 && random % 3 == 0) { // Pokial chceme sledovat, ake cisla boli generovane, tento riadok odkomentujeme // cout << random << endl; sucet += random; i++; } } cout << sucet; return 0; }
#if defined(WIN32) && 0 #include <windows.h> #include <stdio.h> #include <conio.h> #include <mmsystem.h> #include <vector> #include <mutex> #include "IAudioSource.h" #include "platform.h" #pragma comment(lib,"winmm.lib") class WaveInAudioSource : public IAudioSource { public: WaveInAudioSource() :m_handle() { } virtual void Reset() override { } virtual bool Start(int sampleRate, int frameSize) { WAVEFORMATEX fmt; fmt.wFormatTag = WAVE_FORMAT_PCM; fmt.nChannels = 2; fmt.nSamplesPerSec = sampleRate; fmt.wBitsPerSample = 16; fmt.nBlockAlign = fmt.nChannels * (fmt.wBitsPerSample / 8); fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; fmt.cbSize = 0; MMRESULT result = waveInOpen(&m_handle, WAVE_MAPPER, &fmt, (DWORD_PTR)waveInProc, (DWORD_PTR)this, CALLBACK_FUNCTION); if (result != MMSYSERR_NOERROR) return false; for (int i = 0; i < 2; i++) { WAVEHDR *buffer = &m_header[i]; memset(buffer, 0, sizeof(*buffer)); buffer->lpData = (LPSTR)new Sample16[frameSize]; buffer->dwBufferLength = frameSize * sizeof(Sample16); result = waveInPrepareHeader(m_handle, buffer, sizeof(*buffer)); if (result != MMSYSERR_NOERROR) return false; // Insert a wave input buffer result = waveInAddBuffer(m_handle, buffer, sizeof(*buffer)); if (result != MMSYSERR_NOERROR) return false; } result = waveInStart(m_handle); if (result != MMSYSERR_NOERROR) return false; return true; } virtual void Stop() { if (m_handle) { waveInStop(m_handle); for (int i = 0; i < 2; i++) { WAVEHDR *buffer = &m_header[i]; waveInUnprepareHeader(m_handle, buffer, sizeof(*buffer)); delete buffer->lpData; } waveInClose(m_handle); m_handle = NULL; } } virtual bool ReadAudio(Sample *buffer, int size) { std::lock_guard<std::mutex> lock(m_mutex); if (size > (int)m_samples.size()) { //LogPrint("!read %d of %d\n", 0, m_samples.size()); return false; } float scale = 1.0f / 32767.0f; // copy samples to output buffer for (int i = 0; i < size; i++) { buffer[i].left = (float)m_samples[i].left * scale; buffer[i].right = (float)m_samples[i].right * scale; } m_samples.erase(m_samples.begin(), m_samples.begin() + size); //LogPrint("read %d of %d\n", size, m_samples.size()); if (m_samples.size() > (size_t)(size * 4) ) { // LogPrint("clear!\n"); m_samples.clear(); } return true; } static void CALLBACK waveInProc( HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2 ) { auto *self = (WaveInAudioSource *)dwInstance; if (uMsg == WIM_DATA) { self->OnData((WAVEHDR *)dwParam1, (void *)dwParam2); } } virtual void OnData(WAVEHDR *hdr, void *param2) { if (hdr->dwFlags & WHDR_DONE) { int count = hdr->dwBytesRecorded / sizeof(Sample16); const Sample16 *source = (Sample16 *)hdr->lpData; { std::lock_guard<std::mutex> lock(m_mutex); m_samples.insert(m_samples.end(), source, source + count); } // Insert a wave input buffer MMRESULT result = waveInAddBuffer(m_handle, hdr, sizeof(*hdr)); if (result != MMSYSERR_NOERROR) return; } } protected: HWAVEIN m_handle; WAVEHDR m_header[2]; std::mutex m_mutex; std::vector<Sample16> m_samples; }; IAudioSourcePtr CreateWaveInAudioSource(int sampleRate, int frameSize) { auto source = std::make_shared<WaveInAudioSource>(); if (!source->Start(sampleRate, frameSize)) { return nullptr; } return source; } #endif
// // PartyVideoDJ - YouTube crossfading app // Copyright (C) 2008-2017 Michael Fink // /// \file YouTubeWebPageView.hpp View to display YouTube web page // #pragma once #include "WebPageWindowEx.hpp" class VideoInfo; const DISPID c_uiExternalStateId = 0; const DISPID c_uiExternalErrorId = 1; template <typename T> class YouTubePlayerExternalImpl : public IDocHostUIHandlerDispatchImpl, public IOleCommandTarget { public: virtual ULONG STDMETHODCALLTYPE AddRef() override { return IDocHostUIHandlerDispatchImpl::AddRef(); } virtual ULONG STDMETHODCALLTYPE Release() override { return IDocHostUIHandlerDispatchImpl::Release(); } virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject) override { if (riid == IID_IOleCommandTarget) { if (!ppvObject) return E_POINTER; *ppvObject = static_cast<IOleCommandTarget*>(this); AddRef(); return S_OK; } return IDocHostUIHandlerDispatchImpl::QueryInterface(riid, ppvObject); } virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE QueryStatus( const GUID* /*pguidCmdGroup*/, ULONG /*cCmds*/, OLECMD /*prgCmds*/[], OLECMDTEXT* /*pCmdText*/) override { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Exec( const GUID* /*pguidCmdGroup*/, DWORD /*nCmdID*/, DWORD /*nCmdexecopt*/, VARIANT* /*pvaIn*/, VARIANT* /*pvaOut*/) override { return E_NOTIMPL; } // reimplement some methods from IDispatch /// returns IDs by given names virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(const IID&, LPOLESTR* pszoName, UINT cNames, LCID /*lcid*/, DISPID* rgdispid) override { // this function assumes the host always queries only for one name ATLASSERT(cNames == 1); cNames; CString cszName(*pszoName); if (cszName == _T("state")) { rgdispid[0] = c_uiExternalStateId; return S_OK; } else if (cszName == _T("error")) { rgdispid[0] = c_uiExternalErrorId; return S_OK; } return E_FAIL; } /// calls IDispatch methods virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispid, REFIID /*riid*/, LCID /*lcid*/, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/) override { if (dispid == c_uiExternalStateId) { CComVariant varValue(*pDispParams->rgvarg); if (wFlags == DISPATCH_PROPERTYPUT) { T* pT = static_cast<T*>(this); pT->OnChangedState(varValue.intVal); } return S_OK; } if (dispid == c_uiExternalErrorId) { CComVariant varValue(*pDispParams->rgvarg); if (wFlags == DISPATCH_PROPERTYPUT) { T* pT = static_cast<T*>(this); pT->OnPlayerError(varValue.intVal); } return S_OK; } return E_FAIL; } // *** IDocHostUIHandlerDispatchImpl *** virtual HRESULT STDMETHODCALLTYPE GetExternal(IDispatch** ppDispatch) override { *ppDispatch = this; AddRef(); return S_OK; } // non-virtual functions void OnChangedState(int iState) { ATLASSERT(false); } void OnPlayerError(int iError) { ATLASSERT(false); } }; #define WM_STATE_CHANGED WM_APP + 1 #define WM_PLAYER_ERROR WM_APP + 2 class YouTubeWebPageView : public WebPageWindowEx<YouTubeWebPageView, YouTubePlayerExternalImpl<YouTubeWebPageView> > { public: typedef WebPageWindowEx<YouTubeWebPageView, YouTubePlayerExternalImpl<YouTubeWebPageView> > BaseClass; YouTubeWebPageView() throw(); ~YouTubeWebPageView() throw(); BOOL PreTranslateMessage(MSG* pMsg); void OnNewWindow3(const CString& /*cszURL*/, bool& bCancel) const { bCancel = true; // cancel all newly opened windows } enum T_enActionWhenReady { actionDoNothing = 0, actionPlayVideo = 1, ///< immediately start playing video when it's cued actionSeekAndPause = 2, ///< seek forward to position and pause }; void SetActionWhenReady(T_enActionWhenReady enActionWhenReady, double dSeconds = 0.0) throw() { m_enActionWhenReady = enActionWhenReady; m_dSeconds = dSeconds; } enum T_enPlayerState { playerStateUnknown = -3, playerStateInitialized = -2, ///< state set when onYouTubePlayerReady was called playerStateUnstarted = -1, playerStateEnded = 0, playerStatePlaying = 1, playerStatePaused = 2, playerStateBuffering = 3, playerStateVideoCued = 5, ///< video download not yet started, showing "play" button on the video }; enum T_enPlayerErrorCode { errorVideoNotFound = 100, ///< video removed or marked as private errorPlaybackNotAllowed = 101, ///< video isn't allowed to be embedded errorPlaybackNotAllowed2 = 150, ///< same, but different code }; static CString GetStateCodeText(T_enPlayerState enPlayerState); static CString GetPlayerErrorText(T_enPlayerErrorCode enErrorCode); void LoadVideo(const VideoInfo& info); void PlayVideo(); void PauseVideo(); void StopVideo(); void ClearVideo(); unsigned int GetVideoBytesLoaded(); unsigned int GetVideoBytesTotal(); void Mute(); void Unmute(); bool IsMuted(); void SetVolume(unsigned int uiVolume); unsigned int GetVolume(); void SeekTo(double dSeconds, bool bAllowSeekAhead); T_enPlayerState GetPlayerState(); double GetCurrentTime(); double GetDuration(); void SetSize(int iWidth, int iHeight); private: BEGIN_MSG_MAP(YouTubeWebPageView) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_TIMER, OnTimer) MESSAGE_HANDLER(WM_STATE_CHANGED, OnStateChanged) MESSAGE_HANDLER(WM_PLAYER_ERROR, OnPlayerError) MESSAGE_HANDLER(WM_LBUTTONDOWN, OnIgnoreMessage) MESSAGE_HANDLER(WM_LBUTTONUP, OnIgnoreMessage) MESSAGE_HANDLER(WM_LBUTTONDBLCLK, OnIgnoreMessage) MESSAGE_HANDLER(WM_RBUTTONDOWN, OnIgnoreMessage) MESSAGE_HANDLER(WM_RBUTTONUP, OnIgnoreMessage) MESSAGE_HANDLER(WM_RBUTTONDBLCLK, OnIgnoreMessage) MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnIgnoreMessage) CHAIN_MSG_MAP(BaseClass) END_MSG_MAP() LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnStateChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnPlayerError(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnIgnoreMessage(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { bHandled = TRUE; return 0; } void CheckSeekToStart(); bool IsPlayerError() const { return m_iLastError != 0; } static CString GetHtmlTemplate() throw(); // non-virtual functions void OnChangedState(int iState) { m_bLoaded = true; ::PostMessage(m_hWnd, WM_STATE_CHANGED, 0, static_cast<LPARAM>(iState)); } void OnPlayerError(int iError) { ::PostMessage(m_hWnd, WM_PLAYER_ERROR, 0, static_cast<LPARAM>(iError)); } private: T_enActionWhenReady m_enActionWhenReady; double m_dSeconds; unsigned int m_uiSeekAndPauseStopCounter; int m_iLastError; bool m_bLoaded; CString m_cszHtmlFilename; static CString s_cszHtmlTemplate; };
#pragma once #include <map> #include <utility> #include "IAgent.h" class QTable { // find the best action given a state // find the best state regardless of action std::map<State, Reward>; std::map<State, map<Action, State> >; QTable(int states, int actions) { } }; class QLearner : public IAgent < QTable> { };
#ifndef CG_PCH_H #define CG_PCH_H #ifdef COMPUTATIONALGEOMETRY_EXPORTS #define CGAPI __declspec(dllexport) #else #define CGAPI __declspec(dllimport) #endif #include <Windows.h> #include <array> #include <vector> #endif
/* -*- c++ -*- */ /* * Copyright 2018 <+YOU OR YOUR COMPANY+>. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gnuradio/io_signature.h> #include "time_deinterleaver_1seg_impl.h" #include <stdio.h> namespace gr { namespace oneseg { // TODO shouldn't these be defined somewhere else?? const int time_deinterleaver_1seg_impl::d_data_carriers_mode1 = 96; const int time_deinterleaver_1seg_impl::d_total_segments = 1; time_deinterleaver_1seg::sptr time_deinterleaver_1seg::make(int mode, int length) { return gnuradio::get_initial_sptr (new time_deinterleaver_1seg_impl(mode, length)); } /* * The private constructor */ time_deinterleaver_1seg_impl::time_deinterleaver_1seg_impl(int mode, int length) : gr::sync_block("time_deinterleaver_1seg", gr::io_signature::make(1, 1, sizeof(gr_complex)*d_total_segments*d_data_carriers_mode1*((int)pow(2.0,mode-1))), gr::io_signature::make(1, 1, sizeof(gr_complex)*d_total_segments*d_data_carriers_mode1*((int)pow(2.0,mode-1)))) { d_mode = mode; //TODO the length of the interleaver may change from segment to segment. This should be corrected... d_I = length; d_carriers_per_segment = d_data_carriers_mode1*((int)pow(2.0,mode-1)); d_noutput = d_total_segments*d_carriers_per_segment; int mi = 0; for (int segment=0; segment<d_total_segments; segment++) { for (int carrier = 0; carrier<d_carriers_per_segment; carrier++) { mi = (5*carrier) % d_data_carriers_mode1; d_shift.push_back(new std::deque<gr_complex>(d_I*(d_data_carriers_mode1-1-mi),0)); } } } /* * Our virtual destructor. */ time_deinterleaver_1seg_impl::~time_deinterleaver_1seg_impl() { for (unsigned int i=0; i<d_shift.size();i++){ delete d_shift.back(); d_shift.pop_back(); } } int time_deinterleaver_1seg_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; // TODO CHECK the tag propagation policy for the frame // beginnning. for (int i=0; i<noutput_items; i++) { for (int carrier=0; carrier<d_noutput; carrier++) { // a simple FIFO queue performs the interleaving. // The "difficult" part is setting the correct sizes // for each queue. d_shift[carrier]->push_back(in[i*d_noutput + carrier]); out[i*d_noutput + carrier] = d_shift[carrier]->front(); d_shift[carrier]->pop_front(); } } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace oneseg */ } /* namespace gr */
#include "CACLInteger.hpp" // 重载大于号 bool CACLInteger::operator>(const CACLInteger &number) { if (symbol != number.symbol) { return symbol == false ? true : false; } // 从找到this和number中位数最高的,然后最高位开始比较 if (symbol == false) { if (bit > number.bit) { return true; } else if (bit < number.bit) { return false; } else { for (int i = bit - 1; i >= 0; --i) { if (num[i] < number.num[i]) { return false; } } } } // 类似上一个代码块 if (symbol == true) { if (bit < number.bit) { return true; } else if (bit > number.bit) { return false; } else { for (int i = bit - 1; i >= 0; --i) { if (num[i] > number.num[i]) { return false; } } } } return true; } bool CACLInteger::operator>(const long long number) { CACLInteger translatedNumber = translate(number); return *this > translatedNumber; } //重载小于号 bool CACLInteger::operator<(CACLInteger number) { if (symbol != number.symbol) { return symbol == false ? false : true; } // 从找到this和number中位数最高的,然后最高位开始比较 if (symbol == false) { if (bit > number.bit) { return false; } else if (bit < number.bit) { return true; } else { for (int i = bit - 1; i >= 0; --i) { if (num[i] > number.num[i]) { return false; } } } } // 类似上一个代码块 if (this->symbol == true) { if (bit > number.bit) { return true; } else if (bit < number.bit) { return false; } else { for (int i = bit - 1; i >= 0; --i) { if (this->num[i] < number.num[i]) { return false; } } } } return true; } bool CACLInteger::operator<(const long long number) { CACLInteger translatedNumber = translate(number); return *this < translatedNumber; } // 重载等于 bool CACLInteger::operator==(CACLInteger number) { if (symbol != number.symbol) { return false; } if (bit != number.bit) { return false; } for (int i = bit - 1; i >= 0; --i) { if (num[i] != number.num[i]) return false; } return true; } bool CACLInteger::operator==(const long long number) { CACLInteger translatedNumber = translate(number); return *this == translatedNumber; } // 重载不等于 bool CACLInteger::operator!=(CACLInteger number) { return !(*this == number); } bool CACLInteger::operator!=(const long long number) { CACLInteger translatedNumber = translate(number); return !(*this == translatedNumber); } // 重载大于或等于 bool CACLInteger::operator>=(CACLInteger number) { return *this > number || *this == number; } bool CACLInteger::operator>=(const long long number) { CACLInteger translatedNumber = translate(number); return *this >= translatedNumber; } // 重载小于或等于 bool CACLInteger::operator<=(CACLInteger number) { return *this < number || *this == number; } bool CACLInteger::operator<=(const long long number) { CACLInteger translatedNumber = translate(number); return *this <= translatedNumber; }
#include<stdio.h> //#include<conio.h> #include<malloc.h> struct node{ int data; struct node *next; }; int push(struct node **,int); int count(struct node *,int); int main(void){ struct node *head; head=NULL; push(&head,1); push(&head,4); push(&head,6); push(&head,1); push(&head,1); push(&head,1); printf("nos of 1 is = %d",count(head,1)); getchar(); } int push(struct node **p ,int new_data){ struct node *new_node; new_node=(struct node *)malloc(sizeof(struct node)); new_node->data=new_data; new_node->next=*p; *p=new_node; } int count(struct node *Head,int search_for){ struct node *current=Head; int count=0; while(current!=NULL){ if(current->data==search_for){ count++; current=current->next; } } return count; }
#ifndef _SQMYSQL_CONNECTION_HPP_ #define _SQMYSQL_CONNECTION_HPP_ // ------------------------------------------------------------------------------------------------ #include "Handle/Connection.hpp" // ------------------------------------------------------------------------------------------------ namespace SqMod { /* ------------------------------------------------------------------------------------------------ * Allows management and interaction with a connection handle. */ class Connection { private: // -------------------------------------------------------------------------------------------- ConnRef m_Handle; // Reference to the actual database connection. protected: /* -------------------------------------------------------------------------------------------- * Validate the managed connection handle and throw an error if invalid. */ #if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC) void Validate(CCStr file, Int32 line) const; #else void Validate() const; #endif // _DEBUG /* -------------------------------------------------------------------------------------------- * Validate the managed connection handle and throw an error if invalid. */ #if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC) void ValidateCreated(CCStr file, Int32 line) const; #else void ValidateCreated() const; #endif // _DEBUG /* -------------------------------------------------------------------------------------------- * Validate the managed connection handle and throw an error if invalid. */ #if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC) const ConnRef & GetValid(CCStr file, Int32 line) const; #else const ConnRef & GetValid() const; #endif // _DEBUG /* -------------------------------------------------------------------------------------------- * Validate the managed connection handle and throw an error if invalid. */ #if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC) const ConnRef & GetCreated(CCStr file, Int32 line) const; #else const ConnRef & GetCreated() const; #endif // _DEBUG public: /* -------------------------------------------------------------------------------------------- * Default constructor. */ Connection() : m_Handle() { /* ... */ } /* -------------------------------------------------------------------------------------------- * Base constructor. */ Connection(const Account & acc) : m_Handle(new ConnHnd()) { m_Handle->Create(acc); } /* -------------------------------------------------------------------------------------------- * Base constructor. */ Connection(const ConnRef & conn) : m_Handle(conn) { /* ... */ } /* -------------------------------------------------------------------------------------------- * Copy constructor. */ Connection(const Connection & o) = default; /* -------------------------------------------------------------------------------------------- * Move constructor. */ Connection(Connection && o) = default; /* -------------------------------------------------------------------------------------------- * Copy assignment operator. */ Connection & operator = (const Connection & o) = default; /* -------------------------------------------------------------------------------------------- * Move assignment operator. */ Connection & operator = (Connection && o) = default; /* -------------------------------------------------------------------------------------------- * Used by the script engine to compare two instances of this type. */ Int32 Cmp(const Connection & o) const { if (m_Handle.Get() == o.m_Handle.Get()) { return 0; } else if (m_Handle.Get() > o.m_Handle.Get()) { return 1; } else { return -1; } } /* -------------------------------------------------------------------------------------------- * Used by the script engine to convert an instance of this type to a string. */ CSStr ToString() const { return m_Handle ? mysql_get_host_info(m_Handle->mPtr) : _SC(""); } /* -------------------------------------------------------------------------------------------- * Used by the script engine to retrieve the name from instances of this type. */ static SQInteger Typename(HSQUIRRELVM vm); /* -------------------------------------------------------------------------------------------- * Retrieve the associated connection handle. */ const ConnRef & GetHandle() const { return m_Handle; } /* -------------------------------------------------------------------------------------------- * See whether the managed handle is valid. */ bool IsValid() const { return m_Handle; } /* -------------------------------------------------------------------------------------------- * See whether the managed connection handle was connected. */ bool IsConnected() const { return m_Handle && (m_Handle->mPtr != nullptr); } /* -------------------------------------------------------------------------------------------- * Return the number of active references to this connection handle. */ Uint32 GetRefCount() const { return m_Handle.Count(); } /* -------------------------------------------------------------------------------------------- * Retrieve the current error number. */ SQInteger GetErrNo() const { return static_cast< SQInteger >(mysql_errno(SQMOD_GET_CREATED(*this)->mPtr)); } /* -------------------------------------------------------------------------------------------- * Retrieve the current error message. */ CSStr GetErrStr() const { return mysql_error(SQMOD_GET_CREATED(*this)->mPtr); } /* -------------------------------------------------------------------------------------------- * Retrieve the last received error number. */ SQInteger GetLastErrNo() const { return static_cast< SQInteger >(SQMOD_GET_VALID(*this)->mErrNo); } /* -------------------------------------------------------------------------------------------- * Retrieve the last received error message. */ const String & GetLastErrStr() const { return SQMOD_GET_VALID(*this)->mErrStr; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection port number. */ SQInteger GetPortNum() const { return static_cast< SQInteger >(SQMOD_GET_VALID(*this)->mPort); } /* -------------------------------------------------------------------------------------------- * Retrieve the connection host address. */ const String & GetHost() const { return SQMOD_GET_VALID(*this)->mHost; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection user name. */ const String & GetUser() const { return SQMOD_GET_VALID(*this)->mUser; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection password. */ const String & GetPass() const { return SQMOD_GET_VALID(*this)->mPass; } /* -------------------------------------------------------------------------------------------- * Retrieve the selected database name. */ const String & GetName() const { return SQMOD_GET_VALID(*this)->mName; } /* -------------------------------------------------------------------------------------------- * Modify the selected database name. */ void SetName(CSStr name) { // Validate the specified name if (!name) { STHROWF("Invalid MySQL database name"); } // Attempt to select the database with the given name else if (mysql_select_db(SQMOD_GET_CREATED(*this)->mPtr, name) != 0) { SQMOD_THROW_CURRENT(*m_Handle, "Cannot select MySQL database"); } // Remember the database name m_Handle->mName.assign(name); } /* -------------------------------------------------------------------------------------------- * Retrieve the connection socket. */ const String & GetSocket() const { return SQMOD_GET_VALID(*this)->mSocket; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection flags. */ SQInteger GetFlags() const { return static_cast< SQInteger >(SQMOD_GET_VALID(*this)->mFlags); } /* -------------------------------------------------------------------------------------------- * Retrieve the connection SSL key. */ const String & GetSSL_Key() const { return SQMOD_GET_VALID(*this)->mSSL_Key; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection SSL certificate. */ const String & GetSSL_Cert() const { return SQMOD_GET_VALID(*this)->mSSL_Cert; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection SSL certificate authority. */ const String & GetSSL_CA() const { return SQMOD_GET_VALID(*this)->mSSL_CA; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection SSL certificate authority path. */ const String & GetSSL_CA_Path() const { return SQMOD_GET_VALID(*this)->mSSL_CA_Path; } /* -------------------------------------------------------------------------------------------- * Retrieve the connection SSL cipher. */ const String & GetSSL_Cipher() const { return SQMOD_GET_VALID(*this)->mSSL_Cipher; } /* -------------------------------------------------------------------------------------------- * Retrieve the default character set for the managed connection. */ const String & GetCharset() const { return SQMOD_GET_VALID(*this)->mCharset; } /* -------------------------------------------------------------------------------------------- * Modify the default character set for the managed connection. */ void SetCharset(CSStr charset) { // Validate the specified string if (!charset) { STHROWF("Invalid charset string"); } // Attempt to Set the default character set for the managed connection else if (mysql_set_character_set(SQMOD_GET_CREATED(*this)->mPtr, charset) != 0) { SQMOD_THROW_CURRENT(*m_Handle, "Cannot apply character set"); } // Remember the character set m_Handle->mCharset.assign(charset); } /* -------------------------------------------------------------------------------------------- * See whether auto-commit is enabled or not. */ bool GetAutoCommit() const { return SQMOD_GET_VALID((*this))->mAutoCommit; } /* -------------------------------------------------------------------------------------------- * Set whether auto-commit should be enabled or not. */ void SetAutoCommit(bool toggle) { // Attempt to toggle auto-commit if necessary if (SQMOD_GET_CREATED(*this)->mAutoCommit != toggle && mysql_autocommit(m_Handle->mPtr, toggle) != 0) { SQMOD_THROW_CURRENT(*m_Handle, "Cannot toggle auto-commit"); } else { m_Handle->mAutoCommit = toggle; } } /* -------------------------------------------------------------------------------------------- * See whether the connection is in the middle of a transaction. */ bool GetInTransaction() const { return SQMOD_GET_VALID(*this)->mInTransaction; } /* -------------------------------------------------------------------------------------------- * Disconnect from the currently connected database. */ void Disconnect() { SQMOD_GET_CREATED(*this)->Disconnect(); } /* -------------------------------------------------------------------------------------------- * Execute a query on the server. */ Object Execute(CSStr query) { return MakeULongObj(SQMOD_GET_CREATED(*this)->Execute(query)); } /* -------------------------------------------------------------------------------------------- * Execute a query on the server. */ Object Insert(CSStr query); /* -------------------------------------------------------------------------------------------- * Execute a query on the server. */ ResultSet Query(CSStr query); /* -------------------------------------------------------------------------------------------- * Create a new statement on the managed connection. */ Statement GetStatement(CSStr query); /* -------------------------------------------------------------------------------------------- * Create a new transaction on the managed connection. */ Transaction GetTransaction(); /* -------------------------------------------------------------------------------------------- * Escape unwanted characters from a given string. */ LightObj EscapeString(StackStrF & str); /* -------------------------------------------------------------------------------------------- * Attempt to execute the specified query. */ static SQInteger ExecuteF(HSQUIRRELVM vm); /* -------------------------------------------------------------------------------------------- * Attempt to execute the specified query. */ static SQInteger InsertF(HSQUIRRELVM vm); /* -------------------------------------------------------------------------------------------- * Attempt to execute the specified query. */ static SQInteger QueryF(HSQUIRRELVM vm); }; } // Namespace:: SqMod #endif // _SQMYSQL_CONNECTION_HPP_
/** * @File test_chess_board.cpp * @Brief file_description * Details: * @Author guohainan * @Version v0.0.1 * @date 2017-09-06 23:33:16 */ #include "gtest/gtest.h" #define UNIT_TEST true #include "gomoku/chess_board.h" using namespace gomoku; TEST(ChessBoard, isGameOver) { ChessBoard board; board.playChess(ChessMove(COLOR_BLACK, 7, 7)); board.playChess(ChessMove(COLOR_WHITE, 6, 7)); board.playChess(ChessMove(COLOR_BLACK, 7, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 5)); board.playChess(ChessMove(COLOR_BLACK, 6, 6)); board.playChess(ChessMove(COLOR_WHITE, 6, 8)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 8, 6)); board.playChess(ChessMove(COLOR_WHITE, 6, 9)); board.playChess(ChessMove(COLOR_BLACK, 9, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 5, 6)); ASSERT_TRUE(board.isGameOver()); } TEST(ChessBoard, isGameOver_2) { ChessBoard board; board.playChess(ChessMove(COLOR_BLACK, 7, 7)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 7)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 7, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 5)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 6, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 8)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 8, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 9)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 9, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 5, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 4, 7)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 3, 8)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 2, 9)); ASSERT_TRUE(board.isGameOver()); } TEST(ChessBoard, printChessBord) { ChessBoard board; board.playChess(ChessMove(COLOR_BLACK, 7, 7)); board.playChess(ChessMove(COLOR_WHITE, 6, 7)); board.playChess(ChessMove(COLOR_BLACK, 7, 6)); board.playChess(ChessMove(COLOR_WHITE, 6, 5)); board.playChess(ChessMove(COLOR_BLACK, 6, 6)); board.playChess(ChessMove(COLOR_WHITE, 6, 8)); board.playChess(ChessMove(COLOR_BLACK, 8, 6)); board.playChess(ChessMove(COLOR_WHITE, 6, 9)); board.playChess(ChessMove(COLOR_BLACK, 9, 6)); board.playChess(ChessMove(COLOR_WHITE, 5, 6)); board.playChess(ChessMove(COLOR_WHITE, 4, 7)); board.playChess(ChessMove(COLOR_WHITE, 3, 8)); board.playChess(ChessMove(COLOR_WHITE, 2, 9)); board.printChessBord(); } TEST(ChessBoard, undoMove) { ChessBoard board; ASSERT_FALSE(board.undoMove()); board.playChess(ChessMove(COLOR_BLACK, 7, 7)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 7)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 7, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 5)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 6, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 8)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 8, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 6, 9)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_BLACK, 9, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 5, 6)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 4, 7)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 3, 8)); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 2, 9)); ASSERT_TRUE(board.isGameOver()); ChessBoard other = board; ASSERT_TRUE(other== board); board.undoMove(); ASSERT_FALSE(other == board); ASSERT_FALSE(board.isGameOver()); board.playChess(ChessMove(COLOR_WHITE, 2, 9)); ASSERT_TRUE(board.isGameOver()); ASSERT_TRUE(other == board); }
#pragma once namespace Encoder { class Encoder { public: virtual ~Encoder(){}; virtual bool getAngleDeg(float &angle) = 0; virtual bool getAngularVelocityDegPerSec(float &speed) = 0; virtual bool reset() = 0; }; } // namespace Encoder
#include <uWS/uWS.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "helpers.h" #include "json.hpp" #include "spline.h" // for convenience using nlohmann::json; using std::string; using std::vector; int main() { uWS::Hub h; // Load up map values for waypoint's x,y,s and d normalized normal vectors vector<double> map_waypoints_x; vector<double> map_waypoints_y; vector<double> map_waypoints_s; vector<double> map_waypoints_dx; vector<double> map_waypoints_dy; // Waypoint map to read from string map_file_ = "../data/highway_map.csv"; // The max s value before wrapping around the track back to 0 double max_s = 6945.554; std::ifstream in_map_(map_file_.c_str(), std::ifstream::in); // Get data from file string line; while (getline(in_map_, line)) { std::istringstream iss(line); double x; double y; float s; float d_x; float d_y; iss >> x; iss >> y; iss >> s; iss >> d_x; iss >> d_y; map_waypoints_x.push_back(x); map_waypoints_y.push_back(y); map_waypoints_s.push_back(s); map_waypoints_dx.push_back(d_x); map_waypoints_dy.push_back(d_y); } // Set initial lane and velocity int lane = 1; double vel = 3.0; h.onMessage([&vel, &map_waypoints_x,&map_waypoints_y,&map_waypoints_s, &map_waypoints_dx,&map_waypoints_dy, &lane] (uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(data); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { // j[1] is the data JSON object // Main car's localization Data double car_x = j[1]["x"]; double car_y = j[1]["y"]; double car_s = j[1]["s"]; double car_d = j[1]["d"]; double car_yaw = j[1]["yaw"]; double car_speed = j[1]["speed"]; // Previous path data given to the Planner auto previous_path_x = j[1]["previous_path_x"]; auto previous_path_y = j[1]["previous_path_y"]; // Previous path's end s and d values double end_path_s = j[1]["end_path_s"]; double end_path_d = j[1]["end_path_d"]; // Sensor Fusion Data, a list of all other cars on the same side // of the road. auto sensor_fusion = j[1]["sensor_fusion"]; int previous_size = previous_path_x.size(); if(previous_size > 0){ car_s = end_path_s; } bool too_close = false; bool left_free = true; bool right_free = true; // In case when car is driving left or right lane if(lane == 0){ left_free = false; } else if(lane == 2){ right_free = false; } double back = (50 - vel) * 0.4 + 3; // Predict traffic for(int i = 0; i < sensor_fusion.size(); i++){ float d = sensor_fusion[i][6]; double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double speed = sqrt(vx*vx + vy*vy); double s = sensor_fusion[i][5]; s += ((double)previous_size * 0.02 * speed); // car is in my lane if(d < (2+4*lane+2) && d > (2+4*lane-2)){ if((s > car_s) && ((s - car_s) < 30)){ too_close = true; } } // opportunity to change lane else{ if(s - car_s < 33 && car_s - s < back){ if(lane > 0 && d < (4+4*(lane-1)) && d > (4*(lane-1))){ left_free = false; } else if(lane < 2 && d < (4+4*(lane+1)) && d > (4*(lane+1))){ right_free = false; } } } } // max speed and acceleration double max_speed = 49.4; double acc = 0.23; if(too_close){ if(left_free || right_free){ if(left_free){ lane--; } else{ lane++; } } else{ vel -= acc; } } else if(vel < max_speed){ vel += acc; } // Get list of waypoints (x, y) to interpolate them with spline // and fill it in with more points to control speed vector<double> ptsx; vector<double> ptsy; double ref_x = car_x; double ref_y = car_y; double ref_yaw = deg2rad(car_yaw); // if previous_size is almost empty if(previous_size < 2){ double prev_car_x = car_x - cos(car_yaw); double prev_car_y = car_y - sin(car_yaw); ptsx.push_back(prev_car_x); ptsx.push_back(car_x); ptsy.push_back(prev_car_y); ptsy.push_back(car_y); } else { ref_x = previous_path_x[previous_size - 1]; ref_y = previous_path_y[previous_size - 1]; double prev_ref_x = previous_path_x[previous_size - 2]; double prev_ref_y = previous_path_y[previous_size - 2]; ptsx.push_back(prev_ref_x); ptsx.push_back(ref_x); ptsy.push_back(prev_ref_y); ptsy.push_back(ref_y); } // In Freenet add evenly 30m spaced points ahead of the starting reference vector<double> next_wp0 = getXY(car_s+30, (2+4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y); vector<double> next_wp1 = getXY(car_s+60, (2+4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y); vector<double> next_wp2 = getXY(car_s+90, (2+4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y); ptsx.push_back(next_wp0[0]); ptsx.push_back(next_wp1[0]); ptsx.push_back(next_wp2[0]); ptsy.push_back(next_wp0[1]); ptsy.push_back(next_wp1[1]); ptsy.push_back(next_wp2[1]); // shift car reference to 0 degrees for(int i = 0; i < ptsx.size(); i++){ double shift_x = ptsx[i] - ref_x; double shift_y = ptsy[i] - ref_y; ptsx[i] = (shift_x * cos(0-ref_yaw) - shift_y * sin(0-ref_yaw)); ptsy[i] = (shift_x * sin(0-ref_yaw) + shift_y * cos(0-ref_yaw)); } // create a spline tk::spline s; // set (x, y) points to the spline s.set_points(ptsx, ptsy); json msgJson; // define (x, y) points for planner vector<double> next_x_vals; vector<double> next_y_vals; /** * TODO: define a path made up of (x,y) points that the car will visit * sequentially every .02 seconds */ // start planner with points from previous time for(int i = 0; i < previous_size; i++){ next_x_vals.push_back(previous_path_x[i]); next_y_vals.push_back(previous_path_y[i]); } // Calculate how to break up spline points double target_x = 30.0; double target_y = s(target_x); double target_dist = sqrt((target_x * target_x) + (target_y * target_y)); double x_add_on = 0; // Fill up the rest of path planner for(int i = 0; i < (50 - previous_size); i++){ double N = target_dist / (0.02 * vel / 2.24); double x_point = x_add_on + (target_x / N); double y_point = s(x_point); x_add_on = x_point; double x_ref = x_point; double y_ref = y_point; // Rotate them back to normal after rotating them earlier x_point = x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw); y_point = x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw); x_point += ref_x; y_point += ref_y; next_x_vals.push_back(x_point); next_y_vals.push_back(y_point); } // double dist_inc = 0.5; // for (int i = 0; i < 50; ++i) { // next_x_vals.push_back(car_x+(dist_inc*i)*cos(deg2rad(car_yaw))); // next_y_vals.push_back(car_y+(dist_inc*i)*sin(deg2rad(car_yaw))); // } msgJson["next_x"] = next_x_vals; msgJson["next_y"] = next_y_vals; auto msg = "42[\"control\","+ msgJson.dump()+"]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } // end "telemetry" if } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } // end websocket if }); // end h.onMessage h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
#include <unordered_map> #include <unordered_set> #include <vector> using namespace std; class Solution { public: bool uniqueOccurrences(vector<int>& arr) { unordered_map<int, int> m; for (auto elem : arr) { if (m.count(elem)) ++m[elem]; else m[elem] = 1; } unordered_set<int> s; for (auto elem : m) { if (s.count(elem.second)) return false; else s.insert(elem.second); } return true; } };
#include "connectdialog.h" #include "ui_connectdialog.h" connectDialog::connectDialog(QWidget *parent) : QDialog(parent), ui(new Ui::connectDialog) { this->setWindowFlags(this->windowFlags()|Qt::FramelessWindowHint); ui->setupUi(this); } connectDialog::~connectDialog() { delete ui; } void connectDialog::success() { ui->label->setText("连接成功!!"); }
#include "catch.hpp" #include "window.hpp" #include "game.hpp" #include "player.hpp" #include "soldier.hpp" #include "misting.hpp" #include "mistborn.hpp" #include "metal.hpp" // game TEST_CASE("game constructor", "[game]") { Window window((DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, "Test"); SECTION("1") { Game game(&window); REQUIRE(game.get_window() == &window); } } TEST_CASE("player_1", "[game]") { Window window(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, "Test"); Game game(&window); SECTION("1") { Player player_1; game.set_player_1(player_1); REQUIRE(game.get_player_1() == player_1); } } TEST_CASE("player_2", "[game]") { Player player_2; game.set_player_2(player_2); SECTION("1") { REQUIRE(game.get_player_2() == player_2); } } TEST_CASE("field", "[game]") { SECTION("1") { Field field; game.set_field(field); REQUIRE(game.get_field() == field); } } TEST_CASE("game finish", "[game]") { SECTION("1") { REQUIRE(game.has_finished() == false); } } // player TEST_CASE("hp", "[player]") { Player player; SECTION("1") { REQUIRE(player.get_hp() == 0); } } TEST_CASE("soldiers", "[player]") { Player player; Soldier soldier; player.add_soldier(soldier); SECTION("1") { REQUIRE(player.get_soldiers()[0] == soldier); } } TEST_CASE("mistings", "[player]") { Player player; Misting misting; player.add_misting(misting); SECTION("1") { REQUIRE(player.get_mistings()[0] == misting); } } TEST_CASE("mistborns", "[player]") { Player player; Mistborn mistborn; player.add_mistborn(mistborn); SECTION("1") { REQUIRE(player.get_mistborns()[0] == mistborn); } } TEST_CASE("metals", "[player]") { Player player; Metal metal; player.add_metal(metal); SECTION("1") { REQUIRE(player.get_metals()[0] == metal); } }
#include <stdio.h> #include <string.h> #include <vector> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "__t__serviceimpl.h" #include "iComm.h" #include "dn.h" using namespace Comm; using namespace std; __T__ServiceImpl :: __T__ServiceImpl(){} __T__ServiceImpl :: ~__T__ServiceImpl(){} __T_MOTHOD_P__
#pragma once #include "gameNode.h" struct tagWall { RECT top; RECT bot; bool isScored; }; class mainGame : public gameNode { private: RECT _rc; RECT _land[3]; tagWall _wall[10]; char str[64]; char str2[64]; float countdown; int _x, _y; float _jumpPower, _gravity; bool _isStart; bool _isGameOver; bool _isJump; int score; float level; public: virtual HRESULT init(void); //초기화 virtual void release(void); //메모리 해제 virtual void update(void); //연산관련(타이머) virtual void render(HDC hdc); //그려주는 함수 mainGame(); ~mainGame(); };
#include <stdio.h> #include <math.h> #include <iostream> using namespace std; double LM(double *l,double *T1,double *T2); double MM(double *l,double *T3,double *T4); double NM(double *l,double *T1,double *T2,double *T3,double *T4); double Udot(double *X,double *m,double *q,double *r,double *W,double *V,double *th); double Vdot(double *Y,double *m,double *r,double *p,double *U,double *W,double *th,double *phi); double Wdot(double *Z,double *m,double *p,double *q,double *V,double *U,double *th,double *phi); double Wdot(double *Z,double *m,double *p,double *q,double *V,double *U,double *th,double *phi); double Pdot(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N); double Qdot(double *Ix,double *Iy,double *Iz,double *Ixz,double *r,double *p,double *M); double Rdot(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N); double Phidot(double *p,double *q,double *r,double *th,double *phi); double Thdot(double *q,double *r,double *phi); double Yawdot(double *q,double *r,double *phi,double *th); double Fu(double *X,double *m,double *q,double *r,double *W,double *V,double *th,double *h,double *U); double Fv(double *Y,double *m,double *p,double *r,double *W,double *U,double *th,double *h,double *phi,double *V); double Fw(double *Z,double *m,double *p,double *q,double *V,double *U,double *th,double *h,double *phi,double *W); double Fp(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N,double *h,double *P); double Fq(double *Ix,double *Iy,double *Iz,double *Ixz,double *p,double *r,double *M,double *h,double *Q); double Fr(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N,double *h,double *R); double Fphi(double *p,double *q,double *r,double *th,double *phi,double *h,double *Phi); double Fth(double *q,double *r,double *phi,double *h,double *Th); double Fyaw(double *q,double *r,double *th,double *phi,double *h,double *Yaw); main(){ double X,Y,Z,m,p,q,r,phi,W,V,U,P,Q,R,th,Phi,Th,Yaw,yaw,Ix,Iy,Iz,Ixz,Izx,L,M,N,h,LM1,l,MM1,NM1; double T1,T2,T3,T4; double udot,vdot,wdot,pdot,qdot,rdot,phidot,thdot,yawdot; //double k1[9],k2[9],k3[9],k4[9]; X = 3.0; //Xの初期値 Y = 5.0; //Yの初期値 Z = 100.0; //Zの初期値 m = 617.0; //機体の重量 p = 25.0; //x方向の回転角の初期位置 q = 2.0; //y方向の回転角の初期位置 r = 3.0; //z方向の回転角の初期位置 W = 5.0; //x方向の速度の初期位置 V = 4.0; //Y方向の速度の初期位置 U = 50.0; //z方向の速度の初期位置 th = 30.0; //thの初期角度 phi =30.0; //phiの初期角度 yaw = 10.0; //yawの初期角度 Ix = 5.0; //Ixの初期値 Iy = 7.0; //Iyの初期値 Iz = 13.0; //Izの初期値 Ixz = 21.0; //Ixzの初期値 Izx = 9.0; //Izxの初期値 L = 23.0; //Lの初期値 M = 31.0; //Mの初期値 N = 67.0; //Nの初期値 h = 0.01; //刻み幅 l =5.0; //腕の長さ T1 =10.0; T2 =20.0; T3 =15.0; T4 =40.0; // while (1){ printf("%5.3f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f" ,U,V,W,p,q,r,phi,th,yaw); cout<<endl; LM1 = LM(&l,&T1,&T2); MM1 = MM(&l,&T3,&T4); NM1 = NM(&l,&T1,&T2,&T3,&T4); udot = Udot(&X,&m,&q,&r,&W,&V,&th); vdot = Vdot(&Y,&m,&r,&p,&U,&W,&th,&phi); wdot = Wdot(&Z,&m,&p,&q,&V,&U,&th,&phi); pdot = Pdot(&Ix,&Iy,&Iz,&Ixz,&Izx,&p,&q,&r,&L,&N); cout<<"pdot="<<pdot<<endl; qdot = Qdot(&Ix,&Iy,&Iz,&Ixz,&p,&r,&M); cout<<"qdot="<<qdot<<endl; rdot = Rdot(&Ix,&Iy,&Iz,&Ixz,&Izx,&p,&q,&r,&L,&N); cout<<"rdot="<<Rdot(&Ix,&Iy,&Iz,&Ixz,&Izx,&p,&q,&r,&L,&N)<<endl; phidot = Phidot(&p,&q,&r,&phi,&th); cout<<"Phidot="<<phidot<<endl; thdot = Thdot(&q,&r,&phi); cout<<"Thdot="<<Thdot(&q,&r,&phi)<<endl; yawdot = Yawdot(&q,&r,&phi,&th); cout<<"yawdot="<<yawdot<<endl; U = Fu(&X,&m,&p,&r,&W,&V,&th,&h,&U); cout<<"U="<<U<<endl; V = Fv(&Y,&m,&p,&r,&W,&U,&th,&h,&phi,&V); cout<<"V="<<V<<endl; W = Fw(&Z,&m,&p,&q,&V,&U,&th,&h,&phi,&W); cout<<"W="<<W<<endl; p = Fp(&Ix,&Iy,&Iz,&Ixz,&Izx,&p,&q,&r,&L,&N,&h,&P); cout<<"P="<<P<<endl; q = Fq(&Ix,&Iy,&Iz,&Ixz,&p,&r,&M,&h,&Q); cout<<"Q="<<Q<<endl; r = Fr(&Ix,&Iy,&Iz,&Ixz,&Izx,&p,&q,&r,&L,&N,&h,&R); cout<<"R="<<R<<endl; phi = Fphi(&p,&q,&r,&th,&phi,&h,&Phi); cout<<"phi="<<Phi<<endl; th = Fth(&q,&r,&phi,&h,&Th); cout<<"Th="<<Th<<endl; yaw = Fyaw(&q,&r,&th,&phi,&h,&Yaw); cout<<"Yaw="<<Yaw<<endl; // } } double LM(double *l,double *T1,double *T2) { return (*l) * ((*T2) - (*T1)); } double MM(double *l,double *T3,double *T4) { return(*l) * ((*T3) - (*T4)); } double NM(double *l,double *T1,double *T2,double *T3,double *T4) { return (*l) * ((*T1) + (*T2) - ((*T3) + (*T4))); } double Udot(double *X,double *m,double *q,double *r,double *W,double *V,double *th) { return (*X)/(*m) - 9.80665*sin(*th) - (*q)*(*W) + (*r)*(*V); } double Vdot(double *Y,double *m,double *r,double *p,double *U,double *W,double *th,double *phi) { return (*Y)/(*m) + 9.80665*cos(*th)*sin(*phi) - (*r)*(*U) + (*p)*(*W); } double Wdot(double *Z,double *m,double *p,double *q,double *V,double *U,double *th,double *phi) { return (*Z)/(*m )+ 9.80665*cos(*th)*cos(*phi) - (*p)*(*V) + (*q)*(*U); } double Pdot(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N) { double pdot,pbunbo,pbunshi; pbunbo = ((*Iz)*((*L) - (*q)*(*r)*((*Iz)-(*Iy)) + (*p)*(*q)*(*Ixz)) + (*Izx)*((*N) - (*p)*(*q)*((*Iy)-(*Ix)) - (*q)*(*r)*(*Ixz))); pbunshi = (((*Ix)*(*Iz)) - ((*Ixz)*(*Izx))); pdot = pbunbo / pbunshi; return pdot; } double Qdot(double *Ix,double *Iy,double *Iz,double *Ixz,double *r,double *p,double *M) { return ((*M) - ((*r)*(*p)*((*Ix)-(*Iz))) - ((*Ixz)*((*r)*(*r) - (*p)*(*p)))) / (*Iy); } double Rdot(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N) { double rbunbo,rbunshi; rbunbo = ((*Ixz)*((*L) - (*q)*(*r)*((*Iz)-(*Iy)) + (*p)*(*q)*(*Ixz)) + (*Ix)*((*N) - (*p)*(*q)*((*Iz)-(*Ix)) - (*q)*(*r)*(*Ixz))); rbunshi = (((*Ix)*(*Iz)) - ((*Izx)*(*Ixz))); return rbunbo / rbunshi; } double Phidot(double *p,double *q,double *r,double *th,double *phi) { return (*p) + (*q)*sin(*phi)*tan(*th) + (*r)*cos(*phi)*tan(*th); } double Thdot(double *q,double *r,double *phi) { return ((*q)*cos(*phi)) - ((*r)*sin(*phi)); } double Yawdot(double *q,double *r,double *phi,double *th) { return (*q)*sin(*phi)*(1/cos(*th)) + (*r)*cos(*phi)*(1/cos(*th)); } double Fu(double *X,double *m,double *q,double *r,double *W,double *V,double *th,double *h,double *U) { double k[4]; double Fux,Fum,Fuq,Fur,FuW,FuV,Futh; k[0] = Udot(X,m,q,r,W,V,th); for(int i=0;i<2;i++) { Fux=((*X)+(*h)*k[i]*0.5); Fum=((*m)+(*h)*k[i]*0.5); Fuq=((*q)+(*h)*k[i]*0.5); Fur=((*r)+(*h)*k[i]*0.5); FuW=((*W)+(*h)*k[i]*0.5); FuV=((*V)+(*h)*k[i]*0.5); Futh=((*th)+(*h)*k[i]*0.5); k[i+1] = Udot(&Fux,&Fum,&Fuq,&Fur,&FuW,&FuV,&Futh); } Fux=((*X)+(*h)*k[2]); Fum=((*m)+(*h)*k[2]); Fuq=((*q)+(*h)*k[2]); Fur=((*r)+(*h)*k[2]); FuW=((*W)+(*h)*k[2]); FuV=((*V)+(*h)*k[2]); Futh=((*th)+(*h)*k[2]); k[3] = Udot(&Fux,&Fum,&Fuq,&Fur,&FuW,&FuV,&Futh); *U = *U + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *U; } double Fv(double *Y,double *m,double *p,double *r,double *W,double *U,double *th,double *h,double *phi,double *V) { double k[4]; double Fvy,Fvm,Fvp,Fvr,FvW,FvU,Fvth,Fvphi; k[0] = Vdot(Y,m,p,r,W,U,th,phi); for(int i=0;i<3;i++) { Fvy=((*Y)+(*h)*k[i]*0.5); Fvm=((*m)+(*h)*k[i]*0.5); Fvp=((*p)+(*h)*k[i]*0.5); Fvr=((*r)+(*h)*k[i]*0.5); FvW=((*W)+(*h)*k[i]*0.5); FvU=((*U)+(*h)*k[i]*0.5); Fvth=((*th)+(*h)*k[i]*0.5); Fvphi=(*phi)+(*h)*k[i]*0.5; k[i+1] = Vdot(&Fvy,&Fvm,&Fvp,&Fvr,&FvW,&FvU,&Fvth,&Fvphi); } Fvy=((*Y)+(*h)*k[2]); Fvm=((*m)+(*h)*k[2]); Fvp=((*p)+(*h)*k[2]); Fvr=((*r)+(*h)*k[2]); FvW=((*W)+(*h)*k[2]); FvU=((*U)+(*h)*k[2]); Fvth=((*th)+(*h)*k[2]); Fvphi=(*phi)+(*h)*k[2]; k[3] = Vdot(&Fvy,&Fvm,&Fvp,&Fvr,&FvW,&FvU,&Fvth,&Fvphi); *V = *V + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *V; } double Fw(double *Z,double *m,double *p,double *q,double *V,double *U,double *th,double *h,double *phi,double *W) { double k[4]; double Fwy,Fwm,Fwp,Fwq,FwV,FwU,Fwth,Fwphi; k[0] = Wdot(Z,m,p,q,V,U,th,phi); for(int i=0;i<3;i++) { Fwy=((*Z)+(*h)*k[i]*0.5); Fwm=((*m)+(*h)*k[i]*0.5); Fwp=((*p)+(*h)*k[i]*0.5); Fwq=((*q)+(*h)*k[i]*0.5); FwV=((*W)+(*h)*k[i]*0.5); FwU=((*U)+(*h)*k[i]*0.5); Fwth=((*th)+(*h)*k[i]*0.5); Fwphi=(*phi)+(*h)*k[i]*0.5; k[i+1] = Wdot(&Fwy,&Fwm,&Fwp,&Fwq,&FwV,&FwU,&Fwth,&Fwphi); } Fwy=((*Z)+(*h)*k[2]); Fwm=((*m)+(*h)*k[2]); Fwp=((*p)+(*h)*k[2]); Fwq=((*q)+(*h)*k[2]); FwV=((*W)+(*h)*k[2]); FwU=((*U)+(*h)*k[2]); Fwth=((*th)+(*h)*k[2]); Fwphi=(*phi)+(*h)*k[2]; k[3] = Wdot(&Fwy,&Fwm,&Fwp,&Fwq,&FwV,&FwU,&Fwth,&Fwphi); *W = *W + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *W; } double Fp(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N,double *h,double *P) { double FpIx,FpIy,FpIz,FpIxz,FpIzx,Fpp,Fpq,Fpr,FpL,FpN; double k[4]; k[0] = Pdot(Ix,Iy,Iz,Ixz,Izx,p,q,r,L,N); for(int i=0;i<3;i++) { FpIx = (*Ix)+(*h)*k[i]*0.5; FpIy = (*Iy)+(*h)*k[i]*0.5; FpIz = (*Iz)+(*h)*k[i]*0.5; FpIxz = (*Ixz)+(*h)*k[i]*0.5; FpIzx = (*Izx)+(*h)*k[i]*0.5; Fpp = (*p)+(*h)*k[i]*0.5; Fpq = (*q)+(*h)*k[i]*0.5; Fpr = (*r)+(*h)*k[i]*0.5; FpL = (*L)+(*h)*k[i]*0.5; FpN = (*N)+(*h)*k[i]*0.5; k[i+1] = Pdot(&FpIx,&FpIy,&FpIz,&FpIxz,&FpIzx,&Fpp,&Fpq,&Fpr,&FpL,&FpN); } *P = *P + ((*h) * (k[0] + 2*k[1] + 2*k[2] +k[3])) / 6; return *P; } double Fq(double *Ix,double *Iy,double *Iz,double *Ixz,double *p,double *r,double *M,double *h,double *Q) { double k[4]; double FqIx,FqIy,FqIz,FqIxz,Fqp,Fqr,FqM; k[0] = Qdot(Ix,Iy,Iz,Ixz,p,r,M); for(int i=0;i<3;i++) { FqIx = (*Ix)+(*h)*k[i]*0.5; FqIy = (*Iy)+(*h)*k[i]*0.5; FqIz = (*Iz)+(*h)*k[i]*0.5; FqIxz = (*Ixz)+(*h)*k[i]*0.5; Fqp = (*p)+(*h)*k[i]*0.5; Fqr = (*r)+(*h)*k[i]*0.5; FqM = (*M)+(*h)*k[i]*0.5; k[i+1] = Qdot(&FqIx,&FqIy,&FqIz,&FqIxz,&Fqp,&Fqr,&FqM); } *Q = *Q + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *Q; } double Fr(double *Ix,double *Iy,double *Iz,double *Ixz,double *Izx,double *p,double *q,double *r,double *L,double *N,double *h,double *R) { double k[4]; double FrIx,FrIy,FrIz,FrIxz,FrIzx,Frp,Frq,Frr,FrL,FrN; k[0] = Rdot(Ix,Iy,Iz,Ixz,Izx,p,q,r,L,N); for(int i=0;i<3;i++) { FrIx = (*Ix)+(*h)*k[i]*0.5; FrIy = (*Iy)+(*h)*k[i]*0.5; FrIz = (*Iz)+(*h)*k[i]*0.5; FrIxz = (*Ixz)+(*h)*k[i]*0.5; FrIzx = (*Izx)+(*h)*k[i]*0.5; Frp = (*p)+(*h)*k[i]*0.5; Frq = (*q)+(*h)*k[i]*0.5; Frr = (*r)+(*h)*k[i]*0.5; FrL = (*L)+(*h)*k[i]*0.5; FrN = (*N)+(*h)*k[i]*0.5; k[i+1] = Rdot(&FrIx,&FrIy,&FrIz,&FrIxz,&FrIzx,&Frp,&Frq,&Frr,&FrL,&FrN); } *R = *R + ((*h) * (k[0] + 2*k[1] + 2*k[2] +k[3])) / 6; return *R; } double Fphi(double *p,double *q,double *r,double *th,double *phi,double *h,double *Phi) { double k[4]; double Fphi_p,Fphi_q,Fphi_r,Fphi_th,Fphi_phi; k[0] = Phidot(p,q,r,th,phi); for(int i=0;i<3;i++) { Fphi_p = (*p)+(*h)*k[i]*0.5; Fphi_q = (*q)+(*h)*k[i]*0.5; Fphi_r = (*r)+(*h)*k[i]*0.5; Fphi_th = (*th)+(*h)*k[i]*0.5; Fphi_phi = (*phi)+(*h)*k[i]*0.5; k[i+1] = Phidot(&Fphi_p,&Fphi_q,&Fphi_r,&Fphi_th,&Fphi_phi); } *Phi = *Phi + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *Phi; } double Fth(double *q,double *r,double *phi,double *h,double *Th) { double k[4]; double Fth_q,Fth_r,Fth_phi; k[0] = Thdot(q,r,phi); for(int i=0;i<3;i++) { Fth_q = (*q)+(*h)*k[i]*0.5; Fth_r = (*r)+(*h)*k[i]*0.5; Fth_phi = (*phi)+(*h)*k[i]*0.5; k[i+1] = Thdot(&Fth_q,&Fth_r,&Fth_phi); } *Th = *Th + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *Th; } double Fyaw(double *q,double *r,double *th,double *phi,double *h,double *Yaw) { double k[4]; double Fyaw_q,Fyaw_r,Fyaw_th,Fyaw_phi; k[0] = Yawdot(q,r,th,phi); for(int i=0;i<3;i++) { Fyaw_q = (*q)+(*h)*k[i]*0.5; Fyaw_r = (*r)+(*h)*k[i]*0.5; Fyaw_th = (*th)+(*h)*k[i]*0.5; Fyaw_phi = (*phi)+(*h)*k[i]*0.5; } *Yaw = *Yaw + ((*h) * (k[0] + 2*k[1] + 2*k[2] + k[3])) / 6; return *Yaw; }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __YUNOS_VIDEO_CAPTURE_SOURCE_TIME_LAPSE_H_ #define __YUNOS_VIDEO_CAPTURE_SOURCE_TIME_LAPSE_H_ #include <stdint.h> #include <string> #include <list> #include <multimedia/mm_errors.h> #include <multimedia/mm_cpp_utils.h> #include <multimedia/media_buffer.h> #include "video_capture_source.h" #ifdef __MM_YUNOS_YUNHAL_BUILD__ #include "multimedia/mm_surface_compat.h" #endif #include "multimedia/mm_camera_compat.h" namespace YunOSCameraNS { class VideoCaptureCallback; class VideoCapture; class VCMSHMem; class RecordingProxy; class Size; } using YunOSCameraNS::VideoCaptureCallback; using YunOSCameraNS::VideoCapture; using YunOSCameraNS::VCMSHMem; using YunOSCameraNS::RecordingProxy; using YunOSCameraNS::Size; #if MM_USE_CAMERA_VERSION>=30 namespace YunOSCameraNS { class VideoCaptureParam; } using YunOSCameraNS::VideoCaptureParam; #else namespace YunOSCameraNS { class Properties; } using YunOSCameraNS::Properties; #endif namespace YUNOS_MM { /** * @breif Interface for VideoCapture V1. * @since 4.0 */ class VideoCaptureSourceListener; class VideoCaptureSourceTimeLapse : public VideoCaptureSource { public: virtual ~VideoCaptureSourceTimeLapse(); static VideoCaptureSourceTimeLapse* create(VideoCapture *camera, RecordingProxy *recordingProxy, void *surface, Size *videoSize, int32_t frameRate, int64_t captureFrameDurationUs, bool storeMetaDataInVideoBuffers); protected: virtual bool skipCurrentFrame(int64_t *timestampUs); private: VideoCaptureSourceTimeLapse(int32_t cameraId, VideoCapture *camera, RecordingProxy *recordingProxy, void *surface, Size *videoSize, int32_t frameRate, int64_t captureFrameDurationUs, bool storeMetaDataInVideoBuffers); private: // Time between two frames in final video (1/frameRate) int64_t mVideoFrameDurationUs; // Real timestamp of the last encoded time lapse frame int64_t mLastFrameRealTimestampUs; bool mSkipCurrentFrame; MM_DISALLOW_COPY(VideoCaptureSourceTimeLapse); }; } #endif //__YUNOS_VIDEO_CAPTURE_SOURCE_TIME_LAPSE_H_
#pragma once #include <string> /* 문제: 4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일 X가 올바른 괄호열이면 ‘(X)’이나 ‘[X]’도 모두 올바른 괄호열이 된다. X와 Y 모두 올바른 괄호열이라면 이들을 결합한 XY도 올바른 괄호열이 된다. 예를 들어 ‘(()[[]])’나 ‘(())[][]’ 는 올바른 괄호열이지만 ‘([)]’ 나 ‘(()()[]’ 은 모두 올바른 괄호열이 아니다. 우리는 어떤 올바른 괄호열 X에 대하여 그 괄호열의 값(괄호값)을 아래와 같이 정의하고 값(X)로 표시한다. ‘()’ 인 괄호열의 값은 2이다. ‘[]’ 인 괄호열의 값은 3이다. ‘(X)’ 의 괄호값은 2×값(X) 으로 계산된다. ‘[X]’ 의 괄호값은 3×값(X) 으로 계산된다. 올바른 괄호열 X와 Y가 결합된 XY의 괄호값은 값(XY)= 값(X)+값(Y) 로 계산된다. 예를 들어 ‘(()[[]])([])’ 의 괄호값을 구해보자. ‘()[[]]’ 의 괄호값이 2 + 3×3=11 이므로 ‘(()[[ ]])’의 괄호값은 2×11=22 이다. 그리고 ‘([])’의 값은 2×3=6 이므로 전체 괄호열의 값은 22 + 6 = 28 이다. 여러분이 풀어야 할 문제는 주어진 괄호열을 읽고 그 괄호값을 앞에서 정의한대로 계산하여 출력하는 것이다. 입력: 첫째 줄에 괄호열을 나타내는 문자열(스트링)이 주어진다. 단 그 길이는 1 이상, 30 이하이다 출력: 첫째 줄에 그 괄호열의 값을 나타내는 정수를 출력한다. 만일 입력이 올바르지 못한 괄호열이면 반드시 0을 출력해야 한다. 예제 입력 1: (()[[]])([]) 예제 출력 1: 28 나의 방법: 1) 치환으로 풀자 -> 재귀동작을 해야하기 떄문에 메모리도 너무 많이 사용하고, -> 시간도 매우 많이 걸린다. 2) 메모리, 시간을 줄이자. -> 기존에 주어진 스택을 활용하여, 새로운 스택을 만들지 않는 기존 스택을 변경하면서 풀어나간다. 이 방법은 재귀동작도 기하급수적으로 줄고, 추가적인 스택도 사용하지 않는다. 스터디 풀이 방법들: 1. 문자열 검색을 이후 치환하며 풀어간다. (오래걸림 + 정답 따로 스택에 저장) 2. 분할정복 방법 (재귀호출.. 스택 쌓임..) */ using INPUT = std::string; using OUTPUT = int; using SOLUTION = OUTPUT(*)(INPUT); OUTPUT solution2504_1(INPUT); OUTPUT solution2504_2(INPUT); OUTPUT solution2504_3(INPUT);
// Problem : B. Minimum Average Path // Contest : Codeforces - ITMO Academy: pilot course - Binary Search - Step 4 // URL : https://codeforces.com/edu/course/2/lesson/6/4/practice/contest/285069/problem/B // Memory Limit : 512 MB // Time Limit : 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") //#pragma GCC optimize(3) //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") //#pragma GCC target("sse3","sse2","sse") //#pragma GCC target("avx","sse4","sse4.1","sse4.2","ssse3") //#pragma GCC target("f16c") //#pragma GCC optimize("inline","fast-math","unroll-loops","no-stack-protector") //#pragma GCC diagnostic error "-fwhole-program" //#pragma GCC diagnostic error "-fcse-skip-blocks" //#pragma GCC diagnostic error "-funsafe-loop-optimizations" //#pragma GCC diagnostic error "-std=c++14" #include <iostream> #include <vector> #include <cstring> #include <queue> #include <stack> #include <algorithm> #include <cmath> // 时间够不要用unordered_map,unordered_set // 不然会被CF大佬根据STL源码出的数据给hack掉 #include <map> #include <set> #include <unordered_map> #include <unordered_set> using namespace std; typedef unsigned long long ULL; typedef long long LL; typedef pair<int, int> PII; typedef pair<int, pair<int, int>> PIII; typedef pair<LL, int> PLI; typedef pair<ULL, int> PUI; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<LL> VL; typedef vector<PII> VPII; typedef pair<LL,LL> PLL; typedef vector<PLL> VPLL; typedef priority_queue<int, vector<int>, greater<int>> isheap; typedef priority_queue<int> ibheap; typedef priority_queue<PII, vector<PII>, greater<PII>> piisheap; typedef priority_queue<PII> piibheap; typedef priority_queue<PIII, vector<PIII>, greater<PIII>> piiisheap; typedef priority_queue<PIII> piiibheap; // 常用操作的简写 #define PB push_back #define PF push_front #define se second #define fi first #define sz(x) ((int)x.size()) #define fr(x) freopen(x,"r",stdin) #define fw(x) freopen(x,"w",stdout) #define REP(x, l, u) for(int x = l; x <= u; x++) #define RREP(x, u, l) for(int x = u; x >= l; x--) #define sqr(x) (x * x) // 给静态数组设值 #define setZE(x) memset(x, 0, sizeof x) #define setPI(x) memset(x, 0x3f, sizeof x) #define setMI(x) memset(x, -0x3f, sizeof x) // lowbit操作,树状数组 #define lowbit(x) ((x)&(-(x))) // 直接输出x的二进制表示中的1的个数 #define bitcnt(x) (__builtin_popcountll(x)) // 方格问题中的方位 int dx4[4] = {0, 0, -1, 1}; int dy4[4] = {-1, 1, 0, 0}; int dx8[8] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dy8[8] = {-1, 0, 1, -1, 1, -1, 0, 1}; // 常用的取模 constexpr int M1 = 1e9 + 7; LL MOD(LL a, LL M) { a %= M; return a < 0 ? a + M : a; } /* * 数学板子 */ // 最大公约数 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } // 快速幂 LL qmi(LL a, LL b, LL mod) { if (!b) return 1; LL tmp = qmi(a, b >> 1, mod); tmp = (tmp * tmp) % mod; if (b & 1) tmp *= a; return tmp % mod; } /* * 输出输出优化 */ void io() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); } /* * 并查集函数 * 使用的时候需要先根据打下定义好fa数组 */ int UFfind(int f[], int a) { return a == f[a] ? f[a] : f[a] = UFfind(f, f[a]); } void UFinit(int f[], int n) { REP(i, 1, n) f[i] = i; } /****************** * 代码开始 * ************** */ //#define duipai //#define kickstart #define custom // #define multiTask /* * 数据初始定义 */ const int N = 1e5 + 10; int t; int n, m; VPII g[N]; int pre[N]; double dis[N]; // 每个测试数据的方法 void solve() { cin >> n >> m; REP(i, 1, m) { int a, b, c; cin >> a >> b >> c; g[a].PB({b, c}); } double l = 0.5, r = 101; while (r - l > 1e-4) { // cout << l << " " << r << endl; double mid = (l + r) / 2; dis[1] = 0; pre[1] = 0; REP(i, 2, n) dis[i] = 2e18; REP(i, 1, n) { for (auto x : g[i]) { int node = x.fi, dd = x.se; if (dis[node] > dis[i] + dd - mid) { dis[node] = dis[i] + dd - mid; pre[node] = i; } } } if (dis[n] <= 0) r = mid; else l = mid; } VI ans; ans.PB(n); int cur = pre[n]; while (cur) { ans.PB(cur); cur = pre[cur]; } reverse(ans.begin(), ans.end()); cout << sz(ans) - 1 << endl; for (auto x : ans) cout << x << " "; return; } #ifdef custom int main() { io(); #ifdef multiTask cin >> t; while (t --) #endif solve(); return 0; } #endif #ifdef duipai int main() { for(int T = 0; T < 10000; ++T) { system("./random > ./data.in"); double st = clock(); system("./sol < ./data.in > ./data.ans"); double et = clock(); system("./bf < ./data.in > ./data.out"); if(system("diff ./data.out ./ data.ans")) { puts("Wrong Answer\n"); return 0; } else { printf("Accepted, 测试点 #%d, 用时 %.0lfms\n", T, et - st); } } return 0; } #endif
#include <iostream> #include "CharacterVector.h" #include "DoubleVector.h" #include "IntegerVector.h" int main() { CharacterVector cv; DoubleVector dv; IntegerVector iv; //------------------------------------------------------------------------- // test DoubleVector: put, get, size, out_of_range std::cout << "----------------" << std::endl; std::cout << "DoubleVector:" << std::endl; dv.put(1.0); dv.put(-1.0); dv.put(100); std::cout << dv.size() << std::endl; dv.put(5.0,1); dv.put(100.0, 100); std::cout << dv.size() << std::endl; try { std::cout << dv.get(-1) << std::endl; } catch (const std::out_of_range& oor){ std::cerr << "Out of Range error: " << oor.what() << std::endl; } std::cout << "----------------" << std::endl; //------------------------------------------------------------------------- // test CharacterVector: put, get, size, out_of_range std::cout << std::endl; std::cout << "-------------" << std::endl; std::cout << "CharacterVector:" << std::endl; cv.put('p'); cv.put('u'); cv.put('d'); std::cout << cv.size() << std::endl; cv.put('a',1); cv.put('b', 100); std::cout << cv.size() << std::endl; try { std::cout << cv.get(-1) << std::endl; } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } std::cout << "-------------" << std::endl; //------------------------------------------------------------------------- // test IntegerVector: put, get, size, out_of_range std::cout << "--------------" << std::endl; std::cout << "IntegerVector:" << std::endl; std::cout << iv.size() << std::endl; iv.put(2); std::cout << iv.size() << std::endl; iv.put(99, 3); std::cout << iv.size() << std::endl; std::cout << iv.get(1) << "[99]" <<std::endl; std::cout << "[out of range error message next line]" << std::endl; try{ std::cout << iv.get(999) << std::endl; }catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << std::endl; } std::cout << "--------------" << std::endl; //------------------------------------------------------------------------- // using empty CharacterVector, test appending iv & dv from above CharacterVector cv2; std::cout << std::endl; std::cout << "----------------------------" << std::endl; std::cout << "appended-to CharacterVector:" << std::endl; std::cout << "----------------------------" << std::endl; //------------------------------------------------------------------------- // using empty DoubleVector, test appending iv & cv from above DoubleVector dv2; dv2.appendCharacterVector(cv); dv2.appendIntegerVector(iv); std::cout << std::endl; std::cout << dv2.size() << std::endl; std::cout << "-------------------------" << std::endl; std::cout << "appended-to DoubleVector:" << std::endl; std::cout << "-------------------------" << std::endl; //------------------------------------------------------------------------- // using empty IntegerVector, test appending cv & dv from above IntegerVector iv2; std::cout << std::endl; std::cout << "--------------------------" << std::endl; std::cout << "appended-to IntegerVector:" << std::endl; appendDoubleVector(dv); appendCharacterVector(dv); std::cout << "--------------------------" << std::endl; //------------------------------------------------------------------------- return 0; }
/* --- 1D BINARY INDEXED TREE --- */ #include <bits/stdc++.h> using namespace std; const int MAX = 8; // # of elements // 0 1 2 3 4 5 6 7 int arr[] = {1, 0, 2, 1, 1, 3, 0, 4}; vector<int> BIT(MAX); void update(int k, int v) { /* k = indx which need's to be updated v = value to be updated */ for (int i = k; i <= MAX; i += i&-i) { BIT[i] += v; } } int sum(int n) { /* Query sum for [1] to [n]; */ int su = 0; for (int i = n; i > 0; i -= i&-i) { su += BIT[i]; } return su; } int main() { for (int i = 1; i < MAX; i++) { update(i, arr[i]); } // Ex. Query for Sum from [3] to [5] int i = 0; int j = 5; printf("%i\n", sum(j) - sum(i - 1)); }
#ifndef _HS_SFM_UNIT_TEST_SFM_PIPELINE_DATA_TESTER_HPP_ #define _HS_SFM_UNIT_TEST_SFM_PIPELINE_DATA_TESTER_HPP_ #include <iostream> #include <fstream> #include "hs_math/linear_algebra/eigen_macro.hpp" #include "hs_math/geometry/euler_angles.hpp" #include "hs_sfm/sfm_utility/key_type.hpp" #include "hs_sfm/sfm_utility/camera_type.hpp" #include "hs_sfm/sfm_utility/match_type.hpp" #include "hs_sfm/sfm_pipeline/reprojective_error_calculator.hpp" #define DEBUG_TMP 1 namespace hs { namespace sfm { namespace pipeline { template <typename _Scalar> class DataTester { public: typedef _Scalar Scalar; typedef int Err; typedef hs::sfm::CameraIntrinsicParams<Scalar> IntrinsicParams; typedef EIGEN_STD_VECTOR(IntrinsicParams) IntrinsicParamsContainer; typedef hs::sfm::CameraExtrinsicParams<Scalar> ExtrinsicParams; typedef EIGEN_STD_VECTOR(ExtrinsicParams) ExtrinsicParamsContainer; typedef EIGEN_VECTOR(Scalar, 3) Point3D; typedef EIGEN_STD_VECTOR(Point3D) Point3DContainer; typedef hs::sfm::ImageKeys<Scalar> Keyset; typedef EIGEN_STD_VECTOR(Keyset) KeysetContainer; public: Err TestReprojectiveError( const KeysetContainer& keysets, const IntrinsicParamsContainer& intrinsic_params_set, const hs::sfm::TrackContainer& tracks, const hs::sfm::ObjectIndexMap& image_intrinsic_map, const hs::sfm::ObjectIndexMap& image_extrinsic_map, const hs::sfm::ObjectIndexMap& track_point_map, const hs::sfm::ViewInfoIndexer& view_info_indexer, const ExtrinsicParamsContainer& extrinsic_params_set, const Point3DContainer& points, Scalar key_stddev) const { typedef ReprojectiveErrorCalculator<Scalar> ReprojectiveErrorCalculator; ReprojectiveErrorCalculator reprojective_error_calculator; Scalar error = reprojective_error_calculator( keysets, intrinsic_params_set, tracks, image_intrinsic_map, image_extrinsic_map, track_point_map, view_info_indexer, extrinsic_params_set, points); #if DEBUG_TMP std::cout<<"error:"<<error<<"\n"; #endif if (error < key_stddev + 1) { return 0; } else { return -1; } } Err TestExtrinsicAccuracy( const ExtrinsicParamsContainer& extrinsic_params_set_true, const ExtrinsicParamsContainer& extrinsic_params_set_estimate, const std::string& accuracy_path, Scalar threshold) const { typedef EIGEN_MATRIX(Scalar, 3, 3) RMatrix; size_t number_of_extrinsics = extrinsic_params_set_true.size(); if (number_of_extrinsics != extrinsic_params_set_estimate.size()) { return -1; } std::ofstream accuracy_file(accuracy_path.c_str(), std::ios::out); if (!accuracy_file.is_open()) { return -1; } typedef hs::math::geometry::EulerAngles<Scalar> EulerAngles; Scalar mean_position_planar_error = Scalar(0); Scalar mean_position_height_error = Scalar(0); Scalar mean_rotation_angle0_error = Scalar(0); Scalar mean_rotation_angle1_error = Scalar(0); Scalar mean_rotation_angle2_error = Scalar(0); for (size_t i = 0; i < number_of_extrinsics; i++) { const ExtrinsicParams& extrinsic_params_estimate = extrinsic_params_set_estimate[i]; const ExtrinsicParams& extrinsic_params_true = extrinsic_params_set_true[i]; RMatrix rotation_estimate = extrinsic_params_estimate.rotation(); EulerAngles angles_estimate; angles_estimate.template FromOrthoRotMat<2, 1, -3, 1>( rotation_estimate); RMatrix rotation_true = extrinsic_params_true.rotation(); EulerAngles angles_true; angles_true.template FromOrthoRotMat<2, 1, -3, 1>( rotation_true); Scalar rotation_angle0_error = std::abs(angles_true[0] - angles_estimate[0]); Scalar rotation_angle1_error = std::abs(angles_true[1] - angles_estimate[1]); Scalar rotation_angle2_error = std::abs(angles_true[2] - angles_estimate[2]); const Point3D& position_estimate = extrinsic_params_estimate.position(); const Point3D& position_true = extrinsic_params_true.position(); Point3D position_diff = position_estimate - position_true; Scalar position_planar_error = position_diff.segment(0, 2).norm(); Scalar position_height_error = std::abs(position_diff[2]); mean_position_planar_error += position_planar_error; mean_position_height_error += position_height_error; mean_rotation_angle0_error += rotation_angle0_error; mean_rotation_angle1_error += rotation_angle1_error; mean_rotation_angle2_error += rotation_angle2_error; accuracy_file<<i<<" " <<position_estimate[0]<<" " <<position_estimate[1]<<" " <<position_estimate[2]<<" " <<position_planar_error<<" " <<position_height_error<<" " <<rotation_angle0_error<<" " <<rotation_angle1_error<<" " <<rotation_angle2_error<<"\n"; } mean_position_planar_error /= Scalar(number_of_extrinsics); mean_position_height_error /= Scalar(number_of_extrinsics); mean_rotation_angle0_error /= Scalar(number_of_extrinsics); mean_rotation_angle1_error /= Scalar(number_of_extrinsics); mean_rotation_angle2_error /= Scalar(number_of_extrinsics); accuracy_file<<"mean position planar error:" <<mean_position_planar_error<<"\n"; accuracy_file<<"mean position height error:" <<mean_position_height_error<<"\n"; accuracy_file<<"mean rotation angle0 error:" <<mean_rotation_angle0_error<<"\n"; accuracy_file<<"mean rotation angle1 error:" <<mean_rotation_angle1_error<<"\n"; accuracy_file<<"mean rotation angle2 error:" <<mean_rotation_angle2_error<<"\n"; if (mean_position_height_error < threshold) { return 0; } else { return -1; } } Err TestPointsAccuracy( const Point3DContainer& points_true, const Point3DContainer& points_estimate, const std::string& accuracy_path, Scalar threshold) const { size_t number_of_points = points_true.size(); if (points_estimate.size() != number_of_points) { return -1; } std::ofstream accuracy_file(accuracy_path.c_str(), std::ios::out); if (!accuracy_file.is_open()) { return -1; } Scalar mean_point_planar_error = Scalar(0); Scalar mean_point_height_error = Scalar(0); for (size_t i = 0; i < number_of_points; i++) { const Point3D point_estimate = points_estimate[i]; const Point3D point_true = points_true[i]; Point3D diff = point_estimate - point_true; Scalar planar_error = diff.segment(0, 2).norm(); Scalar height_error = std::abs(diff(2)); mean_point_planar_error += planar_error; mean_point_height_error += height_error; accuracy_file<<i<<" " <<point_true[0]<<" " <<point_true[1]<<" " <<point_true[2]<<" " <<point_estimate[0]<<" " <<point_estimate[1]<<" " <<point_estimate[2]<<" " <<planar_error<<" " <<height_error<<"\n"; } mean_point_planar_error /= Scalar(number_of_points); mean_point_height_error /= Scalar(number_of_points); accuracy_file<<"mean point planar error:" <<mean_point_planar_error<<"\n"; accuracy_file<<"mean point height error:" <<mean_point_height_error<<"\n"; return 0; } }; } } } #endif
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.ApplicationModel.Activation.0.h" #include "Windows.ApplicationModel.Appointments.AppointmentsProvider.0.h" #include "Windows.ApplicationModel.Background.0.h" #include "Windows.ApplicationModel.Calls.0.h" #include "Windows.ApplicationModel.Contacts.0.h" #include "Windows.ApplicationModel.Contacts.Provider.0.h" #include "Windows.ApplicationModel.DataTransfer.ShareTarget.0.h" #include "Windows.ApplicationModel.Search.0.h" #include "Windows.ApplicationModel.UserDataAccounts.Provider.0.h" #include "Windows.ApplicationModel.Wallet.0.h" #include "Windows.Devices.Enumeration.0.h" #include "Windows.Devices.Printers.Extensions.0.h" #include "Windows.Foundation.0.h" #include "Windows.Foundation.Collections.0.h" #include "Windows.Media.SpeechRecognition.0.h" #include "Windows.Security.Authentication.Web.0.h" #include "Windows.Security.Authentication.Web.Provider.0.h" #include "Windows.Storage.0.h" #include "Windows.Storage.Pickers.Provider.0.h" #include "Windows.Storage.Provider.0.h" #include "Windows.Storage.Search.0.h" #include "Windows.System.0.h" #include "Windows.UI.ViewManagement.0.h" #include "Windows.Foundation.1.h" #include "Windows.Storage.1.h" #include "Windows.Foundation.Collections.1.h" #include "Windows.UI.Notifications.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::ApplicationModel::Activation { struct __declspec(uuid("cf651713-cd08-4fd8-b697-a281b6544e2e")) __declspec(novtable) IActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Kind(winrt::Windows::ApplicationModel::Activation::ActivationKind * value) = 0; virtual HRESULT __stdcall get_PreviousExecutionState(winrt::Windows::ApplicationModel::Activation::ApplicationExecutionState * value) = 0; virtual HRESULT __stdcall get_SplashScreen(Windows::ApplicationModel::Activation::ISplashScreen ** value) = 0; }; struct __declspec(uuid("1cf09b9e-9962-4936-80ff-afc8e8ae5c8c")) __declspec(novtable) IActivatedEventArgsWithUser : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_User(Windows::System::IUser ** value) = 0; }; struct __declspec(uuid("930cef4b-b829-40fc-88f4-8513e8a64738")) __declspec(novtable) IApplicationViewActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CurrentlyShownApplicationViewId(int32_t * value) = 0; }; struct __declspec(uuid("3364c405-933c-4e7d-a034-500fb8dcd9f3")) __declspec(novtable) IAppointmentsProviderActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Verb(hstring * value) = 0; }; struct __declspec(uuid("a2861367-cee5-4e4d-9ed7-41c34ec18b02")) __declspec(novtable) IAppointmentsProviderAddAppointmentActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_AddAppointmentOperation(Windows::ApplicationModel::Appointments::AppointmentsProvider::IAddAppointmentOperation ** value) = 0; }; struct __declspec(uuid("751f3ab8-0b8e-451c-9f15-966e699bac25")) __declspec(novtable) IAppointmentsProviderRemoveAppointmentActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RemoveAppointmentOperation(Windows::ApplicationModel::Appointments::AppointmentsProvider::IRemoveAppointmentOperation ** value) = 0; }; struct __declspec(uuid("1551b7d4-a981-4067-8a62-0524e4ade121")) __declspec(novtable) IAppointmentsProviderReplaceAppointmentActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ReplaceAppointmentOperation(Windows::ApplicationModel::Appointments::AppointmentsProvider::IReplaceAppointmentOperation ** value) = 0; }; struct __declspec(uuid("3958f065-9841-4ca5-999b-885198b9ef2a")) __declspec(novtable) IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_InstanceStartDate(Windows::Foundation::IReference<Windows::Foundation::DateTime> ** value) = 0; virtual HRESULT __stdcall get_LocalId(hstring * value) = 0; virtual HRESULT __stdcall get_RoamingId(hstring * value) = 0; }; struct __declspec(uuid("9baeaba6-0e0b-49aa-babc-12b1dc774986")) __declspec(novtable) IAppointmentsProviderShowTimeFrameActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_TimeToShow(Windows::Foundation::DateTime * value) = 0; virtual HRESULT __stdcall get_Duration(Windows::Foundation::TimeSpan * value) = 0; }; struct __declspec(uuid("ab14bee0-e760-440e-a91c-44796de3a92d")) __declspec(novtable) IBackgroundActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_TaskInstance(Windows::ApplicationModel::Background::IBackgroundTaskInstance ** value) = 0; }; struct __declspec(uuid("d06eb1c7-3805-4ecb-b757-6cf15e26fef3")) __declspec(novtable) ICachedFileUpdaterActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CachedFileUpdaterUI(Windows::Storage::Provider::ICachedFileUpdaterUI ** value) = 0; }; struct __declspec(uuid("fb67a508-2dad-490a-9170-dca036eb114b")) __declspec(novtable) ICameraSettingsActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_VideoDeviceController(Windows::Foundation::IInspectable ** value) = 0; virtual HRESULT __stdcall get_VideoDeviceExtension(Windows::Foundation::IInspectable ** value) = 0; }; struct __declspec(uuid("d627a1c4-c025-4c41-9def-f1eafad075e7")) __declspec(novtable) IContactActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Verb(hstring * value) = 0; }; struct __declspec(uuid("c2df14c7-30eb-41c6-b3bc-5b1694f9dab3")) __declspec(novtable) IContactCallActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ServiceId(hstring * value) = 0; virtual HRESULT __stdcall get_ServiceUserId(hstring * value) = 0; virtual HRESULT __stdcall get_Contact(Windows::ApplicationModel::Contacts::IContact ** value) = 0; }; struct __declspec(uuid("b32bf870-eee7-4ad2-aaf1-a87effcf00a4")) __declspec(novtable) IContactMapActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Address(Windows::ApplicationModel::Contacts::IContactAddress ** value) = 0; virtual HRESULT __stdcall get_Contact(Windows::ApplicationModel::Contacts::IContact ** value) = 0; }; struct __declspec(uuid("de598db2-0e03-43b0-bf56-bcc40b3162df")) __declspec(novtable) IContactMessageActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ServiceId(hstring * value) = 0; virtual HRESULT __stdcall get_ServiceUserId(hstring * value) = 0; virtual HRESULT __stdcall get_Contact(Windows::ApplicationModel::Contacts::IContact ** value) = 0; }; struct __declspec(uuid("52bb63e4-d3d4-4b63-8051-4af2082cab80")) __declspec(novtable) IContactPanelActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ContactPanel(Windows::ApplicationModel::Contacts::IContactPanel ** value) = 0; virtual HRESULT __stdcall get_Contact(Windows::ApplicationModel::Contacts::IContact ** value) = 0; }; struct __declspec(uuid("ce57aae7-6449-45a7-971f-d113be7a8936")) __declspec(novtable) IContactPickerActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ContactPickerUI(Windows::ApplicationModel::Contacts::Provider::IContactPickerUI ** value) = 0; }; struct __declspec(uuid("b35a3c67-f1e7-4655-ad6e-4857588f552f")) __declspec(novtable) IContactPostActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ServiceId(hstring * value) = 0; virtual HRESULT __stdcall get_ServiceUserId(hstring * value) = 0; virtual HRESULT __stdcall get_Contact(Windows::ApplicationModel::Contacts::IContact ** value) = 0; }; struct __declspec(uuid("61079db8-e3e7-4b4f-858d-5c63a96ef684")) __declspec(novtable) IContactVideoCallActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ServiceId(hstring * value) = 0; virtual HRESULT __stdcall get_ServiceUserId(hstring * value) = 0; virtual HRESULT __stdcall get_Contact(Windows::ApplicationModel::Contacts::IContact ** value) = 0; }; struct __declspec(uuid("4580dca8-5750-4916-aa52-c0829521eb94")) __declspec(novtable) IContactsProviderActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Verb(hstring * value) = 0; }; struct __declspec(uuid("e58106b5-155f-4a94-a742-c7e08f4e188c")) __declspec(novtable) IContinuationActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ContinuationData(Windows::Foundation::Collections::IPropertySet ** value) = 0; }; struct __declspec(uuid("cd50b9a9-ce10-44d2-8234-c355a073ef33")) __declspec(novtable) IDeviceActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_DeviceInformationId(hstring * value) = 0; virtual HRESULT __stdcall get_Verb(hstring * value) = 0; }; struct __declspec(uuid("eba0d1e4-ecc6-4148-94ed-f4b37ec05b3e")) __declspec(novtable) IDevicePairingActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_DeviceInformation(Windows::Devices::Enumeration::IDeviceInformation ** value) = 0; }; struct __declspec(uuid("fb777ed7-85ee-456e-a44d-85d730e70aed")) __declspec(novtable) IDialReceiverActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_AppName(hstring * value) = 0; }; struct __declspec(uuid("bb2afc33-93b1-42ed-8b26-236dd9c78496")) __declspec(novtable) IFileActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Files(Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem> ** value) = 0; virtual HRESULT __stdcall get_Verb(hstring * value) = 0; }; struct __declspec(uuid("2d60f06b-d25f-4d25-8653-e1c5e1108309")) __declspec(novtable) IFileActivatedEventArgsWithCallerPackageFamilyName : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CallerPackageFamilyName(hstring * value) = 0; }; struct __declspec(uuid("433ba1a4-e1e2-48fd-b7fc-b5d6eee65033")) __declspec(novtable) IFileActivatedEventArgsWithNeighboringFiles : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_NeighboringFilesQuery(Windows::Storage::Search::IStorageFileQueryResult ** value) = 0; }; struct __declspec(uuid("72827082-5525-4bf2-bc09-1f5095d4964d")) __declspec(novtable) IFileOpenPickerActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_FileOpenPickerUI(Windows::Storage::Pickers::Provider::IFileOpenPickerUI ** value) = 0; }; struct __declspec(uuid("5e731f66-8d1f-45fb-af1d-73205c8fc7a1")) __declspec(novtable) IFileOpenPickerActivatedEventArgs2 : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CallerPackageFamilyName(hstring * value) = 0; }; struct __declspec(uuid("f0fa3f3a-d4e8-4ad3-9c34-2308f32fcec9")) __declspec(novtable) IFileOpenPickerContinuationEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Files(Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile> ** value) = 0; }; struct __declspec(uuid("81c19cf1-74e6-4387-82eb-bb8fd64b4346")) __declspec(novtable) IFileSavePickerActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_FileSavePickerUI(Windows::Storage::Pickers::Provider::IFileSavePickerUI ** value) = 0; }; struct __declspec(uuid("6b73fe13-2cf2-4d48-8cbc-af67d23f1ce7")) __declspec(novtable) IFileSavePickerActivatedEventArgs2 : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CallerPackageFamilyName(hstring * value) = 0; virtual HRESULT __stdcall get_EnterpriseId(hstring * value) = 0; }; struct __declspec(uuid("2c846fe1-3bad-4f33-8c8b-e46fae824b4b")) __declspec(novtable) IFileSavePickerContinuationEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_File(Windows::Storage::IStorageFile ** value) = 0; }; struct __declspec(uuid("51882366-9f4b-498f-beb0-42684f6e1c29")) __declspec(novtable) IFolderPickerContinuationEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Folder(Windows::Storage::IStorageFolder ** value) = 0; }; struct __declspec(uuid("fbc93e26-a14a-4b4f-82b0-33bed920af52")) __declspec(novtable) ILaunchActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Arguments(hstring * value) = 0; virtual HRESULT __stdcall get_TileId(hstring * value) = 0; }; struct __declspec(uuid("0fd37ebc-9dc9-46b5-9ace-bd95d4565345")) __declspec(novtable) ILaunchActivatedEventArgs2 : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_TileActivatedInfo(Windows::ApplicationModel::Activation::ITileActivatedInfo ** value) = 0; }; struct __declspec(uuid("3ca77966-6108-4a41-8220-ee7d133c8532")) __declspec(novtable) ILockScreenActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Info(Windows::Foundation::IInspectable ** value) = 0; }; struct __declspec(uuid("06f37fbe-b5f2-448b-b13e-e328ac1c516a")) __declspec(novtable) ILockScreenCallActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CallUI(Windows::ApplicationModel::Calls::ILockScreenCallUI ** value) = 0; }; struct __declspec(uuid("360defb9-a9d3-4984-a4ed-9ec734604921")) __declspec(novtable) IPickerReturnedActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_PickerOperationId(hstring * value) = 0; }; struct __declspec(uuid("0c44717b-19f7-48d6-b046-cf22826eaa74")) __declspec(novtable) IPrelaunchActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_PrelaunchActivated(bool * value) = 0; }; struct __declspec(uuid("3f57e78b-f2ac-4619-8302-ef855e1c9b90")) __declspec(novtable) IPrint3DWorkflowActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Workflow(Windows::Devices::Printers::Extensions::IPrint3DWorkflow ** value) = 0; }; struct __declspec(uuid("ee30a0c9-ce56-4865-ba8e-8954ac271107")) __declspec(novtable) IPrintTaskSettingsActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Configuration(Windows::Devices::Printers::Extensions::IPrintTaskConfiguration ** value) = 0; }; struct __declspec(uuid("d6310029-b1e3-4657-aab1-6a9968229592")) __declspec(novtable) IPrintWorkflowForegroundTaskActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_PrintWorkflowSession(Windows::Foundation::IInspectable ** value) = 0; }; struct __declspec(uuid("6095f4dd-b7c0-46ab-81fe-d90f36d00d24")) __declspec(novtable) IProtocolActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Uri(Windows::Foundation::IUriRuntimeClass ** value) = 0; }; struct __declspec(uuid("d84a0c12-5c8f-438c-83cb-c28fcc0b2fdb")) __declspec(novtable) IProtocolActivatedEventArgsWithCallerPackageFamilyNameAndData : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_CallerPackageFamilyName(hstring * value) = 0; virtual HRESULT __stdcall get_Data(Windows::Foundation::Collections::IPropertySet ** value) = 0; }; struct __declspec(uuid("e75132c2-7ae7-4517-80ac-dbe8d7cc5b9c")) __declspec(novtable) IProtocolForResultsActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ProtocolForResultsOperation(Windows::System::IProtocolForResultsOperation ** value) = 0; }; struct __declspec(uuid("e0b7ac81-bfc3-4344-a5da-19fd5a27baae")) __declspec(novtable) IRestrictedLaunchActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_SharedContext(Windows::Foundation::IInspectable ** value) = 0; }; struct __declspec(uuid("8cb36951-58c8-43e3-94bc-41d33f8b630e")) __declspec(novtable) ISearchActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_QueryText(hstring * value) = 0; virtual HRESULT __stdcall get_Language(hstring * value) = 0; }; struct __declspec(uuid("c09f33da-08ab-4931-9b7c-451025f21f81")) __declspec(novtable) ISearchActivatedEventArgsWithLinguisticDetails : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_LinguisticDetails(Windows::ApplicationModel::Search::ISearchPaneQueryLinguisticDetails ** value) = 0; }; struct __declspec(uuid("4bdaf9c8-cdb2-4acb-bfc3-6648563378ec")) __declspec(novtable) IShareTargetActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ShareOperation(Windows::ApplicationModel::DataTransfer::ShareTarget::IShareOperation ** value) = 0; }; struct __declspec(uuid("ca4d975c-d4d6-43f0-97c0-0833c6391c24")) __declspec(novtable) ISplashScreen : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ImageLocation(Windows::Foundation::Rect * value) = 0; virtual HRESULT __stdcall add_Dismissed(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::Activation::SplashScreen, Windows::Foundation::IInspectable> * handler, event_token * cookie) = 0; virtual HRESULT __stdcall remove_Dismissed(event_token cookie) = 0; }; struct __declspec(uuid("80e4a3b1-3980-4f17-b738-89194e0b8f65")) __declspec(novtable) ITileActivatedInfo : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_RecentlyShownNotifications(Windows::Foundation::Collections::IVectorView<Windows::UI::Notifications::ShownTileNotification> ** value) = 0; }; struct __declspec(uuid("92a86f82-5290-431d-be85-c4aaeeb8685f")) __declspec(novtable) IToastNotificationActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Argument(hstring * argument) = 0; virtual HRESULT __stdcall get_UserInput(Windows::Foundation::Collections::IPropertySet ** value) = 0; }; struct __declspec(uuid("1bc9f723-8ef1-4a51-a63a-fe711eeab607")) __declspec(novtable) IUserDataAccountProviderActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Operation(Windows::ApplicationModel::UserDataAccounts::Provider::IUserDataAccountProviderOperation ** value) = 0; }; struct __declspec(uuid("33f288a6-5c2c-4d27-bac7-7536088f1219")) __declspec(novtable) IViewSwitcherProvider : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ViewSwitcher(Windows::UI::ViewManagement::IActivationViewSwitcher ** value) = 0; }; struct __declspec(uuid("ab92dcfd-8d43-4de6-9775-20704b581b00")) __declspec(novtable) IVoiceCommandActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Result(Windows::Media::SpeechRecognition::ISpeechRecognitionResult ** value) = 0; }; struct __declspec(uuid("fcfc027b-1a1a-4d22-923f-ae6f45fa52d9")) __declspec(novtable) IWalletActionActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ItemId(hstring * value) = 0; virtual HRESULT __stdcall get_ActionKind(winrt::Windows::ApplicationModel::Wallet::WalletActionKind * value) = 0; virtual HRESULT __stdcall get_ActionId(hstring * value) = 0; }; struct __declspec(uuid("72b71774-98ea-4ccf-9752-46d9051004f1")) __declspec(novtable) IWebAccountProviderActivatedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Operation(Windows::Security::Authentication::Web::Provider::IWebAccountProviderOperation ** value) = 0; }; struct __declspec(uuid("75dda3d4-7714-453d-b7ff-b95e3a1709da")) __declspec(novtable) IWebAuthenticationBrokerContinuationEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_WebAuthenticationResult(Windows::Security::Authentication::Web::IWebAuthenticationResult ** result) = 0; }; } namespace ABI { template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderAddAppointmentActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IAppointmentsProviderAddAppointmentActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderRemoveAppointmentActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IAppointmentsProviderRemoveAppointmentActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderReplaceAppointmentActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IAppointmentsProviderReplaceAppointmentActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderShowAppointmentDetailsActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderShowTimeFrameActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IAppointmentsProviderShowTimeFrameActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IBackgroundActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::CachedFileUpdaterActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::ICachedFileUpdaterActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::CameraSettingsActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::ICameraSettingsActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactCallActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactCallActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactMapActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactMapActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactMessageActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactMessageActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactPanelActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactPanelActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactPickerActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactPickerActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactPostActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactPostActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ContactVideoCallActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IContactVideoCallActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::DeviceActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IDeviceActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::DevicePairingActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IDevicePairingActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::DialReceiverActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IDialReceiverActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::FileActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IFileActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::FileOpenPickerActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IFileOpenPickerActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::FileOpenPickerContinuationEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IFileOpenPickerContinuationEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::FileSavePickerActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IFileSavePickerActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::FileSavePickerContinuationEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IFileSavePickerContinuationEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::FolderPickerContinuationEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IFolderPickerContinuationEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::LaunchActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::ILaunchActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::LockScreenActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::ILockScreenActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::LockScreenCallActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::ILockScreenCallActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::LockScreenComponentActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::PickerReturnedActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IPickerReturnedActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::Print3DWorkflowActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IPrint3DWorkflowActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::PrintTaskSettingsActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IPrintTaskSettingsActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::PrintWorkflowForegroundTaskActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IPrintWorkflowForegroundTaskActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ProtocolForResultsActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IProtocolForResultsActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::RestrictedLaunchActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IRestrictedLaunchActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::SearchActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::ISearchActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::ShareTargetActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IShareTargetActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::SplashScreen> { using default_interface = Windows::ApplicationModel::Activation::ISplashScreen; }; template <> struct traits<Windows::ApplicationModel::Activation::TileActivatedInfo> { using default_interface = Windows::ApplicationModel::Activation::ITileActivatedInfo; }; template <> struct traits<Windows::ApplicationModel::Activation::ToastNotificationActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IToastNotificationActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::UserDataAccountProviderActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IUserDataAccountProviderActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::VoiceCommandActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IVoiceCommandActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::WalletActionActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IWalletActionActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::WebAccountProviderActivatedEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IWebAccountProviderActivatedEventArgs; }; template <> struct traits<Windows::ApplicationModel::Activation::WebAuthenticationBrokerContinuationEventArgs> { using default_interface = Windows::ApplicationModel::Activation::IWebAuthenticationBrokerContinuationEventArgs; }; } namespace Windows::ApplicationModel::Activation { template <typename D> struct WINRT_EBO impl_IActivatedEventArgs { Windows::ApplicationModel::Activation::ActivationKind Kind() const; Windows::ApplicationModel::Activation::ApplicationExecutionState PreviousExecutionState() const; Windows::ApplicationModel::Activation::SplashScreen SplashScreen() const; }; template <typename D> struct WINRT_EBO impl_IActivatedEventArgsWithUser { Windows::System::User User() const; }; template <typename D> struct WINRT_EBO impl_IApplicationViewActivatedEventArgs { int32_t CurrentlyShownApplicationViewId() const; }; template <typename D> struct WINRT_EBO impl_IAppointmentsProviderActivatedEventArgs { hstring Verb() const; }; template <typename D> struct WINRT_EBO impl_IAppointmentsProviderAddAppointmentActivatedEventArgs { Windows::ApplicationModel::Appointments::AppointmentsProvider::AddAppointmentOperation AddAppointmentOperation() const; }; template <typename D> struct WINRT_EBO impl_IAppointmentsProviderRemoveAppointmentActivatedEventArgs { Windows::ApplicationModel::Appointments::AppointmentsProvider::RemoveAppointmentOperation RemoveAppointmentOperation() const; }; template <typename D> struct WINRT_EBO impl_IAppointmentsProviderReplaceAppointmentActivatedEventArgs { Windows::ApplicationModel::Appointments::AppointmentsProvider::ReplaceAppointmentOperation ReplaceAppointmentOperation() const; }; template <typename D> struct WINRT_EBO impl_IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs { Windows::Foundation::IReference<Windows::Foundation::DateTime> InstanceStartDate() const; hstring LocalId() const; hstring RoamingId() const; }; template <typename D> struct WINRT_EBO impl_IAppointmentsProviderShowTimeFrameActivatedEventArgs { Windows::Foundation::DateTime TimeToShow() const; Windows::Foundation::TimeSpan Duration() const; }; template <typename D> struct WINRT_EBO impl_IBackgroundActivatedEventArgs { Windows::ApplicationModel::Background::IBackgroundTaskInstance TaskInstance() const; }; template <typename D> struct WINRT_EBO impl_ICachedFileUpdaterActivatedEventArgs { Windows::Storage::Provider::CachedFileUpdaterUI CachedFileUpdaterUI() const; }; template <typename D> struct WINRT_EBO impl_ICameraSettingsActivatedEventArgs { Windows::Foundation::IInspectable VideoDeviceController() const; Windows::Foundation::IInspectable VideoDeviceExtension() const; }; template <typename D> struct WINRT_EBO impl_IContactActivatedEventArgs { hstring Verb() const; }; template <typename D> struct WINRT_EBO impl_IContactCallActivatedEventArgs { hstring ServiceId() const; hstring ServiceUserId() const; Windows::ApplicationModel::Contacts::Contact Contact() const; }; template <typename D> struct WINRT_EBO impl_IContactMapActivatedEventArgs { Windows::ApplicationModel::Contacts::ContactAddress Address() const; Windows::ApplicationModel::Contacts::Contact Contact() const; }; template <typename D> struct WINRT_EBO impl_IContactMessageActivatedEventArgs { hstring ServiceId() const; hstring ServiceUserId() const; Windows::ApplicationModel::Contacts::Contact Contact() const; }; template <typename D> struct WINRT_EBO impl_IContactPanelActivatedEventArgs { Windows::ApplicationModel::Contacts::ContactPanel ContactPanel() const; Windows::ApplicationModel::Contacts::Contact Contact() const; }; template <typename D> struct WINRT_EBO impl_IContactPickerActivatedEventArgs { Windows::ApplicationModel::Contacts::Provider::ContactPickerUI ContactPickerUI() const; }; template <typename D> struct WINRT_EBO impl_IContactPostActivatedEventArgs { hstring ServiceId() const; hstring ServiceUserId() const; Windows::ApplicationModel::Contacts::Contact Contact() const; }; template <typename D> struct WINRT_EBO impl_IContactVideoCallActivatedEventArgs { hstring ServiceId() const; hstring ServiceUserId() const; Windows::ApplicationModel::Contacts::Contact Contact() const; }; template <typename D> struct WINRT_EBO impl_IContactsProviderActivatedEventArgs { hstring Verb() const; }; template <typename D> struct WINRT_EBO impl_IContinuationActivatedEventArgs { Windows::Foundation::Collections::ValueSet ContinuationData() const; }; template <typename D> struct WINRT_EBO impl_IDeviceActivatedEventArgs { hstring DeviceInformationId() const; hstring Verb() const; }; template <typename D> struct WINRT_EBO impl_IDevicePairingActivatedEventArgs { Windows::Devices::Enumeration::DeviceInformation DeviceInformation() const; }; template <typename D> struct WINRT_EBO impl_IDialReceiverActivatedEventArgs { hstring AppName() const; }; template <typename D> struct WINRT_EBO impl_IFileActivatedEventArgs { Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem> Files() const; hstring Verb() const; }; template <typename D> struct WINRT_EBO impl_IFileActivatedEventArgsWithCallerPackageFamilyName { hstring CallerPackageFamilyName() const; }; template <typename D> struct WINRT_EBO impl_IFileActivatedEventArgsWithNeighboringFiles { Windows::Storage::Search::StorageFileQueryResult NeighboringFilesQuery() const; }; template <typename D> struct WINRT_EBO impl_IFileOpenPickerActivatedEventArgs { Windows::Storage::Pickers::Provider::FileOpenPickerUI FileOpenPickerUI() const; }; template <typename D> struct WINRT_EBO impl_IFileOpenPickerActivatedEventArgs2 { hstring CallerPackageFamilyName() const; }; template <typename D> struct WINRT_EBO impl_IFileOpenPickerContinuationEventArgs { Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile> Files() const; }; template <typename D> struct WINRT_EBO impl_IFileSavePickerActivatedEventArgs { Windows::Storage::Pickers::Provider::FileSavePickerUI FileSavePickerUI() const; }; template <typename D> struct WINRT_EBO impl_IFileSavePickerActivatedEventArgs2 { hstring CallerPackageFamilyName() const; hstring EnterpriseId() const; }; template <typename D> struct WINRT_EBO impl_IFileSavePickerContinuationEventArgs { Windows::Storage::StorageFile File() const; }; template <typename D> struct WINRT_EBO impl_IFolderPickerContinuationEventArgs { Windows::Storage::StorageFolder Folder() const; }; template <typename D> struct WINRT_EBO impl_ILaunchActivatedEventArgs { hstring Arguments() const; hstring TileId() const; }; template <typename D> struct WINRT_EBO impl_ILaunchActivatedEventArgs2 { Windows::ApplicationModel::Activation::TileActivatedInfo TileActivatedInfo() const; }; template <typename D> struct WINRT_EBO impl_ILockScreenActivatedEventArgs { Windows::Foundation::IInspectable Info() const; }; template <typename D> struct WINRT_EBO impl_ILockScreenCallActivatedEventArgs { Windows::ApplicationModel::Calls::LockScreenCallUI CallUI() const; }; template <typename D> struct WINRT_EBO impl_IPickerReturnedActivatedEventArgs { hstring PickerOperationId() const; }; template <typename D> struct WINRT_EBO impl_IPrelaunchActivatedEventArgs { bool PrelaunchActivated() const; }; template <typename D> struct WINRT_EBO impl_IPrint3DWorkflowActivatedEventArgs { Windows::Devices::Printers::Extensions::Print3DWorkflow Workflow() const; }; template <typename D> struct WINRT_EBO impl_IPrintTaskSettingsActivatedEventArgs { Windows::Devices::Printers::Extensions::PrintTaskConfiguration Configuration() const; }; template <typename D> struct WINRT_EBO impl_IPrintWorkflowForegroundTaskActivatedEventArgs { Windows::Foundation::IInspectable PrintWorkflowSession() const; }; template <typename D> struct WINRT_EBO impl_IProtocolActivatedEventArgs { Windows::Foundation::Uri Uri() const; }; template <typename D> struct WINRT_EBO impl_IProtocolActivatedEventArgsWithCallerPackageFamilyNameAndData { hstring CallerPackageFamilyName() const; Windows::Foundation::Collections::ValueSet Data() const; }; template <typename D> struct WINRT_EBO impl_IProtocolForResultsActivatedEventArgs { Windows::System::ProtocolForResultsOperation ProtocolForResultsOperation() const; }; template <typename D> struct WINRT_EBO impl_IRestrictedLaunchActivatedEventArgs { Windows::Foundation::IInspectable SharedContext() const; }; template <typename D> struct WINRT_EBO impl_ISearchActivatedEventArgs { hstring QueryText() const; hstring Language() const; }; template <typename D> struct WINRT_EBO impl_ISearchActivatedEventArgsWithLinguisticDetails { Windows::ApplicationModel::Search::SearchPaneQueryLinguisticDetails LinguisticDetails() const; }; template <typename D> struct WINRT_EBO impl_IShareTargetActivatedEventArgs { Windows::ApplicationModel::DataTransfer::ShareTarget::ShareOperation ShareOperation() const; }; template <typename D> struct WINRT_EBO impl_ISplashScreen { Windows::Foundation::Rect ImageLocation() const; event_token Dismissed(const Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::Activation::SplashScreen, Windows::Foundation::IInspectable> & handler) const; using Dismissed_revoker = event_revoker<ISplashScreen>; Dismissed_revoker Dismissed(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::Activation::SplashScreen, Windows::Foundation::IInspectable> & handler) const; void Dismissed(event_token cookie) const; }; template <typename D> struct WINRT_EBO impl_ITileActivatedInfo { Windows::Foundation::Collections::IVectorView<Windows::UI::Notifications::ShownTileNotification> RecentlyShownNotifications() const; }; template <typename D> struct WINRT_EBO impl_IToastNotificationActivatedEventArgs { hstring Argument() const; Windows::Foundation::Collections::ValueSet UserInput() const; }; template <typename D> struct WINRT_EBO impl_IUserDataAccountProviderActivatedEventArgs { Windows::ApplicationModel::UserDataAccounts::Provider::IUserDataAccountProviderOperation Operation() const; }; template <typename D> struct WINRT_EBO impl_IViewSwitcherProvider { Windows::UI::ViewManagement::ActivationViewSwitcher ViewSwitcher() const; }; template <typename D> struct WINRT_EBO impl_IVoiceCommandActivatedEventArgs { Windows::Media::SpeechRecognition::SpeechRecognitionResult Result() const; }; template <typename D> struct WINRT_EBO impl_IWalletActionActivatedEventArgs { hstring ItemId() const; Windows::ApplicationModel::Wallet::WalletActionKind ActionKind() const; hstring ActionId() const; }; template <typename D> struct WINRT_EBO impl_IWebAccountProviderActivatedEventArgs { Windows::Security::Authentication::Web::Provider::IWebAccountProviderOperation Operation() const; }; template <typename D> struct WINRT_EBO impl_IWebAuthenticationBrokerContinuationEventArgs { Windows::Security::Authentication::Web::WebAuthenticationResult WebAuthenticationResult() const; }; } namespace impl { template <> struct traits<Windows::ApplicationModel::Activation::IActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IActivatedEventArgsWithUser> { using abi = ABI::Windows::ApplicationModel::Activation::IActivatedEventArgsWithUser; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IActivatedEventArgsWithUser<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IApplicationViewActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IApplicationViewActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IApplicationViewActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IAppointmentsProviderActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IAppointmentsProviderActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IAppointmentsProviderActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IAppointmentsProviderAddAppointmentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IAppointmentsProviderAddAppointmentActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IAppointmentsProviderAddAppointmentActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IAppointmentsProviderRemoveAppointmentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IAppointmentsProviderRemoveAppointmentActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IAppointmentsProviderRemoveAppointmentActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IAppointmentsProviderReplaceAppointmentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IAppointmentsProviderReplaceAppointmentActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IAppointmentsProviderReplaceAppointmentActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IAppointmentsProviderShowTimeFrameActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IAppointmentsProviderShowTimeFrameActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IAppointmentsProviderShowTimeFrameActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IBackgroundActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IBackgroundActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IBackgroundActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ICachedFileUpdaterActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ICachedFileUpdaterActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ICachedFileUpdaterActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ICameraSettingsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ICameraSettingsActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ICameraSettingsActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactCallActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactCallActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactCallActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactMapActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactMapActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactMapActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactMessageActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactMessageActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactMessageActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactPanelActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactPanelActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactPanelActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactPickerActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactPickerActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactPickerActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactPostActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactPostActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactPostActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactVideoCallActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactVideoCallActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactVideoCallActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContactsProviderActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContactsProviderActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContactsProviderActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IContinuationActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IContinuationActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IContinuationActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IDeviceActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IDeviceActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IDeviceActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IDevicePairingActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IDevicePairingActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IDevicePairingActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IDialReceiverActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IDialReceiverActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IDialReceiverActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IFileActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileActivatedEventArgsWithCallerPackageFamilyName> { using abi = ABI::Windows::ApplicationModel::Activation::IFileActivatedEventArgsWithCallerPackageFamilyName; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileActivatedEventArgsWithCallerPackageFamilyName<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileActivatedEventArgsWithNeighboringFiles> { using abi = ABI::Windows::ApplicationModel::Activation::IFileActivatedEventArgsWithNeighboringFiles; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileActivatedEventArgsWithNeighboringFiles<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileOpenPickerActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IFileOpenPickerActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileOpenPickerActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileOpenPickerActivatedEventArgs2> { using abi = ABI::Windows::ApplicationModel::Activation::IFileOpenPickerActivatedEventArgs2; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileOpenPickerActivatedEventArgs2<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileOpenPickerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IFileOpenPickerContinuationEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileOpenPickerContinuationEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileSavePickerActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IFileSavePickerActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileSavePickerActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileSavePickerActivatedEventArgs2> { using abi = ABI::Windows::ApplicationModel::Activation::IFileSavePickerActivatedEventArgs2; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileSavePickerActivatedEventArgs2<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFileSavePickerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IFileSavePickerContinuationEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFileSavePickerContinuationEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IFolderPickerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IFolderPickerContinuationEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IFolderPickerContinuationEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ILaunchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ILaunchActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ILaunchActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ILaunchActivatedEventArgs2> { using abi = ABI::Windows::ApplicationModel::Activation::ILaunchActivatedEventArgs2; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ILaunchActivatedEventArgs2<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ILockScreenActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ILockScreenActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ILockScreenActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ILockScreenCallActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ILockScreenCallActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ILockScreenCallActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IPickerReturnedActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IPickerReturnedActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IPickerReturnedActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IPrelaunchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IPrelaunchActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IPrelaunchActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IPrint3DWorkflowActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IPrint3DWorkflowActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IPrint3DWorkflowActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IPrintTaskSettingsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IPrintTaskSettingsActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IPrintTaskSettingsActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IPrintWorkflowForegroundTaskActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IPrintWorkflowForegroundTaskActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IPrintWorkflowForegroundTaskActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IProtocolActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IProtocolActivatedEventArgsWithCallerPackageFamilyNameAndData> { using abi = ABI::Windows::ApplicationModel::Activation::IProtocolActivatedEventArgsWithCallerPackageFamilyNameAndData; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IProtocolActivatedEventArgsWithCallerPackageFamilyNameAndData<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IProtocolForResultsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IProtocolForResultsActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IProtocolForResultsActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IRestrictedLaunchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IRestrictedLaunchActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IRestrictedLaunchActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ISearchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ISearchActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ISearchActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ISearchActivatedEventArgsWithLinguisticDetails> { using abi = ABI::Windows::ApplicationModel::Activation::ISearchActivatedEventArgsWithLinguisticDetails; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ISearchActivatedEventArgsWithLinguisticDetails<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IShareTargetActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IShareTargetActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IShareTargetActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ISplashScreen> { using abi = ABI::Windows::ApplicationModel::Activation::ISplashScreen; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ISplashScreen<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::ITileActivatedInfo> { using abi = ABI::Windows::ApplicationModel::Activation::ITileActivatedInfo; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_ITileActivatedInfo<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IToastNotificationActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IToastNotificationActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IToastNotificationActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IUserDataAccountProviderActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IUserDataAccountProviderActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IUserDataAccountProviderActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IViewSwitcherProvider> { using abi = ABI::Windows::ApplicationModel::Activation::IViewSwitcherProvider; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IViewSwitcherProvider<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IVoiceCommandActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IVoiceCommandActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IVoiceCommandActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IWalletActionActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IWalletActionActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IWalletActionActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IWebAccountProviderActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IWebAccountProviderActivatedEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IWebAccountProviderActivatedEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::IWebAuthenticationBrokerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::IWebAuthenticationBrokerContinuationEventArgs; template <typename D> using consume = Windows::ApplicationModel::Activation::impl_IWebAuthenticationBrokerContinuationEventArgs<D>; }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderAddAppointmentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::AppointmentsProviderAddAppointmentActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.AppointmentsProviderAddAppointmentActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderRemoveAppointmentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::AppointmentsProviderRemoveAppointmentActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.AppointmentsProviderRemoveAppointmentActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderReplaceAppointmentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::AppointmentsProviderReplaceAppointmentActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.AppointmentsProviderReplaceAppointmentActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderShowAppointmentDetailsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::AppointmentsProviderShowAppointmentDetailsActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.AppointmentsProviderShowAppointmentDetailsActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::AppointmentsProviderShowTimeFrameActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::AppointmentsProviderShowTimeFrameActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.AppointmentsProviderShowTimeFrameActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.BackgroundActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::CachedFileUpdaterActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::CachedFileUpdaterActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.CachedFileUpdaterActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::CameraSettingsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::CameraSettingsActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.CameraSettingsActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactCallActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactCallActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactCallActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactMapActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactMapActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactMapActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactMessageActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactMessageActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactMessageActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactPanelActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactPanelActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactPanelActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactPickerActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactPickerActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactPickerActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactPostActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactPostActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactPostActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ContactVideoCallActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ContactVideoCallActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ContactVideoCallActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::DeviceActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::DeviceActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.DeviceActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::DevicePairingActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::DevicePairingActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.DevicePairingActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::DialReceiverActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::DialReceiverActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.DialReceiverActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::FileActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::FileActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.FileActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::FileOpenPickerActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::FileOpenPickerActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.FileOpenPickerActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::FileOpenPickerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::FileOpenPickerContinuationEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.FileOpenPickerContinuationEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::FileSavePickerActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::FileSavePickerActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.FileSavePickerActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::FileSavePickerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::FileSavePickerContinuationEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.FileSavePickerContinuationEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::FolderPickerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::FolderPickerContinuationEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.FolderPickerContinuationEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::LaunchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.LaunchActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::LockScreenActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::LockScreenActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.LockScreenActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::LockScreenCallActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::LockScreenCallActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.LockScreenCallActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::LockScreenComponentActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::LockScreenComponentActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.LockScreenComponentActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::PickerReturnedActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::PickerReturnedActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.PickerReturnedActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::Print3DWorkflowActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::Print3DWorkflowActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.Print3DWorkflowActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::PrintTaskSettingsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::PrintTaskSettingsActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.PrintTaskSettingsActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::PrintWorkflowForegroundTaskActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::PrintWorkflowForegroundTaskActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.PrintWorkflowForegroundTaskActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ProtocolActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ProtocolForResultsActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ProtocolForResultsActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ProtocolForResultsActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::RestrictedLaunchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::RestrictedLaunchActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.RestrictedLaunchActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::SearchActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::SearchActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.SearchActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ShareTargetActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ShareTargetActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ShareTargetActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::SplashScreen> { using abi = ABI::Windows::ApplicationModel::Activation::SplashScreen; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.SplashScreen"; } }; template <> struct traits<Windows::ApplicationModel::Activation::TileActivatedInfo> { using abi = ABI::Windows::ApplicationModel::Activation::TileActivatedInfo; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.TileActivatedInfo"; } }; template <> struct traits<Windows::ApplicationModel::Activation::ToastNotificationActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::ToastNotificationActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.ToastNotificationActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::UserDataAccountProviderActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::UserDataAccountProviderActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.UserDataAccountProviderActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::VoiceCommandActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::VoiceCommandActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.VoiceCommandActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::WalletActionActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::WalletActionActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.WalletActionActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::WebAccountProviderActivatedEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::WebAccountProviderActivatedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.WebAccountProviderActivatedEventArgs"; } }; template <> struct traits<Windows::ApplicationModel::Activation::WebAuthenticationBrokerContinuationEventArgs> { using abi = ABI::Windows::ApplicationModel::Activation::WebAuthenticationBrokerContinuationEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.ApplicationModel.Activation.WebAuthenticationBrokerContinuationEventArgs"; } }; } }
#include <iostream> #include "version.h" using namespace std; void version::displayVersion(){ cout << "Current version is "; }
#include <iostream> #include <string> #include "Text.h" using std::string; using std::cin; using std::cout; using std::endl; using std::ostream; int main(){ // read text from standard input uint length1 = 0; uint capacity1 = 0; cout << "Enter a sequence of words separated by white spaces and terminated by " << END_OF_TEXT << endl; string* text1 = readText(cin, length1,capacity1); cout<<"Read a text of length "<<length1<<endl; outputText(cout,text1,length1); uint length2 = 0; uint capacity2 = 0; cout << "Enter a sequence of words separated by white spaces and terminated by " << END_OF_TEXT << endl; string* text2 = readText(cin, length2,capacity2); cout<<"Read a text of length "<<length2<<endl; outputText(cout,text2,length2); // append text1 and text2, result stored in text1 appendText(text1,length1,capacity1,text2,length2); cout<<"Result of append:"<<endl; outputText(cout,text1,length1); // unique words string* unique_words=nullptr; uint number_unique=0; uint capacity_unique=0; unique_words = getWords(text1,length1,number_unique,capacity_unique); cout<<"Unique words "<<endl; outputText(cout,unique_words,number_unique); if(unique_words!=nullptr) delete [] unique_words; number_unique=0; capacity_unique=0; string word = ""; cout<<"Enter a word"<<endl; cin>>word; // word occurrences if(containsWord(text1,length1,word)){ cout<<"The text contains "<<word<<endl; } else{ cout<<"The text does not contain "<<word<<endl; } cout<<"Number of occurrences of "<<word<<" is "<<wordCount(text1,length1,word)<<endl; // word replacement replaceWordAll(text1,length1,word,word+"_new"); cout<<"Result of replacing "<<word<<" by "<<word+"_new is"<<endl; outputText(cout,text1,length1); // word delition deleteWordAll(text1,length1,word+"_new"); cout<<"Result of deleting "<<word+"_new is"<<endl; outputText(cout,text1,length1); // phrase replacement uint phrase_length=4; string phrase[4]={"1","2","1","2"}; uint new_phrase_length=3; string new_phrase[3] = {"3","4","5"}; replacePhraseFirst(text1,length1,capacity1,phrase,phrase_length,new_phrase,new_phrase_length); cout<<"Result of replacing first occurrence of the phrase is"<<endl; outputText(cout,text1,length1); if(text1!=nullptr) delete [] text1; if(text2!=nullptr) delete [] text2; return 0; }
#include "virtual_machine.h" using namespace std; int run(uint64_t *main_program, size_t length) { stack<Operand> operand_stack; stack<uint64_t> operand_stack_scope; operand_stack_scope.push(0); stack<uint64_t> function_stack; stack<vector<int64_t>> function_stack_variables; uint64_t ins, pc=0; uint8_t bcode; int64_t a, b; // temp registers a and b int64_t addr_jump; // for address jumping uint64_t oref; // reference argument char * str; // for printing strings Operand temp(a); // temp operand #define VAL() (operand_stack.top().o_type) ?\ operand_stack.top().value :\ function_stack_variables[operand_stack.top().reference];\ operand_stack.pop();\ operand_stack_scope.top()-- #define REF() operand_stack.top().reference;\ operand_stack.pop();\ operand_stack_scope.top()-- #define VAB() b = VAL(); a = VAL() #define ARB() b = VAL(); oref = REF() #define ABO(O) VAB(); temp = Operand((int64_t)(a O b));\ operand_stack.push(temp);\ operand_stack_scope.top()++ #define INS_ADDR_MASK 0x00ffffffffffffff while (pc < length) { ins = main_program[pc++]; bcode = ins & 0xff; addr_jump = ins; addr_jump >>= 8; oref = ins >> 8; switch (bcode) { case ByteCode_ISET::nop: break; case ByteCode_ISET::exit_prog: return addr_jump; case ByteCode_ISET::f_return_item: assert((a = operand_stack_scope.top()) > 0); temp = operand_stack.top(); for (; a > 0; a--) operand_stack.pop(); operand_stack_scope.pop(); operand_stack.push(temp); operand_stack_scope.top()++; pc = function_stack.top(); function_stack.pop(); function_stack_variables.pop(); break; case ByteCode_ISET::f_push: // call a function function_stack.push(pc); // save current pc on stack for later pc = oref >> 8; // first 6 bytes to program counter a = oref & 0xff; // 7th byte = number of stack frame variables function_stack_variables.push(vector<int64_t>(a,0)); // push empty vector for stack frame variables operand_stack_scope.push(0); // push a new operand stack scope break; case ByteCode_ISET::branch_if: a = VAL(); if (a) pc += addr_jump; break; case ByteCode_ISET::branch_nif: a = VAL(); if (!a) pc += addr_jump; break; case ByteCode_ISET::branch: pc += addr_jump; break; case ByteCode_ISET::addi: assert(operand_stack_scope.top() >= 2); ABO(+); break; case ByteCode_ISET::subi: assert(operand_stack_scope.top() >= 2); ABO(-); break; case ByteCode_ISET::muli: assert(operand_stack_scope.top() >= 2); ABO(*); break; case ByteCode_ISET::divi: assert(operand_stack_scope.top() >= 2); ABO(/); break; case ByteCode_ISET::bo_and: assert(operand_stack_scope.top() >= 2); ABO(&&); break; case ByteCode_ISET::bo_or: assert(operand_stack_scope.top() >= 2); ABO(||); break; case ByteCode_ISET::cmp_lt: assert(operand_stack_scope.top() >= 2); ABO(<); break; case ByteCode_ISET::cmp_lte: assert(operand_stack_scope.top() >= 2); ABO(<=); break; case ByteCode_ISET::cmp_gt: assert(operand_stack_scope.top() >= 2); ABO(>); break; case ByteCode_ISET::cmp_gte: assert(operand_stack_scope.top() >= 2); ABO(>=); break; case ByteCode_ISET::cmp_eq: assert(operand_stack_scope.top() >= 2); ABO(==); break; case ByteCode_ISET::print_i: // output integer on top of operand stack assert(operand_stack_scope.top() >= 1); a = VAL(); cout << a; break; case ByteCode_ISET::print_si: // print string from instruction addr str = ((char*)(main_program)) + ((char)(oref)); cout << str << endl; break; case ByteCode_ISET::print_so: // print string from operand stack oref = REF(); str = ((char*)(main_program)) + ((char)(oref)); cout << str << endl; break; case ByteCode_ISET::print_sp: cout << " "; break; case ByteCode_ISET::assn: assert(operand_stack_scope.top() >= 2); if ((temp = operand_stack.top()).o_type == reference_ot) { a = function_stack_variables.top()[temp.reference]; operand_stack.top() = Operand(a); } ARB(); function_stack_variables.top()[oref] = b; break; case ByteCode_ISET::deref: // made useless by assn instruction dereference check assert(operand_stack_scope.top() >= 1); assert((temp = operand_stack.top()).o_type == reference_ot); a = function_stack_variables.top()[temp.reference]; operand_stack.top() = Operand(a); break; case ByteCode_ISET::o_push_const_ri: a = (int64_t)(main_program[oref]); temp = Operand(a); operand_stack.push(temp); operand_stack_scope.top()++; break; case ByteCode_ISET::o_push_const_rr: temp = Operand(oref); operand_stack.push(temp); operand_stack_scope.top()++; break; case ByteCode_ISET::o_clear: assert(a = operand_stack_scope.top()); for (; a > 0; a--) operand_stack.pop(); operand_stack_scope.top() = 0; break; case ByteCode_ISET::o_popN: a = (ins & INS_ADDR_MASK); assert(a >= 0 && a <= operand_stack_scope.top()); for (b = a; b > 0; b--) operand_stack.pop(); operand_stack_scope.top() -= a; break; case ByteCode_ISET::o_pop: assert(operand_stack_scope.top()); operand_stack_scope.top()--; operand_stack.pop(); break; } } return 0; } int main(int argc, char **argv) { //open file fstream infile(argv[1], ios::in | ios::binary); //get length of file infile.seekg(0, infile.end); size_t length = infile.tellg(); infile.seekg(0, infile.beg); length = length - infile.tellg(); //cout << "DEBUG LENGTH:" << length << endl; uint64_t *main_program = new uint64_t[(length / 8) + 1]; char *buffer = (char *)(main_program); memset(buffer, (length / 8 + 1)*8, 0); //read file infile.read(buffer, length); infile.close(); int i = run(main_program, (length / 8) + 1); return i; }
#include <bits/stdc++.h> using namespace std; int test_case; int knapsak_sizes[1000][2]; int weights_profits[1000][3]; float knapsack(int weights[],int profits[], int n, int W) { int i, j, pos; float d[n]; float totalValue = 0, totalWeight = 0; for (i = 0; i < n; i++) { d[i] = profits[i]*1.0 / weights[i]; } for(int i = 0 ; i < n ; i++) { for(int j = i+1 ; j < n ; j++) { if(d[j] > d[i]) { float temp = d[i]; d[i] = d[j]; d[j] = temp; temp = weights[i]; weights[i] = weights[j]; weights[j] = temp; temp = profits[i]; profits[i] = profits[j]; profits[j] = temp; } } } for(i=0; i<n; i++) { if(totalWeight + weights[i]<= W) { totalValue += profits[i]*1.0; totalWeight += weights[i]*1.0; } else { int wt = W-totalWeight; totalValue += (wt * d[i]*1.0); totalWeight += wt; break; } } cout << totalWeight; cout << "\t\t" << totalValue<<endl; return totalValue; } vector<int> removeDupWord(string str) { vector<int> numbers; string word = ""; for (auto x : str) { if (x == ' ') { stringstream degree(word); int temp = 0; degree >> temp; numbers.push_back(temp); word = ""; } else { word = word + x; } } stringstream degree(word); int temp = 0; degree >> temp; numbers.push_back(temp); return numbers; } void readFile(string fname) { int x = -1,y = 0,i = 0; ifstream inFile; inFile.open(fname); if (!inFile) { cout << "Cannot open file.\n"; exit(1); } inFile >> test_case; string str; while (getline(inFile, str)) { vector<int> numbers = removeDupWord(str); if(numbers.size() == 1) { x++; knapsak_sizes[x][0] = numbers.at(0); knapsak_sizes[x][1] = 0; } else if(numbers.size() == 3) { weights_profits[i][0] = numbers.at(0); weights_profits[i][1] = numbers.at(1); weights_profits[i++][2] = numbers.at(2); knapsak_sizes[x][1]++; } numbers.clear(); } inFile.close(); } int main() { int weights[1000]; int profits[1000]; int n; int prev = 0; readFile("greedy.txt"); cout<<"Solution no\tFractional amount\t\t\tTotal weight\tTotal profit"<<endl; cout<<"-----------\t-----------------\t\t\t------------\t------------"<<endl; for(int i = 1 ; i <= test_case ; i++) { int k = 0; cout<<"Solution "<<i<<":\t"; for(int j = prev ; j < prev + knapsak_sizes[i][1] ; j++) { weights[k] = weights_profits[j][1]; profits[k++] = weights_profits[j][2]; cout<<weights_profits[j][1]*1.0/weights_profits[j][2]*1.0<<" "; } cout<<"\t\t"; knapsack(weights, profits, knapsak_sizes[i][1], knapsak_sizes[i][0]); prev += knapsak_sizes[i][1]; } return 0; }
vclass Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) { for (auto & row : A) reverse(row.begin(), row.end()); for (auto & row : A) for (int & num : row) num ^= 1; return A; } };
/* ASSIGNMENT 4 - COEN 244 Jean-Baptiste WARING 40054925 FAROUQ HAMEDALLAH 40087448 HOSPITAL MANAGEMENT SYSTEM */ #include "./date.h" #include <iostream> using namespace std; Date::Date(){ //Default Date; January 24th 1984, presentation of the first Macintosh Computer. date = new int[3]; date[0]=1984; date[1]=1; date[2]=24; long_date = false; } Date::Date(int y, int mo, int d, int h, int mm, int s){ //Explicit Constructor for Date, checking the format is correct. date = new int[3]; date[0]= y ; date[1]= ( mo >= 0 && mo< 13) ? mo : 0; date[2]= ( d >= 0 && d < 32 ) ? d : 0; t = new Time(h,mm,s); long_date = true; } Date::Date(int y, int mo, int d){ date = new int[3]; date[0]= y ; date[1]= ( mo >= 0 && mo< 13) ? mo : 0; date[2]= ( d >= 0 && d < 32 ) ? d : 0; long_date = false; } Date::Date(string dt){ //create date object from user prompted string in "DD/MM/YYYY" format. if(dt==""){ // default date for faster menu testing date = new int[3]; date[0]= 2020; date[1]= 3; date[2]= 18; long_date = false; }else{ string buffer="1"; buffer.clear(); for(int itr=0; itr<2; itr++){ buffer.append(1,dt[itr]); } int d = stoi(buffer); buffer.clear(); for(int itr=3; itr<5; itr++){ buffer.append(1,dt[itr]); } int mo = stoi(buffer); buffer.clear(); for(int itr=6; itr<10; itr++){ buffer.append(1,dt[itr]); } int y = stoi(buffer); date = new int[3]; date[0]= y ; date[1]= ( mo >= 0 && mo< 13) ? mo : 0; date[2]= ( d >= 0 && d < 32 ) ? d : 0; long_date = false; } } Date::Date(const Date &d){ date = new int[3]; // Copy constructor for the date class. if(d.long_date==true){ date[0] = d.date[0]; date[1] = d.date[1]; date[2] = d.date[2]; t = new Time(d.t->get_time(0),d.t->get_time(1),d.t->get_time(2)); long_date=true;} else{ date[0] = d.date[0]; date[1] = d.date[1]; date[2] = d.date[2]; long_date=false; } } Date::Date(const Date* d){ date = new int[3]; // Copy constructor for the date class. if(d->long_date==true){ date[0] = d->date[0]; date[1] = d->date[1]; date[2] = d->date[2]; t = new Time(d->t->get_time(0),d->t->get_time(1),d->t->get_time(2)); long_date=true;} else{ date[0] = d->date[0]; date[1] = d->date[1]; date[2] = d->date[2]; long_date=false; } } Date::~Date(){ delete date; delete t; } vector<int> Date::get_date(){ // Returns a vector containing the date as int. vector<int> redate; if(long_date==false){ redate.push_back(date[0]); redate.push_back(date[1]); redate.push_back(date[2]); return redate; }else{ redate.push_back(date[0]); redate.push_back(date[1]); redate.push_back(date[2]); redate.push_back(t->get_time(0)); redate.push_back(t->get_time(1)); redate.push_back(t->get_time(2)); } return redate; } void Date::print_date(){ //Prints date with proper YYYY/MM/DD Formating including the added '0' if the month or day is less than 10. cout << endl << date[0]<< "/" ; if(date[1]<10){cout << 0 << date[1]<<"/";}else{cout << date[1]<<"/";} if(date[2]<10){cout << 0 << date[2];}else{cout << date[2];} } int Date::get_day(){ return date[2]; } int Date::get_month(){ return date[1]; } int Date::get_year(){ return date[0]; }
#ifndef _GoodsMedicineLife_H_ #define _GoodsMedicineLife_H_ #include <iostream> class Player; /** * 10灵药类 * 对生命的恢复0~100,表示恢复被使用者??%的生命, * 并解除死亡状态,但被使用者必须是死亡状态。 * @author Chen * */ class GoodsMedicineLife: public BaseGoods { public: virtual ~GoodsMedicineLife(){} protected: virtual void setOtherData(char *buf, int offset) { mPercent = buf[offset + 0x17] & 0xff; if (mPercent > 100) { mPercent = 100; } } private: int mPercent; // 恢复百分比 public: virtual void eat(Player *player) { player->setMP(player->getMP() + player->getMaxMP() * mPercent / 100); if (player->getMP() > player->getMaxMP()) { player->setMP(player->getMaxMP()); } player->sGoodsList->deleteGoods(mType, mIndex); } }; #endif
#include "SpellService.h" #include <thrift/transport/TSocket.h> #include <thrift/transport/TBufferTransports.h> #include <thrift/protocol/TBinaryProtocol.h> //#include <boost/thread.hpp> //#include <boost/date_time.hpp> #include <string> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <random> #include <ctype.h> #include <openssl/md5.h> #define NUMSHARDS 2 using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace SpellServer; int main(int argc, char **argv){ //if not enough input, return if(argc < 3) return -1; //reading server list from different serverList std::vector<std::string> serverListS0; std::vector<std::string> serverListS1; std::ifstream inputStream; inputStream.open("serverListS0"); std::string server; std::string lastline = ""; while(true){ getline(inputStream, server); if(server != lastline){ serverListS0.push_back(server); } else{ break; } } inputStream.close(); inputStream.open("serverListS1"); while(true){ getline(inputStream, server); std::cout << server << std::endl; if(server != lastline){ serverListS1.push_back(server); } else{ break; } } printf("server list loaded\n"); //get the input words into 2 request SpellRequest requestS0, requestS1; SpellResponse responseS0, responseS1; //hash the input words, put them into different request vector for(int i = 2; i < argc; i++){ unsigned char shard, hash[16]; std::string input = std::string(argv[i]); MD5((unsigned char*)argv[i], strlen(argv[i]), hash); shard = hash[15] % NUMSHARDS; if(shard){ //std::cout<< "S1 " << input <<std::endl; requestS1.to_check.push_back(input); } else{ //std::cout<< "S0 " << input <<std::endl; requestS0.to_check.push_back(input); } } //time out configure int timeOut = atoi(argv[2]); //randomize the server list std::random_device rd; std::mt19937 g(rd()); std::shuffle(serverListS0.begin(), serverListS0.end(), g); std::shuffle(serverListS1.begin(), serverListS1.end(), g); //get server IP from serverList, the port is in the list for (std::vector<std::string>::iterator i = serverListS0.begin(); i != serverListS0.end(); i++) { std::istringstream buf(*i); std::istream_iterator<std::string> beg(buf), end; std::vector<std::string> tokens(beg, end); boost::shared_ptr<TSocket> socket(new TSocket(tokens[0], atoi(tokens[1].c_str()))); #pragma mark - timeOut setting socket->setConnTimeout(100); socket->setSendTimeout(100); socket->setRecvTimeout(timeOut * 1000); boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); SpellServiceClient client(protocol); //handle TCP connection error with 100ms time out try { //std::cout << "connecting " + *i /*<< e.what()*/ << std::endl; transport -> open(); } catch (TTransportException &e) { printf("open error...changing server...\n"); continue; } //RPC call to the server printf("requesting... \n"); try { client.spellcheck(responseS0, requestS0); transport -> close(); break; } catch (TTransportException &e) { //std::cout << e.what() << std::endl; printf("server busy... changing server...\n"); if (transport->isOpen()) { transport->close(); } continue; } } for (std::vector<std::string>::iterator i = serverListS1.begin(); i != serverListS1.end(); i++) { std::istringstream buf(*i); std::istream_iterator<std::string> beg(buf), end; std::vector<std::string> tokens(beg, end); boost::shared_ptr<TSocket> socket(new TSocket(tokens[0], atoi(tokens[1].c_str()))); #pragma mark - timeOut setting socket->setConnTimeout(100); socket->setSendTimeout(100); socket->setRecvTimeout(timeOut * 1000); boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); SpellServiceClient client(protocol); //handle TCP connection error with 100ms time out try { //std::cout << "connecting " + *i /*<< e.what()*/ << std::endl; transport -> open(); } catch (TTransportException &e) { printf("open error...changing server...\n"); continue; } //RPC call to the server printf("requesting... \n"); try { client.spellcheck(responseS1, requestS1); transport -> close(); break; } catch (TTransportException &e) { //std::cout << e.what() << std::endl; printf("server busy... changing server...\n"); if (transport->isOpen()) { transport->close(); } continue; } } //Output the response (misspell words only) printf("responsing...\n"); printf("misspell words: \n"); for(int i = 0; i < responseS1.is_correct.size(); i++){ if(!responseS1.is_correct[i]){ std::cout << requestS1.to_check.at(i) << " "; } } for(int i = 0; i< responseS0.is_correct.size(); i++){ if(!responseS0.is_correct[i]){ std::cout << requestS0.to_check.at(i) << " "; } } std::cout << std::endl; return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "HealthDisplayComponent.generated.h" class ABasic_UMG_Creator; class UHealthAndDamageComponent; UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class THIRDPERSONSHOOTER_API UHealthDisplayComponent : public UActorComponent { GENERATED_BODY() private: UFUNCTION() void HandleDataFromServer(); UFUNCTION() void HandleHealthChanged(int NewHealth); ABasic_UMG_Creator* _basicUMGCreator; UHealthAndDamageComponent* _healthComponent; protected: virtual void BeginPlay() override; public: UHealthDisplayComponent(); };
#include "SpaceDeletionView.h" #include "../../services/appContext/AppContext.h" #include "../../presentations/space/SpacePresentation.h" #include "../viewUtils/ViewUtils.h" SpaceDeletionView::SpaceDeletionView() { cancelCommandEnabled = true; name = "space deletion"; spaces = SpacePresentation::get_all_spaces(); } void SpaceDeletionView::displayStaticContent() { if (spaces.empty()) { AppContext::setView<SpaceView>(); throw ViewException("No spaces detected"); } else { display_spaces(); } } void SpaceDeletionView::display_spaces() const { unsigned long i = 0; for (const auto &space: spaces) { std::cout << (std::to_string(++i) + ": " + space.get_name()) << std::endl; } } void SpaceDeletionView::displayDynamicContent() { auto space_name = ViewUtils::display_prefix_and_read_input("Space name"); if (!SpacePresentation::does_space_exist(space_name)) { auto message = "Space " + space_name + " doesn't exist"; throw InputException(message); } SpacePresentation::delete_space(space_name); auto message = "Space '" + space_name + "' deleted"; AppContext::setCommunicate(message); AppContext::setView<SpaceView>(); }
class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char, int> m; // char--last pos // left: left indx of last longest substring (window) w.o repeating int res = 0, left = -1; for (int i = 0; i < s.size(); ++i) { // chararcter exist, and its last pos is larger that left indx if (m.count(s[i]) && left < m[s[i]]) left = m[s[i]]; m[s[i]] = i; res = max(res, i - left); } return res; } };
#ifndef ASIO_DGRAM_HANDLER_HPP #define ASIO_DGRAM_HANDLER_HPP #include "asio/connection_handler.hpp" #include "asio/dgram_connection.hpp" template<class conn_T> class dgram_handler : public connection_handler { public: dgram_handler(boost::asio::io_service & io_service, std::unique_ptr<deviceDescription> description) { device_ = std::unique_ptr<dgram_connection<conn_T>>(new dgram_connection<conn_T>(io_service, std::move(description))); } //virtual bool handle_receive(std::shared_ptr<std::vector<uint8_t>> msg) {} //std::shared_ptr<dgram_connection<conn_T>> device_; }; typedef dgram_handler<boost::asio::ip::udp::socket> udp_client_handler; typedef dgram_handler<boost::asio::local::datagram_protocol::socket> local_dgram_handler; #endif
#ifndef PAGEJEUX_H #define PAGEJEUX_H #include <QWidget> #include <QGraphicsScene> #include <QGraphicsView> #include <QString> #include <QStatusBar> #include <QDebug> #include <QKeyEvent> #include "Grille.h" #include "Tableau.h" #include "Score.h" class PageJeu : public QWidget { public: PageJeu(); PageJeu(int mode); ~PageJeu(); QGraphicsView* getView(); QGraphicsScene* getScene(); void AddTuile(int coord_X, int coord_Y, int valeur); void AfficheGrille(Grille* grille); void SyncronisationDesGrilles(); void UpdateScore(); void keyPressEvent(QKeyEvent* event); bool getExist(); private: int scene_width = 1024; //determine la largeur de la scene en pixel int scene_height = 760; // determine la hauteur de la scene en pixel bool existe = false; //---Lorsque Zone de jeux est Loader---// QGraphicsScene* scene; // Pointe la scene correspondant à la zone de jeux QGraphicsView* view; // pointe la vue de la Scene de la zone de Jeux Grille* grillefixe; // point Grille de tuile Grille* grilledynamique; // pointe Grille de tuile Tableau* tableau; // pointe Tableau de base de jeux Score* scoreboard; // pointe le score Board Score Score* nbmouve; // pointe le score Board Nombre de Mouvement }; #endif // PAGEJEUX_H
#pragma once namespace vcpkg::PortFileProvider { struct PortFileProvider; struct PathsPortFileProvider; }
/*vim操作 vimtutor 英文版 vimtutor zh 中文版 */ /* oj:命令提示符 ls : 命令 ls -la : 命令 选项 ls -la a.c : 命令 选项 参数 ls -lad dir :命令 选项 参数 */ /*家目录 权限有r,w,x三种权限分别表示可读、可写、可执行 vim .zshrc cat /etc/shells echo ${SHELL} cat /etc/passwd */ /*树形结构 切换目录、目录跳转: 使用cd,如果有GUI也可使用 查看目录内容: 可以使用ls命令查看目录下的文件 盘符: Linux只有一棵树 打印工作目录:pwd 拷贝:cp mv : 移动文件及目录 rm : 删除文件及目录 mkdir:创建目录 tree: 打印目录树 tar: 文件归档与压缩 ln: 创建连接文件 更新源列表 sudo apt update sudo apt install tree 我是谁:whoami 我在哪:pwd 文件类型:下载.deb使用dpkg -i .deb安装 解压: 下载压缩包***.tar, tar命令解压 安装: apt安装 安装来源: 需要配置合适的下载源 apt upgrade 更新本地软件为最新版本 apt search 搜索软件 apt remove 卸载软件 nethogs - 检测系统占用宽带情况 htop - 交互式的进程浏览器 nmon - 显示所有重要的性能优化信息 dstat - 全能信息统计工具 sudo apt update sudo apt install htop */ /* 文件内容的修改与查看 touch : 创建空白文件 cat : 查看文件内容 vim : 文本编辑器 echo : 打印文本 more: 分页查看文件 less: 分页查看文件 head: 查看文件头部 tail: 查看文件尾部 diff: 对比文件 grep: 检索信息 wc: 计数 */ /*文件的查找与定位 find: 查找文件 which: 查找可执行文件 locate:定位任何文件 whereis:查找可执行、源码、帮助手册 */ /*用户相关命令 useradd: 新建用户 userdel: 删除用户 usermod: 修改用户 passwd: 修改密码 su: 切换用户 sudo: 获取管理员权限 chgrp: 修改文件所属组 chmod: 修改文件权限 chown: 修改文件所属者 logout: 退出用户 exit: 退出用户 */ /*进程相关命令 ps: 打印进程 kill: 终止进程 pkill: 批量终止进程 killall: 批量杀死进程 crontab: 定时任务 ctrl+z: 挂起前台进程 fg: 进程调至前台 bg: 挂起的进程后台执行 jobs: 查看挂起和后台进程 */ /*系统信息获取命令 date : 查看时间 df : 查看文件系统 du : 获取文件大小 free : 查看内存信息 top : 查看进程信息 htop : 查看系统信息 dstat : 查看资源信息 nmon : 系统监控器 ifconfig : 查看IP信息 uname : 查看OS信息 last : 查看最近登录信息 who : 查看当前登录信息 */ /*其他命令 ssh: 远程连接 scp: 远程拷贝 wget: 获取http文件 ping: 测试远程主机 reboot: 重启 poweroff:关机 */
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unistd.h> #include "multimedia/media_attr_str.h" #include "multimedia/cowplayer.h" #include "pipeline_player.h" #include "pipeline_LPA.h" #include "multimedia/pipeline_audioplayer.h" #include "multimedia/mm_debug.h" namespace YUNOS_MM { MM_LOG_DEFINE_MODULE_NAME("COW-PLY") #define FUNC_TRACK() FuncTracker tracker(MM_LOG_TAG, __FUNCTION__, __LINE__) // #define FUNC_TRACK() static const char * MMMSGTHREAD_NAME = "CowPlayer::Private"; #define COWPLAYER_MSG_BRIDGE(msg, param1, param2, async, status) do{ \ status = MM_ERROR_ASYNC; \ if (async) { \ mPriv->postMsgBridge(msg, param1, param2); \ } else { \ MMMsgThread::param1_type rsp_param1; \ MMMsgThread::param2_type rsp_param2; \ if(mPriv->sendMsgBridge(msg, param1, param2, &rsp_param1, &rsp_param2)) { \ return MM_ERROR_UNKNOWN; \ } \ status = mm_status_t(rsp_param1); \ } \ INFO("%s return status %d", __func__, status); \ }while(0) #define ENSURE_PIPELINE() do { \ if (!mPriv->mPipeline) { \ if (!mPriv->createDefaultPipeline()) \ return MM_ERROR_NO_PIPELINE; \ } \ ASSERT(mPriv->mPipeline); \ } while(0) class CowPlayer::ListenerPlayer : public Pipeline::Listener { public: ListenerPlayer(CowPlayer* player) :mWatcher(player) { } virtual ~ListenerPlayer() { } void removeWatcher() { // FIXME, use weak_ptr for mWatcher is another option MMAutoLock locker(mWatchLock); mWatcher = NULL; } void onMessage(int msg, int param1, int param2, const MMParamSP obj) { //FUNC_TRACK(); MMAutoLock locker(mWatchLock); // FIXME, suppose it runs in Pipeline's MMMsgThread, it is light weight thread for message only if (mWatcher) { mWatcher->notify(msg, param1, param2, obj); } else WARNING("new msg(%d) comes, but watcher left already\n", msg); } private: CowPlayer* mWatcher; Lock mWatchLock; MM_DISALLOW_COPY(ListenerPlayer) }; class CowPlayer::Private : public MMMsgThread { public: static PrivateSP create(Pipeline::ListenerSP listener, int playType) { FUNC_TRACK(); PrivateSP priv(new Private(), MMMsgThread::releaseHelper); if (priv) { if (priv->init() == MM_ERROR_SUCCESS) { priv->mListenerReceive = listener; priv->mPlayType = playType; } else priv.reset(); } return priv; } mm_status_t init() { FUNC_TRACK(); int ret = MMMsgThread::run(); if (ret != 0) { ERROR("init failed, ret %d", ret); return MM_ERROR_OP_FAILED; } return MM_ERROR_SUCCESS; } ~Private() {} int postMsgBridge(msg_type what, param1_type param1, param2_type param2, int64_t timeoutUs = 0) { FUNC_TRACK(); return postMsg(what, param1, param2, timeoutUs); } int postMsgBridge2(msg_type what, param1_type param1, param2_type param2, param3_type param3, int64_t timeoutUs = 0) { FUNC_TRACK(); return postMsg(what, param1, param2, timeoutUs, param3); } int sendMsgBridge(msg_type what, param1_type param1, param2_type param2, param1_type * resp_param1, param2_type * resp_param2) { FUNC_TRACK(); return sendMsg(what, param1, param2, resp_param1, resp_param2); } PipelineSP mPipeline; Pipeline::ListenerSP mListenerReceive; // private: Lock mLock; // copied data of setDataSouce std::string mUri; std::string mSubtitleUri; std::string mDisplayName; std::map<std::string, std::string> mHeaders; int mFd; int64_t mOffset; int64_t mLength; //MediaMetaSP mParam; SeekEventParamSP mSeekParam; int mPlayType; Private() : MMMsgThread(MMMSGTHREAD_NAME) , mFd(-1) , mOffset(-1) , mLength(-1) , mPlayType(0) { FUNC_TRACK(); mSeekParam = SeekEventParam::create(); } mm_status_t setPipeline(PipelineSP pipeline) { FUNC_TRACK(); if (pipeline) { mPipeline = pipeline; mPipeline->setListener(mListenerReceive); } return MM_ERROR_SUCCESS; } bool createDefaultPipeline() { FUNC_TRACK(); if (mPlayType == PlayerType_COWAudio) { mPipeline = Pipeline::create(new PipelineAudioPlayer(), mListenerReceive); ASSERT(mPipeline); #if defined(__PHONE_BOARD_QCOM__) } else if (mPlayType == PlayerType_LPA) { mPipeline = Pipeline::create(new PipelineLPA(), mListenerReceive); ASSERT(mPipeline); #endif } else { mPipeline = Pipeline::create(new PipelinePlayer(), mListenerReceive); ASSERT(mPipeline); } return mPipeline; } void flushCommandList() // discard the pending actions in message List { MMAutoLock locker(mMsgThrdLock); // FIXME, we need lock MMMsgThread msg queue; add flushMsgQueue to MMMsgThread // make sure no mem leak to clear the message queue mMsgQ.clear(); } MM_DISALLOW_COPY(Private); DECLARE_MSG_LOOP() DECLARE_MSG_HANDLER(onPipelineMessage) DECLARE_MSG_HANDLER(onSetDataSource_1) DECLARE_MSG_HANDLER(onSetDataSource_2) DECLARE_MSG_HANDLER(onPrepare) DECLARE_MSG_HANDLER(onPrepareAsync) DECLARE_MSG_HANDLER(onSetDisplayName) DECLARE_MSG_HANDLER(onStart) DECLARE_MSG_HANDLER(onStop) DECLARE_MSG_HANDLER(onPause) DECLARE_MSG_HANDLER(onSeek) DECLARE_MSG_HANDLER(onReset) DECLARE_MSG_HANDLER2(onSetParameter) }; #define CPP_MSG_pipelineMessage (MMMsgThread::msg_type)1 #define CPP_MSG_setDataSource1Message (MMMsgThread::msg_type)2 #define CPP_MSG_setDataSource2Message (MMMsgThread::msg_type)3 #define CPP_MSG_prepareMessage (MMMsgThread::msg_type)4 #define CPP_MSG_prepareAsyncMessage (MMMsgThread::msg_type)5 #define CPP_MSG_startMessage (MMMsgThread::msg_type)6 #define CPP_MSG_stopMessage (MMMsgThread::msg_type)7 #define CPP_MSG_pauseMessage (MMMsgThread::msg_type)8 #define CPP_MSG_seekMessage (MMMsgThread::msg_type)9 #define CPP_MSG_resetMessage (MMMsgThread::msg_type)10 #define CPP_MSG_setParameterMessage (MMMsgThread::msg_type)11 #define CPP_MSG_setDisplayName (MMMsgThread::msg_type)12 #define CPP_MSG_setSubtitleSource (MMMsgThread::msg_type)13 BEGIN_MSG_LOOP(CowPlayer::Private) MSG_ITEM(CPP_MSG_pipelineMessage, onPipelineMessage) MSG_ITEM(CPP_MSG_setDataSource1Message, onSetDataSource_1) MSG_ITEM(CPP_MSG_setDataSource2Message, onSetDataSource_2) MSG_ITEM(CPP_MSG_prepareMessage, onPrepare) MSG_ITEM(CPP_MSG_prepareAsyncMessage, onPrepareAsync) MSG_ITEM(CPP_MSG_setDisplayName, onSetDisplayName) MSG_ITEM(CPP_MSG_startMessage, onStart) MSG_ITEM(CPP_MSG_stopMessage, onStop) MSG_ITEM(CPP_MSG_pauseMessage, onPause) MSG_ITEM(CPP_MSG_seekMessage, onSeek) MSG_ITEM(CPP_MSG_resetMessage, onReset) MSG_ITEM2(CPP_MSG_setParameterMessage, onSetParameter) END_MSG_LOOP() CowPlayer::CowPlayer(int playType) :mListenderSend(NULL), mLoop(false), mPlayType(playType) { FUNC_TRACK(); Pipeline::ListenerSP listener(new ListenerPlayer(this)); mPriv = Private::create(listener, playType); } CowPlayer::~CowPlayer() { FUNC_TRACK(); ListenerPlayer* listener = DYNAMIC_CAST<ListenerPlayer*>(mPriv->mListenerReceive.get()); if(listener){ listener->removeWatcher(); } mm_status_t status = reset(); if (status != MM_ERROR_SUCCESS) WARNING("reset() failed during ~CowPlayer, continue\n"); } mm_status_t CowPlayer::setPipeline(PipelineSP pipeline) { FUNC_TRACK(); return mPriv->setPipeline(pipeline); } mm_status_t CowPlayer::setListener(Listener * listener) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); mListenderSend = listener; return MM_ERROR_SUCCESS; } void CowPlayer::removeListener() { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); mListenderSend = NULL; } #define CHECK_PIPELINE_RET(STATUS, CMD_NAME) do { \ \ if (STATUS == MM_ERROR_SUCCESS) { \ /* Pipeline::onComponentMessage has already notify success */ \ } else if (STATUS == MM_ERROR_ASYNC) { \ /* not expected design */ \ WARNING("not expected to reach here\n"); \ } else { \ /* notify failure */ \ ERROR("%s failed\n", CMD_NAME); \ mPipeline->postCowMsgBridge(Component::kEventError, STATUS, NULL); \ } \ } while(0) mm_status_t CowPlayer::setDataSource(const char * uri, const std::map<std::string, std::string> * headers) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); // FIXME, assume caller does reset. mediaplayer.h doesn't have reset(), does it by ourself mPriv->mUri = std::string(uri); INFO("got uri: %s\n", mPriv->mUri.c_str()); if (headers) mPriv->mHeaders = *headers; else mPriv->mHeaders.clear(); mPriv->postMsgBridge(CPP_MSG_setDataSource1Message, 0, NULL); return MM_ERROR_ASYNC; } void CowPlayer::Private::onSetDataSource_1(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT(rspId == 0); // FIXME, make sure uri and headers match mm_status_t status = mPipeline->load(mUri.c_str(), &mHeaders); CHECK_PIPELINE_RET(status, "setDataSource"); } mm_status_t CowPlayer::setDataSourceAsync(int fd, int64_t offset, int64_t length) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); mm_status_t status = MM_ERROR_UNKNOWN; // FIXME, assume caller does reset mPriv->mFd = fd; mPriv->mOffset = offset; mPriv->mLength = length; COWPLAYER_MSG_BRIDGE(CPP_MSG_setDataSource2Message, 0, 0, true, status); return status; } mm_status_t CowPlayer::setDataSource(int fd, int64_t offset, int64_t length) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); mm_status_t status = MM_ERROR_UNKNOWN; // FIXME, assume caller does reset mPriv->mFd = fd; mPriv->mOffset = offset; mPriv->mLength = length; COWPLAYER_MSG_BRIDGE(CPP_MSG_setDataSource2Message, 0, 0, false, status); return status; } void CowPlayer::Private::onSetDataSource_2(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); mm_status_t status = mPipeline->load(mFd, mOffset, mLength); if (rspId) { postReponse(rspId, status, 0); } } mm_status_t CowPlayer::setDataSource(const unsigned char * mem, size_t size) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); // ENSURE_PIPELINE(); ERROR("not implemented yet\n"); return MM_ERROR_UNSUPPORTED; // return mPipeline->setDataSource(mem, size); } mm_status_t CowPlayer::setSubtitleSource(const char* uri) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); if (!uri) return MM_ERROR_INVALID_PARAM; mPriv->mSubtitleUri = std::string(uri); INFO("got subtitle uri: %s\n", mPriv->mSubtitleUri.c_str()); return mPriv->mPipeline->loadSubtitleUri(uri); } mm_status_t CowPlayer::setDisplayName(const char* name) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); if (!name) return MM_ERROR_INVALID_PARAM; mPriv->mDisplayName = std::string(name); INFO("got display name: %s\n", mPriv->mDisplayName.c_str()); mPriv->postMsgBridge(CPP_MSG_setDisplayName, 0, NULL); return MM_ERROR_ASYNC; } void CowPlayer::Private::onSetDisplayName(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT(rspId == 0); mPipeline->setDisplayName(mDisplayName.c_str()); } mm_status_t CowPlayer::setNativeDisplay(void * display) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); return mPriv->mPipeline->setNativeDisplay(display); } mm_status_t CowPlayer::setVideoSurface(void * handle, bool isTexture) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); return mPriv->mPipeline->setVideoSurface(handle, isTexture); } mm_status_t CowPlayer::prepare() { FUNC_TRACK(); mm_status_t status = MM_ERROR_UNKNOWN; ENSURE_PIPELINE(); MMMsgThread::param1_type rsp_param1; MMMsgThread::param2_type rsp_param2; if (mPriv->sendMsgBridge(CPP_MSG_prepareMessage, 0, 0, &rsp_param1, &rsp_param2)) { return MM_ERROR_UNKNOWN; } status = mm_status_t(rsp_param1); return status; } void CowPlayer::Private::onPrepare(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT_NEED_RSP(rspId); mm_status_t status = mPipeline->prepare(); if (status != MM_ERROR_SUCCESS) { ERROR("prepare faild\n"); } postReponse(rspId, status, 0); } mm_status_t CowPlayer::prepareAsync() { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); mPriv->postMsgBridge(CPP_MSG_prepareAsyncMessage, 0, 0); return MM_ERROR_ASYNC; } void CowPlayer::Private::onPrepareAsync(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT(rspId == 0); mm_status_t status = mPipeline->prepare(); CHECK_PIPELINE_RET(status, "prepareAsync"); } mm_status_t CowPlayer::setVolume(const float left, const float right) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); return mPriv->mPipeline->setVolume(left, right); } mm_status_t CowPlayer::getVolume(float& left, float& right) const { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); return mPriv->mPipeline->getVolume(left, right); } mm_status_t CowPlayer::setMute(bool mute) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); PipelinePlayerBase* playBase = DYNAMIC_CAST<PipelinePlayerBase*>(mPriv->mPipeline.get()); if (playBase) return playBase->setMute(mute); else return MM_ERROR_OP_FAILED; } mm_status_t CowPlayer::getMute(bool * mute) const { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); PipelinePlayerBase* playBase = DYNAMIC_CAST<PipelinePlayerBase*>(mPriv->mPipeline.get()); if (playBase) return playBase->getMute(mute); else return MM_ERROR_OP_FAILED; } mm_status_t CowPlayer::start() { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); mPriv->postMsgBridge(CPP_MSG_startMessage, 0, 0); return MM_ERROR_ASYNC; } void CowPlayer::Private::onStart(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT(rspId == 0); mm_status_t status = MM_ERROR_SUCCESS; Pipeline::ComponentStateType state; mPipeline->getState(state); if (state == Pipeline::kComponentStatePaused) { mm_status_t status = mPipeline->resume(); CHECK_PIPELINE_RET(status, "resume"); } else { mm_status_t status = mPipeline->start(); CHECK_PIPELINE_RET(status, "start"); } } mm_status_t CowPlayer::stop() { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); mPriv->postMsgBridge(CPP_MSG_stopMessage, 0, 0); return MM_ERROR_ASYNC; } void CowPlayer::Private::onStop(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); mm_status_t status = mPipeline->stop(); CHECK_PIPELINE_RET(status, "stop"); if (rspId) postReponse(rspId, status, 0); } mm_status_t CowPlayer::pause() { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); mPriv->postMsgBridge(CPP_MSG_pauseMessage, 0, 0); return MM_ERROR_ASYNC; } void CowPlayer::Private::onPause(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT(rspId == 0); mm_status_t status = mPipeline->pause(); CHECK_PIPELINE_RET(status, "pause"); } mm_status_t CowPlayer::seekInternal(int64_t msec) { INFO("seek %ld msec\n", msec); #if 0 // FIXME skip seek temp to run H5 video if (msec == 0) { WARNING("seek skipped\n", msec); return MM_ERROR_SUCCESS; } #endif ENSURE_PIPELINE(); if (msec<0) return MM_ERROR_INVALID_PARAM; int64_t durationMsec = 0; mm_status_t ret = getDuration(durationMsec); if (ret != MM_ERROR_SUCCESS) return ret; if (msec > durationMsec) { ERROR("invalid seek position: %" PRId64 " ms, duration: %" PRId64 " ms\n", msec,durationMsec); return MM_ERROR_INVALID_PARAM; } ASSERT_RET(mPriv->mSeekParam, MM_ERROR_UNKNOWN); mPriv->mSeekParam->updateSeekTime(msec); mPriv->postMsgBridge(CPP_MSG_seekMessage, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t CowPlayer::seek(int64_t msec) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); mm_status_t status = MM_ERROR_SUCCESS; status = seekInternal(msec); // notify kEventSeekComplete. we shouldn't wait until onSeek which runs in a heavy thread mPriv->mPipeline->postCowMsgBridge(Component::kEventSeekComplete, MM_ERROR_SUCCESS, NULL, 5); return status; } void CowPlayer::Private::onSeek(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); ASSERT(rspId == 0); PipelinePlayer *pipelinePlayer = (PipelinePlayer *)mPipeline.get(); mm_status_t status = pipelinePlayer->seek(mSeekParam); CHECK_PIPELINE_RET(status, "seek"); } mm_status_t CowPlayer::reset() { FUNC_TRACK(); ENSURE_PIPELINE(); #if 0 // async mode, client is required to wait KEventResetResult before delete CowPlayer // discard pending commands mPriv->flushCommandList(); // unblock current running execution (may be blocked) mPriv->mPipeline->unblock(); // FIXME: expect no stop() is required before reset(), in case comp is in bad state and stuck in stop() // mPriv->postMsgBridge(CPP_MSG_stopMessage, 0, 0); // does reset mPriv->postMsgBridge(CPP_MSG_resetMessage, 0, 0); return MM_ERROR_ASYNC; #else MMMsgThread::param1_type rsp_param1; MMMsgThread::param2_type rsp_param2; mm_status_t status = MM_ERROR_SUCCESS; if (mPriv && mPriv->mPipeline) { Pipeline::ComponentStateType state = Pipeline::kComponentStateInvalid; status = mPriv->mPipeline->getState(state); if (status == MM_ERROR_SUCCESS && state != Pipeline::kComponentStateStopped && state != Pipeline::kComponentStateStop) { if (mPriv->sendMsgBridge(CPP_MSG_stopMessage, 0, 0, &rsp_param1, &rsp_param2)) { return MM_ERROR_UNKNOWN; } status = mm_status_t(rsp_param1); } } /* if (status != MM_ERROR_SUCCESS) return status; */ if (mPriv->sendMsgBridge(CPP_MSG_resetMessage, 0, 0, &rsp_param1, &rsp_param2)) { return MM_ERROR_UNKNOWN; } status = mm_status_t(rsp_param1); return status; #endif } void CowPlayer::Private::onReset(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); mm_status_t status = mPipeline->reset(); CHECK_PIPELINE_RET(status, "reset"); if (rspId) postReponse(rspId, status, 0); } bool CowPlayer::isPlaying() const { FUNC_TRACK(); Pipeline::ComponentStateType state; ENSURE_PIPELINE(); if (mPriv->mPipeline->getState(state) != MM_ERROR_SUCCESS) return false; DEBUG("state : %d", state); if (state != Pipeline::kComponentStatePlaying) return false; return true; } mm_status_t CowPlayer::getVideoSize(int& width, int& height) const { FUNC_TRACK(); ENSURE_PIPELINE(); return mPriv->mPipeline->getVideoSize(width, height); } mm_status_t CowPlayer::getCurrentPosition(int64_t& msec) const { //FUNC_TRACK(); ENSURE_PIPELINE(); mm_status_t status = mPriv->mPipeline->getCurrentPosition(msec); DEBUG("current playback position: %" PRId64 " ms", msec); return status; } mm_status_t CowPlayer::getDuration(int64_t& msec) const { FUNC_TRACK(); ENSURE_PIPELINE(); return mPriv->mPipeline->getDuration(msec); } mm_status_t CowPlayer::setAudioStreamType(int type) { FUNC_TRACK(); ENSURE_PIPELINE(); return mPriv->mPipeline->setAudioStreamType(type); } mm_status_t CowPlayer::getAudioStreamType(int *type) { FUNC_TRACK(); ENSURE_PIPELINE(); return mPriv->mPipeline->getAudioStreamType(type); } mm_status_t CowPlayer::setAudioConnectionId(const char * connectionId) { FUNC_TRACK(); ENSURE_PIPELINE(); return mPriv->mPipeline->setAudioConnectionId(connectionId); } const char * CowPlayer::getAudioConnectionId() const { FUNC_TRACK(); if (!mPriv->mPipeline) { if (!mPriv->createDefaultPipeline()) return ""; } return mPriv->mPipeline->getAudioConnectionId(); } mm_status_t CowPlayer::setLoop(bool loop) { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); mLoop = loop; return MM_ERROR_SUCCESS; } bool CowPlayer::isLooping() const { FUNC_TRACK(); MMAutoLock locker(mPriv->mLock); return mLoop; } MMParamSP CowPlayer::getTrackInfo() { FUNC_TRACK(); if (!mPriv->mPipeline) { if (!mPriv->createDefaultPipeline()) return nilParam; } return mPriv->mPipeline->getTrackInfo(); } mm_status_t CowPlayer::selectTrack(int mediaType, int index) { FUNC_TRACK(); ENSURE_PIPELINE(); Component::MediaType type = (Component::MediaType)mediaType; return mPriv->mPipeline->selectTrack(type, index); } int CowPlayer::getSelectedTrack(int mediaType) { FUNC_TRACK(); ENSURE_PIPELINE(); Component::MediaType type = (Component::MediaType)mediaType; return mPriv->mPipeline->getSelectedTrack(type); } // A language code in either way of ISO-639-1 or ISO-639-2. When the language is unknown or could not be determined, MM_ERROR_UNSUPPORTED will returned mm_status_t CowPlayer::setParameter(const MediaMetaSP & meta) { FUNC_TRACK(); //MMAutoLock locker(mPriv->mLock); ENSURE_PIPELINE(); //mPriv->mParam = param; mPriv->postMsgBridge2(CPP_MSG_setParameterMessage, 0, 0, meta, 0); //mm_status_t status = mPriv->mPipeline->setParameter(meta); return MM_ERROR_ASYNC; } //#if 0 void CowPlayer::Private::onSetParameter(param1_type param1, param2_type param2, param3_type param3, uint32_t rspId) { FUNC_TRACK(); MediaMetaSP meta = std::tr1::dynamic_pointer_cast<MediaMeta>(param3); mm_status_t status = mPipeline->setParameter(meta); CHECK_PIPELINE_RET(status, "setParameter"); } //#endif mm_status_t CowPlayer::getParameter(MediaMetaSP & meta) { FUNC_TRACK(); mm_status_t status = MM_ERROR_UNKNOWN; ENSURE_PIPELINE(); // not necessary to run on another thread status = mPriv->mPipeline->getParameter(meta); return status; } mm_status_t CowPlayer::invoke(const MMParam * request, MMParam * reply) { ERROR("unsupported invode yet\n"); return MM_ERROR_UNSUPPORTED; } mm_status_t CowPlayer::pushData(MediaBufferSP & buffer) { FUNC_TRACK(); mm_status_t status = MM_ERROR_UNKNOWN; ENSURE_PIPELINE(); status = mPriv->mPipeline->pushData(buffer); return status; } mm_status_t CowPlayer::enableExternalSubtitleSupport(bool enable) { FUNC_TRACK(); mm_status_t status = MM_ERROR_UNKNOWN; ENSURE_PIPELINE(); status = mPriv->mPipeline->enableExternalSubtitleSupport(enable); return status; } void CowPlayer::Private::onPipelineMessage(param1_type param1, param2_type param2, uint32_t rspId) { FUNC_TRACK(); // it is unnecessary. the message from pipeline are posted to app/listener directly. } mm_status_t CowPlayer::notify(int msg, int param1, int param2, const MMParamSP param) { //FUNC_TRACK(); { MMAutoLock locker(mPriv->mLock); if ( !mListenderSend ) { ERROR("listerner is removed or not register, skip msg: %d\n", msg); return MM_ERROR_NOT_INITED; } mListenderSend->onMessage(msg, param1, param2, param); } if (mLoop && msg == Component::kEventEOS) { INFO("replay from the begining\n"); seek(0); start(); } else if (msg == Component::kEventEOS) { INFO("EOS, no loop, pause\n"); pause(); } else if (msg == Component::kEventSeekRequire) { INFO("internal seek require position : %d\n", param1); MMAutoLock locker(mPriv->mLock); seekInternal(int(param1)/1000); } return MM_ERROR_SUCCESS; } } // YUNOS_MM
#pragma once #include "MathLibrary.h" #include "Shape.h" #include "Sphere.h" #include "Plane.h" #include "Ray.h" #include "PointLight.h" #include "Lights.h" #include "BVH.h" #include "Node.h" #include <vector> using namespace std; class Ray; class Sphere; class Shape; class Plane; class vec3; class mat4; class PointLight; class Lights; class BVH; class Tracer { private: float maxDis; float Dis; int ScreenWidth; int ScreenHeight; int ReflectDepth; float AspectRatio; float FOV; const int MaxReflect = 5; const float degToRad = 3.141592653589793238462643383279502884f / 180.0f; vec3 Background; vec3 CameraPosition; vec3 CheckReflection(const Ray& ray, Shape* shape); vec3 ReflectedRayDirection(const vec3& surfacenormal, const vec3& primairyraydirection); vec3 getRefraction(const Ray& ray, Shape* shape, const vec3& hitpoint); vec3 CalcSeparateBlinnPhong(const vec3& raydirection, const vec3& hitpoint, const vec3& surfacenormal); vec3 Shading(const Ray& ray, Shape* shape, const float& t); vector<Lights *> lights; vector<BVH*> Bvhs; vector<Shape*> Shapes; public: Tracer(int width, int height, float aspectratio, vec3 background); ~Tracer(); void AddShape(Shape* shape); void AddLight(Lights * light); void AddBVH(BVH* bvh); void updateCamPos(const mat4& convermat); vec3 Trace(int x, int y, const float& fov, const mat4& convertMat); };
#include <cstdio> #include <cstring> #include <iostream> #include <queue> using namespace std; typedef long long ll; const int maxn = 10005, maxm = 30005; int n, m, eNum; int dis[maxn]; bool vis[maxn]; // 边结构,存储终点和下一条同起点边的下标 struct Edge { int v, d, next; Edge() {} Edge(int _v, int _d, int _next) : v(_v), d(_d), next(_next) {} } edge[maxm]; int head[maxn]; void add_edge(int u, int v, int d) { edge[++eNum] = Edge(v, d, head[u]); head[u] = eNum; } bool spfa(int u) { vis[u] = true; for (int i = head[u]; i; i = edge[i].next) { Edge e = edge[i]; if (dis[u] + e.d > dis[e.v]) { dis[e.v] = dis[u] + e.d; if (vis[e.v]) return false; if (!spfa(e.v)) return false; } } vis[u] = false; return true; } // #define DEBUG int main() { #ifdef DEBUG freopen("d:\\.in", "r", stdin); freopen("d:\\.out", "w", stdout); #endif cin >> n >> m; for (int u = 1; u <= n; ++u) add_edge(0, u, 0); int t, u, v, d; for (int i = 0; i < m; ++i) { cin >> t >> u >> v; if (t == 3) { add_edge(u, v, 0); add_edge(v, u, 0); } else { cin >> d; if (t == 1) add_edge(v, u, d); else add_edge(u, v, -d); } } memset(dis, 0xf1, sizeof(dis)); memset(vis, false, sizeof(vis)); dis[0] = 0; if (spfa(0)) cout << "Yes"; else cout << "No"; return 0; }