text
stringlengths
8
6.88M
#include <boost/math/constants/constants.hpp> #include "point_light.h" point_light::point_light(const vector3 center, const ::color color, const double intensity) : light(color, intensity), _center(center) {} auto point_light::direction_from(const vector3& hit_point) -> vector3 { return (_center - hit_point).normalize(); } auto point_light::distance(const vector3& hit_point) -> double { return (_center - hit_point).length(); } auto point_light::intensity(const vector3& hit_point) -> double { const auto distance_to_light_2 = direction_from(hit_point).length2(); return _intensity / (4.0 * boost::math::constants::pi<double>() * distance_to_light_2); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef PI_SELFTEST_HELPERS_ADDRESSBOOKSELFTESTHELPER_H #define PI_SELFTEST_HELPERS_ADDRESSBOOKSELFTESTHELPER_H #if defined(SELFTEST) && defined(PI_ADDRESSBOOK) #include "modules/pi/device_api/OpAddressBook.h" #include "modules/selftest/src/testutils.h" #include "modules/selftest/src/asynctest.h" class AddressBookSelftestHelper { public: // returns TRUE if arg1 is the same addressbook item as arg2 static BOOL AddressBookItemsEqual(OpAddressBookItem& arg1, OpAddressBookItem& arg2); static OP_STATUS FillAddressBookItemWithData(OpAddressBookItem& item, BOOL add_randomness = FALSE); static OP_STATUS GenerateRandomString(OpString& output, const uni_char* allowed_chars, unsigned int max_length); class AddressBookAsyncTest : public AsyncTest { public: AddressBookAsyncTest(OpAddressBook* address_book); OP_STATUS GetItemCount(UINT32* count_ptr); OP_STATUS AddItem(OpAddressBookItem* item, OpString* id_ptr); OP_STATUS RemoveItem(const uni_char* id, OpString* id_ptr); OP_STATUS CommitItem(OpAddressBookItem* item, OpString* id_ptr); OP_STATUS GetItem(const uni_char* id, OpVector<OpAddressBookItem>* items_ptr); OP_STATUS GetAllItems(OpVector<OpAddressBookItem>* items_ptr); virtual void OnContinue(); OP_STATUS m_last_operation_result; protected: OpAddressBook* m_address_book; private: BOOL m_async_operation_in_progress; }; }; #endif // defined(SELFTEST) && defined(PI_ADDRESSBOOK) #endif // !PI_SELFTEST_HELPERS_ADDRESSBOOKSELFTESTHELPER_H
#include <iostream> using namespace std; int matrix[10][10]; int paperCnt[6] = {0, 5, 5, 5, 5, 5}; int ans = 987654321; int cnt = 0; bool checkArea(int size, int dir_i, int dir_j){ for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ int cur_i = dir_i + i; int cur_j = dir_j + j; if(cur_i >= 10 || cur_j >= 10 || matrix[cur_i][cur_j] == 0){ return false; } } } return true; } void pasteArea(int size, int dir_i, int dir_j, bool isPaste){ int val = (isPaste) ? 0 : 1; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ int cur_i = dir_i + i; int cur_j = dir_j + j; matrix[cur_i][cur_j] = val; } } } void check(int _i, int _j){ if(_i >= 10){ if(ans > cnt){ ans = cnt; } return; } if(_j >= 10){ check(_i + 1, 0); return; } if(matrix[_i][_j] == 0){ check(_i, _j + 1); return; } for(int pSize = 5; pSize > 0; pSize--){ if(checkArea(pSize, _i, _j) && paperCnt[pSize] > 0){ pasteArea(pSize, _i, _j, true); cnt++; paperCnt[pSize]--; check(_i, _j + 1); pasteArea(pSize, _i, _j, false); cnt--; paperCnt[pSize]++; } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); for(int i = 0; i < 10; i++){ for(int j = 0; j < 10; j++){ cin >> matrix[i][j]; } } /* dfs 로 접근, 재귀적으로 접근한다. */ check(0, 0); ans = (ans == 987654321) ? -1 : ans; cout << ans << '\n'; return 0; }
#ifndef AWS_NODES_NODEEXCEPTION #define AWS_NODES_NODEEXCEPTION /* * aws/nodes/nodeexception.h * AwesomeScript Node Exception * Author: Dominykas Djacenka * Email: Chaosteil@gmail.com */ #include "../exception.h" namespace AwS{ class NodeException : public Exception{ public: enum NodeError{ Undefined = 0, NoMemory }; NodeException(const std::string& message, NodeError error = Undefined) : Exception(Exception::ConvertError, static_cast<int>(error), message), _error(error){ } private: NodeError _error; }; }; #endif
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "CryptoNote.h" #include "P2pProtocolTypes.h" #include <list> #include <boost/uuid/uuid.hpp> namespace cn { struct CryptoNoteConnectionContext; struct IP2pEndpoint { virtual ~IP2pEndpoint() = default; virtual void relay_notify_to_all(int command, const BinaryArray &data_buff, const net_connection_id *excludeConnection) = 0; virtual bool invoke_notify_to_peer(int command, const BinaryArray &req_buff, const cn::CryptoNoteConnectionContext &context) = 0; virtual uint64_t get_connections_count() = 0; virtual void for_each_connection(const std::function<void(cn::CryptoNoteConnectionContext &, PeerIdType)> &f) = 0; virtual void drop_connection(CryptoNoteConnectionContext &context, bool add_fail) = 0; // can be called from external threads virtual void externalRelayNotifyToAll(int command, const BinaryArray &data_buff, const net_connection_id *excludeConnection) = 0; virtual void externalRelayNotifyToList(int command, const BinaryArray &data_buff, const std::list<boost::uuids::uuid> &relayList) = 0; }; struct p2p_endpoint_stub : public IP2pEndpoint { void relay_notify_to_all(int command, const BinaryArray &data_buff, const net_connection_id *excludeConnection) override {} bool invoke_notify_to_peer(int command, const BinaryArray &req_buff, const cn::CryptoNoteConnectionContext &context) override { return true; } void drop_connection(CryptoNoteConnectionContext &context, bool add_fail) override {} void for_each_connection(const std::function<void(cn::CryptoNoteConnectionContext &, PeerIdType)> &f) override {} uint64_t get_connections_count() override { return 0; } void externalRelayNotifyToAll(int command, const BinaryArray &data_buff, const net_connection_id *excludeConnection) override {} void externalRelayNotifyToList(int command, const BinaryArray &data_buff, const std::list<boost::uuids::uuid> &relayList) override {} }; }
#include <iostream> using namespace std; int main() { /* - 하나의 문자를 가리키는 포인터 - 10개의 정수 요소를 가지는 배열 - 10개의 정수 요소를 가지는 배열을 가리키는 포인터 - 문자로 이루어진 배열을 가리키는 포인터 - “문자를 가리키는 포인터”를 가리키는 포인터 - 정숫값을 가지는 상수 - 정숫값을 가지는 상수를 가리키는 포인터 - 정수를 가리키는 상수 포인터 */ char* str = "bottle"; // 하나의 문자를 가리키는 포인터 int number[10] = {1,2,3,4,5,6,7,8,9,10}; // 10개의 정수 요소를 가지는 배열 int* x = new int[10]; // 10개의 정수 요소를 가지는 배열을 가리키는 포인터 char array[10] = "mouse"; char *p = array; // 문자로 이루어진 배열을 가리키는 포인터 char **s = &p; // “문자를 가리키는 포인터”를 가리키는 포인터 const int size = 1234; // 정숫값을 가지는 상수 const int *pp = &size; // 정숫값을 가지는 상수를 가리키는 포인터 int value = 777; int* const ptr = &value; // 정수를 가리키는 상수 포인터 /* - 2번 문제 - 스택(고정 크기 배열) 및 힙(동적 할당 사용)에 배열을 만드는 작은 프로그램을 작성하라. - 그리고 vargrind를 사용해 올바르게 delete를 사용하지 않으면 어떻게 되는지 확인하라. */ int stack[1024]; int *second_array = new int[10]; second_array[0] = 4095; cout << "second_array[0] = " << second_array[0] << endl; // delete[] second_array; // definitely lost 80 byte, 2leak 발생 return 0; }
// // EPITECH PROJECT, 2018 // nanotekspice // File description: // simulate chipsets // #include <stdlib.h> #include <iostream> #include <string> #include "../include/ErrorManage.hpp" ErrorManage::ErrorManage(std::string path) { this->_my_comps = Components(); this->_path = path; this->_file.open(this->_path.c_str()); this->_douille.open(std::string("tmp_file.txt").c_str()); if (!this->_file.is_open() || !this->_douille.is_open()) exit(84); this->do_all_checks(); } ErrorManage::~ErrorManage() { this->_file.close(); this->_douille.close(); } bool ErrorManage::do_all_checks() { this->check_for_coms(); this->check_for_empty_line(); this->check_for_tabs(); this->check_for_useless_space(); if (this->check_for_names() == false) return (false); return (true); } void ErrorManage::check_for_coms() { unsigned long found; while (std::getline(this->_file, this->_str)) { found = this->_str.find("#"); if (found == std::string::npos) this->_douille << this->_str << std::endl; } this->back_in(); } void ErrorManage::check_for_empty_line() { while (std::getline(this->_file, this->_str)) { if (this->_str != "") this->_douille << this->_str << std::endl; } this->back_in(); } void ErrorManage::check_for_tabs() { int found; while (std::getline(this->_file, this->_str)) { do { found = this->_str.find('\t'); if (found != -1) this->_str.replace(found, 1, " "); } while (found != -1); this->_douille << this->_str << std::endl; } this->back_in(); } void ErrorManage::check_for_useless_space() { unsigned long found; while (std::getline(this->_file, this->_str)) { do { while (this->_str.c_str()[0] == ' ') this->_str.replace(0, 1, ""); found = this->_str.find(" "); if (found != std::string::npos) this->_str.replace(found, 2, " "); } while (found != std::string::npos); if (this->_str.c_str()[this->_str.size() - 1] == ' ') this->_str = this->_str.substr(0, this->_str.size() - 1); this->_douille << this->_str << std::endl; } this->back_in(); std::remove(std::string("tmp_file.txt").c_str()); } bool ErrorManage::check_for_names() { int i; while (std::getline(this->_file, this->_str)) { i = this->_my_comps.find_in_component_tab(this->_str); if (i != -1) return (true); } return (false); } bool ErrorManage::check_for_struct() { std::cout << "We are in check_for_struct" << std::endl; while (std::getline(this->_file, this->_str)) { std::cout << this->_str << this->_str.size() << std::endl; std::cout << "before if" << std::endl; if (this->_str.find(".chipsets:") != std::string::npos && this->_str.size() == 10) std::cout << "lala" << std::endl; if (this->_str.find(".links:") != std::string::npos && this->_str.size() == 7) std::cout << "lele" << std::endl; if (this->_str.find("input ") != std::string::npos && this->_str.size() >= 7) std::cout << "lili" << std::endl; if (this->_str.find("output ") != std::string::npos && this->_str.size() >= 8) std::cout << "lolo" << std::endl; if (this->_my_comps.find_in_component_tab(this->_str) != -1 && this->_str.size() == 5) std::cout << "lulu" << std::endl; else if (check_for_links(this->_str) == true) return (true); } return (false); } bool ErrorManage::check_for_links(std::string to_test) { std::cout << "We are in check for links:" << to_test << std::endl; unsigned long i; unsigned long j; i = to_test.find(":"); j = to_test.find(" "); if (i == std::string::npos || j == std::string::npos || i >= j) return (false); to_test = to_test.substr(j + 1, to_test.size()); std::cout << to_test << std::endl; return (true); } bool ErrorManage::back_in() { int i; this->_file.close(); this->_douille.close(); if (std::remove(this->_path.c_str()) != 0) { std::cout << "ERROR 0" << std::endl; return (false); } i = std::rename(std::string("tmp_file.txt").c_str(), this->_path.c_str()); if (i != 0) { std::cout << "ERROR 1" << i <<std::endl; std::perror("rename"); return (false); } this->_file.open(this->_path.c_str()); this->_douille.open(std::string("tmp_file.txt").c_str()); if (!this->_file.is_open() || !this->_douille.is_open()) exit(84); return (true); }
// Birthday Cake Candles // https://www.hackerrank.com/challenges/birthday-cake-candles/problem #include<bits/stdc++.h> using namespace std; int birthdayCakeCandles(vector<int> candles) { auto tallest=max_element(candles.begin(), candles.end()); int count=0; for(auto itr=candles.begin(); itr!=candles.end(); itr++) { count+=(*itr==*tallest)?1:0; } return count; } int main() { vector<int> arr; int i, n, candle; cin>>n; for(i=0; i<n; i++) { cin>>candle; arr.push_back(candle); } cout<<birthdayCakeCandles(arr)<<endl; return 0; }
#include <iostream> #include <vector> #include "limits.h" using namespace std; /** * Definition for singly-linked list. **/ struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; // FIGURE OUT a BETTR SOLUTION // This soultion creates a new list and leaves the original lists data // structure in place. First a traversing pointer is ListNode* mergeKLists(vector<ListNode*>& lists) { vector<ListNode*> ptr; ListNode tmp(0); ListNode *currPtr = &tmp, *rtn = currPtr; int k = lists.size(); // Add pointers to a new array for (int i = 0; i < k; i++) { ptr.push_back(lists[i]); } while (1) { int fullyTraversedLists = 0; int min = INT_MAX; int min_index = 0; for (int i = 0; i < k; i++) { if (ptr[i] == nullptr) { fullyTraversedLists++; continue; } else { if (ptr[i]->val <= min) { min = ptr[i]->val; min_index = i; } } } //for if (fullyTraversedLists == k) break; ptr[min_index] = ptr[min_index]->next; currPtr->next = new ListNode(min); // insert currPtr = currPtr->next; } //while return(rtn->next); } int main (int argc, char **argv) { vector<ListNode*> lists; ListNode tmp, tmp1, tmp2; tmp.val = 1; tmp.next = nullptr; lists.push_back(&tmp); tmp1.val = 4; tmp1.next = nullptr; lists[0]->next = &tmp1; tmp2.val = 5; tmp2.next = nullptr; lists[0]->next->next = &tmp2; ListNode tmp3, tmp4, tmp5; tmp3.val = 1; tmp3.next = nullptr; lists.push_back(&tmp3); tmp4.val = 3; tmp4.next = nullptr; lists[1]->next = &tmp4; tmp5.val = 4; tmp5.next = nullptr; lists[1]->next->next = &tmp5; ListNode tmp6, tmp7; tmp6.val = 2; lists.push_back(&tmp6); tmp7.val = 6; lists[2]->next = &tmp7; ListNode *rtn = mergeKLists(lists); }
#include "stdafx.h" #include "MessageLoop.h" #include "TlsHelper.h" #include "MessagePumpForUI.h" #include "MessagePumpForIO.h" #include "MessagePumpDefault.h" static TlsHelper g_TlsMessageLoopInstanc; MessageLoop::MessageLoop(Type type) : m_Type(type) , m_pState(NULL) , m_iNextSequenceNum(0) , m_bReentrantAllowed(true) { if (m_Type == Type_UI) { m_pMessagePump.reset(new MessagePumpForUI); } else if (m_Type == Type_IO) { m_pMessagePump.reset(new MessagePumpForIO); } else { ZhanAssert(m_Type == Type_default); m_pMessagePump.reset(new MessagePumpDefault); } g_TlsMessageLoopInstanc.SetValue(this); } MessageLoop::~MessageLoop() { g_TlsMessageLoopInstanc.SetValue(NULL); // try to delete for (int iIndex = 0; iIndex < 10; ++iIndex) { DeletePendingTasks(); ReloadWorkQueue(); if (!DeletePendingTasks()) { break; } } for (DestructionObserverVectorIter iter = m_vecDestructionObserver.begin(); iter != m_vecDestructionObserver.end(); ++iter) { (*iter)->WillDestructMessageLoop(); } } bool MessageLoop::PendingTask::operator < (const PendingTask &task) const { // 大根堆 if (dwDelayedWorkTime != task.dwDelayedWorkTime) { return dwDelayedWorkTime > task.dwDelayedWorkTime; } return iSequenceNum > task.iSequenceNum; } MessageLoop* MessageLoop::Current() { return reinterpret_cast<MessageLoop*>(g_TlsMessageLoopInstanc.GetValue()); } void MessageLoop::AddDestructionObserver(DestructionObserver *pObserver) { m_vecDestructionObserver.push_back(pObserver); } void MessageLoop::RemoveDestructionObserver(DestructionObserver *pObserver) { for (DestructionObserverVectorIter iter = m_vecDestructionObserver.begin(); iter != m_vecDestructionObserver.end(); ++iter) { if (pObserver == *iter) { m_vecDestructionObserver.erase(iter); break; } } } void MessageLoop::Run() { AutoRunState state(this); m_pMessagePump->Run(this); } void MessageLoop::RunAllPending() { AutoRunState state(this); m_pState->bShouldQuit = true; m_pMessagePump->Run(this); } void MessageLoop::QuitByTaskClosure() { TaskClosure task = CreateTaskClosure(&MessageLoop::Quit, this); PostTask(task); } void MessageLoop::Quit() { if (m_pState) { m_pState->bShouldQuit = true; } } void MessageLoop::QuitNow() { if (m_pState) { m_pState->bShouldQuit = true; m_pMessagePump->Quit(); } } void MessageLoop::SetNestalbeTaskAllowed(bool bNestable) { if (m_bReentrantAllowed != bNestable) { m_bReentrantAllowed = bNestable; if (m_bReentrantAllowed) { // activate to do work if already stop for nestable loop m_pMessagePump->ScheduleWork(); } } } bool MessageLoop::DoWork() { if (!m_bReentrantAllowed) { return false; } for (;;) { ReloadWorkQueue(); if (m_WorkQueue.empty()) { break; } PendingTask task = m_WorkQueue.front(); m_WorkQueue.pop(); if (task.dwDelayedWorkTime) { AddTaskToDelayedQueue(task); if (m_DelayedWorkQueue.top().dwDelayedWorkTime == task.dwDelayedWorkTime) { m_pMessagePump->ScheduleDelayedWork(task.dwDelayedWorkTime); } } else { if (DeferOrRunPendingTask(task)) { return true; } } } return false; } bool MessageLoop::DoDelayedWork(DWORD *pDelayedWorkTime) { if (!m_bReentrantAllowed) { *pDelayedWorkTime = 0; return false; } for (;;) { if (m_DelayedWorkQueue.empty()) { *pDelayedWorkTime = 0; break; } if (m_DelayedWorkQueue.top().dwDelayedWorkTime > GetTickCount()) { *pDelayedWorkTime = m_DelayedWorkQueue.top().dwDelayedWorkTime; break; } PendingTask task = m_DelayedWorkQueue.top(); m_DelayedWorkQueue.pop(); if (DeferOrRunPendingTask(task)) { if (m_DelayedWorkQueue.empty()) { *pDelayedWorkTime = 0; break; } *pDelayedWorkTime = m_DelayedWorkQueue.top().dwDelayedWorkTime; return true; } } return false; } bool MessageLoop::DoIdleWork() { if (!m_bReentrantAllowed || IsNested() || m_DeferredNonNestableWorkQueue.empty()) { if (m_pState->bShouldQuit) { m_pMessagePump->Quit(); } return false; } PendingTask task = m_DeferredNonNestableWorkQueue.front(); m_DeferredNonNestableWorkQueue.pop(); RunTask(task); return true; } void MessageLoop::PostTask(const TaskClosure &task) { PendingTask pendingTask(task, 0); AddTaskToIncomingQueue(pendingTask); } void MessageLoop::PostDelayedTask(const TaskClosure &task, DWORD dwTimeout) { PendingTask pendingTask(task, GetTickCount() + dwTimeout); AddTaskToIncomingQueue(pendingTask); } void MessageLoop::PostNonNestableTask(const TaskClosure &task) { PendingTask pendingTask(task, 0, false); AddTaskToIncomingQueue(pendingTask); } void MessageLoop::PostNonNestableDelayedTask(const TaskClosure &task, DWORD dwTimeout) { PendingTask pendingTask(task, GetTickCount() + dwTimeout, false); AddTaskToIncomingQueue(pendingTask); } bool MessageLoop::IsIdle() const { AutoLock autoLock(m_lock); return m_IncomingQueue.empty(); } void MessageLoop::AddTaskToIncomingQueue(const PendingTask &task) { std::shared_ptr<MessagePump> pPump; { AutoLock autoLock(m_lock); bool bWasEmpty = m_IncomingQueue.empty(); m_IncomingQueue.push(task); if (!bWasEmpty) { return; } // 增加pump引用计数,防止被队列中的任务析构了 pPump = m_pMessagePump; } pPump->ScheduleWork(); } void MessageLoop::AddTaskToDelayedQueue(PendingTask &task) { task.iSequenceNum = m_iNextSequenceNum++; m_DelayedWorkQueue.push(task); } void MessageLoop::ReloadWorkQueue() { if (!m_WorkQueue.empty()) { return; } AutoLock autoLock(m_lock); if (m_IncomingQueue.empty()) { return; } m_WorkQueue.swap(m_IncomingQueue); } bool MessageLoop::DeletePendingTasks() { bool bDidWork = false; while (!m_WorkQueue.empty()) { m_WorkQueue.pop(); bDidWork = true; } while (!m_DelayedWorkQueue.empty()) { m_DelayedWorkQueue.pop(); bDidWork = true; } while (!m_DeferredNonNestableWorkQueue.empty()) { m_DeferredNonNestableWorkQueue.pop(); bDidWork = true; } return bDidWork; } bool MessageLoop::DeferOrRunPendingTask(const PendingTask &task) { if (!task.bNestable && IsNested()) { m_DeferredNonNestableWorkQueue.push(task); return false; } RunTask(task); return true; } void MessageLoop::RunTask(const PendingTask &task) { m_bReentrantAllowed = false; task.task->Run(); m_bReentrantAllowed = true; }
#include "stdafx.h" #include "MultipleChoiceQuestionViewController.h" #include "MultipleChoiceQuestionState.h" #include "MultipleChoiceQuestionView.h" namespace qp { CMultipleChoiceQuestionViewController::CMultipleChoiceQuestionViewController(IMultipleChoiceQuestionStatePtr const& questionState, CMultipleChoiceQuestionViewPtr const& view) :CQuestionViewController(questionState, view) ,m_questionState(questionState) ,m_view(view) ,m_answerSelectedRequestedConnection(view->DoOnAnswerSelected(bind(&CMultipleChoiceQuestionViewController::OnAnswerSelectedRequest, this, _1))) { } CMultipleChoiceQuestionViewController::~CMultipleChoiceQuestionViewController() { } void CMultipleChoiceQuestionViewController::OnAnswerSelectedRequest(size_t answerIndex) { m_questionState->SetUserAnswerIndex(answerIndex); m_view->Show(); } }
void changeNumberForID(const string& inFilename,int ID,const string& inNewNumber) { fstream ioData(inFilename.c_str()); if(!ioData) { cerr<<"Error while opening file "<<inFilename<<endl; exit(1); } while(ioData.good()) { int id; string number; ioData>>id; if(id==inID) { ioData.seekp(ioData.tellg()); ioData<<" "<<inNewNumber; break ; } ioData>>number; } }
#include<string> #include"bmi.h" void BMI::setmass(double num){ mass=num; } void BMI::sethigh(double num){ high=num; } double BMI:: getmass(){ return mass; } double BMI::gethigh(){ return high; } double BMI::bmivalue(){ return high==0?0: mass/(high*high); } string BMI::category(double bmi){ if(bmi==0) return" "; if(bmi<15.0)return "Very severely underweight"; else if(bmi<16.0)return "Severely underweight"; else if(bmi<18.5)return "Underweight "; else if(bmi<25.0)return "Normal"; else if(bmi<30.0)return "Overweight "; else if(bmi<35.0)return "Obese Class I (Moderately obese) "; else if(bmi<40.0)return "Obese Class II (Severely obese)"; else return "Obese Class III (Very severely obese) "; }
#include <Servo.h> // Incluir la librería Servo #include <LiquidCrystal.h> //Libreria para el LCD #include<Wire.h> //Libreria para el LCD #include <LiquidCrystal_I2C.h> //Libreria para el LCD #include <DHT.h> //cargamos la librería DHT. #define DHTPIN 2 //Seleccionamos el pin 2 digital en el que se conectará el sensor. #define DHTTYPE DHT22 //Se selecciona el DHT22. DHT dht(DHTPIN, DHTTYPE); //Se inicia una variable que será usada por Arduino para comunicarse con el sensor. //DECLARAMOS VARIABLES. int temperatura, humedad; int hora, minuto, segundo; int dia=0;//Declaramos la variable dia que es la que indica dia de inicio. int bombillo1= 28; //Declaramos pin 28DIG, de las bombillas int bombillo2= 29; //Declaramos pin 29DIG, de las bombillas int ventilador1=30; //Declaramos pin 30DIG, para controlar el ventilador 1 int ventilador2=31; //Declaramos pin 31DIG, para controlar el ventilador 2 int d; int h; int m; int s; int posicion=0;//Declaramos una variable para indicar los grados del servo. int comandosEntrada; int validacion; Servo servo1; //Se inicia una variable que será usada por Arduino para comunicarse con el servo. LiquidCrystal_I2C lcd(0x3F,16,2); //Se inicia una variable que será usada por Arduino para comunicarse con la pantalla LCD. void setup(){ Serial.begin(9600); dht.begin();//Lectura del sensor. pinMode(bombillo1, OUTPUT);//Declaramos el pin del bombillo1 como salida. pinMode(bombillo2, OUTPUT);//Declaramos el pin del bombillo2 como salida. pinMode(ventilador1, OUTPUT);//Declaramos el pin del ventilador1 como salida. pinMode(ventilador2,OUTPUT);//Declaramos el pin del ventilador2 como salida. Wire.begin();//Lectura del I2C. lcd.begin(16,2);//Lectura de la pantalla LCD. lcd.clear();//Limpiamos pantalla. lcd.backlight();//Prendemos la luz de fondo del LCD. servo1.attach(9); //Declaramos el pin 9 digital para el servo. } void procedimiento() { for(d=dia+1;d<=21;d++){//Ciclo para recorrer los días. hora=0; if(d>=19){//Instrucciones para los días de nacimiento que van desde el dia 19 hasta el 21, para para los motores de rotacion. posicion=90; servo1.write(posicion); if(temperatura< 37){ digitalWrite(bombillo1,HIGH); digitalWrite(bombillo2,HIGH); }else{ digitalWrite(bombillo1,LOW); digitalWrite(bombillo1,LOW); } if (humedad < 60){ digitalWrite(ventilador1, LOW); digitalWrite(ventilador2,LOW); }else{ digitalWrite(ventilador1, HIGH); digitalWrite(ventilador2,HIGH); } } for(h=hora;h<=23;h++){ minuto=0; for(m=minuto;m<=59;m++){//CAMBIAR A 59 segundo=0; for(s=segundo;s<=59;s++){//CAMBIAR A 59 temperatura = dht.readTemperature(); humedad = dht.readHumidity(); String R=""; Serial.print(temperatura); Serial.print(","); Serial.print(humedad); Serial.print(","); R+=d; R+=":"; R+=h; R+=":"; R+=m; R+=":"; R+=s; Serial.print(R); Serial.println(); if ( temperatura < 37 ){ digitalWrite(bombillo1, HIGH); digitalWrite(bombillo2, HIGH); }else if(temperatura > 37){ digitalWrite(bombillo1, LOW); digitalWrite(bombillo2, LOW); } if (humedad > 75){ digitalWrite(ventilador1, LOW); digitalWrite(ventilador2,LOW); }else{ digitalWrite(ventilador1, HIGH); digitalWrite(ventilador2,HIGH); } lcd.setCursor(0,0); lcd.print("Temp:"); lcd.print(temperatura); lcd.print(" Dia:"); lcd.setCursor(0,1); lcd.print("Hum:"); lcd.print(humedad); lcd.print("% ");//--CAMBIAR " " lcd.print(d); if(h==0 || h==1 || h==4 || h==5 || h==8 || h==9 || h==12 || h==13 || h==16 || h==17 || h==20 || h==21 && d<19){ posicion=135; servo1.write(posicion); }else{ posicion=45; servo1.write(posicion); } delay(1000);//CAMBIAR A 1000 } } } } } void loop(){ if(Serial.available()>0) { comandosEntrada=Serial.read(); if(comandosEntrada=='1') { validacion=1; } } if(validacion==1) { procedimiento(); }else { lcd.clear(); lcd.setCursor(0,0); lcd.print("Esperando"); lcd.setCursor(0,1); lcd.print("Inicio..."); delay(2000); posicion=90; servo1.write(posicion); digitalWrite(bombillo1, HIGH); digitalWrite(bombillo2, HIGH); } }
#include <iostream> #include <string> #include "mappings.hpp" using namespace mappings; void test0() { std::string* str = Create1("hello", Type2Type<std::string>{}); Widget<int>* pw = Create1(100, Type2Type<Widget<int>>{}); } int main() { return 0; }
#include "Texture.h" #include "sdlwrap.h" #include <SDL_image.h> #include <SDL_render.h> #include <memory> #include <unordered_map> Texture::Texture() {} Texture::Texture(char const* path) { load(path); } void Texture::load(char const* path) { SDL_Surface* buf = IMG_Load(path); if(!buf) { SDL_Log("Failed loading %s. %s.\n", path, IMG_GetError()); throw FailedToLoadTextureException(); } SDL_Texture* newTex = SDL_CreateTextureFromSurface(renderer(), buf); if(!newTex) { SDL_Log("Failed creating texture %s. %s.\n", path, SDL_GetError()); SDL_FreeSurface(buf); throw FailedToLoadTextureException(); } SDL_Log("Loaded texture: %s.\n", path); if(_tex) SDL_DestroyTexture(_tex); _tex = newTex; _w = buf->w; _h = buf->h; SDL_FreeSurface(buf); } Texture::~Texture() { if(_tex) { SDL_DestroyTexture(_tex); } } void Texture::render(int x, int y) const { if(!_tex) return; SDL_Rect dstrect = {x, y, _w, _h}; SDL_RenderCopy(renderer(), _tex, nullptr, &dstrect); } void Texture::render(int x, int y, float angle) const { if(!_tex) return; SDL_Rect dstrect = {x, y, _w, _h}; SDL_RenderCopyEx(renderer(), _tex, nullptr, &dstrect, angle, nullptr, SDL_FLIP_NONE); } void Texture::render(int x, int y, float angle, int w, int h) const { if(!_tex) return; SDL_Rect dstrect = {x, y, w, h}; SDL_Rect srcrect = {0, 0, w, h}; SDL_RenderCopyEx(renderer(), _tex, &srcrect, &dstrect, angle, nullptr, SDL_FLIP_NONE); } void Texture::render(SDL_Point const& pos) const { render(pos.x, pos.y); } void Texture::render(SDL_Point const& pos, float angle) const { render(pos.x, pos.y, angle); } void Texture::render(SDL_Point const& pos, float angle, SDL_Rect const& clip) const { render(pos.x, pos.y, angle, clip.w, clip.h); } void Texture::render(SDL_Point const& pos, SDL_Rect const& clip) const { SDL_Rect dstrect = {pos.x, pos.y, clip.w, clip.h}; SDL_Rect srcrect = {clip.x, clip.y, clip.w, clip.h}; SDL_RenderCopy(renderer(), _tex, &srcrect, &dstrect); } Texture& textures(std::string const& name) { static std::unordered_map<std::string, Texture> ret; return ret[name]; }
#ifndef CAMERA_H #define CAMERA_H #include "GL/gl.h" #include <math.h> #include <../mat.h> class Camera { public: Camera(); virtual ~Camera(); vec4 pos; vec4 focus; vec4 side; GLfloat yaw, pitch; void translate(vec3 d); void rotate(); void forward(GLfloat d); void strafe(GLfloat d); void vert(GLfloat d); void rotate(GLfloat p, GLfloat y); mat4 mProj; protected: private: void proj_matrix(); }; #endif // CAMERA_H
// script.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "custom-hooks.h" #include "script.h" #include "MFUtility.h" #include "encoder.h" #include "logger.h" #include "util.h" #include "yara-helper.h" #include "game-detour-def.h" #include <DirectXMath.h> //#include <C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\comdecl.h> //#include <C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\xaudio2.h> //#include <C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\XAudio2fx.h> //#include <C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\XAPOFX.h> #pragma warning(push) #pragma warning( disable : 4005 ) //#include <C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\x3daudio.h> #pragma warning(pop) //#pragma comment(lib,"x3daudio.lib") //#pragma comment(lib,"xapofx.lib") #include "..\DirectXTex\DirectXTex\DirectXTex.h" #include "hook-def.h" using namespace Microsoft::WRL; using namespace DirectX; namespace { std::shared_ptr<PLH::VFuncDetour> hkIMFSinkWriter_AddStream(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkIMFSinkWriter_SetInputMediaType(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkIMFSinkWriter_WriteSample(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkIMFSinkWriter_Finalize(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkOMSetRenderTargets(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkDraw(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkCreateSourceVoice(new PLH::VFuncDetour); std::shared_ptr<PLH::VFuncDetour> hkSubmitSourceBuffer(new PLH::VFuncDetour); std::shared_ptr<PLH::IATHook> hkCoCreateInstance(new PLH::IATHook); std::shared_ptr<PLH::IATHook> hkMFCreateSinkWriterFromURL(new PLH::IATHook); std::shared_ptr<PLH::X64Detour> hkGetFrameRateFraction(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetRenderTimeBase(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkStepAudio(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetGameSpeedMultiplier(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkCreateThread(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetFrameRate(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetAudioSamples(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkUnk01(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkCreateTexture(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkCreateExportTexture(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkLinearizeTexture(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkAudioUnk01(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkWaitForSingleObject(new PLH::X64Detour); /*std::shared_ptr<PLH::X64Detour> hkGetGlobalVariableIndex(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetVariable(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetMatrices(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetVar(new PLH::X64Detour); std::shared_ptr<PLH::X64Detour> hkGetVarPtrByHash(new PLH::X64Detour);*/ ComPtr<ID3D11Texture2D> pGameBackBuffer; ComPtr<ID3D11Texture2D> pGameBackBufferResolved; ComPtr<ID3D11Texture2D> pGameDepthBufferQuarterLinear; ComPtr<ID3D11Texture2D> pGameDepthBufferQuarter; ComPtr<ID3D11Texture2D> pGameDepthBufferResolved; ComPtr<ID3D11Texture2D> pGameDepthBuffer; ComPtr<ID3D11Texture2D> pGameGBuffer0; ComPtr<ID3D11Texture2D> pGameEdgeCopy; ComPtr<ID3D11Texture2D> pLinearDepthTexture; ComPtr<ID3D11Texture2D> pStencilTexture; DWORD threadIdRageAudioMixThread = 0; void* pCtxLinearizeBuffer = NULL; //std::shared_ptr<PLH::X64Detour> hkGetTexture(new PLH::X64Detour); bool isCustomFrameRateSupported = false; std::unique_ptr<Encoder::Session> session; std::mutex mxSession; void *pGlobalUnk01 = NULL; std::thread::id mainThreadId; ComPtr<IDXGISwapChain> mainSwapChain; ComPtr<IDXGIFactory> pDXGIFactory; struct ExportContext { ExportContext() { PRE(); POST(); } ~ExportContext() { PRE(); POST(); } float audioSkipCounter = 0; float audioSkip = 0; bool isAudioExportDisabled = false; bool captureRenderTargetViewReference = false; bool captureDepthStencilViewReference = false; ComPtr<ID3D11Texture2D> pExportRenderTarget; ComPtr<ID3D11DeviceContext> pDeviceContext; ComPtr<ID3D11Device> pDevice; ComPtr<IDXGIFactory> pDXGIFactory; ComPtr<IDXGISwapChain> pSwapChain; float far_clip = 0; float near_clip = 0; std::shared_ptr<DirectX::ScratchImage> capturedImage = std::make_shared<DirectX::ScratchImage>(); UINT pts = 0; ComPtr<IMFMediaType> videoMediaType; }; std::shared_ptr<ExportContext> exportContext; std::shared_ptr<YaraHelper> pYaraHelper; } tCoCreateInstance oCoCreateInstance; tMFCreateSinkWriterFromURL oMFCreateSinkWriterFromURL; tIMFSinkWriter_SetInputMediaType oIMFSinkWriter_SetInputMediaType; tIMFSinkWriter_AddStream oIMFSinkWriter_AddStream; tIMFSinkWriter_WriteSample oIMFSinkWriter_WriteSample; tIMFSinkWriter_Finalize oIMFSinkWriter_Finalize; tOMSetRenderTargets oOMSetRenderTargets; tGetRenderTimeBase oGetRenderTimeBase; //tGetGameSpeedMultiplier oGetGameSpeedMultiplier; tCreateThread oCreateThread; //tWaitForSingleObject oWaitForSingleObject; //tStepAudio oStepAudio; tCreateTexture oCreateTexture; //tCreateSourceVoice oCreateSourceVoice; //tSubmitSourceBuffer oSubmitSourceBuffer; tDraw oDraw; tAudioUnk01 oAudioUnk01; void avlog_callback(void *ptr, int level, const char* fmt, va_list vargs) { static char msg[8192]; vsnprintf_s(msg, sizeof(msg), fmt, vargs); Logger::instance().write( Logger::instance().getTimestamp(), " ", Logger::instance().getLogLevelString(LL_NON), " ", Logger::instance().getThreadId(), " AVCODEC: "); if (ptr) { AVClass *avc = *(AVClass**)ptr; Logger::instance().write("("); Logger::instance().write(avc->item_name(ptr)); Logger::instance().write("): "); } Logger::instance().write(msg); } //static HRESULT CreateSourceVoice( // IXAudio2 *pThis, // IXAudio2SourceVoice **ppSourceVoice, // const WAVEFORMATEX *pSourceFormat, // UINT32 Flags, // float MaxFrequencyRatio, // IXAudio2VoiceCallback *pCallback, // const XAUDIO2_VOICE_SENDS *pSendList, // const XAUDIO2_EFFECT_CHAIN *pEffectChain // ) { // PRE(); // HRESULT result = oCreateSourceVoice(pThis, ppSourceVoice, pSourceFormat, Flags, MaxFrequencyRatio, pCallback, pSendList, pEffectChain); // if (SUCCEEDED(result)) { // hookVirtualFunction(*ppSourceVoice, 21, &SubmitSourceBuffer, &oSubmitSourceBuffer, hkSubmitSourceBuffer); // } // //WAVEFORMATEX *pSourceFormatRW = (WAVEFORMATEX *)pSourceFormat; // //pSourceFormatRW->nSamplesPerSec = pSourceFormat->nSamplesPerSec; // POST(); // return result; //} //static HRESULT SubmitSourceBuffer( // IXAudio2SourceVoice *pThis, // const XAUDIO2_BUFFER *pBuffer, // const XAUDIO2_BUFFER_WMA *pBufferWMA // ) { // //StackDump(128, __func__); // return oSubmitSourceBuffer(pThis, pBuffer, pBufferWMA); // //return S_OK; //} void onPresent(IDXGISwapChain *swapChain) { mainSwapChain = swapChain; static bool initialized = false; if (!initialized) { initialized = true; try { ComPtr<ID3D11Device> pDevice; ComPtr<ID3D11DeviceContext> pDeviceContext; ComPtr<ID3D11Texture2D> texture; DXGI_SWAP_CHAIN_DESC desc; swapChain->GetDesc(&desc); LOG(LL_NFO, "BUFFER COUNT: ", desc.BufferCount); REQUIRE(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)texture.GetAddressOf()), "Failed to get the texture buffer"); REQUIRE(swapChain->GetDevice(__uuidof(ID3D11Device), (void**)pDevice.GetAddressOf()), "Failed to get the D3D11 device"); pDevice->GetImmediateContext(pDeviceContext.GetAddressOf()); NOT_NULL(pDeviceContext.Get(), "Failed to get D3D11 device context"); REQUIRE(hookVirtualFunction(pDeviceContext.Get(), 13, &Draw, &oDraw, hkDraw), "Failed to hook ID3DDeviceContext::Draw"); REQUIRE(hookVirtualFunction(pDeviceContext.Get(), 33, &Hook_OMSetRenderTargets, &oOMSetRenderTargets, hkOMSetRenderTargets), "Failed to hook ID3DDeviceContext::OMSetRenderTargets"); ComPtr<IDXGIDevice> pDXGIDevice; REQUIRE(pDevice.As(&pDXGIDevice), "Failed to get IDXGIDevice from ID3D11Device"); ComPtr<IDXGIAdapter> pDXGIAdapter; REQUIRE(pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)pDXGIAdapter.GetAddressOf()), "Failed to get IDXGIAdapter"); REQUIRE(pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void**)pDXGIFactory.GetAddressOf()), "Failed to get IDXGIFactory"); } catch (std::exception& ex) { LOG(LL_ERR, ex.what()); } } } void initialize() { PRE(); try { mainThreadId = std::this_thread::get_id(); /*REQUIRE(CoInitializeEx(NULL, COINIT_MULTITHREADED), "Failed to initialize COM"); ComPtr<IXAudio2> pXAudio; REQUIRE(XAudio2Create(pXAudio.GetAddressOf(), 0, XAUDIO2_DEFAULT_PROCESSOR), "Failed to create XAudio2 object");*/ //REQUIRE(hookVirtualFunction(pXAudio.Get(), 11, &CreateSourceVoice, &oCreateSourceVoice, hkCreateSourceVoice), "Failed to hook IXAudio2::CreateSourceVoice"); //IXAudio2MasteringVoice *pMasterVoice; //WAVEFORMATEX waveFormat; //UINT32 deviceCount; // Number of devices //pXAudio->GetDeviceCount(&deviceCount); //XAUDIO2_DEVICE_DETAILS deviceDetails; // Structure to hold details about audio device //int preferredDevice = 0; // Device to be used // // Loop through devices //for (unsigned int i = 0; i < deviceCount; i++) //{ // // Get device details // pXAudio->GetDeviceDetails(i, &deviceDetails); // // Check conditions ( default device ) // if (deviceDetails.Role == DefaultCommunicationsDevice) // { // preferredDevice = i; // break; // } //} REQUIRE(hookNamedFunction("mfreadwrite.dll", "MFCreateSinkWriterFromURL", &Hook_MFCreateSinkWriterFromURL, &oMFCreateSinkWriterFromURL, hkMFCreateSinkWriterFromURL), "Failed to hook MFCreateSinkWriterFromURL in mfreadwrite.dll"); //REQUIRE(hookNamedFunction("ole32.dll", "CoCreateInstance", &Hook_CoCreateInstance, &oCoCreateInstance, hkCoCreateInstance), "Failed to hook CoCreateInstance in ole32.dll"); pYaraHelper.reset(new YaraHelper()); pYaraHelper->initialize(); MODULEINFO info; GetModuleInformation(GetCurrentProcess(), GetModuleHandle(NULL), &info, sizeof(info)); LOG(LL_NFO, "Image base:", ((void*)info.lpBaseOfDll)); void *pGetRenderTimeBase = NULL; void *pCreateTexture = NULL; void *pLinearizeTexture = NULL; void *pAudioUnk01 = NULL; void *pGetGameSpeedMultiplier = NULL; void *pStepAudio = nullptr; void *pCreateThread = nullptr; void *pWaitForSingleObject = nullptr; pYaraHelper->addEntry("yara_get_render_time_base_function", yara_get_render_time_base_function, &pGetRenderTimeBase); pYaraHelper->addEntry("yara_get_game_speed_multiplier_function", yara_get_game_speed_multiplier_function, &pGetGameSpeedMultiplier); pYaraHelper->addEntry("yara_step_audio_function", yara_step_audio_function, &pStepAudio); pYaraHelper->addEntry("yara_audio_unk01_function", yara_audio_unk01_function, &pAudioUnk01); pYaraHelper->addEntry("yara_create_thread_function", yara_create_thread_function, &pCreateThread); //pYaraHelper->addEntry("yara_create_export_texture_function", yara_create_export_texture_function, &pCreateExportTexture); pYaraHelper->addEntry("yara_create_texture_function", yara_create_texture_function, &pCreateTexture); pYaraHelper->addEntry("yara_wait_for_single_object", yara_wait_for_single_object, &pWaitForSingleObject); /*pYaraHelper->addEntry("yara_global_unk01_command", yara_global_unk01_command, &pGlobalUnk01Cmd); pYaraHelper->addEntry("yara_get_var_ptr_by_hash_2", yara_get_var_ptr_by_hash_2, &pGetVarPtrByHash);*/ pYaraHelper->performScan(); //LOG(LL_NFO, (VOID*)(0x311C84 + (intptr_t)info.lpBaseOfDll)); //REQUIRE(hookX64Function((BYTE*)(0x11441F4 + (intptr_t)info.lpBaseOfDll), &Detour_GetVarHash, &oGetVarHash, hkGetVar), "Failed to hook GetVar function."); try { if (pGetRenderTimeBase) { REQUIRE(hookX64Function(pGetRenderTimeBase, &Detour_GetRenderTimeBase, &oGetRenderTimeBase, hkGetRenderTimeBase), "Failed to hook FPS function."); isCustomFrameRateSupported = true; } else { LOG(LL_ERR, "Could not find the address for FPS function."); LOG(LL_ERR, "Custom FPS support is DISABLED!!!"); } if (pCreateTexture) { REQUIRE(hookX64Function(pCreateTexture, &Detour_CreateTexture, &oCreateTexture, hkCreateTexture), "Failed to hook CreateTexture function."); } else { LOG(LL_ERR, "Could not find the address for CreateTexture function."); } if (pCreateThread) { REQUIRE(hookX64Function(pCreateThread, &Detour_CreateThread, &oCreateThread, hkCreateThread), "Failed to hook CreateThread function."); } else { LOG(LL_ERR, "Could not find the address for CreateThread function."); } /*if (pWaitForSingleObject) { REQUIRE(hookX64Function(pWaitForSingleObject, &Detour_WaitForSingleObject, &oWaitForSingleObject, hkWaitForSingleObject), "Failed to hook WaitForSingleObject function."); } else { LOG(LL_ERR, "Could not find the address for WaitForSingleObject function."); }*/ /*if (pStepAudio) { REQUIRE(hookX64Function(pStepAudio, &Detour_StepAudio, &oStepAudio, hkStepAudio), "Failed to hook StepAudio function."); } else { LOG(LL_ERR, "Could not find the address for StepAudio."); } */ /*if (pGetGameSpeedMultiplier) { REQUIRE(hookX64Function(pGetGameSpeedMultiplier, &Detour_GetGameSpeedMultiplier, &oGetGameSpeedMultiplier, hkGetGameSpeedMultiplier), "Failed to hook GetGameSpeedMultiplier function."); } else { LOG(LL_ERR, "Could not find the address for GetGameSpeedMultiplier function."); }*/ /*if (pAudioUnk01) { REQUIRE(hookX64Function(pAudioUnk01, &Detour_AudioUnk01, &oAudioUnk01, hkAudioUnk01), "Failed to hook AudioUnk01 function."); } else { LOG(LL_ERR, "Could not find the address for AudioUnk01 function."); }*/ /*if (pCreateExportTexture) { REQUIRE(hookX64Function(pCreateExportTexture, &Detour_CreateTexture, &oCreateTexture, hkCreateExportTexture), "Failed to hook CreateExportTexture function."); }*/ /*if (pGlobalUnk01Cmd) { uint32_t offset = *(uint32_t*)((uint8_t*)pGlobalUnk01Cmd + 3); pGlobalUnk01 = (uint8_t*)pGlobalUnk01Cmd + offset + 7; LOG(LL_DBG, "pGlobalUnk01: ", pGlobalUnk01); } else { LOG(LL_ERR, "Could not find the address for global var: pGlobalUnk0"); } if (pGetVarPtrByHash) { REQUIRE(hookX64Function(pGetVarPtrByHash, &Detour_GetVarPtrByHash2, &oGetVarPtrByHash2, hkGetVarPtrByHash), "Failed to hook GetVarPtrByHash function."); } else { }*/ } catch (std::exception& ex) { LOG(LL_ERR, ex.what()); } ////0x14CC6AC; //REQUIRE(hookX64Function((BYTE*)(0x14CC6AC + (intptr_t)info.lpBaseOfDll), &Detour_GetFrameRate, &oGetFrameRate, hkGetFrameRate), "Failed to hook frame rate function."); ////0x14CC64C; //REQUIRE(hookX64Function((BYTE*)(0x14CC64C + (intptr_t)info.lpBaseOfDll), &Detour_GetAudioSamples, &oGetAudioSamples, hkGetAudioSamples), "Failed to hook audio sample function."); //0x14CBED8; //REQUIRE(hookX64Function((BYTE*)(0x14CBED8 + (intptr_t)info.lpBaseOfDll), &Detour_getFrameRateFraction, &ogetFrameRateFraction, hkGetFrameRateFraction), "Failed to hook audio sample function."); //0x87CC80; //REQUIRE(hookX64Function((BYTE*)(0x87CC80 + (intptr_t)info.lpBaseOfDll), &Detour_Unk01, &oUnk01, hkUnk01), "Failed to hook audio sample function."); //0x4BB744; //0x754884 //REQUIRE(hookX64Function((BYTE*)(0x754884 + (intptr_t)info.lpBaseOfDll), &Detour_GetTexture, &oGetTexture, hkGetTexture), "Failed to hook GetTexture function."); //0x11C4980 //REQUIRE(hookX64Function((BYTE*)(0x11C4980 + (intptr_t)info.lpBaseOfDll), &Detour_GetGlobalVariableIndex, &oGetGlobalVariableIndex, hkGetGlobalVariableIndex), "Failed to hook GetSomething function."); //0x1552198 //REQUIRE(hookX64Function((BYTE*)(0x1552198 + (intptr_t)info.lpBaseOfDll), &Detour_GetVariable, &oGetVariable, hkGetVariable), "Failed to hook GetVariable function."); //REQUIRE(hookX64Function((BYTE*)(0x15546F8 + (intptr_t)info.lpBaseOfDll), &Detour_GetVariable, &oGetVariable, hkGetVariable), "Failed to hook GetVariable function."); //11CA828 //REQUIRE(hookX64Function((BYTE*)(0x11CA828 + (intptr_t)info.lpBaseOfDll), &Detour_GetMatrices, &oGetMatrices, hkGetMatrices), "Failed to hook GetMatrices function."); //11441F4 //0x352A3C //REQUIRE(hookX64Function((BYTE*)(0x352A3C + (intptr_t)info.lpBaseOfDll), &Detour_GetVarPtrByHash, &oGetVarPtrByHash, hkGetVarPtrByHash), "Failed to hook GetVarPtrByHash function."); LOG_CALL(LL_DBG, av_register_all()); LOG_CALL(LL_DBG, avcodec_register_all()); LOG_CALL(LL_DBG, av_log_set_level(AV_LOG_TRACE)); LOG_CALL(LL_DBG, av_log_set_callback(&avlog_callback)); } catch (std::exception& ex) { // TODO cleanup POST(); throw ex; } POST(); } void ScriptMain() { PRE(); LOG(LL_NFO, "Starting main loop"); while (true) { WAIT(0); } POST(); } static HRESULT Hook_CoCreateInstance( REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv ) { PRE(); HRESULT result = oCoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv); /*if (IsEqualGUID(riid, _uuidof(IXAudio2))) { IXAudio2* pXAudio = (IXAudio2*)(*ppv); REQUIRE(hookVirtualFunction(pXAudio, 8, &CreateSourceVoice, &oCreateSourceVoice, hkCreateSourceVoice), "Failed to hook IXAudio2::CreateSourceVoice"); }*/ char buffer[64]; GUIDToString(rclsid, buffer, 64); LOG(LL_NFO, "CoCreateInstance: ", buffer); POST(); return result; } static void Hook_OMSetRenderTargets( ID3D11DeviceContext *pThis, UINT NumViews, ID3D11RenderTargetView *const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView ) { if (::exportContext) { for (uint32_t i = 0; i < NumViews; i++) { if (ppRenderTargetViews[i]) { ComPtr<ID3D11Resource> pResource; ComPtr<ID3D11Texture2D> pTexture2D; ppRenderTargetViews[i]->GetResource(pResource.GetAddressOf()); if (SUCCEEDED(pResource.As(&pTexture2D))) { if (pTexture2D.Get() == pGameDepthBufferQuarterLinear.Get()) { LOG(LL_DBG, " i:", i, " num:", NumViews, " dsv:", (void*)pDepthStencilView); pCtxLinearizeBuffer = pThis; } } } } } ComPtr<ID3D11Resource> pRTVTexture; if ((ppRenderTargetViews) && (ppRenderTargetViews[0])) { ppRenderTargetViews[0]->GetResource(pRTVTexture.GetAddressOf()); } ComPtr<ID3D11RenderTargetView> pOldRTV; ComPtr<ID3D11Resource> pOldRTVTexture; pThis->OMGetRenderTargets(1, pOldRTV.GetAddressOf(), NULL); if (pOldRTV) { pOldRTV->GetResource(pOldRTVTexture.GetAddressOf()); } if ((::exportContext != NULL) && (::exportContext->pExportRenderTarget != NULL) && (::exportContext->pExportRenderTarget == pRTVTexture)) { std::lock_guard<std::mutex> sessionLock(mxSession); if ((session != NULL) && (session->isCapturing)) { // Time to capture rendered frame try { ComPtr<ID3D11Device> pDevice; pThis->GetDevice(pDevice.GetAddressOf()); ComPtr<ID3D11Texture2D> pDepthBufferCopy = nullptr; ComPtr<ID3D11Texture2D> pBackBufferCopy = nullptr; ComPtr<ID3D11Texture2D> pStencilBufferCopy = nullptr; if (config::export_openexr) { { D3D11_TEXTURE2D_DESC desc; pLinearDepthTexture->GetDesc(&desc); desc.CPUAccessFlags = D3D11_CPU_ACCESS_FLAG::D3D11_CPU_ACCESS_READ; desc.BindFlags = 0; desc.MiscFlags = 0; desc.Usage = D3D11_USAGE::D3D11_USAGE_STAGING; REQUIRE(pDevice->CreateTexture2D(&desc, NULL, pDepthBufferCopy.GetAddressOf()), "Failed to create depth buffer copy texture"); pThis->CopyResource(pDepthBufferCopy.Get(), pLinearDepthTexture.Get()); } { D3D11_TEXTURE2D_DESC desc; pGameBackBufferResolved->GetDesc(&desc); desc.CPUAccessFlags = D3D11_CPU_ACCESS_FLAG::D3D11_CPU_ACCESS_READ; desc.BindFlags = 0; desc.MiscFlags = 0; desc.Usage = D3D11_USAGE::D3D11_USAGE_STAGING; REQUIRE(pDevice->CreateTexture2D(&desc, NULL, pBackBufferCopy.GetAddressOf()), "Failed to create back buffer copy texture"); pThis->CopyResource(pBackBufferCopy.Get(), pGameBackBufferResolved.Get()); } { D3D11_TEXTURE2D_DESC desc; pStencilTexture->GetDesc(&desc); desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.BindFlags = 0; desc.MiscFlags = 0; desc.Usage = D3D11_USAGE::D3D11_USAGE_STAGING; REQUIRE(pDevice->CreateTexture2D(&desc, NULL, pStencilBufferCopy.GetAddressOf()), "Failed to create stencil buffer copy"); //pThis->ResolveSubresource(pStencilBufferCopy.Get(), 0, pGameDepthBuffer.Get(), 0, DXGI_FORMAT::DXGI_FORMAT_R32G8X24_TYPELESS); pThis->CopyResource(pStencilBufferCopy.Get(), pGameEdgeCopy.Get()); } session->enqueueEXRImage(pThis, pBackBufferCopy, pDepthBufferCopy, pStencilBufferCopy); } LOG_CALL(LL_DBG, ::exportContext->pSwapChain->Present(0, DXGI_PRESENT_TEST)); // IMPORTANT: This call makes ENB and ReShade effects to be applied to the render target ComPtr<ID3D11Texture2D> pSwapChainBuffer; REQUIRE(::exportContext->pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)pSwapChainBuffer.GetAddressOf()), "Failed to get swap chain's buffer"); auto& image_ref = *(::exportContext->capturedImage); LOG_CALL(LL_DBG, DirectX::CaptureTexture(::exportContext->pDevice.Get(), ::exportContext->pDeviceContext.Get(), pSwapChainBuffer.Get(), image_ref)); if (::exportContext->capturedImage->GetImageCount() == 0) { LOG(LL_ERR, "There is no image to capture."); throw std::exception(); } const DirectX::Image* image = ::exportContext->capturedImage->GetImage(0, 0, 0); NOT_NULL(image, "Could not get current frame."); NOT_NULL(image->pixels, "Could not get current frame."); REQUIRE(session->enqueueVideoFrame(image->pixels, (int)(image->width * image->height * 4)), "Failed to enqueue frame"); ::exportContext->capturedImage->Release(); } catch (std::exception&) { LOG(LL_ERR, "Reading video frame from D3D Device failed."); ::exportContext->capturedImage->Release(); LOG_CALL(LL_DBG, session.reset()); LOG_CALL(LL_DBG, ::exportContext.reset()); } } } oOMSetRenderTargets(pThis, NumViews, ppRenderTargetViews, pDepthStencilView); } static HRESULT Hook_MFCreateSinkWriterFromURL( LPCWSTR pwszOutputURL, IMFByteStream *pByteStream, IMFAttributes *pAttributes, IMFSinkWriter **ppSinkWriter ) { PRE(); HRESULT result = oMFCreateSinkWriterFromURL(pwszOutputURL, pByteStream, pAttributes, ppSinkWriter); if (SUCCEEDED(result)) { try { REQUIRE(hookVirtualFunction(*ppSinkWriter, 3, &Hook_IMFSinkWriter_AddStream, &oIMFSinkWriter_AddStream, hkIMFSinkWriter_AddStream), "Failed to hook IMFSinkWriter::AddStream"); REQUIRE(hookVirtualFunction(*ppSinkWriter, 4, &IMFSinkWriter_SetInputMediaType, &oIMFSinkWriter_SetInputMediaType, hkIMFSinkWriter_SetInputMediaType), "Failed to hook IMFSinkWriter::SetInputMediaType"); REQUIRE(hookVirtualFunction(*ppSinkWriter, 6, &Hook_IMFSinkWriter_WriteSample, &oIMFSinkWriter_WriteSample, hkIMFSinkWriter_WriteSample), "Failed to hook IMFSinkWriter::WriteSample"); REQUIRE(hookVirtualFunction(*ppSinkWriter, 11, &Hook_IMFSinkWriter_Finalize, &oIMFSinkWriter_Finalize, hkIMFSinkWriter_Finalize), "Failed to hook IMFSinkWriter::Finalize"); } catch (...) { LOG(LL_ERR, "Hooking IMFSinkWriter functions failed"); } } POST(); return result; } static HRESULT Hook_IMFSinkWriter_AddStream( IMFSinkWriter *pThis, IMFMediaType *pTargetMediaType, DWORD *pdwStreamIndex ) { PRE(); LOG(LL_NFO, "IMFSinkWriter::AddStream: ", GetMediaTypeDescription(pTargetMediaType).c_str()); POST(); return oIMFSinkWriter_AddStream(pThis, pTargetMediaType, pdwStreamIndex); } static HRESULT IMFSinkWriter_SetInputMediaType( IMFSinkWriter *pThis, DWORD dwStreamIndex, IMFMediaType *pInputMediaType, IMFAttributes *pEncodingParameters ) { PRE(); LOG(LL_NFO, "IMFSinkWriter::SetInputMediaType: ", GetMediaTypeDescription(pInputMediaType).c_str()); GUID majorType; if (SUCCEEDED(pInputMediaType->GetMajorType(&majorType))) { if (IsEqualGUID(majorType, MFMediaType_Video)) { ::exportContext->videoMediaType = pInputMediaType; } else if (IsEqualGUID(majorType, MFMediaType_Audio)) { try { std::lock_guard<std::mutex> sessionLock(mxSession); UINT width, height, fps_num, fps_den; MFGetAttribute2UINT32asUINT64(::exportContext->videoMediaType.Get(), MF_MT_FRAME_SIZE, &width, &height); MFGetAttributeRatio(::exportContext->videoMediaType.Get(), MF_MT_FRAME_RATE, &fps_num, &fps_den); GUID pixelFormat; ::exportContext->videoMediaType->GetGUID(MF_MT_SUBTYPE, &pixelFormat); DXGI_SWAP_CHAIN_DESC desc; ::exportContext->pSwapChain->GetDesc(&desc); if (isCustomFrameRateSupported) { auto fps = config::fps; fps_num = fps.first; fps_den = fps.second; float gameFrameRate = ((float)fps.first * ((float)config::motion_blur_samples + 1) / (float)fps.second); if ( gameFrameRate > 60.0f) { LOG(LL_NON, "fps * (motion_blur_samples + 1) > 60.0!!!"); LOG(LL_NON, "Audio export will be disabled!!!"); //::exportContext->audioSkip = gameFrameRate / 60; //::exportContext->audioSkipCounter = ::exportContext->audioSkip; ::exportContext->isAudioExportDisabled = true; } } //REQUIRE(session->createVideoContext(desc.BufferDesc.Width, desc.BufferDesc.Height, "bgra", fps_num, fps_den, config::motion_blur_samples, config::video_fmt, config::video_enc, config::video_cfg), "Failed to create video context"); UINT32 blockAlignment, numChannels, sampleRate, bitsPerSample; GUID subType; pInputMediaType->GetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, &blockAlignment); pInputMediaType->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &numChannels); pInputMediaType->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &sampleRate); pInputMediaType->GetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, &bitsPerSample); pInputMediaType->GetGUID(MF_MT_SUBTYPE, &subType); /*if (IsEqualGUID(subType, MFAudioFormat_PCM)) { REQUIRE(session->createAudioContext(numChannels, sampleRate, bitsPerSample, "s16", blockAlignment, config::audio_fmt, config::audio_enc, config::audio_cfg), "Failed to create audio context."); } else { char buffer[64]; GUIDToString(subType, buffer, 64); LOG(LL_ERR, "Unsupported input audio format: ", buffer); throw std::runtime_error("Unsupported input audio format"); }*/ char buffer[128]; std::string output_file = config::output_dir; std::string exrOutputPath; output_file += "\\EVE-"; time_t rawtime; struct tm timeinfo; time(&rawtime); localtime_s(&timeinfo, &rawtime); strftime(buffer, 128, "%Y%m%d%H%M%S", &timeinfo); output_file += buffer; exrOutputPath = std::regex_replace(output_file, std::regex("\\\\+"), "\\"); output_file += "." + config::format_ext; std::string filename = std::regex_replace(output_file, std::regex("\\\\+"), "\\"); LOG(LL_NFO, "Output file: ", filename); REQUIRE(session->createContext(config::container_format, filename.c_str(), exrOutputPath, config::format_cfg, desc.BufferDesc.Width, desc.BufferDesc.Height, "bgra", fps_num, fps_den, config::motion_blur_samples, 1 - config::motion_blur_strength, config::video_fmt, config::video_enc, config::video_cfg, numChannels, sampleRate, bitsPerSample, "s16", blockAlignment, config::audio_fmt, config::audio_enc, config::audio_cfg), "Failed to create encoding context."); } catch (std::exception& ex) { LOG(LL_ERR, ex.what()); LOG_CALL(LL_DBG, session.reset()); LOG_CALL(LL_DBG, ::exportContext.reset()); } } } POST(); return oIMFSinkWriter_SetInputMediaType(pThis, dwStreamIndex, pInputMediaType, pEncodingParameters); } static HRESULT Hook_IMFSinkWriter_WriteSample( IMFSinkWriter *pThis, DWORD dwStreamIndex, IMFSample *pSample ) { std::lock_guard<std::mutex> sessionLock(mxSession); if ((session != NULL) && (dwStreamIndex == 1) && (!::exportContext->isAudioExportDisabled)) { ComPtr<IMFMediaBuffer> pBuffer = NULL; try { LONGLONG sampleTime; pSample->GetSampleTime(&sampleTime); pSample->ConvertToContiguousBuffer(pBuffer.GetAddressOf()); DWORD length; pBuffer->GetCurrentLength(&length); BYTE *buffer; if (SUCCEEDED(pBuffer->Lock(&buffer, NULL, NULL))) { LOG_CALL(LL_DBG, session->writeAudioFrame(buffer, length, sampleTime)); } } catch (std::exception& ex) { LOG(LL_ERR, ex.what()); LOG_CALL(LL_DBG, session.reset()); LOG_CALL(LL_DBG, ::exportContext.reset()); if (pBuffer != NULL) { pBuffer->Unlock(); } } } /*if (!session) { return E_FAIL; }*/ return S_OK; } static HRESULT Hook_IMFSinkWriter_Finalize( IMFSinkWriter *pThis ) { PRE(); std::lock_guard<std::mutex> sessionLock(mxSession); try { if (session != NULL) { LOG_CALL(LL_DBG, session->finishAudio()); LOG_CALL(LL_DBG, session->finishVideo()); LOG_CALL(LL_DBG, session->endSession()); } } catch (std::exception& ex) { LOG(LL_ERR, ex.what()); } LOG_CALL(LL_DBG, session.reset()); LOG_CALL(LL_DBG, ::exportContext.reset()); POST(); return S_OK; } void finalize() { PRE(); hkCoCreateInstance->UnHook(); hkMFCreateSinkWriterFromURL->UnHook(); hkIMFSinkWriter_AddStream->UnHook(); hkIMFSinkWriter_SetInputMediaType->UnHook(); hkIMFSinkWriter_WriteSample->UnHook(); hkIMFSinkWriter_Finalize->UnHook(); POST(); } static void Draw( ID3D11DeviceContext *pThis, UINT VertexCount, UINT StartVertexLocation ) { oDraw(pThis, VertexCount, StartVertexLocation); if (pCtxLinearizeBuffer == pThis) { pCtxLinearizeBuffer = nullptr; ComPtr<ID3D11Device> pDevice; pThis->GetDevice(pDevice.GetAddressOf()); ComPtr<ID3D11RenderTargetView> pCurrentRTV; LOG_CALL(LL_DBG, pThis->OMGetRenderTargets(1, pCurrentRTV.GetAddressOf(), NULL)); D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; pCurrentRTV->GetDesc(&rtvDesc); LOG_CALL(LL_DBG, pDevice->CreateRenderTargetView(pLinearDepthTexture.Get(), &rtvDesc, pCurrentRTV.ReleaseAndGetAddressOf())); LOG_CALL(LL_DBG, pThis->OMSetRenderTargets(1, pCurrentRTV.GetAddressOf(), NULL)); D3D11_TEXTURE2D_DESC ldtDesc; pLinearDepthTexture->GetDesc(&ldtDesc); D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>(ldtDesc.Width); viewport.Height = static_cast<float>(ldtDesc.Height); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.MinDepth = 0; viewport.MaxDepth = 1; pThis->RSSetViewports(1, &viewport); D3D11_RECT rect; rect.left = rect.top = 0; rect.right = ldtDesc.Width; rect.bottom = ldtDesc.Height; pThis->RSSetScissorRects(1, &rect); LOG_CALL(LL_TRC, oDraw(pThis, VertexCount, StartVertexLocation)); } } //static void Detour_StepAudio(void* rcx) { // if (::exportContext) { // ::exportContext->audioSkipCounter += 1.0f; // if (::exportContext->audioSkipCounter >= ::exportContext->audioSkip) { // oStepAudio(rcx); // } // while (::exportContext->audioSkipCounter >= ::exportContext->audioSkip) { // ::exportContext->audioSkipCounter -= ::exportContext->audioSkip; // } // } else { // oStepAudio(rcx); // } // static int x = 0; // if (x == 0) { // } // x = ++x % 2; //} static HANDLE Detour_CreateThread(void* pFunc, void* pParams, int32_t r8d, int32_t r9d, void* rsp20, int32_t rsp28, char* name) { void* result = oCreateThread(pFunc, pParams, r8d, r9d, rsp20, rsp28, name); LOG(LL_TRC, "CreateThread:", " pFunc:", pFunc, " pParams:", pParams, " r8d:", Logger::hex(r8d, 4), " r9d:", Logger::hex(r9d, 4), " rsp20:", rsp20, " rsp28:", rsp28, " name:", name ? name : "<NULL>"); //if (name) { // if (std::string("RageAudioMixThread").compare(name) == 0) { // threadIdRageAudioMixThread = ::GetThreadId(result); // } //} return result; } //static float Detour_GetGameSpeedMultiplier(void* rcx) { // float result = oGetGameSpeedMultiplier(rcx); // //if (exportContext) { // std::pair<int32_t, int32_t> fps = config::fps; // result = 60.0f * (float)fps.second / ((float)fps.first * ((float)config::motion_blur_samples + 1)); // //} // return result; //} static float Detour_GetRenderTimeBase(int64_t choice) { std::pair<int32_t, int32_t> fps = config::fps; float result = 1000.0f * (float)fps.second / ((float)fps.first * ((float)config::motion_blur_samples + 1)); //float result = 1000.0f / 60.0f; LOG(LL_NFO, "Time step: ", result); return result; } //static void Detour_WaitForSingleObject(void* rcx, int32_t edx) { // oWaitForSingleObject(rcx, edx); // while (threadIdRageAudioMixThread && (threadIdRageAudioMixThread == ::GetCurrentThreadId())) { // static int x = 3; // x++; // x %= 4; // ReleaseSemaphore(rcx, 1, NULL); // oWaitForSingleObject(rcx, edx); // if (x == 0) { // break; // } // Sleep(0); // } //} //static uint8_t Detour_AudioUnk01(void* rcx) { // return 1; //} static void* Detour_CreateTexture(void* rcx, char* name, uint32_t r8d, uint32_t width, uint32_t height, uint32_t format, void* rsp30) { void* result = oCreateTexture(rcx, name, r8d, width, height, format, rsp30); void** vresult = (void**)result; ComPtr<ID3D11Texture2D> pTexture; DXGI_FORMAT fmt = DXGI_FORMAT::DXGI_FORMAT_UNKNOWN; if ((name != NULL) && (result != NULL)) { IUnknown* pUnknown = (IUnknown*)(*(vresult + 7)); if (pUnknown && SUCCEEDED(pUnknown->QueryInterface(pTexture.GetAddressOf()))) { D3D11_TEXTURE2D_DESC desc; pTexture->GetDesc(&desc); fmt = desc.Format; } } LOG(LL_TRC, "CreateTexture:", " rcx:", rcx, " name:", name ? name : "<NULL>", " r8d:", Logger::hex(r8d, 8), " width:", width, " height:", height, " fmt:", conv_dxgi_format_to_string(fmt), " result:", result, " *r+0:", vresult ? *(vresult + 0) : "<NULL>", " *r+1:", vresult ? *(vresult + 1) : "<NULL>", " *r+2:", vresult ? *(vresult + 2) : "<NULL>", " *r+3:", vresult ? *(vresult + 3) : "<NULL>", " *r+4:", vresult ? *(vresult + 4) : "<NULL>", " *r+5:", vresult ? *(vresult + 5) : "<NULL>", " *r+6:", vresult ? *(vresult + 6) : "<NULL>", " *r+7:", vresult ? *(vresult + 7) : "<NULL>", " *r+8:", vresult ? *(vresult + 8) : "<NULL>", " *r+9:", vresult ? *(vresult + 9) : "<NULL>", " *r+10:", vresult ? *(vresult + 10) : "<NULL>", " *r+11:", vresult ? *(vresult + 11) : "<NULL>", " *r+12:", vresult ? *(vresult + 12) : "<NULL>", " *r+13:", vresult ? *(vresult + 13) : "<NULL>", " *r+14:", vresult ? *(vresult + 14) : "<NULL>", " *r+15:", vresult ? *(vresult + 15) : "<NULL>"); if (pTexture) { ComPtr<ID3D11Device> pDevice; pTexture->GetDevice(pDevice.GetAddressOf()); if ((std::string("DepthBuffer_Resolved").compare(name) == 0) || (std::string("DepthBufferCopy").compare(name) == 0)) { pGameDepthBufferResolved = pTexture; } else if (std::string("DepthBuffer").compare(name) == 0) { pGameDepthBuffer = pTexture; } else if (std::string("Depth Quarter").compare(name) == 0) { pGameDepthBufferQuarter = pTexture; } else if (std::string("GBUFFER_0").compare(name) == 0) { pGameGBuffer0 = pTexture; } else if (std::string("Edge Copy").compare(name) == 0) { pGameEdgeCopy = pTexture; D3D11_TEXTURE2D_DESC desc; pTexture->GetDesc(&desc); pDevice->CreateTexture2D(&desc, NULL, pStencilTexture.GetAddressOf()); } else if (std::string("Depth Quarter Linear").compare(name) == 0) { pGameDepthBufferQuarterLinear = pTexture; D3D11_TEXTURE2D_DESC desc, resolvedDesc; if (!pGameDepthBufferResolved) { pGameDepthBufferResolved = pGameDepthBuffer; } pGameDepthBufferResolved->GetDesc(&resolvedDesc); resolvedDesc.ArraySize = 1; resolvedDesc.SampleDesc.Count = 1; resolvedDesc.SampleDesc.Quality = 0; pGameDepthBufferQuarterLinear->GetDesc(&desc); desc.Width = resolvedDesc.Width; desc.Height = resolvedDesc.Height; desc.BindFlags = D3D11_BIND_RENDER_TARGET; desc.Usage = D3D11_USAGE_DEFAULT; desc.CPUAccessFlags = 0; LOG_CALL(LL_DBG, pDevice->CreateTexture2D(&desc, NULL, pLinearDepthTexture.GetAddressOf())); } else if (std::string("BackBuffer").compare(name) == 0) { pGameBackBufferResolved = nullptr; pGameDepthBuffer = nullptr; pGameDepthBufferQuarter = nullptr; pGameDepthBufferQuarterLinear = nullptr; pGameDepthBufferResolved = nullptr; pGameEdgeCopy = nullptr; pGameGBuffer0 = nullptr; pGameBackBuffer = pTexture; } else if ((std::string("BackBuffer_Resolved").compare(name) == 0) || (std::string("BackBufferCopy").compare(name) == 0)) { pGameBackBufferResolved = pTexture; } else if (std::string("VideoEncode").compare(name) == 0) { ComPtr<ID3D11Texture2D> pExportTexture; pExportTexture = pTexture; D3D11_TEXTURE2D_DESC desc; pExportTexture->GetDesc(&desc); LOG(LL_NFO, "Detour_CreateTexture: fmt:", conv_dxgi_format_to_string(desc.Format), " w:", desc.Width, " h:", desc.Height); std::lock_guard<std::mutex> sessionLock(mxSession); LOG_CALL(LL_DBG, ::exportContext.reset()); LOG_CALL(LL_DBG, session.reset()); try { LOG(LL_NFO, "Creating session..."); if (config::auto_reload_config) { LOG_CALL(LL_DBG, config::reload()); } session.reset(new Encoder::Session()); NOT_NULL(session, "Could not create the session"); ::exportContext.reset(new ExportContext()); NOT_NULL(::exportContext, "Could not create export context"); ::exportContext->pSwapChain = mainSwapChain; ::exportContext->pExportRenderTarget = pExportTexture; pExportTexture->GetDevice(::exportContext->pDevice.GetAddressOf()); ::exportContext->pDevice->GetImmediateContext(::exportContext->pDeviceContext.GetAddressOf()); } catch (std::exception& ex) { LOG(LL_ERR, ex.what()); LOG_CALL(LL_DBG, session.reset()); LOG_CALL(LL_DBG, ::exportContext.reset()); } //} } } return result; }
// Copyright (c) 2021 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GCPnts_TCurveTypes_HeaderFile #define _GCPnts_TCurveTypes_HeaderFile #include <Adaptor2d_Curve2d.hxx> #include <Adaptor3d_Curve.hxx> #include <Geom_BezierCurve.hxx> #include <Geom_BSplineCurve.hxx> #include <Geom2d_BezierCurve.hxx> #include <Geom2d_BSplineCurve.hxx> #include <GCPnts_DistFunction.hxx> #include <GCPnts_DistFunction2d.hxx> //! Auxiliary tool to resolve 2D/3D curve classes. template<class TheCurve> struct GCPnts_TCurveTypes {}; //! Auxiliary tool to resolve 3D curve classes. template<> struct GCPnts_TCurveTypes<Adaptor3d_Curve> { typedef gp_Pnt Point; typedef Geom_BezierCurve BezierCurve; typedef Geom_BSplineCurve BSplineCurve; typedef GCPnts_DistFunction DistFunction; typedef GCPnts_DistFunctionMV DistFunctionMV; }; //! Auxiliary tool to resolve 2D curve classes. template<> struct GCPnts_TCurveTypes<Adaptor2d_Curve2d> { typedef gp_Pnt2d Point; typedef Geom2d_BezierCurve BezierCurve; typedef Geom2d_BSplineCurve BSplineCurve; typedef GCPnts_DistFunction2d DistFunction; typedef GCPnts_DistFunction2dMV DistFunctionMV; }; #endif // _GCPnts_TCurveTypes_HeaderFile
/** \file Sonar.hpp \author UnBeatables \date LARC2018 \name Sonar */ #pragma once #include <alproxies/almemoryproxy.h> #include <alproxies/alsonarproxy.h> #include <string> namespace SonarData { enum{ NONE = 0, LEFT, MIDDLE, RIGHT }; } /** \brief This class is responsable for interpreting the data received from the sonar sensors and writing it on UnBoard. */ class SonarClass { private: AL::ALMemoryProxy *memory; AL::ALSonarProxy *sonar; int sizeSonarLeft, sizeSonarRight, sizePos, Pos; float sonarAverageLeft, sonarAverageRight; int sonarAverageOut; float left, right; public: /** \brief Class constructor. \details Inicialize class parameters. \param naoIP */ SonarClass(std::string naoIP); /** \brief Class destructor. */ ~SonarClass(); /** \brief This function writes the data interpreted by getSonar on UnBoard \param _ub void pointer for UnBoard. */ void writeFunction(void*); /** \brief This function interprets the data received from sonar sensor and determines if there is presence detected in the left, right, front or if there is no presence. \param _ub void pointer for UnBoard. */ void getSonar(void*); };
#pragma once #include "rule.h" #include "../physicpoint.h" namespace sbg { template<int n> struct Gravity : Rule<n> { Gravity(const Vector<n, double> value = Vector<n, double>()); Vector<n, double> getResult(const PhysicPoint<n>& object) const override; Gravity<n>* clone() const override; Vector<n, double> getValue() const; void setValue(const Vector<n, double> value); private: Vector<n, double> _value; }; extern template struct Gravity<2>; extern template struct Gravity<3>; using Gravity2D = Gravity<2>; using Gravity3D = Gravity<3>; }
#include <Stage.h> #include <iostream> using namespace std; Stage* Stage::uniqueStage = NULL; Stage::Stage(RenderController* renderController) :RenderColleague(renderController) { this->initGLSLPrograms(); //-- Init local structures this->projection = new Projection(); //-- Initialize default values this->selectedModel = new float; *(this->selectedModel) = -1.0f; this->selectedLight = new float; *(this->selectedLight) = -1.0f; displayType = new int; *(displayType) = 0; //-- Models Loading vector<Routes*> modelsRoutes; vector<Transformation*> modelsTransform; modelsRoutes.push_back(new Routes( /*RAW File*/ "../models/8b/foot_8_256_256_256.raw", /*Width*/ 256, /*Height*/ 256, /*Depth*/ 256, /*Bytes*/ 1 )); modelsTransform.push_back(new Transformation( /*Scale*/ 1.0f, /*Position*/ glm::vec3(0.0f, 0.0f, 0.0f), /*Angle*/ 0.0f, /*Rot Direction*/ glm::vec3(0.0f, 1.0f, 0.0f) )); //-- Init Render Facade this->renderFacade = new RenderFacade(); this->renderFacade->initModelEntities(modelsRoutes, modelsTransform); //-- Initializing Player this->camera = new Camera(this->renderFacade->getModel(0)->getTransformation()); //-- Bindind data to render facade this->renderFacade->bindShaderPrograms(this->illuminationPrograms); this->renderFacade->bindCamera(this->camera); this->renderFacade->bindProjection(this->projection); } Stage::~Stage() { this->camera->~Camera(); this->projection->~Projection(); } void Stage::frontRender(){ //-- Move Camera if (!this->renderFacade->ttfClicked()) this->camera->move(); //-- Display if (*(displayType) == 0) this->renderFacade->render2DImageBased("2DTextureRender_Init", "2DTextureRender_a", "2DTextureRender", "2DTextureRender_Test"); else if (*(displayType) == 2) this->renderFacade->renderRayCasting("RayCasting_BackFace", "RayCasting"); this->renderFacade->renderTTF(); } void Stage::initGLSLPrograms(){ //-- Graphic Card Info GLint texture_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texture_size); std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "Max Texture Size: " << texture_size << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; //-- Structure to initialize this->illuminationPrograms = new map<string, CGLSLProgram*>(); vector< map<string, string>* > *routes = new vector< map<string, string>* >({ //-- For 2D Axis Aligned new map<string, string>( { { "name", "2DTextureRender_a" }, { "vertex", "../src/shaders/2DTextureRender_a.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/2DTextureRender_a.frag" } }), new map<string, string>( { { "name", "2DTextureRender" }, { "vertex", "../src/shaders/2DTextureRender.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/2DTextureRender.frag" } }), new map<string, string>( { { "name", "2DTextureRender_Init" }, { "vertex", "../src/shaders/2DTextureRender_Init.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/2DTextureRender_Init.frag" } }), new map<string, string>( { { "name", "2DTextureRender_Test" }, { "vertex", "../src/shaders/flat.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/flat.frag" } }), //-- For 3D Viewport Aligned new map<string, string>( { { "name", "3DTextureRender" }, { "vertex", "../src/shaders/3DTextureRender.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/3DTextureRender.frag" } }), //-- For RayCasting new map<string, string>( { { "name", "RayCasting_BackFace" }, { "vertex", "../src/shaders/backface.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/backface.frag" } }), new map<string, string>( { { "name", "RayCasting" }, { "vertex", "../src/shaders/raycasting.vert" }, { "geometry", "" }, { "fragment", "../src/shaders/raycasting.frag" } }) }); //-- Initialize Shader Programs std::vector< map<string, string>* >::iterator programRoute; for (programRoute = routes->begin(); programRoute != routes->end(); programRoute++){ std::cout << "\nLoading " << (*programRoute)->at("name") << " shading program...\n"; this->illuminationPrograms->insert_or_assign( (*programRoute)->at("name"), new CGLSLProgram() ); this->illuminationPrograms->at( (*programRoute)->at("name") )->loadShader( (*programRoute)->at("vertex"), CGLSLProgram::VERTEX ); //-- Loading Geometry shader if its possible if ((*programRoute)->at("geometry") != "") { this->illuminationPrograms->at((*programRoute)->at("name"))->loadShader( (*programRoute)->at("geometry"), CGLSLProgram::GEOMETRY ); } this->illuminationPrograms->at((*programRoute)->at("name"))->loadShader( (*programRoute)->at("fragment"), CGLSLProgram::FRAGMENT ); this->illuminationPrograms->at((*programRoute)->at("name"))->create_link(); } } Stage * Stage::Instance(RenderController * renderController) { if (!uniqueStage) uniqueStage = new Stage(renderController); return uniqueStage; } void Stage::Destroy() { if (!uniqueStage) return; uniqueStage->~Stage(); } Projection * Stage::getProjection() { return this->projection; } Model * Stage::getSelectedModel(){ return this->renderFacade->getModel(unsigned int(*(this->selectedModel))); } float * Stage::getSelectedModelIndex(){ return this->selectedModel; } float * Stage::getSelectedLightIndex(){ return this->selectedLight; } void Stage::Notify(string message, void* data) { /* if (message == "initVBOs()") this->renderFacade->initVBOs();*/ /*else*/ if (message == "width/height") { this->width = ((float*)data)[0]; this->height = ((float*)data)[1]; } else if (message == "initSideBar()") { this->Send("MainObject", (void*)this->renderFacade->getModel(0)); this->Send("tffColor->SideBar", (void*)this->renderFacade->getTff()->getColor()); } //-- Managing Events else if (message == "eventScroll") this->camera->calculateZoom( *((int*)data) ); else if (message == "mouseButton") { if (this->renderFacade->ttfClicked()) return; if (((int*)data)[0] == GLFW_MOUSE_BUTTON_LEFT && ((int*)data)[1] == GLFW_PRESS && !this->clicked) { //-- Save first click this->clicked = true; this->xPos = ((int*)data)[2]; this->yPos = ((int*)data)[3]; this->xPosFirst = this->xPos; this->yPosFirst = this->yPos; this->camera->calculatePitch(this->yPos); this->camera->calculateAngleAroundPlayer(this->xPos); } else if (((int*)data)[0] == GLFW_MOUSE_BUTTON_LEFT && ((int*)data)[1] == GLFW_PRESS) { //-- Updating click values this->xPos = this->xPosFirst - ((int*)data)[2]; this->yPos = this->yPosFirst - ((int*)data)[3]; this->camera->calculatePitch(this->yPos); this->camera->calculateAngleAroundPlayer(this->xPos); } else if (((int*)data)[0] == GLFW_MOUSE_BUTTON_LEFT && ((int*)data)[1] == GLFW_RELEASE) { //-- Key released this->clicked = false; } } else if (message == "RenderType") { this->displayType = (int*)data; } } void Stage::render() { this->frontRender(); }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/web_applications/bookmark_apps/system_web_app_manager.h" #include <memory> #include <utility> #include <vector> #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/web_applications/components/pending_app_manager.h" #include "chrome/browser/web_applications/components/test_pending_app_manager.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/extensions/web_app_extension_ids_map.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/crx_file/id_util.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension_builder.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace web_app { namespace { const char kWindowedUrl[] = "https://windowed.example"; const char kTabbedUrl[] = "https://tabbed.example"; const char kDefaultContainerUrl[] = "https://default-container.example"; PendingAppManager::AppInfo GetWindowedAppInfo() { return PendingAppManager::AppInfo( GURL(kWindowedUrl), LaunchContainer::kWindow, InstallSource::kSystemInstalled, false /* create_shortcuts */); } PendingAppManager::AppInfo GetTabbedAppInfo() { return PendingAppManager::AppInfo(GURL(kTabbedUrl), LaunchContainer::kTab, InstallSource::kSystemInstalled, false /* create_shortcuts */); } } // namespace class TestSystemWebAppManager : public SystemWebAppManager { public: TestSystemWebAppManager(Profile* profile, PendingAppManager* pending_app_manager, std::vector<PendingAppManager::AppInfo> system_apps) : SystemWebAppManager(profile, pending_app_manager), system_apps_(std::move(system_apps)) {} ~TestSystemWebAppManager() override {} std::vector<PendingAppManager::AppInfo> CreateSystemWebApps() override { return std::move(system_apps_); } private: std::vector<PendingAppManager::AppInfo> system_apps_; DISALLOW_COPY_AND_ASSIGN(TestSystemWebAppManager); }; class SystemWebAppManagerTest : public ChromeRenderViewHostTestHarness { public: SystemWebAppManagerTest() = default; ~SystemWebAppManagerTest() override = default; void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); scoped_feature_list_.InitWithFeatures({features::kSystemWebApps}, {}); // Reset WebAppProvider so that its SystemWebAppManager doesn't interfere // with tests. WebAppProvider::Get(profile())->Reset(); } void SimulatePreviouslyInstalledApp( TestPendingAppManager* pending_app_manager, GURL url, InstallSource install_source) { std::string id = crx_file::id_util::GenerateId("fake_app_id_for:" + url.spec()); extensions::ExtensionRegistry::Get(profile())->AddEnabled( extensions::ExtensionBuilder("Dummy Name").SetID(id).Build()); ExtensionIdsMap extension_ids_map(profile()->GetPrefs()); extension_ids_map.Insert(url, id, install_source); pending_app_manager->SimulatePreviouslyInstalledApp(url, install_source); } private: base::test::ScopedFeatureList scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(SystemWebAppManagerTest); }; // Test that System Apps are uninstalled with the feature disabled. TEST_F(SystemWebAppManagerTest, Disabled) { base::test::ScopedFeatureList disable_feature_list; disable_feature_list.InitWithFeatures({}, {features::kSystemWebApps}); auto pending_app_manager = std::make_unique<TestPendingAppManager>(); SimulatePreviouslyInstalledApp(pending_app_manager.get(), GURL(kWindowedUrl), InstallSource::kSystemInstalled); std::vector<PendingAppManager::AppInfo> system_apps; system_apps.push_back(GetWindowedAppInfo()); TestSystemWebAppManager system_web_app_manager( profile(), pending_app_manager.get(), std::move(system_apps)); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(pending_app_manager->install_requests().empty()); // We should try to uninstall the app that is no longer in the System App // list. EXPECT_EQ(std::vector<GURL>({GURL(kWindowedUrl)}), pending_app_manager->uninstall_requests()); } // Test that System Apps do install with the feature enabled. TEST_F(SystemWebAppManagerTest, Enabled) { auto pending_app_manager = std::make_unique<TestPendingAppManager>(); std::vector<PendingAppManager::AppInfo> system_apps; system_apps.push_back(GetWindowedAppInfo()); system_apps.push_back(GetTabbedAppInfo()); TestSystemWebAppManager system_web_app_manager( profile(), pending_app_manager.get(), std::move(system_apps)); base::RunLoop().RunUntilIdle(); const auto& apps_to_install = pending_app_manager->install_requests(); EXPECT_FALSE(apps_to_install.empty()); } // Test that changing the set of System Apps uninstalls apps. TEST_F(SystemWebAppManagerTest, UninstallAppInstalledInPreviousSession) { auto pending_app_manager = std::make_unique<TestPendingAppManager>(); // Simulate System Apps and a regular app that were installed in the // previous session. SimulatePreviouslyInstalledApp(pending_app_manager.get(), GURL(kWindowedUrl), InstallSource::kSystemInstalled); SimulatePreviouslyInstalledApp(pending_app_manager.get(), GURL(kTabbedUrl), InstallSource::kSystemInstalled); SimulatePreviouslyInstalledApp(pending_app_manager.get(), GURL(kDefaultContainerUrl), InstallSource::kInternal); std::vector<PendingAppManager::AppInfo> system_apps; system_apps.push_back(GetWindowedAppInfo()); TestSystemWebAppManager system_web_app_manager( profile(), pending_app_manager.get(), std::move(system_apps)); base::RunLoop().RunUntilIdle(); // We should only try to install the app in the System App list. std::vector<PendingAppManager::AppInfo> expected_apps_to_install; expected_apps_to_install.push_back(GetWindowedAppInfo()); EXPECT_EQ(pending_app_manager->install_requests(), expected_apps_to_install); // We should try to uninstall the app that is no longer in the System App // list. EXPECT_EQ(std::vector<GURL>({GURL(kTabbedUrl)}), pending_app_manager->uninstall_requests()); } } // namespace web_app
#include <iostream> using namespace std; int main() { string sirch = "hello world"; cout<<sirch<<endl; string adresa = "home\\git_workspaces\\cp\\ex04"; cout<<adresa<<endl; string blank = " "; cout<<blank; return 0; }
#include <iostream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <set> #include <cstdio> #include <cstdlib> using namespace std; vector<string> values; bool checkPassport(const string& s){ set<string> fields({"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"});//, "cid"}); set<string> inFields; stringstream ss(s); string key_value; // cout << s << "\n\t | "; while(!ss.eof()){ ss >> key_value; size_t pos = key_value.find(':'); if(pos != string::npos){ string key = key_value.substr(0, pos); // cout << key << " "; inFields.insert(key); string value = key_value.substr(pos+1, key_value.length()-(pos+1)); if(!key.compare("byr")){ values[0] = value; } else if(!key.compare("iyr")){ values[1] = value; } else if(!key.compare("eyr")){ values[2] = value; } else if(!key.compare("hgt")){ values[3] = value; } else if(!key.compare("hcl")){ values[4] = value; } else if(!key.compare("ecl")){ values[5] = value; } else if(!key.compare("pid")){ values[6] = value; } } } bool ret = includes(inFields.begin(), inFields.end(), fields.begin(), fields.end()); // cout << " | " << ret << endl; return ret; } bool validatePassport(){ int byr = atoi(values[0].c_str()); if(!(1920 <= byr && byr <= 2002)){ // cout << "0" << endl; return false; } int iyr = atoi(values[1].c_str()); if(!(2010 <= iyr && iyr <= 2020)){ // cout << "1" << endl; return false; } int eyr = atoi(values[2].c_str()); if(!(2020 <= eyr && eyr <= 2030)){ // cout << "2" << endl; return false; } //int hgt = atoi(values[3]); stringstream ss(values[3]); string str; int hgt; ss >> hgt >> str; if(!str.compare("cm")){ if(!(150 <= hgt && hgt <= 193)){ // cout << "3a" << endl; return false; } } else if(!str.compare("in")){ if(!(59 <= hgt && hgt <= 76)){ // cout << "eb" << endl; return false; } } else { // cout << "3c" << endl; return false; } if(values[4].length() != 7 || values[4][0] != '#'){ // cout << "4a" << endl; return false; } for(int i = 1; i < values[4].length(); i++){ if(!(('0' <= values[4][i] && values[4][i] <= '9') || ('a' <= values[4][i] && values[4][i] <= 'f'))){ // cout << "4b" << endl; return false; } } string hairs[] = {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"}; bool match = false; for(int i = 0; i < 7; i++){ if(!values[5].compare(hairs[i])){ // cout << "5" << endl; match = true; break; } } if(!match){ return false; } if(values[6].length() != 9){ // cout << "6a" << endl; return false; } for(int i = 0; i < values[6].length(); i++){ if(!('0' <= values[6][i] && values[6][i] <= '9')){ // cout << "6b" << endl; return false; } } return true; } int main(){ values.resize(7); string input, line; while (getline(cin, line)) { input += line + '\n'; } //cout << input << endl; int iter = 0; int count = 0; bool lastPassport = false; for(size_t pos = 0, prev_pos = 0; true; ){ pos = input.find("\n\n", prev_pos); if (pos == string::npos){ if(prev_pos < input.length()-1){ lastPassport = true; pos = input.length()-1; } else { break; } } //cout << "=========================\n"; string s = input.substr(prev_pos, pos-prev_pos); //cout << s << endl; //cout << "=========================\n"; prev_pos = pos + 2; iter++; if(checkPassport(s) && validatePassport()){ count++; } if(lastPassport){ break; } } cout << count << endl; return 0; }
const byte pwm_left = 6; const byte pwm_right = 5; void setup() { // put your setup code here, to run once: pinMode(31,OUTPUT); //IN1 from motor driver to 28th pin of arduino mega pinMode(33,OUTPUT); //IN2 from motor driver to 30th pin of arduino mega pinMode(35,OUTPUT); //IN3 from motor driver to 32nd pin of arduino mega pinMode(37,OUTPUT); //IN4 from motor driver to 34th pin of arduino mega Serial.begin(9600); digitalWrite(31,LOW); //right motor digitalWrite(33,HIGH); //right motor digitalWrite(35,HIGH); // left motor digitalWrite(37,LOW); //left motor } void loop() { // put your main code here, to run repeatedly: analogWrite(pwm_left,0); analogWrite(pwm_right,200); delay(7530); analogWrite(pwm_left,200); analogWrite(pwm_right,200); delay(2150); analogWrite(pwm_left,0); analogWrite(pwm_right,200); delay(8640); analogWrite(pwm_left,200); analogWrite(pwm_right,200); delay(2000); analogWrite(pwm_left,0); analogWrite(pwm_right,200); delay(8620); analogWrite(pwm_left,200); analogWrite(pwm_right,200); delay(3010); analogWrite(pwm_left,0); analogWrite(pwm_right,200); delay(8060); analogWrite(pwm_left,200); analogWrite(pwm_right,200); delay(1960); }
// Wrapper class for infrared sensor. // The greater the distance value, the closer an object is to the sensor. // 1cm is equal to about 15 sensor units. class IRSensor { private: int Pin; const int MIN_DISTANCE = 200; const int MAX_DISTANCE = 300; public: void Init(int pin) { Pin = pin; } bool BallIsDetected() { int currentDistance = GetDistance(); // if the current distance is outside the range if((currentDistance < MIN_DISTANCE) or (currentDistance > MAX_DISTANCE)) { return false; } else { return true; } } int GetDistance() { int currentDistance = analogRead(Pin); return currentDistance; } void PrintDistance() { Serial.print("Current Distance: "); Serial.println(GetDistance()); } };
template<int maxv> struct BridgesFinder { typedef UnweighedGraph<maxv, false> Graph; BridgesFinder(const Graph& _g) : g(_g) {} vector<pair<int, int>> findBridges() { for (int v = 0; v < maxv; ++v) if (!tin[v]) dfs(v, -1); return bridges; } private: void addBridge(int v, int u) { if (v > u) swap(v, u); bridges.push_back(make_pair(v, u)); } void dfs(int v, int p) { static int number = 1; tin[v] = tout[v] = number++; for (const int u : g.g[v]) { if (!tin[u]) { dfs(u, v); tout[v] = min(tout[v], tout[u]); if (tout[u] > tin[v]) addBridge(v, u); } else if (u != p) { tout[v] = min(tout[v], tin[u]); } } } // input const Graph g; // temporary int tin[maxv], tout[maxv]; // output vector<pair<int, int>> bridges; }; template<int maxv> struct BridgeCuts { typedef UnweighedGraph<maxv, false> Graph; BridgeCuts(const Graph& g) : graph(g) { memset(visited, 0, sizeof(visited)); memset(block, 0, sizeof(block)); } Graph run() { vector<pair<int, int>> bs = BridgesFinder<maxv>(graph).findBridges(); for (pair<int, int> e : bs) bridges.insert(e); int blocks_count = 0; for (int v = 0; v < maxv; ++v) if (!visited[v]) dfs(v, blocks_count++); Graph result; for (auto edge : bridges) { const int ba = block[edge.first]; const int bb = block[edge.second]; result.addEdge(ba, bb); } return result; } private: void dfs(int v, int bid) { visited[v] = true; block[v] = bid; for (int u : graph.g[v]) { if (visited[u] || hasBridge(v, u)) continue; dfs(u, bid); } } bool hasBridge(int v, int u) { if (v > u) swap(v, u); return bridges.count(make_pair(v, u)); } // input const Graph graph; // temporary bool visited[maxv]; int block[maxv]; // map: vertex -> block id set<pair<int, int>> bridges; };
#include <iostream> using namespace std; double getAverage(int *dat,const int len) { double avg = 0; for(int i = 0;i<len;i++) { avg += *(dat+i); } avg /= len; return avg; } int main() { const int ARR_SIZE = 5; int balance[ARR_SIZE]= {1000,2,3,17,50}; double avg = 0; avg= getAverage(balance,ARR_SIZE); cout<<avg<<endl; cout<<*balance<<endl; }
// Created on : Sat May 02 12:41:15 2020 // Created by: Irina KRYLOVA // Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0 // Copyright (c) Open CASCADE 2020 // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepKinematics_ActuatedKinematicPair_HeaderFile_ #define _StepKinematics_ActuatedKinematicPair_HeaderFile_ #include <Standard.hxx> #include <StepKinematics_KinematicPair.hxx> #include <TCollection_HAsciiString.hxx> #include <StepRepr_RepresentationItem.hxx> #include <StepKinematics_KinematicJoint.hxx> #include <StepKinematics_ActuatedDirection.hxx> DEFINE_STANDARD_HANDLE(StepKinematics_ActuatedKinematicPair, StepKinematics_KinematicPair) //! Representation of STEP entity ActuatedKinematicPair class StepKinematics_ActuatedKinematicPair : public StepKinematics_KinematicPair { public : //! default constructor Standard_EXPORT StepKinematics_ActuatedKinematicPair(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Name, const Standard_Boolean hasItemDefinedTransformation_Description, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Description, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem1, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem2, const Handle(StepKinematics_KinematicJoint)& theKinematicPair_Joint, const Standard_Boolean hasTX, const StepKinematics_ActuatedDirection theTX, const Standard_Boolean hasTY, const StepKinematics_ActuatedDirection theTY, const Standard_Boolean hasTZ, const StepKinematics_ActuatedDirection theTZ, const Standard_Boolean hasRX, const StepKinematics_ActuatedDirection theRX, const Standard_Boolean hasRY, const StepKinematics_ActuatedDirection theRY, const Standard_Boolean hasRZ, const StepKinematics_ActuatedDirection theRZ); //! Returns field TX Standard_EXPORT StepKinematics_ActuatedDirection TX() const; //! Sets field TX Standard_EXPORT void SetTX (const StepKinematics_ActuatedDirection theTX); //! Returns True if optional field TX is defined Standard_EXPORT Standard_Boolean HasTX() const; //! Returns field TY Standard_EXPORT StepKinematics_ActuatedDirection TY() const; //! Sets field TY Standard_EXPORT void SetTY (const StepKinematics_ActuatedDirection theTY); //! Returns True if optional field TY is defined Standard_EXPORT Standard_Boolean HasTY() const; //! Returns field TZ Standard_EXPORT StepKinematics_ActuatedDirection TZ() const; //! Sets field TZ Standard_EXPORT void SetTZ (const StepKinematics_ActuatedDirection theTZ); //! Returns True if optional field TZ is defined Standard_EXPORT Standard_Boolean HasTZ() const; //! Returns field RX Standard_EXPORT StepKinematics_ActuatedDirection RX() const; //! Sets field RX Standard_EXPORT void SetRX (const StepKinematics_ActuatedDirection theRX); //! Returns True if optional field RX is defined Standard_EXPORT Standard_Boolean HasRX() const; //! Returns field RY Standard_EXPORT StepKinematics_ActuatedDirection RY() const; //! Sets field RY Standard_EXPORT void SetRY (const StepKinematics_ActuatedDirection theRY); //! Returns True if optional field RY is defined Standard_EXPORT Standard_Boolean HasRY() const; //! Returns field RZ Standard_EXPORT StepKinematics_ActuatedDirection RZ() const; //! Sets field RZ Standard_EXPORT void SetRZ (const StepKinematics_ActuatedDirection theRZ); //! Returns True if optional field RZ is defined Standard_EXPORT Standard_Boolean HasRZ() const; DEFINE_STANDARD_RTTIEXT(StepKinematics_ActuatedKinematicPair, StepKinematics_KinematicPair) private: StepKinematics_ActuatedDirection myTX; //!< optional StepKinematics_ActuatedDirection myTY; //!< optional StepKinematics_ActuatedDirection myTZ; //!< optional StepKinematics_ActuatedDirection myRX; //!< optional StepKinematics_ActuatedDirection myRY; //!< optional StepKinematics_ActuatedDirection myRZ; //!< optional Standard_Boolean defTX; //!< flag "is TX defined" Standard_Boolean defTY; //!< flag "is TY defined" Standard_Boolean defTZ; //!< flag "is TZ defined" Standard_Boolean defRX; //!< flag "is RX defined" Standard_Boolean defRY; //!< flag "is RY defined" Standard_Boolean defRZ; //!< flag "is RZ defined" }; #endif // _StepKinematics_ActuatedKinematicPair_HeaderFile_
#include "stdafx.h" #include "CPortableDeviceManager.h" CPortableDeviceManager::CPortableDeviceManager() { } std::unique_ptr<CPortableDeviceManager> CPortableDeviceManager::GetCPortableDeviceManager() { std::unique_ptr<CPortableDeviceManager> pCPortableDeviceManager = std::unique_ptr<CPortableDeviceManager>(new CPortableDeviceManager); // CoCreate the IPortableDeviceManager interface to enumerate // portable devices and to get information about them. //<SnippetDeviceEnum1> HRESULT hr = CoCreateInstance(CLSID_PortableDeviceManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&(pCPortableDeviceManager->pPortableDeviceManager))); if (FAILED(hr)) { pCPortableDeviceManager = nullptr; } return pCPortableDeviceManager; } int CPortableDeviceManager::EnumerateAllDevices() const { return 0; }
#pragma once typedef unsigned short MaterialHandle_t; class IMaterialSystem { public: IMaterial* CreateMaterial( bool flat, bool ignorez, bool wireframed ); IMaterial* FindMaterial( char const* pMaterialName, const char *pTextureGroupName, bool complain = true, const char *pComplainPrefix = NULL ); MaterialHandle_t FirstMaterial(); MaterialHandle_t NextMaterial(MaterialHandle_t h); MaterialHandle_t InvalidMaterial(); IMaterial * GetMaterial(MaterialHandle_t h); };
#ifndef APPLICATION_MESSAGESTATUS_H #define APPLICATION_MESSAGESTATUS_H #include <string> #include "BaseObject.h" #include "KeyWords.h" // Message status of reading class MessageStatus : public BaseObject { public: MessageStatus(); MessageStatus(int chatId); ~MessageStatus() override = default; // Get encode string std::string encode() const override; // Set string for decoding void decode(const std::string& jsonStr) override; public: int chatId; }; #endif //APPLICATION_MESSAGESTATUS_H
#include <iostream> #include <fstream> #include <ross/ross.hpp> #include "../tools/ppm.hpp" void example_1(); void example_2(); void example_3(); void write_canvas_to_disk(const ross::canvas& canvas, const std::string& ascii_out_path); const ross::color_rgb magenta{ { 1.0, 0.0, 1.0 } }; const ross::color_rgb yellow{ { 1.0, 1.0, 0.0 } }; const ross::color_rgb cyan{ { 0.0, 1.0, 1.0 } }; const ross::color_rgb black{ { 0.0, 0.0, 0.0 } }; int main(int argc, char** argv) { std::cout << "Welcome to Ross!\n"; example_1(); example_2(); example_3(); return 0; } void example_3() { ross::canvas canvas({ 64,64 }); std::memset(canvas.data(), 0xFF, canvas.size()); canvas.draw_rect({ 15.0, 15.0 }, { 45.0, 45.0 }, magenta); write_canvas_to_disk(canvas, "example3.ppm"); } void example_2() { ross::canvas canvas({64,64}); std::memset(canvas.data(), 0xFF, canvas.size()); canvas.draw_line({ 0.0, 24.0 }, { 64.0, 44.0 }, magenta); canvas.draw_line({ 0.0, 0.0 }, { 64.0, 64.0 }, magenta); canvas.draw_line({ 64.0, 24.0 }, { 0.0, 44.0 }, cyan); //canvas.draw_line({ 0.0, 64.0 }, { 64.0, 0.0 }, cyan); canvas.draw_line({ 32.0, 0.0 }, { 32.0, 64.0 }, yellow); canvas.draw_line({ 0.0, 32.0 }, { 64.0, 32.0 }, black); write_canvas_to_disk(canvas, "example2.ppm"); } void example_1() { // create 64x64 pixel surface // ross::surface_rgb24<64, 64> surface; // create canvas with surface // ross::canvas canvas; // draw horizontal line // canvas.moveto // canvas.lineto ross::canvas canvas({64, 64}); std::memset(canvas.data(), 0xFF, canvas.size()); ross::color_rgb magenta{{1.0, 0.0, 1.0}}; for(ross::size_t x = 0; x < canvas.dimension.x; ++x) { canvas.set_pixel({x, x}, magenta); } write_canvas_to_disk(canvas, "example1.ppm"); } void write_canvas_to_disk(const ross::canvas& canvas, const std::string& ascii_out_path) { std::ofstream fout(ascii_out_path, std::ios::binary); ross::ppm_write(fout, canvas.data(), canvas.dimension.x, canvas.dimension.y); }
/* Name: һ����ֵ��� Copyright: Author: Hill bamboo Date: 2019/8/17 10:31:14 Description: ���� �˷���д�� */ #include <bits/stdc++.h> using namespace std; const int maxn = 10000 + 5; int feq[26]; int n; char str[maxn]; int main() { for (int i = 0; i < 26; ++i) { scanf("%d", &feq[i]); } scanf("%s", str); n = strlen(str); int cnt = 0; int lines = 0; for (int i = 0; i < n; ++i) { if (cnt + feq[str[i] - 'a'] > 100) { ++lines; cnt = feq[str[i] - 'a']; } else cnt += feq[str[i] - 'a']; } printf("%d %d\n", lines + 1, cnt); return 0; }
/* @lc app=leetcode.cn id=23 lang=cpp * [23] 合并K个排序链表 */ // @lc code=start /** Definition for singly-linked list. */ #include<iostream> #include<vector> #include<queue> using namespace std; // struct ListNode { // int val; // ListNode *next; // ListNode(int x) : val(x), next(NULL) {} // }; class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { // auto cmp = [](ListNode* &left, ListNode* &right){ // return left->val > right->val; // }; // priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> q; struct node{ ListNode* p=NULL; int val; node(){ } node(ListNode* p, int val):p(p), val(val){} bool operator > (const node &r) const{ return p->val > r.val; } }; priority_queue<node, vector<node>, greater<node>> q; int n = lists.size(); if(n==0)return NULL; for(int i=0;i<n;i++) { if(lists[i]) q.emplace(lists[i], lists[i]->val); } // ListNode* head = q.top().p; // ListNode* p = head; ListNode head(0), *p = &head; while(!q.empty()) { auto top = q.top(); q.pop(); p->next = top.p; p = p->next; if(top.p->next!=NULL) q.emplace(top.p->next, top.p->next->val); } p->next = NULL; return head.next; } }; // @lc code=end
#pragma once #include <Eigen/Dense> #include <limits> #include <solvers/qp.hpp> namespace sqp { template <typename T> class SQP; template <typename Scalar> struct sqp_settings_t { Scalar tau = 0.5; /**< line search iteration decrease, 0 < tau < 1 */ Scalar eta = 0.25; /**< line search parameter, 0 < eta < 1 */ Scalar rho = 0.5; /**< line search parameter, 0 < rho < 1 */ Scalar eps_prim = 1e-4; /**< primal step termination threshold, eps_prim > 0 */ Scalar eps_dual = 1e-4; /**< dual step termination threshold, eps_dual > 0 */ int max_iter = 100; int line_search_max_iter = 20; bool second_order_correction = false; std::function<void(SQP<Scalar>&)> iteration_callback; bool validate() { bool valid; valid = 0.0 < tau && tau < 1.0 && 0.0 < eta && eta < 1.0 && 0.0 < rho && rho < 1.0 && eps_prim < 0.0 && eps_dual < 0.0 && max_iter > 0 && line_search_max_iter > 0; return valid; } }; typedef enum { SOLVED, MAX_ITER_EXCEEDED, INVALID_SETTINGS } Status; struct Info { int iter; int qp_solver_iter; Status status; void print() { printf("SQP info:\n"); printf(" iter: %d\n", iter); printf(" qp_solver_iter: %d\n", qp_solver_iter); printf(" status: "); switch (status) { case SOLVED: printf("SOLVED\n"); break; case MAX_ITER_EXCEEDED: printf("MAX_ITER_EXCEEDED\n"); break; case INVALID_SETTINGS: printf("INVALID_SETTINGS\n"); break; default: printf("UNKNOWN\n"); break; } } }; template <typename Scalar_ = double> struct NonLinearProblem { using Scalar = Scalar_; using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>; int num_var; int num_constr; virtual void objective(const Vector& x, Scalar& obj) = 0; virtual void objective_linearized(const Vector& x, Vector& grad, Scalar& obj) = 0; virtual void constraint(const Vector& x, Vector& c, Vector& l, Vector& u) = 0; virtual void constraint_linearized(const Vector& x, Matrix& Jc, Vector& c, Vector& l, Vector& u) = 0; }; /* * minimize f(x) * subject to l <= c(x) <= u */ template <typename Scalar_> class SQP { public: using Scalar = Scalar_; using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>; using Problem = NonLinearProblem<Scalar>; using Settings = sqp_settings_t<Scalar>; // Constants static constexpr Scalar DIV_BY_ZERO_REGUL = std::numeric_limits<Scalar>::epsilon(); // enforce 16 byte alignment // https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html EIGEN_MAKE_ALIGNED_OPERATOR_NEW SQP(); ~SQP() = default; void solve(Problem& prob, const Vector& x0, const Vector& lambda0); void solve(Problem& prob); inline const Vector& primal_solution() const { return x_; } inline Vector& primal_solution() { return x_; } inline const Vector& dual_solution() const { return lambda_; } inline Vector& dual_solution() { return lambda_; } inline const Settings& settings() const { return settings_; } inline Settings& settings() { return settings_; } inline const Info& info() const { return info_; } inline Info& info() { return info_; } // private: void run_solve(Problem& prob); bool termination_criteria(const Vector& x, Problem& prob); void solve_qp(Problem& prob, Vector& p, Vector& lambda); bool run_solve_qp(const Matrix& P, const Vector& q, const Matrix& A, const Vector& l, const Vector& u, Vector& prim, Vector& dual); /** Second order correction by solving the same QP with corrected constraints. */ void second_order_correction(Problem& prob, Vector& p, Vector& lambda); /** Line search in direction p using l1 merit function. */ Scalar line_search(Problem& prob, const Vector& p); /** L1 norm of constraint violation */ Scalar constraint_norm(const Vector& x, Problem& prob); /** L1 norm of constraint violation, for given constraint evaluation */ Scalar constraint_norm(const Vector &constr, const Vector &l, const Vector &u) const; /** L_inf norm of constraint violation */ Scalar max_constraint_violation(const Vector& x, Problem& prob); // Solver state variables Vector x_; Vector lambda_; Vector step_prev_; Vector grad_L_; Vector delta_grad_L_; Matrix Hess_; Vector grad_obj_; Scalar obj_; Matrix Jac_constr_; Vector constr_; Vector l_, u_; // info Scalar dual_step_norm_; Scalar primal_step_norm_; Settings settings_; Info info_; qp_solver::QPSolver<Scalar> qp_solver_; }; extern template class SQP<double>; } // namespace sqp
#pragma once #include "Movable.h" #include "OMesh.h" #include "Light.h" //#include "AnimationState.h" #include <list> #include "PreDefine.h" namespace HW { class Camera; /** */ class Entity : public Movable { public: // never use this constructor. Entity():m_CastShadow(true){} Entity(const string &name,SceneManager * creator = NULL); ~Entity(); void setMesh(MeshPtr mesh) ; //AnimationState * getAnimationState() //{ // if(!animationstate) // { // return NULL; // } // return animationstate; //} // MeshPtr getMesh() const { return m_Mesh; } //void setMaterial(MaterialPtr material); const std::map<string,Light*>& getLightList() const { return m_LightList; } void recordLight(Light *light) { if(m_LightList.find(light->getName()) == m_LightList.end()) m_LightList.insert(std::make_pair(light->getName(),light)); } void clearLightList() { m_LightList.clear(); } bool isCastShadow() { return m_CastShadow; } /** set this entity castShadow or Not */ void setCastShadow(bool cast) { m_CastShadow = cast; } virtual void updateRenderqueue(Camera * came,RenderQueue & renderqueue); virtual void updateRenderqueue_as(Camera * came, RenderQueue & renderqueue); void setEffect(Effect *effect) { m_Mesh->setLocalEffect(effect); } protected: // set bounding box and bounding sphere invalid. virtual void moveActionImp() { m_boundingBoxCurrent = false; m_boundingSphereCurrent = false; } // transform bounding box from model space to global space. virtual void getBoundingBoxImp(); // transform bounding sphere from model space to global space. virtual void getBoundingSphereImp(); // hint bounding box bool m_boundingBoxCurrent; bool m_boundingSphereCurrent; MeshPtr m_Mesh; //AnimationState * animationstate; /** a list of light which influence this entity. */ std::map<string,Light*> m_LightList; bool m_CastShadow; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MODULES_PUBSUFFIX_MODULE_H #define MODULES_PUBSUFFIX_MODULE_H #if defined PUBSUFFIX_ENABLED #include "modules/hardcore/opera/module.h" class AutoFetch_Manager; /** Module object. Includes all global infrastructure for the public suffix module * * Public Suffix is a list over all domains that can be considered registry like, that is, * similar to a TLD, as well as some that are not, when all other domains at the same hierarchical * level are such domains. * * The list is stored as separate, digitally signed files on certs.opera.com (the same * server used for root certificate updates) in a XML format defined by an Internet draft * published by Opera. * * When loaded, all active ServerName objects in the TLD will be tagged with the category * of hostname that they are, TLD, registry, domain, or host. "Domains" are names immediately * below a registry domain, or a TLD, if there are no second level registries. * * The API in this module should not be accessed directly, but through the asynchronous ServerName API, * which require the client to register a callback listener if the module have to go online to fetch * the information first. */ class PubsuffixModule : public OperaModule { private: /** List of domains already checked; no need to check them again */ AutoDeleteHead checked_domains; #ifdef PUBSUFFIX_OVERRIDE_UPDATE /** List of domains that are not going to be checked using the normal URLs, and the URLs to use instead */ AutoDeleteHead predef_domains; #endif /** List of active updaters */ AutoDeleteHead updaters; /** Update manager */ OP_STATUS LoadPubSuffixState(); public: /** Constructor */ PubsuffixModule(); /** Destructor */ virtual ~PubsuffixModule(){}; /** Initialization */ virtual void InitL(const OperaInitInfo& info); /** Clean up the module object */ virtual void Destroy(); /** Check the specificed domain */ OP_STATUS CheckDomain(ServerName *domain); /** Have this TLD been checked ? */ BOOL HaveCheckedDomain(const OpStringC8 &tld); /** Set that we have checked this TLD */ void SetHaveCheckedDomain(const OpStringC8 &tld); #ifdef PUBSUFFIX_OVERRIDE_UPDATE /** Add a URL override for a TLD */ OP_STATUS AddUpdateOverride(const OpStringC8 &tld, const OpStringC8 &url); #endif }; #define PUBSUFFIX_MODULE_REQUIRED #define g_pubsuf_api (&(g_opera->pubsuffix_module)) #define g_pubsuffix_context g_opera->pubsuffix_module.m_pubsuffix_context #endif // PUBSUFFIX_ENABLED #endif // !MODULES_PUBSUFFIX_MODULE_H
#include "player.h" #include "videowidget.h" #include <QMediaService> #include <QMediaPlaylist> #include <QtWidgets> #include <windows.h> Player::Player(QWidget *parent) : QWidget(parent) { m_player = new QMediaPlayer(this); m_player->setAudioRole(QAudio::VideoRole); qInfo() << "Supported audio roles:"; for (QAudio::Role role : m_player->supportedAudioRoles()) qInfo() << " " << role; // owned by PlaylistModel m_playlist = new QMediaPlaylist(); m_player->setPlaylist(m_playlist); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); showMaximized(); setCursor(Qt::BlankCursor); setMouseTracking(true); QRect rec = QApplication::desktop()->screenGeometry(); auto height = rec.height(); auto width = rec.width(); this->setMaximumHeight(height); this->setMinimumHeight(height); this->setMaximumWidth(width); this->setMinimumWidth(width); m_videoWidget = new VideoWidget(this); m_player->setVideoOutput(m_videoWidget); m_videoWidget->setMouseTracking(true); m_videoWidget->installEventFilter(this); QBoxLayout *layout = new QVBoxLayout; layout->addWidget(m_videoWidget); layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); setLayout(layout); timeStart = QTime::currentTime(); { HWND hwnd = FindWindow(L"Shell_traywnd", L""); if(hwnd) SetWindowPos(hwnd,0,0,0,0,0,SWP_HIDEWINDOW); } { HWND hwnd = FindWindow(L"Shell_SecondaryTrayWnd", L""); if(hwnd) SetWindowPos(hwnd,0,0,0,0,0,SWP_HIDEWINDOW); } // connect(m_playlist, &QMediaPlaylist::currentIndexChanged, // this, &Player::indexChanged); // connect(m_player, &QMediaPlayer::positionChanged, // this, &Player::slotPositionChanged); } void Player::slotPositionChanged(int pos) { if(pos >= m_player->duration()-1 && m_player->playlist()->currentIndex() == 0) { m_player->playlist()->setCurrentIndex(1); m_player->play(); qWarning("setPosition(0)"); } if(pos >= m_player->duration()-100 && m_player->playlist()->currentIndex() == 1) { m_player->playlist()->setCurrentIndex(0); m_player->play(); qWarning("setPosition(1)"); } } void Player::play(int index) { m_player->playlist()->setCurrentIndex(index); m_player->play(); } //bool Player::eventFilter(QObject *obj, QEvent *event) //{ // qDebug() <<QMetaEnum::fromType<QEvent::Type>().valueToKey(event->type()); // if(event->type() == QEvent::MouseMove // && // timeStart.msecsTo(QTime::currentTime()) > 1000) // { // close(); // deleteLater(); // return true; // } // return QWidget::eventFilter(obj, event); //} void Player::addToPlaylist(const QList<QUrl> &urls) { foreach(auto url, urls) { m_playlist->addMedia(url); } //m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop); m_player->setPlaylist(m_playlist); } void Player::keyPressEvent(QKeyEvent *event) { if(timeStart.msecsTo(QTime::currentTime()) > 1000) { close(); deleteLater(); } QWidget::keyPressEvent(event); } //void Player::mouseMoveEvent(QMouseEvent *event) //{ // if(timeStart.msecsTo(QTime::currentTime()) > 1000) // { // close(); // deleteLater(); // } // QWidget::mouseMoveEvent(event); //} //void Player::mousePressEvent(QMouseEvent *event) //{ // if(timeStart.msecsTo(QTime::currentTime()) > 1000) // { // close(); // deleteLater(); // } // QWidget::mousePressEvent(event); //} void Player::closeEvent(QCloseEvent *event) { emit closing(); QWidget::closeEvent(event); } Player::~Player() { { HWND hwnd = FindWindow(L"Shell_traywnd", L""); if(hwnd) SetWindowPos(hwnd,0,0,0,0,0,SWP_SHOWWINDOW); } { HWND hwnd = FindWindow(L"Shell_SecondaryTrayWnd", L""); if(hwnd) SetWindowPos(hwnd,0,0,0,0,0,SWP_SHOWWINDOW); } }
#include<iostream> using namespace std; void riempi(int A1[10][5], int A2[10][5]); void cross(int A1[10][5],int A2[10][5],bool B[][5]); bool compareRowColumn(int A1[10][5],int A2[10][5],int rowA1,int columnA2); main(){ int A1[10][5],A2[10][5]; riempi(A1,A2); bool B[10][5]; cross(A1,A2,B); } //PRE = Gli array sono di 50 posizioni in totale dentro una matrice da 5x10 elementi void riempi(int A1[10][5], int A2[10][5]){ int* pA1 = &A1[0][0]; for(int i=0;i<50;i++){ int x; cin >> x; //A1 righe pA1[i] = x; //A2 Colonne A2[i%10][i/10] = x; } //Print Output //A1 for(int i=0;i<10;i++){ for(int e=0;e<5;e++){ cout << " " <<A1[i][e]; } cout << endl; } cout <<endl; //A2 for(int i=0;i<10;i++){ for(int e=0;e<5;e++){ cout << " " << A2[i][e]; } cout << endl; } cout << endl; } /* POST = i due array A1 e A2 sono stati rimepiti con i primi 50 caratteri immessi da tastiera Rispettivamente A1 per riga, e A2 epr colonna; Alla fine della funzione entrambi gli array vengono stampati a schermo. */ /* PRE= gli array A1 e A2 sono matrici di 5x10 elementi ciscuano, tutte gli elementi sono pieni e contengono un input precedentemente immesso da tastiera. IN B[i][j], essendo B la matrice presente nella funzione chiamante, sono : rowA1 una variabile che contiene l'indice della riga "i" di A1 , con cui cercare se ha qualche elemento in comune con la colonna "j" di A2. collumnA1 una variabile che contiene l'indice della colonna "j" di A2, con cui cercare se ha qualche elemento in comune con la riga "i" di A1. */ bool compareRowColumn(int A1[10][5],int A2[10][5],int rowA1,int columnA2){ bool equal = false; /**R = ( 0<=cA1<cA1 && !equal ) : finche si scorre A2[0..rA2-1][columnA2] && finchè A1[rowA1][0..cA1-1]!=A2[0..rA2-1][columnA2] quindi equal == false cioè finchè un elemento della riga rowA1, quale sia esse A1[rowA1][0..cA1-1] è != da un elemento della colonna columnA2 quale esso sia A2[0..rA2-1][columnA2] */ for(int cA1=0;cA1<5 && !equal;cA1++){ /**R = ( 0<=rA2<rA2 && !equal ) : finche si scorre A2[0..rA2-1][columnA2] && finchè A1[rowA1][0..cA1-1]!=A2[0..rA2-1][columnA2] quindi equal == false **/ for(int rA2=0;rA2<10 && !equal;rA2++){ if(A1[rowA1][cA1]==A2[rA2][columnA2]){ equal=true; } }//r }//c /** POST alla fine del ciclo, quindi la sua causa di terminazione sarà 1)o per scorrimento di tutti gli indici dei rispettivi cicli r o c 2)o per il ritrovamento di un qualsiasi A1[rowA1][0..cA1-1]!=A2[0..rA2-1][columnA2] quindi: Avremo come parametro di return la variabile equal: Se l'insieme dei due cicli finisce per la prima motivazione avremo : FALSE perchè abbiamo tutti A1[rowA1][0..cA1-1]!=A2[0..rA2-1][columnA2] Nel Caso finisse per il secondo motivo avremo TRUE perchè abbiamo almeno un A1[rowA1][0..cA1-1]==A2[0..rA2-1][columnA2] **/ return equal; } /* POST=viene returnato dalla funzione : TRUE nel caso nella riga rowA1 di A1 è presente un elemento in comune con la collonna columnA2 di A2; FALSE nel caso contrario. */ /** PRE=A1 è un array bidimensionale riempito con valori interi di grandezza 10x5 elementi A2 è un array bidimensionale riempito con valori interi di grandezza 10x5 elementi B è un array bidimensionale vuoto pronto ad ospitare volori booleani con una grandezza di 10x5 elementi */ void cross(int A1[10][5],int A2[10][5],bool B[10][5]){ /**R = ( 0<=i<50 ) viene fatto scorrere i da 0 fino a 50 escluso perchè, avendo noi 10 righe per 5 colonne facendo 5x10 = 50 posizioni nel array. la condizione di permanenza nel ciclo implica solo il scorrere tutti gli elementi del array B. */ for(int i=0;i<50;i++){ //Abbiamo come da richiesta B[i][j] con i == i/5 e j == i%5 //per ogni posizione B[i][j] richiamiamo la funzione compareRowColumn e inseriamo il corrispettivo valore booleano. B[i/5][i%5]=compareRowColumn(A1,A2,i/5,i%5); } //POST=Avremo tutti gli elementi di B , una matrice con 5x10 elementi riempita con i corrispetivi valori boolean. //Print Output //B for(int i=0;i<10;i++){ for(int e=0;e<5;e++){ cout << " " <<B[i][e]; } cout << endl; } } /**POST= Per ogni elemento di B, viene calcolato il valore del sudetto elemento secondo questa condizione: * true sse la riga i di A1 ha qualche elemento in comune con la colonna j di A2 * con i == al indice delle righe di B e J == al indice delle colonne di B. * Alla fine viene stampato per righe l'array B e vengono visualizzati a schermo i dati presenti * per ogni posizione B[0..i-1][0..j-1] avremmo : * TRUE se * la riga i di A1 ha qualche elemento in comune con la colonna j di A2 * FALSE * nel caso contrario */
// // Created by litalfel@wincs.cs.bgu.ac.il on 14/01/2020. // #ifndef ASSIGNMENT3CLIENT_BOOK_H #define ASSIGNMENT3CLIENT_BOOK_H using namespace std; #include <string> class Book { private: string name; string topic; string owner; public: Book(string name, string topic, string owner); string getowner(); string gettopic(); string getname(); }; #endif
#include"Anyinclude.h" #include"compman.h" #include"Collider.h" #include"ObjColli.h" #include"hitboxtest.h" #include"TextFont.h" #include"Menu.h" #include"PauseMenu.h" static const float VIEW_HEIGHT = 900.0f; static const float boxes = 512.0f; static const float boxes2 = 513.0f; static const float boxes2_2 = 229.5f; static const float boxes3 = 463.0f; static const float boxes3_3 = 320.0f; static const float arr_point = 640.0f; static const float arr_point2 = 640.0f - 100.0f; using namespace std; float max_spacebartimer = 450; float spacebartimer = 0; static const float eraseObj = 7000.0f; void ResizeView(const sf::RenderWindow& window, sf::View& view) { float aspectRatio = float(window.getSize().x) / float(window.getSize().y); view.setSize(VIEW_HEIGHT * aspectRatio, VIEW_HEIGHT); } int main() { sf::RenderWindow window(sf::VideoMode(1000, 900), "Box Way", sf::Style::Close /*| sf::Style::Resize*/); bool Game_run = true; //--Obj Everythings--// Texture MNp; MNp.loadFromFile("Object/Menu/MenuP.png"); Sprite BGmn; BGmn.setTexture(MNp); Texture Gp0; Gp0.loadFromFile("Object/Guide.png"); Sprite BG_Gp; BG_Gp.setTexture(Gp0); Texture Guide_page; Guide_page.loadFromFile("Object/Guide.png"); Sprite Gp; Gp.setTexture(Guide_page); Music stage1; Music menums; menums.openFromFile("Object/Menu/menusound.wav"); menums.setVolume(50); menums.setLoop(true); menums.play(); Texture BGpmn; BGpmn.loadFromFile("Object/BGpause.png"); Sprite pause_bg; pause_bg.setTexture(BGpmn); sf::Texture CompmanTexture; CompmanTexture.loadFromFile("Object/compmanA1.png"); compman Compman(&CompmanTexture, sf::Vector2u(8, 4), 0.2f, 350.0f, 150.0f); TextFont SDid; TextFont NameT; Font font; font.loadFromFile("Object/cour.ttf"); //init state bool checkColli = false; bool checkGameOpen = false; bool p_Menu = false; bool Game = false; int Game_State = 0; int P_State = 0; float deltaTime = 1500.0f; float GameTime = 0; if (Game_run == true) { Menu menu(window.getSize().x, window.getSize().y); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyReleased: switch (event.key.code) { case sf::Keyboard::Up: if (menu.selectedItem >= 0) { menu.Moveup(); break; } case sf::Keyboard::Down: if (menu.selectedItem < Max_Items) { menu.Movedown(); break; } case sf::Keyboard::Return: switch (menu.GetPressedItem()) { case 0: cout << "Start has been pressed" << endl; //go to state menums.stop(); Game_State = 1; checkGameOpen = true; break; case 1: cout << "Guide has been pressed" << endl; //go to state //menums.stop(); Game_State = 4; checkGameOpen = true; break; case 2: cout << "HighScore has been pressed" << endl; //go to state Game_State = 6; checkGameOpen = true; break; case 3: window.close(); menums.stop(); break; } break; } break; case sf::Event::Closed: window.close(); break; } } window.clear(); window.draw(BGmn); menu.draw(window); SDid.drawtext(63010467, (string)".", (string)" THIRAPHAT KETSINGNOI", sf::Vector2f(600, 865), window, sf::Color(0, 120, 255)); window.display(); if (checkGameOpen == true) break; } } if (Game_State == 4) //guide { sf::Clock deCLK = sf::Clock(); double debounce; Texture Gp1; Gp1.loadFromFile("Object/Guide/Control.png"); Sprite Gpo; Gpo.setTexture(Gp1); int Guide_State = 0; double deTime = 0; while (window.isOpen() && Game_State == 4) { deTime += deCLK.getElapsedTime().asSeconds(); sf::Event event; if (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; } if (Guide_State == 0) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::N)) { Guide_State = 1; debounce = deTime; } window.clear(); window.draw(BG_Gp); window.draw(Gpo); window.display(); } if (Guide_State == 1) { Texture Gp2; Gp2.loadFromFile("Object/Guide/Obj.png"); Sprite Gpo2; Gpo2.setTexture(Gp2); window.clear(); window.draw(BG_Gp); window.draw(Gpo2); window.display(); if (sf::Keyboard::isKeyPressed(sf::Keyboard::N) && deTime - debounce >= 100.f) { menums.stop(); Game_State = 1; } } } } } if (Game_State == 6) { cout << "in"; sf::Clock deCLK = sf::Clock(); double debounce; Texture hScore; hScore.loadFromFile("Object/HScore.png"); Sprite HS; HS.setTexture(hScore); double deTime = 0; bool scorenaja = false; int cnt = 0; vector<pair<int, string>> scoreboard; scoreboard.clear(); ifstream loadFile; loadFile.open("HS.txt"); if (!loadFile.eof()) { string tempName; int tempScore; loadFile >> tempName >> tempScore; scoreboard.push_back({ tempScore,tempName }); cout << "xxx"; } loadFile.close(); sort(scoreboard.begin(), scoreboard.end(), greater<pair<int, string>>()); while (window.isOpen() && Game_State == 6) { sf::Event event; if (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: cout << "Mouse button has been pressed" << endl; switch (event.key.code) { case sf::Mouse::Left: cout << "LEFT KEY has been pressed" << endl; break; } break; case sf::Event::MouseButtonReleased: cout << "Mouse button has been released" << endl; break; } } window.clear(); window.draw(HS); for (vector<pair<int, string>>::iterator k = scoreboard.begin(); k != scoreboard.end(); ++k) { ++cnt; if (cnt > 5) break; sf::Text hname, hscore; hscore.setString(to_string(k->first)); hscore.setFont(font); hscore.setCharacterSize(20); hscore.setOrigin(HS.getLocalBounds().width / 2, HS.getLocalBounds().height / 2); hscore.setPosition(window.getSize().x / 2, window.getSize().y + (80 * cnt)); hscore.setFillColor(sf::Color::Blue); window.draw(hscore); hname.setString(k->second); hname.setFont(font); hname.setCharacterSize(20); hname.setOrigin(HS.getLocalBounds().width / 2, HS.getLocalBounds().height / 2); hname.setPosition(window.getSize().x / 2, window.getSize().y + (80 * cnt)); hname.setFillColor(sf::Color::Blue); window.draw(hname); } window.display(); if (sf::Keyboard::isKeyPressed(sf::Keyboard::N)) { debounce = deTime; menums.stop(); Game_State = 1; } } } //-----------------Loop Game Stage------------------// //--Stage 1--// if (Game_State == 1) { sf::View view(sf::Vector2f(1.0f, 1.0f), sf::Vector2f(VIEW_HEIGHT, VIEW_HEIGHT)); stage1.openFromFile("Object/stage1.wav"); stage1.setVolume(50); stage1.setLoop(true); stage1.play(); //***Player**// //***BoxStage**// sf::Texture box; box.loadFromFile("Object/box.png"); std::vector<ObjColli>Objs1; Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 2, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 3, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 4, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 5, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 6, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 7, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 8, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 9, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 10, 1000.0f))); Objs1.push_back(ObjColli(&box, sf::Vector2f(boxes, boxes), sf::Vector2f(0.0f + boxes * 11, 1000.0f))); //----box--pick----// sf::Texture box2; box2.loadFromFile("Object/box2.png"); std::vector<ObjColli>Objs2; for (size_t i = 0;i <= 20;i++) { Objs2.push_back(ObjColli(&box2, sf::Vector2f(54.0f, 54.0f), sf::Vector2f(rand() % (4000 - 1500) + 1500, 400.0f))); } //---Limit Stage---// sf::Texture box3; std::vector<ObjColli>Objs3; Objs3.push_back(ObjColli(&box3, sf::Vector2f(2.0f, 5000.0f), sf::Vector2f(-268.0f, 724.f))); Objs3.push_back(ObjColli(&box3, sf::Vector2f(2.0f, 5000.0f), sf::Vector2f(5890.f, 724.f))); //----item----// //ITEM_1 Texture item11; item11.loadFromFile("Object/Item_stage1/1.png"); Sprite bt; bt.setTexture(item11); bt.setScale(1.2, 1.2); bt.setPosition(eraseObj, eraseObj); bt.setOrigin(bt.getScale().x / 2, bt.getScale().y / 2); //ITEM_2 Texture item12; item12.loadFromFile("Object/Item_stage1/2.png"); Sprite bt2; bt2.setTexture(item12); bt2.setScale(1.2, 1.2); bt2.setPosition(eraseObj, eraseObj); bt2.setOrigin(bt2.getScale().x / 2, bt2.getScale().y / 2); //ITEM_3 Texture item13; item13.loadFromFile("Object/Item_stage1/3.png"); Sprite bt3; bt3.setTexture(item13); bt3.setScale(1.2, 1.2); bt3.setPosition(eraseObj, eraseObj); bt3.setOrigin(bt3.getScale().x / 2, bt3.getScale().y / 2); Texture arr; arr.loadFromFile("Object/ArrRed.png"); Sprite arr1; arr1.setTexture(arr); arr1.setScale(0.9, 0.9); arr1.setPosition(2700.0f, arr_point); arr1.setOrigin(arr1.getScale().x / 2, arr1.getScale().y / 2); Sprite arr2; arr2.setTexture(arr); arr2.setScale(0.9, 0.9); arr2.setPosition(eraseObj, eraseObj); arr2.setOrigin(arr2.getScale().x / 2, arr2.getScale().y / 2); Sprite arr3; arr3.setTexture(arr); arr3.setScale(0.9, 0.9); arr3.setPosition(eraseObj, eraseObj); arr3.setOrigin(arr3.getScale().x / 2, arr3.getScale().y / 2); //---Next-Arrow---// Texture Narr_s; Narr_s.loadFromFile("Object/NArrS2.png"); Sprite Narr_is; Narr_is.setTexture(Narr_s); Narr_is.setScale(1.2, 1.2); Narr_is.setPosition(eraseObj, eraseObj); //Narr_i1.setRotation(135); Narr_is.setOrigin(Narr_is.getScale().x / 2, Narr_is.getScale().y / 2); Narr_is.setPosition(Compman.getPosition().x + 200.f, arr_point); Texture Narr; Narr.loadFromFile("Object/NArrRed.png"); Sprite Narr1; Narr1.setTexture(Narr); Narr1.setScale(1.2, 1.2); Narr1.setPosition(eraseObj, eraseObj); Narr1.setOrigin(Narr1.getScale().x / 2, Narr1.getScale().y / 2); Texture Narr_2; Narr_2.loadFromFile("Object/NArrRed2.png"); Sprite Narr2; Narr2.setTexture(Narr_2); Narr2.setScale(1.2, 1.2); Narr2.setPosition(eraseObj, eraseObj); Narr2.setOrigin(Narr2.getScale().x / 2, Narr2.getScale().y / 2); Texture Darr_1; Darr_1.loadFromFile("Object/DoorArr.png"); Sprite Darr1; Darr1.setTexture(Darr_1); Darr1.setScale(1.2, 1.2); Darr1.setPosition(eraseObj, eraseObj); Darr1.setOrigin(Darr1.getScale().x / 2, Darr1.getScale().y / 2); Texture DGo; DGo.loadFromFile("Object/DoorArrGo.png"); Sprite D_Go; D_Go.setTexture(DGo); D_Go.setScale(1.2, 1.2); D_Go.setPosition(eraseObj, eraseObj); D_Go.setOrigin(D_Go.getScale().x / 2, D_Go.getScale().y / 2); sf::Texture Holl; Holl.loadFromFile("Object/Holl.png"); sf::Sprite hell(Holl); hell.setScale(1.2, 1.2); hell.setPosition(eraseObj, eraseObj ); hell.setOrigin(hell.getScale().x / 2, hell.getScale().y / 2); //----hitboxtest----// hitboxtest hitbox0(0, 0, Vector2f(54, Objs2[0].GetSize().x), Objs2[0].GetPosition()); hitboxtest hitbox1(0, 0, Vector2f(50, Compman.GetSize().x), Compman.GetPosition()); //--Text--// TextFont text1; TextFont text2; //----bool for if rand y position item----// bool item_s11 = true; bool item_s12 = true; bool item_s13 = true; sf::Clock clock; float timeElasped = 0; float PointTime = 100; while (window.isOpen()) { timeElasped += deltaTime; deltaTime = clock.restart().asSeconds(); if (deltaTime > 1.0f / 20.0f) deltaTime = 1.0f / 20.0f; /*if (GameTime > 0)*/ /*if (GameTime <= 0)*/ GameTime += deltaTime; /*PointTime -= deltaTime;*/ /*if (PointTime <= 0) PointTime = 0;*/ sf::Event event; if (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: ResizeView(window, view); break; case sf::Event::MouseButtonPressed: cout << "Mouse button has been pressed" << endl; switch (event.key.code) { case sf::Mouse::Left: cout << "LEFT KEY has been pressed" << endl; break; } break; case sf::Event::MouseButtonReleased: cout << "Mouse button has been released" << endl; break; } //cout << "Position x : " << Compman.getPosition().x << "\n" << "Position y : " << Compman.getPosition().y << "\n" << endl; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { stage1.stop(); } spacebartimer += 1; Compman.Update(deltaTime); sf::Vector2f direction; //--Collider_Update--// Collider c = Compman.GetCollider(); for (ObjColli& Obj : Objs1) { Collider O = Obj.GetCollider(); if (Obj.GetCollider().CheckCollision(c, direction, 1.0f)) { Compman.OnCollision(direction); } for (ObjColli& Obj2 : Objs2) { if (Obj2.GetCollider().CheckCollision(O, direction, 0.0f)) { Obj2.Oncollision(direction); } } } //---Hold_Obj---// for (int i = 0;i < Objs2.size();i++) { Objs2[i].Update(deltaTime, Compman.getPosition()); if (Objs2[i].GetCollider().CheckCollision(c, direction, 0.0f)) { if (Objs2[i].getPickObj() == false) { Compman.OnCollision(direction); //cout << "Collision" << endl; } if ((Keyboard::isKeyPressed(Keyboard::Space)) && spacebartimer >= max_spacebartimer && Compman.getHold() == false && Objs2[i].getPickObj() == false /*&& Compman.getPosition().y >= Objs2[i].getbody().getPosition().y - 20 && Compman.getPosition().y <= Objs2[i].getbody().getPosition().y + 20*/) { spacebartimer = 0; Objs2[i].setPickObj(true); Compman.setHold(true); } if (Objs2[i].getPickObj() == true && (Keyboard::isKeyPressed(Keyboard::Space)) && spacebartimer >= max_spacebartimer && Compman.getcanJump() == false) { spacebartimer = 0; Objs2[i].getbody().setPosition(Compman.getPosition().x, Compman.getPosition().y + 60); Compman.setHold(false); Objs2[i].setPickObj(false); } } Collider o = Objs2[i].GetCollider(); for (int j = 0; j < Objs2.size();j++) { if (i != j) { if (Objs2[j].GetCollider().CheckCollision(o, direction, 1.0f)) { Objs2[i].Oncollision(direction); } } } } for (ObjColli& Obj : Objs3) { Collider b = Obj.GetCollider(); if (Obj.GetCollider().CheckCollision(c, direction, 1.0f)) { Compman.OnCollision(direction); } for (ObjColli& Obj2 : Objs2) { if (Obj2.GetCollider().CheckCollision(b, direction, 0.0f)) { Obj2.Oncollision(direction); } } } //--hitboxtest_Update--// hitbox1.Update(-21.5, -35.5, Compman.GetPosition()); hitbox0.Update(-27, -27, Objs2[0].GetPosition()); //----------Set_View----------// view.setCenter(Compman.GetPosition().x, Compman.GetPosition().y); if (view.getCenter().x - 195.0f <= 0.0f) { if (view.getCenter().y - 450.0f <= 0.0f) { view.setCenter(195.f, Compman.GetPosition().y); } if (view.getCenter().y + 450.0f >= 900.0f) { view.setCenter(195.f, Compman.GetPosition().y); } if (view.getCenter().y - 450.0f > 0.0f && view.getCenter().y + 450.0f < 900.0f) { view.setCenter(195.f, Compman.GetPosition().y); } } if (view.getCenter().x + 415.0f >= 5850.f) { if (view.getCenter().y - 450.0f <= 0.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } if (view.getCenter().y + 450.0f >= 900.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } if (view.getCenter().y - 450.0f > 0.0f && view.getCenter().y + 450.0f < 900.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } } //cout << view.getCenter().x << "\t" << view.getCenter().y << endl ; //---loop pick item---// for (size_t i = 0;i < Objs2.size(); i++) { if ((Objs2[i].getGlobalbounds().intersects(arr1.getGlobalBounds()) or Compman.getGlobalbounds().intersects(arr1.getGlobalBounds())) and item_s11 == true) { Narr_is.setPosition(eraseObj, eraseObj); bt.setPosition(arr1.getPosition().x, rand() % (150 - 40) + 40); item_s11 = false; } if (Compman.getGlobalbounds().intersects(bt.getGlobalBounds())) { arr1.setPosition(eraseObj, eraseObj); bt.setPosition(eraseObj, eraseObj); Narr1.setPosition(Compman.getPosition().x - 200.0f, 200.0f); Narr1.setRotation(135); arr2.setPosition(Narr1.getPosition().x - 900.0f, arr_point); } if ((Compman.getGlobalbounds().intersects(arr2.getGlobalBounds()) or Objs2[i].getGlobalbounds().intersects(arr2.getGlobalBounds())) and item_s12 == true) { bt2.setPosition(arr2.getPosition().x, rand() % (150 - 40) + 40); item_s12 = false; Narr1.setPosition(eraseObj, eraseObj); } if(Compman.getGlobalbounds().intersects(bt2.getGlobalBounds())) { arr2.setPosition(eraseObj, eraseObj); bt2.setPosition(eraseObj, eraseObj); Narr2.setPosition(Compman.getPosition().x + 200.0f, 200.0f); Narr2.setRotation(45); arr3.setPosition(Narr2.getPosition().x + (900.0f*2), arr_point); } if ((Compman.getGlobalbounds().intersects(arr3.getGlobalBounds()) or Objs2[i].getGlobalbounds().intersects(arr3.getGlobalBounds())) and item_s13 == true) { bt3.setPosition(arr3.getPosition().x, rand() % (150 - 40) + 40); item_s13 = false; Narr2.setPosition(eraseObj, eraseObj); } if (Compman.getGlobalbounds().intersects(bt3.getGlobalBounds())) { arr3.setPosition(eraseObj, eraseObj); bt3.setPosition(eraseObj, eraseObj); Darr1.setPosition(Compman.getPosition().x + 200.0f, 200.0f); Darr1.setRotation(45); D_Go.setPosition(Darr1.getPosition().x + 600.0f, arr_point+50.0f); } if (Compman.getGlobalbounds().intersects(D_Go.getGlobalBounds())) { Darr1.setPosition(eraseObj, eraseObj); hell.setPosition(D_Go.getPosition().x + 300.0f, arr_point+30.0f); } } if (Compman.getGlobalbounds().intersects(hell.getGlobalBounds())) { cout << "Go State 2" << endl; Game_State = 2; stage1.stop(); window.clear(); break; } if (Keyboard::isKeyPressed(Keyboard::End)) { hell.setPosition(sf::Vector2f(Compman.getPosition().x + 50.0f, Compman.getPosition().y - 30.0f)); } window.clear(sf::Color(255, 255, 255)); window.setView(view); window.draw(bt); window.draw(arr1); window.draw(Narr1); window.draw(arr2); window.draw(bt2); window.draw(Narr2); window.draw(arr3); window.draw(bt3); window.draw(Darr1); window.draw(D_Go); window.draw(Narr_is); Compman.Draw(window); for (ObjColli& Obj : Objs1) Obj.Draw(window); for (ObjColli& Obj : Objs2) Obj.Draw(window); for (ObjColli& Obj : Objs3) Obj.Draw(window); /*hitbox0.Draw(window); hitbox1.Draw(window);*/ window.draw(hell); text1.drawtext((float)abs(GameTime), (string)"Time : ", (string)" s", sf::Vector2f(view.getCenter().x + (window.getSize().x / 2) - 250, view.getCenter().y - (window.getSize().y / 2) + 20), window, sf::Color(255, 0, 0)); //text2.drawtext((int)abs(PointTime), (string)"Point : ", (string)"", sf::Vector2f(view.getCenter().x + (window.getSize().x / 2) - 200, view.getCenter().y - (window.getSize().y / 2) + 55), window, sf::Color(255, 150, 0)); window.display(); } } //--Stage 2--// if (Game_State == 2) { sf::View view(sf::Vector2f(1.0f, 1.0f), sf::Vector2f(VIEW_HEIGHT, VIEW_HEIGHT)); sf::Music stage2; stage2.openFromFile("Object/stage2.wav"); stage2.setVolume(50); stage2.setLoop(true); stage2.play(); sf::Texture Holl; Holl.loadFromFile("Object/Holl.png"); sf::Sprite hell(Holl); hell.setScale(1.2, 1.2); hell.setPosition(eraseObj, eraseObj); hell.setOrigin(hell.getScale().x / 2, hell.getScale().y / 2); //---------Item---------// Texture WFt; WFt.loadFromFile("Object/Item_stage2/1.png"); Sprite WFs; WFs.setTexture(WFt); WFs.setScale(1.2, 1.2); WFs.setPosition(eraseObj, eraseObj); WFs.setOrigin(WFs.getScale().x / 2, WFs.getScale().y / 2); Texture ELt; ELt.loadFromFile("Object/Item_stage2/2.png"); Sprite ELs; ELs.setTexture(ELt); ELs.setScale(1.2, 1.2); ELs.setPosition(eraseObj, eraseObj); ELs.setOrigin(ELs.getScale().x / 2, ELs.getScale().y / 2); Texture LKt; LKt.loadFromFile("Object/Item_stage2/3.png"); Sprite LKs; LKs.setTexture(LKt); LKs.setScale(1.2, 1.2); LKs.setPosition(eraseObj, eraseObj); LKs.setOrigin(LKs.getScale().x / 2, LKs.getScale().y / 2); Texture LCt; LCt.loadFromFile("Object/Item_stage2/4.png"); Sprite LCs; LCs.setTexture(LCt); LCs.setScale(1.2, 1.2); LCs.setPosition(eraseObj, eraseObj); LCs.setOrigin(LCs.getScale().x / 2, LCs.getScale().y / 2); //-------------------------------------------------------------------- //--Arrow point Item--// Texture ArrR; ArrR.loadFromFile("Object/ArrRed.png"); Sprite ArrR_i1; ArrR_i1.setTexture(ArrR); ArrR_i1.setScale(0.9, 0.9); ArrR_i1.setPosition(3900.0f, arr_point2); ArrR_i1.setOrigin(ArrR_i1.getScale().x / 2, ArrR_i1.getScale().y / 2); Sprite ArrR_i2; ArrR_i2.setTexture(ArrR); ArrR_i2.setScale(0.9, 0.9); ArrR_i2.setPosition(eraseObj, eraseObj); ArrR_i2.setOrigin(ArrR_i2.getScale().x / 2, ArrR_i2.getScale().y / 2); Sprite ArrR_i3; ArrR_i3.setTexture(ArrR); ArrR_i3.setScale(0.9, 0.9); ArrR_i3.setPosition(eraseObj, eraseObj); ArrR_i3.setOrigin(ArrR_i3.getScale().x / 2, ArrR_i3.getScale().y / 2); Sprite ArrR_i4; ArrR_i4.setTexture(ArrR); ArrR_i4.setScale(0.9, 0.9); ArrR_i4.setPosition(eraseObj, eraseObj); ArrR_i4.setOrigin(ArrR_i4.getScale().x / 2, ArrR_i4.getScale().y / 2); //------------------------------------------------------------------------ //----Arrow guide Item----// Texture Narr_s; Narr_s.loadFromFile("Object/NArrS2.png"); Sprite Narr_is; Narr_is.setTexture(Narr_s); Narr_is.setScale(1.2, 1.2); Narr_is.setPosition(eraseObj, eraseObj); //Narr_i1.setRotation(135); Narr_is.setOrigin(Narr_is.getScale().x / 2, Narr_is.getScale().y / 2); Narr_is.setPosition(ArrR_i1.getPosition().x + 200.f, arr_point2); Texture Narr; Narr.loadFromFile("Object/NArrRed.png"); Sprite Narr_i1; Narr_i1.setTexture(Narr); Narr_i1.setScale(1.2, 1.2); Narr_i1.setPosition(eraseObj, eraseObj); //Narr_i1.setRotation(135); Narr_i1.setOrigin(Narr_i1.getScale().x / 2, Narr_i1.getScale().y / 2); Texture Narr2; Narr2.loadFromFile("Object/NArrRed2.png"); Sprite Narr_i2; Narr_i2.setTexture(Narr); Narr_i2.setScale(1.2, 1.2); Narr_i2.setPosition(eraseObj, eraseObj); //Narr_i2.setRotation(45); Narr_i2.setOrigin(Narr_i2.getScale().x / 2, Narr_i2.getScale().y / 2); Sprite Narr_i3; Narr_i3.setTexture(Narr2); Narr_i3.setScale(1.2, 1.2); Narr_i3.setPosition(eraseObj, eraseObj); //Narr_i3.setRotation(135); Narr_i3.setOrigin(Narr_i3.getScale().x / 2, Narr_i3.getScale().y / 2); Texture Darr_1; Darr_1.loadFromFile("Object/DoorArr.png"); Sprite Darr1; Darr1.setTexture(Darr_1); Darr1.setScale(1.2, 1.2); Darr1.setPosition(eraseObj, eraseObj); //Darr1.setRotation(45); Darr1.setOrigin(Darr1.getScale().x / 2, Darr1.getScale().y / 2); Texture DGo; DGo.loadFromFile("Object/DoorArrGo.png"); Sprite D_Go; D_Go.setTexture(DGo); D_Go.setScale(1.2, 1.2); D_Go.setPosition(eraseObj, eraseObj); D_Go.setOrigin(D_Go.getScale().x / 2, D_Go.getScale().y / 2); //***BoxStage**// sf::Texture box12; box12.loadFromFile("Object/box23.png"); std::vector<ObjColli>Objs12; Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 2, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 3, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 4, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 5, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 6, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 7, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 8, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 9, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 10, 770.0f))); Objs12.push_back(ObjColli(&box12, sf::Vector2f(boxes2, boxes2_2), sf::Vector2f(0.0f + boxes2 * 11, 770.0f))); //----box--pick----// sf::Texture box22; box22.loadFromFile("Object/box3.png"); std::vector<ObjColli>Objs22; for (size_t i = 0;i <= 30;i++) { Objs22.push_back(ObjColli(&box22, sf::Vector2f(54.0f, 54.0f), sf::Vector2f(rand() % (4300 - 1200) + 1200, 400.0f))); } //---Limit Stage---// sf::Texture box32; std::vector<ObjColli>Objs32; Objs32.push_back(ObjColli(&box32, sf::Vector2f(2.0f, 5000.0f), sf::Vector2f(-268.0f, 724.f))); Objs32.push_back(ObjColli(&box32, sf::Vector2f(2.0f, 5000.0f), sf::Vector2f(5890.f, 724.f))); //----hitboxtest----// hitboxtest hitbox0(0, 0, Vector2f(54, Objs22[0].GetSize().x), Objs22[0].GetPosition()); hitboxtest hitbox1(0, 0, Vector2f(50, Compman.GetSize().x), Compman.GetPosition()); TextFont text1; TextFont text2; bool item_s21 = true; bool item_s22 = true; bool item_s23 = true; bool item_s24 = true; sf::Clock clock; float timeElasped = 0; float PointTime = 100; while (window.isOpen()) { timeElasped += deltaTime; deltaTime = clock.restart().asSeconds(); if (deltaTime > 1.0f / 20.0f) deltaTime = 1.0f / 20.0f; /*if (GameTime > 0)*/ /*if (GameTime <= 0)*/ GameTime += deltaTime; /*PointTime -= deltaTime;*/ /*if (PointTime <= 0) PointTime = 0;*/ sf::Event event; if (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: ResizeView(window, view); break; case sf::Event::MouseButtonPressed: cout << "Mouse button has been pressed" << endl; switch (event.key.code) { case sf::Mouse::Left: cout << "LEFT KEY has been pressed" << endl; break; } break; case sf::Event::MouseButtonReleased: cout << "Mouse button has been released" << endl; break; } //cout << "Position x : " << Compman.getPosition().x << "\n" << "Position y : " << Compman.getPosition().y << "\n" << endl; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { stage2.stop(); } } spacebartimer += 1; Compman.Update(deltaTime); sf::Vector2f direction; //--Collider_Update--// Collider c = Compman.GetCollider(); for (ObjColli& Obj : Objs12) { Collider O = Obj.GetCollider(); if (Obj.GetCollider().CheckCollision(c, direction, 1.0f)) { Compman.OnCollision(direction); } for (ObjColli& Obj22 : Objs22) { if (Obj22.GetCollider().CheckCollision(O, direction, 0.0f)) { Obj22.Oncollision(direction); } } } //---Hold_Obj---// for (int i = 0;i < Objs22.size();i++) { Objs22[i].Update(deltaTime, Compman.getPosition()); if (Objs22[i].GetCollider().CheckCollision(c, direction, 0.0f)) { if (Objs22[i].getPickObj() == false) { Compman.OnCollision(direction); //cout << "Collision" << endl; } if ((Keyboard::isKeyPressed(Keyboard::Space)) && spacebartimer >= max_spacebartimer && Compman.getHold() == false && Objs22[i].getPickObj() == false /*&& Compman.getPosition().y >= Objs2[i].getbody().getPosition().y - 20 && Compman.getPosition().y <= Objs2[i].getbody().getPosition().y + 20*/) { spacebartimer = 0; Objs22[i].setPickObj(true); Compman.setHold(true); } if (Objs22[i].getPickObj() == true && (Keyboard::isKeyPressed(Keyboard::Space)) && spacebartimer >= max_spacebartimer && Compman.getcanJump() == false) { spacebartimer = 0; Objs22[i].getbody().setPosition(Compman.getPosition().x, Compman.getPosition().y + 60); Compman.setHold(false); Objs22[i].setPickObj(false); } } Collider o = Objs22[i].GetCollider(); for (int j = 0; j < Objs22.size();j++) { if (i != j) { if (Objs22[j].GetCollider().CheckCollision(o, direction, 1.0f)) { Objs22[i].Oncollision(direction); } } } } for (ObjColli& Obj : Objs32) { Collider b = Obj.GetCollider(); if (Obj.GetCollider().CheckCollision(c, direction, 1.0f)) { Compman.OnCollision(direction); } for (ObjColli& Obj2 : Objs32) { if (Obj2.GetCollider().CheckCollision(b, direction, 0.0f)) { Obj2.Oncollision(direction); } } } //--hitboxtest_Update--// hitbox1.Update(-21.5, -35.5, Compman.GetPosition()); hitbox0.Update(-27, -27, Objs22[0].GetPosition()); //----------Set_View----------// view.setCenter(Compman.GetPosition().x, Compman.GetPosition().y); if (view.getCenter().x - 195.0f <= 0.0f) { if (view.getCenter().y - 450.0f <= 0.0f) { view.setCenter(195.f, Compman.GetPosition().y); } if (view.getCenter().y + 450.0f >= 900.0f) { view.setCenter(195.f, Compman.GetPosition().y); } if (view.getCenter().y - 450.0f > 0.0f && view.getCenter().y + 450.0f < 900.0f) { view.setCenter(195.f, Compman.GetPosition().y); } } if (view.getCenter().x + 415.0f >= 5850.f) { if (view.getCenter().y - 450.0f <= 0.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } if (view.getCenter().y + 450.0f >= 900.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } if (view.getCenter().y - 450.0f > 0.0f && view.getCenter().y + 450.0f < 900.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } } //cout << view.getCenter().x << "\t" << view.getCenter().y << endl ; for (size_t i = 0;i < Objs22.size(); i++) { if ((Objs22[i].getGlobalbounds().intersects(ArrR_i1.getGlobalBounds()) or Compman.getGlobalbounds().intersects(ArrR_i1.getGlobalBounds())) and item_s21 == true) { WFs.setPosition(ArrR_i1.getPosition().x, rand() % (50 - 10) + 10); item_s21 = false; } if (Compman.getGlobalbounds().intersects(WFs.getGlobalBounds())) { Narr_is.setPosition(eraseObj, eraseObj); ArrR_i1.setPosition(eraseObj, eraseObj); WFs.setPosition(eraseObj, eraseObj); Narr_i1.setPosition(Compman.getPosition().x - 200.0f, 100.0f); Narr_i1.setRotation(135); ArrR_i2.setPosition(Narr_i1.getPosition().x - 900.0f, arr_point2); cout << ArrR_i2.getPosition().x << endl; } if ((Compman.getGlobalbounds().intersects(ArrR_i2.getGlobalBounds()) or Objs22[i].getGlobalbounds().intersects(ArrR_i2.getGlobalBounds())) and item_s22 == true) { LKs.setPosition(ArrR_i2.getPosition().x, rand() % (50 - 10) + 10); item_s22 = false; } if (Compman.getGlobalbounds().intersects(LKs.getGlobalBounds())) { Narr_i1.setPosition(eraseObj, eraseObj); ArrR_i2.setPosition(eraseObj, eraseObj); LKs.setPosition(eraseObj, eraseObj); Narr_i2.setPosition(Compman.getPosition().x - 200.0f, 100.0f); Narr_i2.setRotation(135); ArrR_i3.setPosition(Narr_i2.getPosition().x - (900.0f * 2), arr_point2); } if ((Compman.getGlobalbounds().intersects(ArrR_i3.getGlobalBounds()) or Objs22[i].getGlobalbounds().intersects(ArrR_i3.getGlobalBounds())) and item_s23 == true) { LCs.setPosition(ArrR_i3.getPosition().x, rand() % (50 - 10) + 10); item_s23 = false; } if (Compman.getGlobalbounds().intersects(LCs.getGlobalBounds())) { Narr_i2.setPosition(eraseObj, eraseObj); ArrR_i3.setPosition(eraseObj, eraseObj); LCs.setPosition(eraseObj, eraseObj); Narr_i3.setPosition(Compman.getPosition().x + 200.0f, 100.0f); Narr_i3.setRotation(45); ArrR_i4.setPosition(Narr_i3.getPosition().x + (900.0f *2), arr_point2); } if ((Compman.getGlobalbounds().intersects(ArrR_i4.getGlobalBounds()) or Objs22[i].getGlobalbounds().intersects(ArrR_i4.getGlobalBounds())) and item_s24 == true) { ELs.setPosition(ArrR_i4.getPosition().x, rand() % (60 - 20) + 20); item_s24 = false; } if (Compman.getGlobalbounds().intersects(ELs.getGlobalBounds())) { Narr_i3.setPosition(eraseObj, eraseObj); ArrR_i4.setPosition(eraseObj, eraseObj); ELs.setPosition(eraseObj, eraseObj); Darr1.setPosition(Compman.getPosition().x + 200.0f, Compman.getPosition().y); cout << Darr1.getPosition().x << "\t" << Darr1.getPosition().y << endl; Darr1.setRotation(45); D_Go.setPosition(Darr1.getPosition().x + 600.0f, arr_point2 + 50.0f); } if (Compman.getGlobalbounds().intersects(D_Go.getGlobalBounds())) { Darr1.setPosition(eraseObj, eraseObj); hell.setPosition(D_Go.getPosition().x + 300.0f, arr_point2 + 30.0f); } } if (Keyboard::isKeyPressed(Keyboard::End)) { hell.setPosition(sf::Vector2f(Compman.getPosition().x + 50.0f, Compman.getPosition().y - 30.0f)); } if (Compman.getGlobalbounds().intersects(hell.getGlobalBounds())) { cout << "Go State 3" << endl; Game_State = 3; stage2.stop(); window.clear(); break; } window.clear(sf::Color(255, 255, 255)); //--DrawEverythings--// window.setView(view); window.draw(WFs); window.draw(LKs); window.draw(LCs); window.draw(ELs); window.draw(ArrR_i1); window.draw(ArrR_i2); window.draw(ArrR_i3); window.draw(ArrR_i4); window.draw(Narr_i1); window.draw(Narr_i2); window.draw(Narr_i3); window.draw(Darr1); window.draw(D_Go); window.draw(Narr_is); Compman.Draw(window); for (ObjColli& Obj : Objs12) Obj.Draw(window); for (ObjColli& Obj : Objs22) Obj.Draw(window); for (ObjColli& Obj : Objs32) Obj.Draw(window); window.draw(hell); text1.drawtext((float)abs(GameTime), (string)"Time : ", (string)" s", sf::Vector2f(view.getCenter().x + (window.getSize().x / 2) - 250, view.getCenter().y - (window.getSize().y / 2) + 20), window, sf::Color(255, 0, 0)); window.display(); } } ////--Stage 3--// if (Game_State == 3) { sf::View view(sf::Vector2f(1.0f, 1.0f), sf::Vector2f(VIEW_HEIGHT, VIEW_HEIGHT)); sf::Music stage3; stage3.openFromFile("Object/stage3.wav"); stage3.setVolume(50); stage3.setLoop(true); stage3.play(); sf::Texture Holl; Holl.loadFromFile("Object/Holl.png"); sf::Sprite hell(Holl); hell.setScale(1.2, 1.2); hell.setPosition(eraseObj, eraseObj); hell.setOrigin(hell.getScale().x / 2, hell.getScale().y / 2); Texture Gt; Gt.loadFromFile("Object/Item_stage3/1.png"); Sprite Gs; Gs.setTexture(Gt); Gs.setScale(0.7, 0.7); Gs.setPosition(eraseObj, eraseObj); Gs.setOrigin(Gs.getScale().x / 2, Gs.getScale().y / 2); Texture ArrR; ArrR.loadFromFile("Object/ArrRed.png"); Sprite ArrR_i1; ArrR_i1.setTexture(ArrR); ArrR_i1.setScale(0.9, 0.9); ArrR_i1.setPosition(2400.0f, arr_point2); ArrR_i1.setOrigin(ArrR_i1.getScale().x / 2, ArrR_i1.getScale().y / 2); Texture Narr_s; Narr_s.loadFromFile("Object/NArrS.png"); Sprite Narr_is; Narr_is.setTexture(Narr_s); Narr_is.setScale(1.2, 1.2); Narr_is.setPosition(eraseObj, eraseObj); //Narr_i1.setRotation(135); Narr_is.setOrigin(Narr_is.getScale().x / 2, Narr_is.getScale().y / 2); Narr_is.setPosition(ArrR_i1.getPosition().x - 200.f, arr_point2); Texture Darr_1; Darr_1.loadFromFile("Object/DoorArr.png"); Sprite Darr1; Darr1.setTexture(Darr_1); Darr1.setScale(1.2, 1.2); Darr1.setPosition(eraseObj, eraseObj); //Darr1.setRotation(45); Darr1.setOrigin(Darr1.getScale().x / 2, Darr1.getScale().y / 2); Texture DGo; DGo.loadFromFile("Object/DoorArrGo.png"); Sprite D_Go; D_Go.setTexture(DGo); D_Go.setScale(1.2, 1.2); D_Go.setPosition(eraseObj, eraseObj); D_Go.setOrigin(D_Go.getScale().x / 2, D_Go.getScale().y / 2); bool item_s31 = true; //***BoxStage**// sf::Texture box31; box31.loadFromFile("Object/Christmas_box.png"); std::vector<ObjColli>Objs12; Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 2, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 3, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 4, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 5, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 6, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 7, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 8, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 9, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 10, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 11, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 12, 1000-192.0f))); Objs12.push_back(ObjColli(&box31, sf::Vector2f(boxes3, boxes3_3), sf::Vector2f(0.0f + boxes3 * 13, 1000-192.0f))); //----box--pick----// sf::Texture box32; box32.loadFromFile("Object/Christbox_pick.png"); std::vector<ObjColli>Objs32; for (size_t i = 0;i <= 40;i++) { Objs32.push_back(ObjColli(&box32, sf::Vector2f(54.0f, 54.0f), sf::Vector2f(rand() % (5000 - 1000) + 1000, 400.0f))); } //---Limit Stage---// sf::Texture box33; std::vector<ObjColli>Objs33; Objs33.push_back(ObjColli(&box33, sf::Vector2f(2.0f, 5000.0f), sf::Vector2f(-268.0f, 724.f))); Objs33.push_back(ObjColli(&box33, sf::Vector2f(2.0f, 5000.0f), sf::Vector2f(5890.f, 724.f))); //----hitboxtest----// hitboxtest hitbox0(0, 0, Vector2f(54, Objs32[0].GetSize().x), Objs32[0].GetPosition()); hitboxtest hitbox1(0, 0, Vector2f(50, Compman.GetSize().x), Compman.GetPosition()); TextFont text1; TextFont text2; sf::Clock clock; float timeElasped = 0; float PointTime = 100; while (window.isOpen()) { timeElasped += deltaTime; deltaTime = clock.restart().asSeconds(); if (deltaTime > 1.0f / 20.0f) deltaTime = 1.0f / 20.0f; /*if (GameTime > 0)*/ /*if (GameTime <= 0)*/ GameTime += deltaTime; /*PointTime -= deltaTime;*/ /*if (PointTime <= 0) PointTime = 0;*/ sf::Event event; if (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: ResizeView(window, view); break; case sf::Event::MouseButtonPressed: cout << "Mouse button has been pressed" << endl; switch (event.key.code) { case sf::Mouse::Left: cout << "LEFT KEY has been pressed" << endl; break; } break; case sf::Event::MouseButtonReleased: cout << "Mouse button has been released" << endl; break; } //cout << "Position x : " << Compman.getPosition().x << "\n" << "Position y : " << Compman.getPosition().y << "\n" << endl; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { stage3.stop(); } } spacebartimer += 1; Compman.Update(deltaTime); sf::Vector2f direction; //--Collider_Update--// Collider c = Compman.GetCollider(); for (ObjColli& Obj : Objs12) { Collider O = Obj.GetCollider(); if (Obj.GetCollider().CheckCollision(c, direction, 1.0f)) { Compman.OnCollision(direction); } for (ObjColli& Obj32 : Objs32) { if (Obj32.GetCollider().CheckCollision(O, direction, 0.0f)) { Obj32.Oncollision(direction); } } } //---Hold_Obj---// for (int i = 0;i < Objs32.size();i++) { Objs32[i].Update(deltaTime, Compman.getPosition()); if (Objs32[i].GetCollider().CheckCollision(c, direction, 0.0f)) { if (Objs32[i].getPickObj() == false) { Compman.OnCollision(direction); //cout << "Collision" << endl; } if ((Keyboard::isKeyPressed(Keyboard::Space)) && spacebartimer >= max_spacebartimer && Compman.getHold() == false && Objs32[i].getPickObj() == false /*&& Compman.getPosition().y >= Objs2[i].getbody().getPosition().y - 20 && Compman.getPosition().y <= Objs2[i].getbody().getPosition().y + 20*/) { spacebartimer = 0; Objs32[i].setPickObj(true); Compman.setHold(true); } if (Objs32[i].getPickObj() == true && (Keyboard::isKeyPressed(Keyboard::Space)) && spacebartimer >= max_spacebartimer && Compman.getcanJump() == false) { spacebartimer = 0; Objs32[i].getbody().setPosition(Compman.getPosition().x, Compman.getPosition().y + 60); Compman.setHold(false); Objs32[i].setPickObj(false); } } Collider o = Objs32[i].GetCollider(); for (int j = 0; j < Objs32.size();j++) { if (i != j) { if (Objs32[j].GetCollider().CheckCollision(o, direction, 1.0f)) { Objs32[i].Oncollision(direction); } } } } for (ObjColli& Obj : Objs33) { Collider b = Obj.GetCollider(); if (Obj.GetCollider().CheckCollision(c, direction, 1.0f)) { Compman.OnCollision(direction); } for (ObjColli& Obj2 : Objs33) { if (Obj2.GetCollider().CheckCollision(b, direction, 0.0f)) { Obj2.Oncollision(direction); } } } //--hitboxtest_Update--// hitbox1.Update(-21.5, -35.5, Compman.GetPosition()); hitbox0.Update(-27, -27, Objs32[0].GetPosition()); //----------Set_View----------// view.setCenter(Compman.GetPosition().x, Compman.GetPosition().y); if (view.getCenter().x - 195.0f <= 0.0f) { if (view.getCenter().y - 450.0f <= 0.0f) { view.setCenter(195.f, Compman.GetPosition().y); } if (view.getCenter().y + 450.0f >= 900.0f) { view.setCenter(195.f, Compman.GetPosition().y); } if (view.getCenter().y - 450.0f > 0.0f && view.getCenter().y + 450.0f < 900.0f) { view.setCenter(195.f, Compman.GetPosition().y); } } if (view.getCenter().x + 415.0f >= 5850.f) { if (view.getCenter().y - 450.0f <= 0.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } if (view.getCenter().y + 450.0f >= 900.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } if (view.getCenter().y - 450.0f > 0.0f && view.getCenter().y + 450.0f < 900.0f) { view.setCenter(5435.f, Compman.GetPosition().y); } } //cout << view.getCenter().x << "\t" << view.getCenter().y << endl ; for (size_t i = 0;i < Objs32.size(); i++) { if ((Objs32[i].getGlobalbounds().intersects(ArrR_i1.getGlobalBounds()) or Compman.getGlobalbounds().intersects(ArrR_i1.getGlobalBounds())) and item_s31 == true) { Gs.setPosition(ArrR_i1.getPosition().x, -100.0f); item_s31 = false; } if (Compman.getGlobalbounds().intersects(Gs.getGlobalBounds())) { Narr_is.setPosition(eraseObj, eraseObj); ArrR_i1.setPosition(eraseObj, eraseObj); Gs.setPosition(eraseObj, eraseObj); Darr1.setPosition(Compman.getPosition().x + 200.0f, Compman.getPosition().y); cout << Darr1.getPosition().x << "\t" << Darr1.getPosition().y << endl; Darr1.setRotation(45); D_Go.setPosition(Darr1.getPosition().x + 600.0f, arr_point2 + 50.0f); } if (Compman.getGlobalbounds().intersects(D_Go.getGlobalBounds())) { Darr1.setPosition(eraseObj, eraseObj); hell.setPosition(D_Go.getPosition().x + 300.0f, arr_point2 + 30.0f); } } if (Keyboard::isKeyPressed(Keyboard::End)) { hell.setPosition(sf::Vector2f(Compman.getPosition().x + 50.0f, Compman.getPosition().y - 30.0f)); } if (Compman.getGlobalbounds().intersects(hell.getGlobalBounds())) { Game_State = 5; stage3.stop(); window.clear(); break; } window.clear(sf::Color(255, 255, 255)); //--DrawEverythings--// window.setView(view); window.draw(Gs); window.draw(Narr_is); window.draw(ArrR_i1); window.draw(Darr1); window.draw(D_Go); Compman.Draw(window); for (ObjColli& Obj : Objs12) Obj.Draw(window); for (ObjColli& Obj : Objs32) Obj.Draw(window); for (ObjColli& Obj : Objs33) Obj.Draw(window); window.draw(hell); text1.drawtext((float)abs(GameTime), (string)"Time : ", (string)" s", sf::Vector2f(view.getCenter().x + (window.getSize().x / 2) - 250, view.getCenter().y - (window.getSize().y / 2) + 20), window, sf::Color(255, 0, 0)); window.display(); } } if (Game_State == 5) { //cout << "Stage 5"; sf::View view(sf::Vector2f(500.0f, 450.0f), sf::Vector2f(VIEW_HEIGHT, VIEW_HEIGHT)); sf::Clock deCLK = sf::Clock(); double debounce; string name1; String name; Text yourname; Texture Mapname; Mapname.loadFromFile("Object/StageName.png"); Sprite name_key; name_key.setTexture(Mapname); int Name_State = 0; double deTime = 0; bool enterinto = false; while (window.isOpen()) { deTime += deCLK.getElapsedTime().asSeconds(); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: cout << "Mouse button has been pressed" << endl; switch (event.key.code) { case sf::Mouse::Left: cout << "LEFT KEY has been pressed" << endl; break; } break; case sf::Event::MouseButtonReleased: cout << "Mouse button has been released" << endl; break; } if (event.type == sf::Event::TextEntered) { enterinto = true; if (event.text.unicode == '\b' && (name.getSize() > 0)) { name1.erase(name.getSize() - 1, 1); name.erase(name.getSize() - 1, 1); } else { if ((event.text.unicode < 128) && (name.getSize() < 10) && (event.text.unicode != '\b')) { name += static_cast<char>(event.text.unicode); name1 += static_cast<char>(event.text.unicode); } } yourname.setFont(font); yourname.setString(name); yourname.setFillColor(sf::Color(240,200,0)); yourname.setCharacterSize(60); yourname.setOrigin(yourname.getLocalBounds().width / 2, yourname.getLocalBounds().height / 2); yourname.setPosition(window.getSize().x/2, window.getSize().y/2 + 280); } if (Keyboard::isKeyPressed(Keyboard::Enter)) { window.close(); } } window.clear(Color(255,255,255)); window.setView(view); window.draw(name_key); window.draw(yourname); window.display(); } //cout << "Position x : " << Compman.getPosition().x << "\n" << "Position y : " << Compman.getPosition().y << "\n" << endl; //cout << "Go State Score"; ofstream highscore; highscore.open("HS.txt", ios::out | ios::app); highscore << "\n" << name1 << " " << GameTime; highscore.close(); } while (P_State == 1) { PauseMenu Pmenu(500.f, 500.f); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyReleased: switch (event.key.code) { case sf::Keyboard::Up: if (Pmenu.PselectedItem >= 0) { Pmenu.Moveup(); break; } case sf::Keyboard::Down: if (Pmenu.PselectedItem < PMax_Items) { Pmenu.Movedown(); break; } case sf::Keyboard::Return: switch (Pmenu.GetPressedItem()) { case 0: cout << "Resume has been pressed" << endl; //go to state Game_State = 1; checkGameOpen = true; break; case 1: cout << "Main Menu has been pressed" << endl; //go to state break; case 2: cout << "Quit has been pressed" << endl; window.close(); menums.stop(); break; } break; } break; case sf::Event::Closed: window.close(); break; } } window.clear(); Pmenu.draw(window); window.draw(pause_bg); window.display(); if (checkGameOpen == true) break; } return 0; }
#ifndef __GLUTIL_H__ #define __GLUTIL_H__ #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> //#define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <renderer/path.h> #include <math.h> #include <fstream> #include <iostream> #include <string> #include <time.h> #include <unordered_map> typedef float f32; typedef double f64; typedef char i8; typedef short int i16; typedef int i32; typedef long long i64; typedef std::unordered_map<std::string, i32> U_Tree; typedef unsigned char ui8; typedef unsigned short int ui16; typedef unsigned int ui32; typedef unsigned long long ui64; GLFWwindow* glutilInit(i32 major, i32 minor, i32 width, i32 height, const i8* title) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(width, height, title, nullptr, nullptr); if (window == nullptr) { std::cerr << "Failed to create GLFW Window\n"; glfwTerminate(); return nullptr; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cerr << "Not GLAD at all!\n"; return nullptr; } return window; } class Shader { ui32 pid; Path* path; i32 ok; // check for error status i8 infoLog[512]; // get error status info mutable U_Tree uniforms_cache; public: Shader(const std::string& shader_folder, std::string texture_folder="assets/textures/") : path(new Path(shader_folder, texture_folder)) { std::ifstream vertexFile(path->sp("shader.vert")); std::string vertexSrc; std::cout << "[VS] Compiling from " << path->sp("shader.vert") << "\n"; std::getline(vertexFile, vertexSrc, '\0'); std::cout << vertexSrc << "\n"; std::ifstream fragmentFile(path->sp("shader.frag")); std::string fragmentSrc; std::cout << "[FS] Compiling from " << path->sp("shader.frag") << "\n"; std::getline(fragmentFile, fragmentSrc, '\0'); std::cout << fragmentSrc << "\n"; ui32 vertex = mkShader(vertexSrc.c_str(), GL_VERTEX_SHADER); ui32 fragment = mkShader(fragmentSrc.c_str(), GL_FRAGMENT_SHADER); pid = glCreateProgram(); glAttachShader(pid, vertex); glAttachShader(pid, fragment); glLinkProgram(pid); glGetProgramiv(pid, GL_LINK_STATUS, &ok); if (!ok) { glGetProgramInfoLog(pid, 512, nullptr, infoLog); std::cout << "Error::shader::program::link_failed\n" << infoLog << std::endl; } glDeleteShader(vertex); glDeleteShader(fragment); } ~Shader() { glDeleteProgram(pid); } void useProgram() { glUseProgram(pid); } ui32 getProgram() { // might need to refactor this later ughhh return pid; } // retreive uniforms GLint selfGetUniformLocation(const i8* name) const { if(uniforms_cache.find(name) != uniforms_cache.end()) return uniforms_cache[name]; GLuint loc = glGetUniformLocation(pid, name); uniforms_cache[name] = loc; return loc; } // Set uniforms void setMat4(const i8* name, const glm::mat4& mat) const { glUniformMatrix4fv(selfGetUniformLocation(name), 1, GL_FALSE, &mat[0][0]); } void setFloat(const i8* name, const f32 f) const { glUniform1f(selfGetUniformLocation(name), f); } void setVec3(const i8* name, const glm::vec3& vec) const { glUniform3fv(selfGetUniformLocation(name), 1, &vec[0]); } void setVec3(const i8* name, f32 a, f32 b, f32 c) const { glUniform3f(selfGetUniformLocation(name), a, b, c); } // Texture loading ui32 loadTexture(const std::string& textureFile) { ui32 texture; std::string fileName = path->tp(textureFile); std::cout << " [LOADING TEXTURE FROM ] " << fileName << "\n"; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); i32 width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // porque en opgl el eje Y invertio ui8* data = stbi_load(fileName.c_str(), &width, &height, &nrChannels, 0); if (data != nullptr) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cerr << "Can't load texture\n"; } stbi_image_free(data); return texture; } std::string get_texture_path(const std::string& fn){ return path->tp(fn); } private: ui32 mkShader(const i8* source, GLenum type) { ui32 shader = glCreateShader(type); glShaderSource(shader, 1, &source, nullptr); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); if (!ok) { glGetShaderInfoLog(shader, 512, nullptr, infoLog); std::cerr << "Error::shader::compilation_failed\n" << infoLog << std::endl; return 0; } return shader; } }; #endif
//#include <fstream> //#include <sstream> #include <bcm2835.h> #include "mcp4921.h" //using namespace std; mcp4921::mcp4921() { bcm2835_init(); bcm2835_spi_begin(); bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_64); // ~ 4 MHz //bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_16); //bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_1024); bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default } mcp4921::~mcp4921() { bcm2835_spi_end(); bcm2835_close(); } void mcp4921::write(uint16_t value) { if(value>4095) value=4095; const uint16_t cmd = 0b0111 << 12; // I usually use 0b0011 << 12 //value |= 0b0011000000000000; value |= cmd; char buf[2]; buf[0] = value >>8; buf[1] = value & 0xff; bcm2835_spi_writenb(buf, 2); }
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> #include <memory> #include <valarray> using namespace std; void inorder(int root, const vector<int>& lch, const vector<int>& rch, vector<int>& in, const vector<int>& data, int& index) { if (root == -1) return; inorder(lch[root], lch, rch, in, data, index); in[root] = data[index++]; inorder(rch[root], lch, rch, in, data, index); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<int> lch(n, -1), rch(n, -1); for (int i = 0; i < n; i++) scanf("%d %d", &lch[i], &rch[i]); vector<int> data(n, 0), in(n, 0); for (int i = 0; i < n; i++) scanf("%d", &data[i]); sort(data.begin(), data.end()); int index = 0; inorder(0, lch, rch, in, data, index); queue<int> q; q.push(0); while (!q.empty()) { int t = q.front(); q.pop(); if (t != 0) printf(" "); printf("%d", in[t]); if (lch[t] != -1) q.push(lch[t]); if (rch[t] != -1) q.push(rch[t]); } return 0; }
// Created on: 1993-03-24 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Geom2d_BSplineCurve_HeaderFile #define _Geom2d_BSplineCurve_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Precision.hxx> #include <GeomAbs_BSplKnotDistribution.hxx> #include <GeomAbs_Shape.hxx> #include <Standard_Integer.hxx> #include <TColgp_HArray1OfPnt2d.hxx> #include <TColStd_HArray1OfReal.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <Geom2d_BoundedCurve.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColStd_Array1OfInteger.hxx> class gp_Pnt2d; class gp_Vec2d; class gp_Trsf2d; class Geom2d_Geometry; class Geom2d_BSplineCurve; DEFINE_STANDARD_HANDLE(Geom2d_BSplineCurve, Geom2d_BoundedCurve) //! Describes a BSpline curve. //! A BSpline curve can be: //! - uniform or non-uniform, //! - rational or non-rational, //! - periodic or non-periodic. //! A BSpline curve is defined by: //! - its degree; the degree for a //! Geom2d_BSplineCurve is limited to a value (25) //! which is defined and controlled by the system. This //! value is returned by the function MaxDegree; //! - its periodic or non-periodic nature; //! - a table of poles (also called control points), with //! their associated weights if the BSpline curve is //! rational. The poles of the curve are "control points" //! used to deform the curve. If the curve is //! non-periodic, the first pole is the start point of the //! curve, and the last pole is the end point of the //! curve. The segment, which joins the first pole to the //! second pole, is the tangent to the curve at its start //! point, and the segment, which joins the last pole to //! the second-from-last pole, is the tangent to the //! curve at its end point. If the curve is periodic, these //! geometric properties are not verified. It is more //! difficult to give a geometric signification to the //! weights but they are useful for providing exact //! representations of the arcs of a circle or ellipse. //! Moreover, if the weights of all the poles are equal, //! the curve has a polynomial equation; it is //! therefore a non-rational curve. //! - a table of knots with their multiplicities. For a //! Geom2d_BSplineCurve, the table of knots is an //! increasing sequence of reals without repetition; the //! multiplicities define the repetition of the knots. A //! BSpline curve is a piecewise polynomial or rational //! curve. The knots are the parameters of junction //! points between two pieces. The multiplicity //! Mult(i) of the knot Knot(i) of the BSpline //! curve is related to the degree of continuity of the //! curve at the knot Knot(i), which is equal to //! Degree - Mult(i) where Degree is the //! degree of the BSpline curve. //! If the knots are regularly spaced (i.e. the difference //! between two consecutive knots is a constant), three //! specific and frequently used cases of knot distribution //! can be identified: //! - "uniform" if all multiplicities are equal to 1, //! - "quasi-uniform" if all multiplicities are equal to 1, //! except the first and the last knot which have a //! multiplicity of Degree + 1, where Degree is //! the degree of the BSpline curve, //! - "Piecewise Bezier" if all multiplicities are equal to //! Degree except the first and last knot which have //! a multiplicity of Degree + 1, where Degree is //! the degree of the BSpline curve. A curve of this //! type is a concatenation of arcs of Bezier curves. //! If the BSpline curve is not periodic: //! - the bounds of the Poles and Weights tables are 1 //! and NbPoles, where NbPoles is the number of //! poles of the BSpline curve, //! - the bounds of the Knots and Multiplicities tables are //! 1 and NbKnots, where NbKnots is the number //! of knots of the BSpline curve. //! If the BSpline curve is periodic, and if there are k //! periodic knots and p periodic poles, the period is: //! period = Knot(k + 1) - Knot(1) //! and the poles and knots tables can be considered as //! infinite tables, such that: //! - Knot(i+k) = Knot(i) + period //! - Pole(i+p) = Pole(i) //! Note: data structures of a periodic BSpline curve are //! more complex than those of a non-periodic one. //! Warnings : //! In this class we consider that a weight value is zero if //! Weight <= Resolution from package gp. //! For two parametric values (or two knot values) U1, U2 we //! consider that U1 = U2 if Abs (U2 - U1) <= Epsilon (U1). //! For two weights values W1, W2 we consider that W1 = W2 if //! Abs (W2 - W1) <= Epsilon (W1). The method Epsilon is //! defined in the class Real from package Standard. //! //! References : //! . A survey of curve and surface methods in CADG Wolfgang BOHM //! CAGD 1 (1984) //! . On de Boor-like algorithms and blossoming Wolfgang BOEHM //! cagd 5 (1988) //! . Blossoming and knot insertion algorithms for B-spline curves //! Ronald N. GOLDMAN //! . Modelisation des surfaces en CAO, Henri GIAUME Peugeot SA //! . Curves and Surfaces for Computer Aided Geometric Design, //! a practical guide Gerald Farin class Geom2d_BSplineCurve : public Geom2d_BoundedCurve { public: //! Creates a non-rational B_spline curve on the //! basis <Knots, Multiplicities> of degree <Degree>. //! The following conditions must be verified. //! 0 < Degree <= MaxDegree. //! //! Knots.Length() == Mults.Length() >= 2 //! //! Knots(i) < Knots(i+1) (Knots are increasing) //! //! 1 <= Mults(i) <= Degree //! //! On a non periodic curve the first and last multiplicities //! may be Degree+1 (this is even recommended if you want the //! curve to start and finish on the first and last pole). //! //! On a periodic curve the first and the last multicities //! must be the same. //! //! on non-periodic curves //! //! Poles.Length() == Sum(Mults(i)) - Degree - 1 >= 2 //! //! on periodic curves //! //! Poles.Length() == Sum(Mults(i)) except the first or last Standard_EXPORT Geom2d_BSplineCurve(const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Multiplicities, const Standard_Integer Degree, const Standard_Boolean Periodic = Standard_False); //! Creates a rational B_spline curve on the basis //! <Knots, Multiplicities> of degree <Degree>. //! The following conditions must be verified. //! 0 < Degree <= MaxDegree. //! //! Knots.Length() == Mults.Length() >= 2 //! //! Knots(i) < Knots(i+1) (Knots are increasing) //! //! 1 <= Mults(i) <= Degree //! //! On a non periodic curve the first and last multiplicities //! may be Degree+1 (this is even recommended if you want the //! curve to start and finish on the first and last pole). //! //! On a periodic curve the first and the last multicities //! must be the same. //! //! on non-periodic curves //! //! Poles.Length() == Sum(Mults(i)) - Degree - 1 >= 2 //! //! on periodic curves //! //! Poles.Length() == Sum(Mults(i)) except the first or last Standard_EXPORT Geom2d_BSplineCurve(const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal& Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Multiplicities, const Standard_Integer Degree, const Standard_Boolean Periodic = Standard_False); //! Increases the degree of this BSpline curve to //! Degree. As a result, the poles, weights and //! multiplicities tables are modified; the knots table is //! not changed. Nothing is done if Degree is less than //! or equal to the current degree. //! Exceptions //! Standard_ConstructionError if Degree is greater than //! Geom2d_BSplineCurve::MaxDegree(). Standard_EXPORT void IncreaseDegree (const Standard_Integer Degree); //! Increases the multiplicity of the knot <Index> to //! <M>. //! //! If <M> is lower or equal to the current //! multiplicity nothing is done. If <M> is higher than //! the degree the degree is used. //! If <Index> is not in [FirstUKnotIndex, LastUKnotIndex] Standard_EXPORT void IncreaseMultiplicity (const Standard_Integer Index, const Standard_Integer M); //! Increases the multiplicities of the knots in //! [I1,I2] to <M>. //! //! For each knot if <M> is lower or equal to the //! current multiplicity nothing is done. If <M> is //! higher than the degree the degree is used. //! As a result, the poles and weights tables of this curve are modified. //! Warning //! It is forbidden to modify the multiplicity of the first or //! last knot of a non-periodic curve. Be careful as //! Geom2d does not protect against this. //! Exceptions //! Standard_OutOfRange if either Index, I1 or I2 is //! outside the bounds of the knots table. Standard_EXPORT void IncreaseMultiplicity (const Standard_Integer I1, const Standard_Integer I2, const Standard_Integer M); //! Increases by M the multiplicity of the knots of indexes //! I1 to I2 in the knots table of this BSpline curve. For //! each knot, the resulting multiplicity is limited to the //! degree of this curve. If M is negative, nothing is done. //! As a result, the poles and weights tables of this //! BSpline curve are modified. //! Warning //! It is forbidden to modify the multiplicity of the first or //! last knot of a non-periodic curve. Be careful as //! Geom2d does not protect against this. //! Exceptions //! Standard_OutOfRange if I1 or I2 is outside the //! bounds of the knots table. Standard_EXPORT void IncrementMultiplicity (const Standard_Integer I1, const Standard_Integer I2, const Standard_Integer M); //! Inserts a knot value in the sequence of knots. If //! <U> is an existing knot the multiplicity is //! increased by <M>. //! //! If U is not on the parameter range nothing is //! done. //! //! If the multiplicity is negative or null nothing is //! done. The new multiplicity is limited to the //! degree. //! //! The tolerance criterion for knots equality is //! the max of Epsilon(U) and ParametricTolerance. //! Warning //! - If U is less than the first parameter or greater than //! the last parameter of this BSpline curve, nothing is done. //! - If M is negative or null, nothing is done. //! - The multiplicity of a knot is limited to the degree of //! this BSpline curve. Standard_EXPORT void InsertKnot (const Standard_Real U, const Standard_Integer M = 1, const Standard_Real ParametricTolerance = 0.0); //! Inserts the values of the array Knots, with the //! respective multiplicities given by the array Mults, into //! the knots table of this BSpline curve. //! If a value of the array Knots is an existing knot, its multiplicity is: //! - increased by M, if Add is true, or //! - increased to M, if Add is false (default value). //! The tolerance criterion used for knot equality is the //! larger of the values ParametricTolerance (defaulted //! to 0.) and Standard_Real::Epsilon(U), //! where U is the current knot value. //! Warning //! - For a value of the array Knots which is less than //! the first parameter or greater than the last //! parameter of this BSpline curve, nothing is done. //! - For a value of the array Mults which is negative or //! null, nothing is done. //! - The multiplicity of a knot is limited to the degree of //! this BSpline curve. Standard_EXPORT void InsertKnots (const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const Standard_Real ParametricTolerance = 0.0, const Standard_Boolean Add = Standard_False); //! Reduces the multiplicity of the knot of index Index //! to M. If M is equal to 0, the knot is removed. //! With a modification of this type, the array of poles is also modified. //! Two different algorithms are systematically used to //! compute the new poles of the curve. If, for each //! pole, the distance between the pole calculated //! using the first algorithm and the same pole //! calculated using the second algorithm, is less than //! Tolerance, this ensures that the curve is not //! modified by more than Tolerance. Under these //! conditions, true is returned; otherwise, false is returned. //! A low tolerance is used to prevent modification of //! the curve. A high tolerance is used to "smooth" the curve. //! Exceptions //! Standard_OutOfRange if Index is outside the //! bounds of the knots table. Standard_EXPORT Standard_Boolean RemoveKnot (const Standard_Integer Index, const Standard_Integer M, const Standard_Real Tolerance); //! The new pole is inserted after the pole of range Index. //! If the curve was non rational it can become rational. //! //! Raised if the B-spline is NonUniform or PiecewiseBezier or if //! Weight <= 0.0 //! Raised if Index is not in the range [1, Number of Poles] Standard_EXPORT void InsertPoleAfter (const Standard_Integer Index, const gp_Pnt2d& P, const Standard_Real Weight = 1.0); //! The new pole is inserted before the pole of range Index. //! If the curve was non rational it can become rational. //! //! Raised if the B-spline is NonUniform or PiecewiseBezier or if //! Weight <= 0.0 //! Raised if Index is not in the range [1, Number of Poles] Standard_EXPORT void InsertPoleBefore (const Standard_Integer Index, const gp_Pnt2d& P, const Standard_Real Weight = 1.0); //! Removes the pole of range Index //! If the curve was rational it can become non rational. //! //! Raised if the B-spline is NonUniform or PiecewiseBezier. //! Raised if the number of poles of the B-spline curve is lower or //! equal to 2 before removing. //! Raised if Index is not in the range [1, Number of Poles] Standard_EXPORT void RemovePole (const Standard_Integer Index); //! Reverses the orientation of this BSpline curve. As a result //! - the knots and poles tables are modified; //! - the start point of the initial curve becomes the end //! point of the reversed curve; //! - the end point of the initial curve becomes the start //! point of the reversed curve. Standard_EXPORT void Reverse() Standard_OVERRIDE; //! Computes the parameter on the reversed curve for //! the point of parameter U on this BSpline curve. //! The returned value is: UFirst + ULast - U, //! where UFirst and ULast are the values of the //! first and last parameters of this BSpline curve. Standard_EXPORT Standard_Real ReversedParameter (const Standard_Real U) const Standard_OVERRIDE; //! Modifies this BSpline curve by segmenting it //! between U1 and U2. Either of these values can be //! outside the bounds of the curve, but U2 must be greater than U1. //! All data structure tables of this BSpline curve are //! modified, but the knots located between U1 and U2 //! are retained. The degree of the curve is not modified. //! //! Parameter theTolerance defines the possible proximity of the segment //! boundaries and B-spline knots to treat them as equal. //! //! Warnings : //! Even if <me> is not closed it can become closed after the //! segmentation for example if U1 or U2 are out of the bounds //! of the curve <me> or if the curve makes loop. //! After the segmentation the length of a curve can be null. //! - The segmentation of a periodic curve over an //! interval corresponding to its period generates a //! non-periodic curve with equivalent geometry. //! Exceptions //! Standard_DomainError if U2 is less than U1. //! raises if U2 < U1. //! Standard_DomainError if U2 - U1 exceeds the period for periodic curves. //! i.e. ((U2 - U1) - Period) > Precision::PConfusion(). Standard_EXPORT void Segment (const Standard_Real U1, const Standard_Real U2, const Standard_Real theTolerance = Precision::PConfusion()); //! Modifies this BSpline curve by assigning the value K //! to the knot of index Index in the knots table. This is a //! relatively local modification because K must be such that: //! Knots(Index - 1) < K < Knots(Index + 1) //! Exceptions //! Standard_ConstructionError if: //! - K is not such that: //! Knots(Index - 1) < K < Knots(Index + 1) //! - M is greater than the degree of this BSpline curve //! or lower than the previous multiplicity of knot of //! index Index in the knots table. //! Standard_OutOfRange if Index is outside the bounds of the knots table. Standard_EXPORT void SetKnot (const Standard_Integer Index, const Standard_Real K); //! Modifies this BSpline curve by assigning the array //! K to its knots table. The multiplicity of the knots is not modified. //! Exceptions //! Standard_ConstructionError if the values in the //! array K are not in ascending order. //! Standard_OutOfRange if the bounds of the array //! K are not respectively 1 and the number of knots of this BSpline curve. Standard_EXPORT void SetKnots (const TColStd_Array1OfReal& K); //! Modifies this BSpline curve by assigning the value K //! to the knot of index Index in the knots table. This is a //! relatively local modification because K must be such that: //! Knots(Index - 1) < K < Knots(Index + 1) //! The second syntax allows you also to increase the //! multiplicity of the knot to M (but it is not possible to //! decrease the multiplicity of the knot with this function). //! Exceptions //! Standard_ConstructionError if: //! - K is not such that: //! Knots(Index - 1) < K < Knots(Index + 1) //! - M is greater than the degree of this BSpline curve //! or lower than the previous multiplicity of knot of //! index Index in the knots table. //! Standard_OutOfRange if Index is outside the bounds of the knots table. Standard_EXPORT void SetKnot (const Standard_Integer Index, const Standard_Real K, const Standard_Integer M); //! Computes the parameter normalized within the //! "first" period of this BSpline curve, if it is periodic: //! the returned value is in the range Param1 and //! Param1 + Period, where: //! - Param1 is the "first parameter", and //! - Period the period of this BSpline curve. //! Note: If this curve is not periodic, U is not modified. Standard_EXPORT void PeriodicNormalization (Standard_Real& U) const; //! Changes this BSpline curve into a periodic curve. //! To become periodic, the curve must first be closed. //! Next, the knot sequence must be periodic. For this, //! FirstUKnotIndex and LastUKnotIndex are used to //! compute I1 and I2, the indexes in the knots array //! of the knots corresponding to the first and last //! parameters of this BSpline curve. //! The period is therefore Knot(I2) - Knot(I1). //! Consequently, the knots and poles tables are modified. //! Exceptions //! Standard_ConstructionError if this BSpline curve is not closed. Standard_EXPORT void SetPeriodic(); //! Assigns the knot of index Index in the knots table as //! the origin of this periodic BSpline curve. As a //! consequence, the knots and poles tables are modified. //! Exceptions //! Standard_NoSuchObject if this curve is not periodic. //! Standard_DomainError if Index is outside the //! bounds of the knots table. Standard_EXPORT void SetOrigin (const Standard_Integer Index); //! Changes this BSpline curve into a non-periodic //! curve. If this curve is already non-periodic, it is not modified. //! Note that the poles and knots tables are modified. //! Warning //! If this curve is periodic, as the multiplicity of the first //! and last knots is not modified, and is not equal to //! Degree + 1, where Degree is the degree of //! this BSpline curve, the start and end points of the //! curve are not its first and last poles. Standard_EXPORT void SetNotPeriodic(); //! Modifies this BSpline curve by assigning P to the //! pole of index Index in the poles table. //! Exceptions //! Standard_OutOfRange if Index is outside the //! bounds of the poles table. //! Standard_ConstructionError if Weight is negative or null. Standard_EXPORT void SetPole (const Standard_Integer Index, const gp_Pnt2d& P); //! Modifies this BSpline curve by assigning P to the //! pole of index Index in the poles table. //! The second syntax also allows you to modify the //! weight of the modified pole, which becomes Weight. //! In this case, if this BSpline curve is non-rational, it //! can become rational and vice versa. //! Exceptions //! Standard_OutOfRange if Index is outside the //! bounds of the poles table. //! Standard_ConstructionError if Weight is negative or null. Standard_EXPORT void SetPole (const Standard_Integer Index, const gp_Pnt2d& P, const Standard_Real Weight); //! Assigns the weight Weight to the pole of index Index of the poles table. //! If the curve was non rational it can become rational. //! If the curve was rational it can become non rational. //! Exceptions //! Standard_OutOfRange if Index is outside the //! bounds of the poles table. //! Standard_ConstructionError if Weight is negative or null. Standard_EXPORT void SetWeight (const Standard_Integer Index, const Standard_Real Weight); //! Moves the point of parameter U of this BSpline //! curve to P. Index1 and Index2 are the indexes in the //! table of poles of this BSpline curve of the first and //! last poles designated to be moved. //! FirstModifiedPole and LastModifiedPole are the //! indexes of the first and last poles, which are //! effectively modified. //! In the event of incompatibility between Index1, //! Index2 and the value U: //! - no change is made to this BSpline curve, and //! - the FirstModifiedPole and LastModifiedPole are returned null. //! Exceptions //! Standard_OutOfRange if: //! - Index1 is greater than or equal to Index2, or //! - Index1 or Index2 is less than 1 or greater than the //! number of poles of this BSpline curve. Standard_EXPORT void MovePoint (const Standard_Real U, const gp_Pnt2d& P, const Standard_Integer Index1, const Standard_Integer Index2, Standard_Integer& FirstModifiedPole, Standard_Integer& LastModifiedPole); //! Move a point with parameter U to P. //! and makes it tangent at U be Tangent. //! StartingCondition = -1 means first can move //! EndingCondition = -1 means last point can move //! StartingCondition = 0 means the first point cannot move //! EndingCondition = 0 means the last point cannot move //! StartingCondition = 1 means the first point and tangent cannot move //! EndingCondition = 1 means the last point and tangent cannot move //! and so forth //! ErrorStatus != 0 means that there are not enough degree of freedom //! with the constrain to deform the curve accordingly Standard_EXPORT void MovePointAndTangent (const Standard_Real U, const gp_Pnt2d& P, const gp_Vec2d& Tangent, const Standard_Real Tolerance, const Standard_Integer StartingCondition, const Standard_Integer EndingCondition, Standard_Integer& ErrorStatus); //! Returns true if the degree of continuity of this //! BSpline curve is at least N. A BSpline curve is at least GeomAbs_C0. //! Exceptions Standard_RangeError if N is negative. Standard_EXPORT Standard_Boolean IsCN (const Standard_Integer N) const Standard_OVERRIDE; //! Check if curve has at least G1 continuity in interval [theTf, theTl] //! Returns true if IsCN(1) //! or //! angle between "left" and "right" first derivatives at //! knots with C0 continuity is less then theAngTol //! only knots in interval [theTf, theTl] is checked Standard_EXPORT Standard_Boolean IsG1 (const Standard_Real theTf, const Standard_Real theTl, const Standard_Real theAngTol) const; //! Returns true if the distance between the first point and the //! last point of the curve is lower or equal to Resolution //! from package gp. //! Warnings : //! The first and the last point can be different from the first //! pole and the last pole of the curve. Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE; //! Returns True if the curve is periodic. Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE; //! Returns True if the weights are not identical. //! The tolerance criterion is Epsilon of the class Real. Standard_EXPORT Standard_Boolean IsRational() const; //! Returns the global continuity of the curve : //! C0 : only geometric continuity, //! C1 : continuity of the first derivative all along the Curve, //! C2 : continuity of the second derivative all along the Curve, //! C3 : continuity of the third derivative all along the Curve, //! CN : the order of continuity is infinite. //! For a B-spline curve of degree d if a knot Ui has a //! multiplicity p the B-spline curve is only Cd-p continuous //! at Ui. So the global continuity of the curve can't be greater //! than Cd-p where p is the maximum multiplicity of the interior //! Knots. In the interior of a knot span the curve is infinitely //! continuously differentiable. Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE; //! Returns the degree of this BSpline curve. //! In this class the degree of the basis normalized B-spline //! functions cannot be greater than "MaxDegree" //! Computation of value and derivatives Standard_EXPORT Standard_Integer Degree() const; Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt2d& P) const Standard_OVERRIDE; //! Raised if the continuity of the curve is not C1. Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1) const Standard_OVERRIDE; //! Raised if the continuity of the curve is not C2. Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2) const Standard_OVERRIDE; //! For this BSpline curve, computes //! - the point P of parameter U, or //! - the point P and one or more of the following values: //! - V1, the first derivative vector, //! - V2, the second derivative vector, //! - V3, the third derivative vector. //! Warning //! On a point where the continuity of the curve is not the //! one requested, these functions impact the part //! defined by the parameter with a value greater than U, //! i.e. the part of the curve to the "right" of the singularity. //! Raises UndefinedDerivative if the continuity of the curve is not C3. Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const Standard_OVERRIDE; //! For the point of parameter U of this BSpline curve, //! computes the vector corresponding to the Nth derivative. //! Warning //! On a point where the continuity of the curve is not the //! one requested, this function impacts the part defined //! by the parameter with a value greater than U, i.e. the //! part of the curve to the "right" of the singularity. //! Raises UndefinedDerivative if the continuity of the curve is not CN. //! RangeError if N < 1. //! The following functions computes the point of parameter U //! and the derivatives at this point on the B-spline curve //! arc defined between the knot FromK1 and the knot ToK2. //! U can be out of bounds [Knot (FromK1), Knot (ToK2)] but //! for the computation we only use the definition of the curve //! between these two knots. This method is useful to compute //! local derivative, if the order of continuity of the whole //! curve is not greater enough. Inside the parametric //! domain Knot (FromK1), Knot (ToK2) the evaluations are //! the same as if we consider the whole definition of the //! curve. Of course the evaluations are different outside //! this parametric domain. Standard_EXPORT gp_Vec2d DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE; //! Raised if FromK1 = ToK2. Standard_EXPORT gp_Pnt2d LocalValue (const Standard_Real U, const Standard_Integer FromK1, const Standard_Integer ToK2) const; //! Raised if FromK1 = ToK2. Standard_EXPORT void LocalD0 (const Standard_Real U, const Standard_Integer FromK1, const Standard_Integer ToK2, gp_Pnt2d& P) const; //! Raised if the local continuity of the curve is not C1 //! between the knot K1 and the knot K2. //! Raised if FromK1 = ToK2. Standard_EXPORT void LocalD1 (const Standard_Real U, const Standard_Integer FromK1, const Standard_Integer ToK2, gp_Pnt2d& P, gp_Vec2d& V1) const; //! Raised if the local continuity of the curve is not C2 //! between the knot K1 and the knot K2. //! Raised if FromK1 = ToK2. Standard_EXPORT void LocalD2 (const Standard_Real U, const Standard_Integer FromK1, const Standard_Integer ToK2, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2) const; //! Raised if the local continuity of the curve is not C3 //! between the knot K1 and the knot K2. //! Raised if FromK1 = ToK2. Standard_EXPORT void LocalD3 (const Standard_Real U, const Standard_Integer FromK1, const Standard_Integer ToK2, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const; //! Raised if the local continuity of the curve is not CN //! between the knot K1 and the knot K2. //! Raised if FromK1 = ToK2. //! Raised if N < 1. Standard_EXPORT gp_Vec2d LocalDN (const Standard_Real U, const Standard_Integer FromK1, const Standard_Integer ToK2, const Standard_Integer N) const; //! Returns the last point of the curve. //! Warnings : //! The last point of the curve is different from the last //! pole of the curve if the multiplicity of the last knot //! is lower than Degree. Standard_EXPORT gp_Pnt2d EndPoint() const Standard_OVERRIDE; //! For a B-spline curve the first parameter (which gives the start //! point of the curve) is a knot value but if the multiplicity of //! the first knot index is lower than Degree + 1 it is not the //! first knot of the curve. This method computes the index of the //! knot corresponding to the first parameter. Standard_EXPORT Standard_Integer FirstUKnotIndex() const; //! Computes the parametric value of the start point of the curve. //! It is a knot value. Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE; //! Returns the knot of range Index. When there is a knot //! with a multiplicity greater than 1 the knot is not repeated. //! The method Multiplicity can be used to get the multiplicity //! of the Knot. //! Raised if Index < 1 or Index > NbKnots Standard_EXPORT Standard_Real Knot (const Standard_Integer Index) const; //! returns the knot values of the B-spline curve; //! //! Raised K.Lower() is less than number of first knot or //! K.Upper() is more than number of last knot. Standard_EXPORT void Knots (TColStd_Array1OfReal& K) const; //! returns the knot values of the B-spline curve; Standard_EXPORT const TColStd_Array1OfReal& Knots() const; //! Returns the knots sequence. //! In this sequence the knots with a multiplicity greater than 1 //! are repeated. //! Example : //! K = {k1, k1, k1, k2, k3, k3, k4, k4, k4} //! //! Raised if K.Lower() is less than number of first knot //! in knot sequence with repetitions or K.Upper() is more //! than number of last knot in knot sequence with repetitions. Standard_EXPORT void KnotSequence (TColStd_Array1OfReal& K) const; //! Returns the knots sequence. //! In this sequence the knots with a multiplicity greater than 1 //! are repeated. //! Example : //! K = {k1, k1, k1, k2, k3, k3, k4, k4, k4} Standard_EXPORT const TColStd_Array1OfReal& KnotSequence() const; //! Returns NonUniform or Uniform or QuasiUniform or PiecewiseBezier. //! If all the knots differ by a positive constant from the //! preceding knot the BSpline Curve can be : //! - Uniform if all the knots are of multiplicity 1, //! - QuasiUniform if all the knots are of multiplicity 1 except for //! the first and last knot which are of multiplicity Degree + 1, //! - PiecewiseBezier if the first and last knots have multiplicity //! Degree + 1 and if interior knots have multiplicity Degree //! A piecewise Bezier with only two knots is a BezierCurve. //! else the curve is non uniform. //! The tolerance criterion is Epsilon from class Real. Standard_EXPORT GeomAbs_BSplKnotDistribution KnotDistribution() const; //! For a BSpline curve the last parameter (which gives the //! end point of the curve) is a knot value but if the //! multiplicity of the last knot index is lower than //! Degree + 1 it is not the last knot of the curve. This //! method computes the index of the knot corresponding to //! the last parameter. Standard_EXPORT Standard_Integer LastUKnotIndex() const; //! Computes the parametric value of the end point of the curve. //! It is a knot value. Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE; //! Locates the parametric value U in the sequence of knots. //! If "WithKnotRepetition" is True we consider the knot's //! representation with repetition of multiple knot value, //! otherwise we consider the knot's representation with //! no repetition of multiple knot values. //! Knots (I1) <= U <= Knots (I2) //! . if I1 = I2 U is a knot value (the tolerance criterion //! ParametricTolerance is used). //! . if I1 < 1 => U < Knots (1) - Abs(ParametricTolerance) //! . if I2 > NbKnots => U > Knots (NbKnots) + Abs(ParametricTolerance) Standard_EXPORT void LocateU (const Standard_Real U, const Standard_Real ParametricTolerance, Standard_Integer& I1, Standard_Integer& I2, const Standard_Boolean WithKnotRepetition = Standard_False) const; //! Returns the multiplicity of the knots of range Index. //! Raised if Index < 1 or Index > NbKnots Standard_EXPORT Standard_Integer Multiplicity (const Standard_Integer Index) const; //! Returns the multiplicity of the knots of the curve. //! //! Raised if the length of M is not equal to NbKnots. Standard_EXPORT void Multiplicities (TColStd_Array1OfInteger& M) const; //! returns the multiplicity of the knots of the curve. Standard_EXPORT const TColStd_Array1OfInteger& Multiplicities() const; //! Returns the number of knots. This method returns the number of //! knot without repetition of multiple knots. Standard_EXPORT Standard_Integer NbKnots() const; //! Returns the number of poles Standard_EXPORT Standard_Integer NbPoles() const; //! Returns the pole of range Index. //! Raised if Index < 1 or Index > NbPoles. Standard_EXPORT const gp_Pnt2d& Pole (const Standard_Integer Index) const; //! Returns the poles of the B-spline curve; //! //! Raised if the length of P is not equal to the number of poles. Standard_EXPORT void Poles (TColgp_Array1OfPnt2d& P) const; //! Returns the poles of the B-spline curve; Standard_EXPORT const TColgp_Array1OfPnt2d& Poles() const; //! Returns the start point of the curve. //! Warnings : //! This point is different from the first pole of the curve if the //! multiplicity of the first knot is lower than Degree. Standard_EXPORT gp_Pnt2d StartPoint() const Standard_OVERRIDE; //! Returns the weight of the pole of range Index . //! Raised if Index < 1 or Index > NbPoles. Standard_EXPORT Standard_Real Weight (const Standard_Integer Index) const; //! Returns the weights of the B-spline curve; //! //! Raised if the length of W is not equal to NbPoles. Standard_EXPORT void Weights (TColStd_Array1OfReal& W) const; //! Returns the weights of the B-spline curve; Standard_EXPORT const TColStd_Array1OfReal* Weights() const; //! Applies the transformation T to this BSpline curve. Standard_EXPORT void Transform (const gp_Trsf2d& T) Standard_OVERRIDE; //! Returns the value of the maximum degree of the normalized //! B-spline basis functions in this package. Standard_EXPORT static Standard_Integer MaxDegree(); //! Computes for this BSpline curve the parametric //! tolerance UTolerance for a given tolerance //! Tolerance3D (relative to dimensions in the plane). //! If f(t) is the equation of this BSpline curve, //! UTolerance ensures that: //! | t1 - t0| < Utolerance ===> //! |f(t1) - f(t0)| < ToleranceUV Standard_EXPORT void Resolution (const Standard_Real ToleranceUV, Standard_Real& UTolerance); //! Creates a new object which is a copy of this BSpline curve. Standard_EXPORT Handle(Geom2d_Geometry) Copy() const Standard_OVERRIDE; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(Geom2d_BSplineCurve,Geom2d_BoundedCurve) protected: private: //! Recompute the flatknots, the knotsdistribution, the continuity. Standard_EXPORT void UpdateKnots(); Standard_Boolean rational; Standard_Boolean periodic; GeomAbs_BSplKnotDistribution knotSet; GeomAbs_Shape smooth; Standard_Integer deg; Handle(TColgp_HArray1OfPnt2d) poles; Handle(TColStd_HArray1OfReal) weights; Handle(TColStd_HArray1OfReal) flatknots; Handle(TColStd_HArray1OfReal) knots; Handle(TColStd_HArray1OfInteger) mults; Standard_Real maxderivinv; Standard_Boolean maxderivinvok; }; #endif // _Geom2d_BSplineCurve_HeaderFile
#include <iostream> #include <fstream> #include "specex_linalg.h" #include "specex_legendre.h" #include "specex_message.h" #include "specex_fits.h" // for debugging //! base of (not-normalized) Legendre polynomials static double LegendrePol(const int Degree, const double &X) { switch (Degree) { case 0: return 1; break; case 1: return X; break; case 2: return 0.5*(3*X*X-1.); break; case 3: return 0.5*(5*X*X-3)*X; break; case 4: return 0.125*((35*X*X-30)*X*X+3); break; case 5: return 0.125*(((63*X*X-70)*X*X+15)*X); break; case 6: return (((231*X*X-315)*X*X+105)*X*X-5)/16.; break; default : return ((2*Degree-1)*X*LegendrePol(Degree-1, X) - (Degree-1)*LegendrePol(Degree-2, X))/double(Degree); /* FatalError(" consider implementing Legendre pol of abitrary degree"); return 1; */ break; } } specex::Legendre1DPol::Legendre1DPol(int i_deg, const double& i_xmin, const double& i_xmax) : name("undefined"), deg(i_deg), xmin(i_xmin), xmax(i_xmax) { coeff.resize(deg+1); unbls::zero(coeff); } unbls::vector_double specex::Legendre1DPol::Monomials(const double &x) const { // range is -1,1 if xmin<x<xmax double rx= 2*(x-xmin)/(xmax-xmin)-1; unbls::vector_double m(deg+1); for(int i=0;i<=deg;i++) { m[i]=LegendrePol(i,rx); } return m; } double specex::Legendre1DPol::Value(const double &x) const { return specex::dot(coeff,Monomials(x)); } bool specex::Legendre1DPol::Fit(const unbls::vector_double& X, const unbls::vector_double& Y, const unbls::vector_double* Yerr, bool set_range) { // fit x if(X.size() != Y.size()) SPECEX_ERROR("Legendre1DPol::Fit, not same size X:" << X.size() << " Y:" << Y.size()); if(Yerr!=0 && X.size() != Yerr->size()) SPECEX_ERROR("Legendre1DPol::Fit, not same size"); int npar = deg+1; int ndata = X.size(); if(set_range) { specex::minmax(X,xmin,xmax); } unbls::matrix_double A(npar,npar); unbls::zero(A); unbls::vector_double B(npar,0.0); for(int i=0;i<ndata;i++) { double w=1; if(Yerr) { w=1./square((*Yerr)[i]); } unbls::vector_double h=Monomials(X[i]); specex::syr(w,h,A); // A += w*Mat(h)*h.transposed(); specex::axpy(double(w*Y[i]),h,B); //B += (w*Y[i])*h; } int status = cholesky_solve(A,B); if(status != 0) { if(0) { for(int i=0;i<ndata;i++) { double w=1; if(Yerr) { w=1./square((*Yerr)[i]); } cout << i << " " << X[i] << " " << Y[i] << " " << w << endl; } } SPECEX_ERROR("Legendre1DPol::Fit cholesky_solve failed with status " << status << " deg= " << deg << " xmin=" << xmin << " xmax=" << xmax); } coeff=B; // SPECEX_INFO("successful Legendre1DPol::Fit"); return true; } specex::Legendre1DPol specex::Legendre1DPol::Invert(int add_degree) const { specex::Legendre1DPol inverse; inverse.deg = deg+add_degree; inverse.coeff.resize(inverse.deg+1); unbls::zero(inverse.coeff); int npar = inverse.deg + 1; int ndata = npar*4; // double dx = (xmax-xmin)/ndata; unbls::vector_double X(ndata); unbls::vector_double Y(ndata); for(int i=0;i<ndata;i++) { X[i] = xmin+i*dx; Y[i] = Value(X[i]); } bool ok = inverse.Fit(Y,X,0,true); if(!ok) abort(); return inverse; } //============================ specex::Legendre2DPol::Legendre2DPol(int i_xdeg, const double& i_xmin, const double& i_xmax, int i_ydeg, const double& i_ymin, const double& i_ymax ) : name("undefined"), xdeg(i_xdeg), xmin(i_xmin), xmax(i_xmax), ydeg(i_ydeg), ymin(i_ymin), ymax(i_ymax) { Fill(); } void specex::Legendre2DPol::Fill() { coeff.resize((xdeg+1)*(ydeg+1)); unbls::zero(coeff); } unbls::vector_double specex::Legendre2DPol::Monomials(const double &x, const double &y) const { // range is -1,1 if xmin<x<xmax double rx= 2*(x-xmin)/(xmax-xmin)-1; double ry= 2*(y-ymin)/(ymax-ymin)-1; unbls::vector_double mx(xdeg+1,0.0); for(int i=0;i<=xdeg;i++) mx[i]=LegendrePol(i,rx); unbls::vector_double m((xdeg+1)*(ydeg+1)); int index=0; for(int j=0;j<=ydeg;j++) { double myj = LegendrePol(j,ry); for(int i=0;i<=xdeg;i++,index++) { m[index]=mx[i]*myj; } } return m; } double specex::Legendre2DPol::Value(const double &x,const double &y) const { return specex::dot(coeff,Monomials(x,y)); } //============================ specex::SparseLegendre2DPol::SparseLegendre2DPol(int i_xdeg, const double& i_xmin, const double& i_xmax, int i_ydeg, const double& i_ymin, const double& i_ymax ) : name("undefined"), xdeg(i_xdeg), xmin(i_xmin), xmax(i_xmax), ydeg(i_ydeg), ymin(i_ymin), ymax(i_ymax) { } void specex::SparseLegendre2DPol::Add(int i,int j) { if(i<0 || i>xdeg || j<0 || j>ydeg) {SPECEX_ERROR("in SparseLegendre2DPol::Add not valid indices " << i << " " << j);} int index=i+j*(xdeg+1); // checking for(std::vector<int>::const_iterator k = non_zero_indices.begin(); k!= non_zero_indices.end(); k++) { if(*k == index) { SPECEX_WARNING("in SparseLegendre2DPol::Add, indices " << i << " " << j << " already set"); return; } } non_zero_indices.push_back(index); coeff.resize(non_zero_indices.size()); unbls::zero(coeff); } void specex::SparseLegendre2DPol::Fill(bool sparse) { unbls::zero(non_zero_indices); if ( ! sparse ) { for(int k=0;k<(xdeg+1)*(ydeg+1);k++) non_zero_indices.push_back(k); coeff.resize(non_zero_indices.size()); unbls::zero(coeff); }else{ for(int i=0;i<=xdeg;i++) { // x coordinate for(int j=0;j<=ydeg;j++) { // wave coordinate if(i==0) { Add(i,j); // full wavelength resolution }else if(i==1) { if(j<2) Add(i,j); // only first x * wavelength cross-term }else{ if(j==0) Add(i,j); // only x terms } } } } } void specex::SparseLegendre2DPol::Clear() { unbls::zero(non_zero_indices); coeff.resize(0); } unbls::vector_double specex::SparseLegendre2DPol::Monomials(const double &x, const double &y) const { // range is -1,1 if xmin<x<xmax double rx= 2*(x-xmin)/(xmax-xmin)-1; double ry= 2*(y-ymin)/(ymax-ymin)-1; unbls::vector_double m(non_zero_indices.size(),0.0); int index=0; for(std::vector<int>::const_iterator k = non_zero_indices.begin(); k!= non_zero_indices.end(); k++, index++) { int i = (*k)%(xdeg+1); int j = (*k)/(xdeg+1); m[index]=LegendrePol(i,rx)*LegendrePol(j,ry); } return m; } double specex::SparseLegendre2DPol::Value(const double &x,const double &y) const { return specex::dot(coeff,Monomials(x,y)); }
#include "StdAfx.h" #include "Hide.h" namespace ui { Hide* Hide::Create() { return new (std::nothrow) Hide(); } Hide* Hide::Clone() const { return Hide::Create(); } InstantAction* Hide::Reverse() const { return Show::Create(); } void Hide::Update(float time) { InstantAction::Update(time); if (target_) { target_->SetVisible(false); } } }
#ifndef __COLORUTILS_H__ #define __COLORUTILS_H__ static void RGBfromU32(const uint32_t in, uint8_t & R, uint8_t & G, uint8_t & B) { // TODO inline R = in; G = in >> 8; B = in >> 16; } static __inline__ uint32_t RGBtoU32(const uint8_t R, const uint8_t G, const uint8_t B) { uint32_t output = R; output |= G << 8; output |= B << 16; return output; } static __inline__ uint32_t AlphaMask(uint32_t input, const uint8_t A) { input &= (~0) >> 8; input |= A << 24; return input; } static __inline__ float constrain(float x) { if(x < 0) return 0; else if(x > 255) return 255; return x; } static __inline__ uint32_t * pixRef(AndroidBitmapInfo & info, void * pixels, unsigned int x, unsigned int y) { pixels = (char*) pixels + y * info.stride; uint32_t * line = (uint32_t *) pixels; return line + x; } class Color3f { public: float r, g, b; Color3f() {} Color3f(float R, float G, float B) { r = R; g = G; b = B; } Color3f(uint32_t v) { uint8_t R, G, B; RGBfromU32(v, R, G, B); r = R; g = G; b = B; } uint32_t U32() { return RGBtoU32(constrain(r), constrain(g), constrain(b)); } float Luminance() { return 0.299f*b + 0.587f*g + 0.114f*b; } inline Color3f& operator+=(const Color3f& right) { r += right.r; g += right.g; b += right.b; return *this; } }; inline Color3f operator*(const Color3f& v, float a) { return Color3f(v.r*a, v.g*a, v.b*a); } inline Color3f operator*(float a, const Color3f& v) { return Color3f(v.r*a, v.g*a, v.b*a); } inline Color3f operator*(const Color3f& a, const Color3f& b) { return Color3f(a.r*b.r, a.g*b.g, a.b*b.b); } inline Color3f operator+(const Color3f& left, const Color3f& right) { return Color3f(left.r + right.r, left.g + right.g, left.b + right.b); } inline Color3f operator-(const Color3f& left, const Color3f& right) { return Color3f(left.r - right.r, left.g - right.g, left.b - right.b); } inline Color3f operator/(const Color3f& c, float a) { return Color3f(c.r/a, c.g/a, c.b/a); } inline bool operator==(const Color3f& left, const Color3f& right) { return left.r==right.r && left.g==right.g && left.b==right.b; } #endif
#pragma once namespace q3bsp { enum eLumps { kEntities = 0, // Stores player/object positions, etc... kTextures, // Stores texture information kPlanes, // Stores the splitting planes kNodes, // Stores the BSP nodes kLeafs, // Stores the leafs of the nodes kLeafFaces, // Stores the leaf's indices into the faces kLeafBrushes, // Stores the leaf's indices into the brushes kModels, // Stores the info of world models kBrushes, // Stores the brushes info (for collision) kBrushSides, // Stores the brush surfaces info kVertices, // Stores the level vertices kMeshVerts, // Stores the model vertices offsets kShaders, // Stores the shader files (blending, anims..) kFaces, // Stores the faces for the level kLightmaps, // Stores the lightmaps for the level kLightVolumes, // Stores extra world lighting information kVisData, // Stores PVS and cluster info (visibility) kMaxLumps // A constant to store the number of lumps }; struct tBSPLump { int offset; int length; }; struct tBSPHeader { char strID[4]; // This should always be 'IBSP' int version; // This should be 0x2e for Quake 3 files }; struct tBSPVertex { float vPosition[3]; // (x, y, z) position. float vTextureCoord[2]; // (u, v) texture coordinate float vLightmapCoord[2]; // (u, v) lightmap coordinate float vNormal[3]; // (x, y, z) normal vector byte color[4]; // RGBA color for the vertex }; struct tBSPFace { int textureID; // The index into the texture array int effect; // The index for the effects (or -1 = n/a) int type; // 1=polygon, 2=patch, 3=mesh, 4=billboard int vertexIndex; // The index into this face's first vertex int numOfVerts; // The number of vertices for this face int meshVertIndex; // The index into the first meshvertex int numMeshVerts; // The number of mesh vertices int lightmapID; // The texture index for the lightmap int lMapCorner[2]; // The face's lightmap corner in the image int lMapSize[2]; // The size of the lightmap section float lMapPos[3]; // The 3D origin of lightmap. float lMapBitsets[2][3]; // The 3D space for s and t unit vectors. float vNormal[3]; // The face normal. int size[2]; // The bezier patch dimensions. }; struct tBSPTexture { char strName[64]; // The name of the texture w/o the extension int flags; // The surface flags (unknown) int contents; // The content flags (unknown) }; struct tBSPLightmap { byte imageBits[128][128][3]; // The RGB data in a 128x128 image }; struct tBSPNode { int plane; // The index into the planes array int front; // The child index for the front node int back; // The child index for the back node int min[3]; // The bounding box min position. int max[3]; // The bounding box max position. }; struct tBSPLeaf { int cluster; // The visibility cluster int area; // The area portal int min[3]; // The bounding box min position int max[3]; // The bounding box max position int leafface; // The first index into the face array int numOfLeafFaces; // The number of faces for this leaf int leafBrush; // The first index for into the brushes int numOfLeafBrushes; // The number of brushes for this leaf }; struct tBSPPlane { D3DXVECTOR3 vNormal; // Plane normal. float d; // The plane distance from origin }; struct tBSPVisData { int numOfClusters; // The number of clusters int bytesPerCluster; // Bytes (8 bits) in the cluster's bitset byte *pBitsets; // Array of bytes holding the cluster vis. }; struct tBSPBrush { int brushSide; // The starting brush side for the brush int numOfBrushSides; // Number of brush sides for the brush int textureID; // The texture index for the brush }; struct tBSPBrushSide { int plane; // The plane index int textureID; // The texture index }; struct tBSPModel { float min[3]; // The min position for the bounding box float max[3]; // The max position for the bounding box. int faceIndex; // The first face index in the model int numOfFaces; // The number of faces in the model int brushIndex; // The first brush index in the model int numOfBrushes; // The number brushes for the model }; struct tBSPShader { char strName[64]; // The name of the shader file int brushIndex; // The brush index for this shader int unknown; // This is 99% of the time 5 }; struct tBSPLights { U8 ambient[3]; // This is the ambient color in RGB U8 directional[3]; // This is the directional color in RGB U8 direction[2]; // The direction of the light: [phi,theta] }; };
#include <iostream> using namespace std; int MOD = 1000003; int SPRIME = 107; // correctly calculates a mod MOD even if a < 0 int mod(int a) { return (a % MOD + MOD) % MOD; } int whash(string pattern){ int h = 0; for(int i = 0, len = pattern.length(); i < len; i++){ h *= SPRIME; h += pattern[i]; h = mod(h); } return h; } int power(int l){ int r = 1; for(int i = 0; i<l; i++){ r *= SPRIME; r = mod(r); } return r; } int main() { string text; string pattern; cin >> text >> pattern; //idiot proof if(pattern.length() > text.length()){ cout << 0; return 0; } int length = pattern.length(); int pwr = power(length - 1); int phash = whash(pattern); //pattern hash int fhash = whash(text.substr(0, length)); //first hash int counter = 0; if(phash == fhash){ if(pattern == text.substr(0, length)) counter++; } //Rabin-Karp alg for(int i = 0, len = text.length() - length; i <= len; i++){ fhash -= mod(text[i] * pwr); fhash *= SPRIME; fhash += text[i + length]; fhash = mod(fhash); if(fhash == phash){ //possible match if(pattern == text.substr(i+1, length)) counter++; } } cout << counter; return 0; }
#pragma once #include "..\resource.hpp" #include "detail\texture_subresource.hpp" namespace leaves { namespace pipeline { struct texture_traits_base { static constexpr bool is_texture_1d() noexcept { return false; } static constexpr bool is_texture_2d() noexcept { return true; } static constexpr bool is_texture_3d() noexcept { return false; } static constexpr bool is_texture_cube() noexcept { return false; } static constexpr bool is_texture_array() noexcept { return false; } static constexpr bool is_texture_rt() noexcept { return false; } static constexpr bool is_texture_ds() noexcept { return false; } }; struct texture_meta { pixel_format format; uint16_t width; uint16_t height; uint16_t depth; uint16_t array_size; bool has_mipmap; }; template <typename Impl> class texture : public resource { public: using traits_type = texture_traits<Impl>; using subresource_container = std::vector<subresource>; using meta_data = typename traits_type::meta; protected: /* * constructor */ texture( string name, // resource name texture_meta const& meta_data, // meta data device_access cpu_access, // host access device_access gpu_access) // device access : resource(traits_type::type(), std::move(name), 0, cpu_access, gpu_access) , meta_data_(meta_data) , subresources_() { construct(meta_data); } /* * construct function */ void construct(texture_meta const& meta_data) { texture_subresource ctr { meta_data.format, meta_data.width, meta_data.height, meta_data.depth, meta_data.array_size, meta_data.has_mipmap }; subresources_ = std::move(ctr.move_subres()); replace(std::move(ctr.move_data())); } public: /* * get the texture meta data */ texture_meta const& get_meta() const noexcept { return meta_data_; } /* * iterate through all subresources */ auto begin() noexcept { return subresources_.begin(); } /* * iterate through all subresources */ auto end() noexcept { return subresources_.end(); } /* * reset this texture resource */ void reset(meta_data const& meta_data_spec) { auto meta_data = meta_data_spec.to_tex_meta(); // if meta equals, no construct needed if (::memcmp(&meta_data, &meta_data_, sizeof(texture_meta)) == 0) return; construct(meta_data); // basic guarantee meta_data_ = meta_data; // no exception(copy assign is with noexcept signature) } protected: texture_meta meta_data_; subresource_container subresources_; }; } }
#include "DataAdmin.h" #include "LobbyLayer.h" DataAdmin* DataAdmin::_Instance = nullptr; DataAdmin::DataAdmin() { } DataAdmin::~DataAdmin() { } char * DataAdmin::ConvertWCtoC(WCHAR * str) { //반환할 char* 변수 선언 char* pStr; //입력받은 wchar_t 변수의 길이를 구함 int strSize = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL); //char* 메모리 할당 pStr = new char[strSize]; //형 변환 WideCharToMultiByte(CP_ACP, 0, str, -1, pStr, strSize, 0, 0); return pStr; } void DataAdmin::SetRoomListData(ROOM_LIST_DATA * Data) { auto _layer = SceneManager::GetInstance()->GetLayer(); LobbyLayer* _lobby = dynamic_cast<LobbyLayer*>(_layer); for (int i = 0; i < 10; i++) { if (Data[i].CurrentUser > 0) { m_Room_list_data[i].RoomIndex = Data[i].RoomIndex; m_Room_list_data[i].CurrentUser = Data[i].CurrentUser; wcscpy(m_Room_list_data[i].RoomName, Data[i].RoomName); if (_lobby) { _lobby->AddBtn(m_Room_list_data[i].RoomIndex); } } else { m_Room_list_data[i].RoomIndex = -1; m_Room_list_data[i].CurrentUser = 0; ZeroMemory(m_Room_list_data[i].RoomName, sizeof(WCHAR)* 32); } } } void DataAdmin::SetRoomMemberList(SLOT_USER_DATA Data[4]) { auto _layer = SceneManager::GetInstance()->GetLayer(); RoomLayer* _room = dynamic_cast<RoomLayer*>(_layer); if (_room) { _room->ClearRoom(); for (int i = 0; i < 4; i++) { if (Data[i].IsEmpty == FALSE) { _room->SetRoomMemberList(Data[i]); } } } }
#include <iostream> #include "noteContainer.h" int main() { int k = 10; noteContainer cont; string name, lastName; int number, day, month, year, i; while (k != 0){ cout << "Меню: \n" << "0.Закрыть программу\n" << "1.Заполнить\n" << "2.Вывести запись" << endl; cin >> k; switch (k) { case 1: while(i < 8) { cout << "Введите имя фамилию номер день месяц год рождения" << endl; cin >> name >> lastName >> number >> day >> month >> year; cont.book[i] = note(name, lastName, number, day, month, year); i++; } cont.sort(); break; case 3: cout << "Имя " << " Фамилия " << " Номер " << " Дата рождения" << endl; for (int j = 0; j < 8; ++j) { cout << cont.book[j].getName() << " " << cont.book[j].getLastName() << " " << cont.book[j].getNumber() << " " << cont.book[j].getBDay()[0] << "." << cont.book[j].getBDay()[1] << "." << cont.book[j].getBDay()[2] << endl; } break; case 2: cout << "Введите фамилию" << endl; cin >> lastName; note n = cont.select(lastName); if(n.getName() != ""){ cout << "Имя: " << n.getName() << endl << "Фамилия: " << n.getLastName() << endl << "Номер: " << n.getNumber() << endl << "Дата рождения: " << n.getBDay()[0] << "." << n.getBDay()[1] << "." << n.getBDay()[2] << endl; }else cout << "Такой записи не существует!" << endl; break; } } return 0; }
#pragma once #include <memory> #include <vector> #include "UnionFind.h" class UnionFind { private: std::vector<int> id; int size; public: UnionFind(int size); bool Connected(int a, int b); void Union(int a, int b); int Find(int i); int NumSets(); };
/* * SignalingService.cpp * * Created on: 30/11/2019 * Author: frank */ #include "SignalingService.h" SignalingService::SignalingService(Led *ledTemp, Led *lamp, Buzzer *buzina, Delay *delay) { this->ledTemp = ledTemp; this->lampada = lamp; this->buzina = buzina; this->delay = delay; this->i = 0; } void SignalingService::beep(){ this->buzina->buzzerTurnOn(); int a = 0; while(a < 9){ a = a + 1; this->delay->delay(); } this->buzina->buzzerTurnOff(); } void SignalingService::beepOn(){ this->buzina->buzzerTurnOn(); } void SignalingService::beepOff(){ this->buzina->buzzerTurnOff(); } void SignalingService::lampadaTurnOn(){ this->lampada->turnOn(); } void SignalingService::lampadaTurnOff(){ this->lampada->turnOff(); } void SignalingService::tempTurnOn(){ this->ledTemp->turnOn(); } void SignalingService::tempTurnOff(){ this->ledTemp->turnOff(); } void SignalingService::delayServ(){ this->delay->delay(); }
#include bitsstdc++.h using namespace std; vectorstring split_string(string); void printReverse(vectorint arr) { int length = arr.size(); for (int i = 0; i length; i++) { cout arr[length - 1 - i] ; } } int main() { int n; cin n; cin.ignore(numeric_limitsstreamsizemax(), 'n'); string arr_temp_temp; getline(cin, arr_temp_temp); vectorstring arr_temp = split_string(arr_temp_temp); vectorint arr(n); for (int i = 0; i n; i++) { int arr_item = stoi(arr_temp[i]); arr[i] = arr_item; } printReverse(arr); return 0; } vectorstring split_string(string input_string) { stringiterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vectorstring splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != stringnpos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
#include "Order.h"
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <string> #include <cstdio> #include <cstring> #include <climits> #include <set> using namespace std; int main() { string s, sub; getline(cin, s); vector<bool> m(128, false); getline(cin, sub); for (auto item : sub) { m[item - 0] = true; } for (auto item : s) { if (!m[item - 0]) printf("%c", item); } return 0; }
/* Author: Mikko Finell * License: Public Domain */ #ifndef CASE_EVENTS #define CASE_EVENTS #include <functional> #include <SFML/Graphics.hpp> namespace CASE { inline void eventhandling(sf::RenderWindow & window, bool & running, bool & pause, bool & single_step, double & framerate, const std::function<void()> & reset, const std::function<void(const int)> & fast_forward) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::KeyPressed) { switch (event.key.code) { case sf::Keyboard::Pause: pause = !pause; continue; case sf::Keyboard::R: using _ = sf::Keyboard; if (_::isKeyPressed(_::RControl) || _::isKeyPressed(_::LControl)) case sf::Keyboard::F5: { reset(); } continue; case sf::Keyboard::Q: case sf::Keyboard::End: case sf::Keyboard::Escape: running = false; continue; case sf::Keyboard::Right: if (pause) single_step = true; else pause = true; continue; case sf::Keyboard::Left: continue; case sf::Keyboard::Up: if (pause) pause = false; else framerate += 5.0; continue; case sf::Keyboard::Down: if (pause) pause = false; else framerate = std::max<double>(1, framerate - 5); continue; case sf::Keyboard::Num1: fast_forward(1); continue; case sf::Keyboard::Num2: fast_forward(2); continue; case sf::Keyboard::Num3: fast_forward(3); continue; case sf::Keyboard::Num4: fast_forward(4); continue; case sf::Keyboard::Num5: fast_forward(5); continue; case sf::Keyboard::Num6: fast_forward(6); continue; default: continue; } } if (event.type == sf::Event::Closed) { running = false; continue; } } } } // CASE #endif // EVENTS
#include <iostream> #include <stdio.h> #include <algorithm> #include <vector> using namespace std; typedef long long ll; struct cell { ll x, y; int id; cell(ll ax, ll ay, int aid = 0) : x(ax) , y(ay) , id(aid) {} bool operator <(const cell& A) const { return x < A.x || (x == A.x && y < A.y); } }; bool cw(cell a, cell b, cell c) { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < 0; } bool ccw(cell a, cell b, cell c) { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > 0; } void convex_hull(vector<cell>& a) { if (a.size() < 3) return; sort(a.begin(), a.end()); cell p0 = a[0], pn = a.back(); vector<cell> up, down; up.push_back(p0); down.push_back(p0); for (size_t i = 1; i < a.size(); ++i) { if (i + 1 == a.size() || cw(p0, a[i], pn)) { while (up.size() >= 2 && !cw(up[up.size() - 2], up[up.size() - 1], a[i])) { up.pop_back(); } up.push_back(a[i]); } if (i + 1 == a.size() || ccw(p0, a[i], pn)) { while (down.size() >= 2 && !ccw(down[down.size() - 2], down[down.size() - 1], a[i])) { down.pop_back(); } down.push_back(a[i]); } } a = up; for (int i = down.size() - 2; i >= 0; --i) a.push_back(down[i]); } const int N = 1000111; vector<int> g[N]; ll x[N], y[N], z[N]; ll sqr(ll x) { return x * x; } ll dis2(int id1, int id2) { return sqr(x[id1] - x[id2]) + sqr(y[id1] - y[id2]) + sqr(z[id1] - z[id2]); } int cl[N]; void dfs(int x, int color) { cl[x] = color; for (int i = 0; i < g[x].size(); ++i) if (cl[ g[x][i] ] == -1) { dfs(g[x][i], 1 - color); } } int sign(ll x) { if (x < 0) return -1; if (x == 0) return 0; return 1; } ll myabs(ll x) { if (x < 0) return -x; return x;} ll baddist(ll x, ll y, ll A, ll B, ll C) { return myabs(A * x + B * y + C); } ll baddist(ll x, ll y, ll x1, ll y1, ll x2, ll y2) { ll A = y1 - y2; ll B = x2 - x1; return baddist(x, y , A, B, -A * x1 - B * y1); } ll bestd = -1; vector< pair<int, int> > edges; vector<cell> a; void relax(int x, int y) { ll dist = dis2(a[x].id, a[y].id); if (dist > bestd) { bestd = dist; edges.clear(); } if (dist == bestd) { edges.push_back(make_pair(x, y)); } } int main() { int T; scanf("%d", &T); while (T--) { edges.clear(); bestd = -1; int n; scanf("%d", &n); a.clear(); for (int i = 0; i < n; ++i) { int ax, ay, az; scanf("%d%d%d", &ax, &ay, &az); x[i] = ax; y[i] = ay; z[i] = az; a.push_back(cell(x[i], y[i], i)); } if (a.size() == 1) { puts("NIE"); continue; } convex_hull(a); int m = a.size(); if (m > 10000) { int pos = 0; ll bestd = 0; for (int i = 0; i < m; ++i) { if (baddist(a[i].x, a[i].y, a[0].x, a[0].y, a[1].x, a[1].y) >= bestd) { pos = i; bestd = dis2(a[i].id, a[0].id); } } relax(0, pos); relax(1, pos); relax(0, (pos + 1) % m); relax(1, (pos + 1) % m); relax(0, (pos + m - 1) % m); relax(1, (pos + m - 1) % m); ll curd = bestd; for (int i = 1; i < m; ++i) { int nxt = (i + 1) % m; while (true) { int npos = (pos + 1) % m; ll cand = baddist(a[npos].x, a[npos].y, a[i].x, a[i].y, a[nxt].x, a[nxt].y); if (cand >= curd) { curd = cand; pos = npos; } else break; } relax(i, (pos + m - 1) % m); relax(nxt, (pos + m - 1) % m); relax(i, pos); relax(nxt, pos); relax(i, (pos + 1) % m); relax(nxt, (pos + 1) % m); } } else { for (int i = 0; i < m; ++i) for (int j = i + 1; j < m; ++j) relax(i, j); } for (int i = 0; i < n; ++i) { g[i].clear(); cl[i] = -1; } for (int i = 0; i < edges.size(); ++i) { g[ edges[i].first ].push_back( edges[i].second ); g[ edges[i].second].push_back( edges[i].first ); } for (int i = 0; i < n; ++i) if (cl[i] == -1) { dfs(i, 0); } bool cool = true; for (int i = 0; cool && i < n; ++i) for (int j = 0; j < g[i].size(); ++j) if (cl[i] == cl[ g[i][j] ]) { cool = false; break; } if (cool) puts("TAK"); else puts("NIE"); } return 0; }
/**************************************************************************** ** ** Copyright (C) 2010 Instituto Nokia de Tecnologia (INdT) ** ** This file is part of the Rask Browser project. ** ** This file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact ** the openBossa stream from INdT <renato.chencarek@openbossa.org>. ** ****************************************************************************/ #include "mobilewebview.h" #include "mobilewebpage.h" #include "scrollbar.h" #include "kineticscroll.h" #include <QTimer> #include <QWebFrame> #include <QApplication> #include <QGraphicsScene> #include <QPropertyAnimation> #include <QParallelAnimationGroup> #include <QGraphicsSceneMouseEvent> #include <QGesture> #define CLICK_CONSTANT 15 #define TILE_FROZEN_DELAY 100 #define FADE_SCROLL_TIMEOUT 300 #define MIN_ZOOM_SCALE 0.1 #define MAX_ZOOM_SCALE 6.0 #define DPI_ADJUSTMENT_SCALE 1.0 class MobileWebViewPrivate { public: MobileWebViewPrivate(MobileWebView *qptr); MobileWebView *q; KineticScroll *kinetic; ScrollBar *verticalScroll; ScrollBar *horizontalScroll; bool isDragging; bool acceptsClick; QPoint pressPos; QPoint scenePressPos; QList<QEvent *> ignored; QTimer timer; bool scrollVisible; QTimer fadeScrollTimer; QGraphicsWebView *webview; void init(); void updateScrollBars(); QRectF contentGeometry() const; void setContentPos(const QPointF &pos); void sendSceneClick(const QPointF &pos); bool isClickPossible(const QPoint &pos); void setScrollBarsVisible(bool visible); }; MobileWebViewPrivate::MobileWebViewPrivate(MobileWebView *qptr) : q(qptr), isDragging(false), acceptsClick(true), scrollVisible(false) { kinetic = new KineticScroll(q); } void MobileWebViewPrivate::init() { q->setFlag(QGraphicsItem::ItemHasNoContents, true); q->setFlag(QGraphicsItem::ItemClipsChildrenToShape, true); verticalScroll = new ScrollBar(Qt::Vertical, q); verticalScroll->setBackgroundColor(Qt::transparent); verticalScroll->setForegroundColor(Qt::gray); verticalScroll->setZValue(1); verticalScroll->setOpacity(0.0); horizontalScroll = new ScrollBar(Qt::Horizontal, q); horizontalScroll->setBackgroundColor(Qt::transparent); horizontalScroll->setForegroundColor(Qt::gray); horizontalScroll->setZValue(1); horizontalScroll->setOpacity(0.0); webview = new QGraphicsWebView(q); webview->installEventFilter(q); webview->grabGesture(Qt::TapAndHoldGesture); webview->setResizesToContents(true); webview->setAttribute(Qt::WA_OpaquePaintEvent, true); MobileWebPage *page = new MobileWebPage(q); webview->setPage(page); timer.setSingleShot(true); fadeScrollTimer.setSingleShot(true); QObject::connect(&fadeScrollTimer, SIGNAL(timeout()), q, SLOT(onFadeScrollTimeout())); // connect frozen tile timer delay QObject::connect(&timer, SIGNAL(timeout()), q, SLOT(enableContentUpdate())); // connect kinetic signals QObject::connect(kinetic, SIGNAL(offsetChanged(const QPoint &)), q, SLOT(moveOffset(const QPoint &))); // connect webview signals QObject::connect(webview, SIGNAL(loadProgress(int)), q, SIGNAL(loadProgress(int))); QObject::connect(webview, SIGNAL(loadFinished(bool)), q, SIGNAL(loadFinished(bool))); QObject::connect(webview, SIGNAL(urlChanged(const QUrl &)), q, SLOT(onUrlChanged())); QObject::connect(webview, SIGNAL(titleChanged(const QString &)), q, SIGNAL(titleChanged(const QString &))); QObject::connect(webview->page()->mainFrame(), SIGNAL(contentsSizeChanged(const QSize &)), q, SLOT(onContentsSizeChanged(const QSize &))); QObject::connect(webview->page()->mainFrame(), SIGNAL(initialLayoutCompleted()), q, SLOT(onInitialLayoutCompleted())); webview->setScale(DPI_ADJUSTMENT_SCALE); } QRectF MobileWebViewPrivate::contentGeometry() const { // FIXME: dynamically add bottom paddding for virtual keyboard return QRectF(webview->x(), webview->y(), webview->size().width() * webview->scale(), webview->size().height() * webview->scale() + 352); } void MobileWebViewPrivate::setScrollBarsVisible(bool visible) { if (scrollVisible == visible) return; scrollVisible = visible; QParallelAnimationGroup *result = new QParallelAnimationGroup(q); QPropertyAnimation *animation; animation = new QPropertyAnimation(verticalScroll, "opacity"); animation->setDuration(400); animation->setStartValue(verticalScroll->opacity()); animation->setEndValue(visible ? 0.7 : 0); result->addAnimation(animation); animation = new QPropertyAnimation(horizontalScroll, "opacity"); animation->setDuration(400); animation->setStartValue(horizontalScroll->opacity()); animation->setEndValue(visible ? 0.7 : 0); result->addAnimation(animation); result->start(QAbstractAnimation::DeleteWhenStopped); } bool MobileWebViewPrivate::isClickPossible(const QPoint &pos) { if (kinetic->isAnimating() || !acceptsClick) return false; else return abs(pos.x() - pressPos.x()) <= CLICK_CONSTANT && abs(pos.y() - pressPos.y()) <= CLICK_CONSTANT; } void MobileWebViewPrivate::setContentPos(const QPointF &pos) { const QSizeF &webSize = contentGeometry().size(); int minX = qMin<int>(0, q->width() - webSize.width()); int minY = qMin<int>(0, q->height() - webSize.height()); // enforce boundaries webview->setX(qBound<int>(minX, pos.x(), 0)); webview->setY(qBound<int>(minY, pos.y(), 0)); updateScrollBars(); } void MobileWebViewPrivate::updateScrollBars() { const QSizeF &webSize = contentGeometry().size(); verticalScroll->setGeometry(q->width() - 10, 14, 7, q->height() - 28); horizontalScroll->setGeometry(14, q->height() - 10, q->width() - 28, 7); verticalScroll->setValue(-webview->y()); verticalScroll->setPageSize(q->height()); verticalScroll->setMaximum(-qMin<int>(0, q->height() - webSize.height())); horizontalScroll->setValue(-webview->x()); horizontalScroll->setPageSize(q->width()); horizontalScroll->setMaximum(-qMin<int>(0, q->width() - webSize.width())); setScrollBarsVisible(true); fadeScrollTimer.start(FADE_SCROLL_TIMEOUT); } void MobileWebViewPrivate::sendSceneClick(const QPointF &pos) { QGraphicsSceneMouseEvent *event; event = new QGraphicsSceneMouseEvent(QEvent::GraphicsSceneMousePress); event->setButton(Qt::LeftButton); event->setScenePos(pos); ignored << event; QCoreApplication::postEvent(q->scene(), event); event = new QGraphicsSceneMouseEvent(QEvent::GraphicsSceneMouseRelease); event->setButton(Qt::LeftButton); event->setScenePos(pos); ignored << event; QCoreApplication::postEvent(q->scene(), event); } MobileWebView::MobileWebView(QDeclarativeItem *parent) : QDeclarativeItem(parent) { dd = new MobileWebViewPrivate(this); dd->init(); dd->updateScrollBars(); } MobileWebView::~MobileWebView() { delete dd; } QString MobileWebView::title() const { return dd->webview->title(); } QString MobileWebView::url() const { return dd->webview->url().toString(); } void MobileWebView::setUrl(const QString &url) { dd->webview->setUrl(QUrl::fromUserInput(url)); } bool MobileWebView::isFrozen() const { return dd->webview->isTiledBackingStoreFrozen(); } void MobileWebView::setFrozen(bool enabled) { dd->webview->setTiledBackingStoreFrozen(enabled); } QPointF MobileWebView::contentPos() const { return dd->webview->pos(); } void MobileWebView::setContentPos(const QPointF &pos) { dd->setContentPos(pos); } void MobileWebView::back() { dd->webview->back(); } void MobileWebView::forward() { dd->webview->forward(); } void MobileWebView::reload() { dd->webview->reload(); } void MobileWebView::stop() { dd->webview->stop(); } void MobileWebView::onUrlChanged() { emit urlChanged(); } bool MobileWebView::handleMouseEvent(QGraphicsSceneMouseEvent *e) { if (dd->ignored.removeAll(e)) return false; const QPoint &mousePos = e->screenPos(); if (e->type() == QEvent::GraphicsSceneMouseDoubleClick) { setZoomScale(1.5); qDebug() << "double click"; return true; } if (e->type() == QEvent::GraphicsSceneMousePress) { if (e->buttons() != Qt::LeftButton) return false; dd->acceptsClick = !dd->kinetic->isAnimating(); dd->kinetic->mousePress(mousePos); dd->isDragging = false; dd->pressPos = mousePos; dd->scenePressPos = e->scenePos().toPoint(); return true; } if (e->type() == QEvent::GraphicsSceneMouseMove) { if (!dd->isClickPossible(mousePos)) dd->isDragging = true; if (dd->isDragging) { dd->kinetic->mouseMove(mousePos); } else { dd->kinetic->mousePress(mousePos); } return true; } if (e->type() == QEvent::GraphicsSceneMouseRelease) { if (dd->isClickPossible(mousePos)) { dd->kinetic->stop(); dd->sendSceneClick(dd->scenePressPos); } else { dd->kinetic->mouseRelease(mousePos); } dd->acceptsClick = true; return true; } return false; } void MobileWebView::moveOffset(const QPoint &value) { const QPoint &oldPos = dd->webview->pos().toPoint(); dd->setContentPos(dd->webview->pos() + value); if (dd->webview->pos().toPoint() == oldPos) dd->kinetic->stop(); setFrozen(true); dd->timer.start(TILE_FROZEN_DELAY); } bool MobileWebView::eventFilter(QObject *object, QEvent *e) { QGestureEvent *gestureEvent = dynamic_cast<QGestureEvent*>(e); if (gestureEvent) { if (const QGesture *g = gestureEvent->gesture(Qt::TapAndHoldGesture)) { if (g->state() == Qt::GestureStarted) { qDebug() << "tap-n-hold event started"; /* QGraphicsSceneMouseEvent pressEvent(QEvent::GraphicsSceneMousePress); pressEvent.setScenePos(QPointF(100, 100)); pressEvent.setButton(Qt::RightButton); pressEvent.setButtons(Qt::RightButton); QApplication::sendEvent(dd->webview, &pressEvent); */ QGraphicsSceneMouseEvent *mouseEvent = static_cast<QGraphicsSceneMouseEvent *>(e); const QPoint &mousePos = mouseEvent->screenPos(); QContextMenuEvent pressEvent(QContextMenuEvent::Mouse, mousePos); QApplication::sendEvent(dd->webview, &pressEvent); qDebug() << "context menu sent event"; } } } switch(e->type()) { case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMouseMove: case QEvent::GraphicsSceneMouseRelease: case QEvent::GraphicsSceneMouseDoubleClick: return handleMouseEvent(static_cast<QGraphicsSceneMouseEvent *>(e)); // case QEvent::GraphicsSceneContextMenu: // ignore native context menu // return true; case QEvent::GraphicsSceneHoverMove: case QEvent::GraphicsSceneHoverLeave: case QEvent::GraphicsSceneHoverEnter: // ignore hover events return true; default: return QObject::eventFilter(object, e); } } void MobileWebView::enableContentUpdate() { setFrozen(false); } void MobileWebView::onInitialLayoutCompleted() { dd->kinetic->stop(); dd->setContentPos(QPointF(0, 0)); } void MobileWebView::onContentsSizeChanged(const QSize &newSize) { Q_UNUSED(newSize); // enforce boundaries dd->kinetic->stop(); dd->setContentPos(dd->webview->pos()); } void MobileWebView::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { QDeclarativeItem::geometryChanged(newGeometry, oldGeometry); // enforce boundaries dd->kinetic->stop(); dd->setContentPos(dd->webview->pos()); // reconfigure preferred size dd->webview->page()->setPreferredContentsSize(newGeometry.size().toSize() / DPI_ADJUSTMENT_SCALE); } void MobileWebView::onFadeScrollTimeout() { dd->setScrollBarsVisible(false); } qreal MobileWebView::zoomScale() const { return dd->webview->scale(); } void MobileWebView::setZoomScale(qreal value) { value = qBound<qreal>(MIN_ZOOM_SCALE, value, MAX_ZOOM_SCALE); if (value != zoomScale()) { dd->webview->setScale(value * DPI_ADJUSTMENT_SCALE); } // fallback to normal at the second double-tap else { dd->webview->setScale( 1.0 * DPI_ADJUSTMENT_SCALE); } } QPixmap MobileWebView::snapshot(int w, int h) const { QImage result(w, h, QImage::Format_RGB32); QPainter painter(&result); painter.fillRect(result.rect(), Qt::white); if (!dd->webview->url().isEmpty()) { qreal scale = dd->webview->scale(); int ix = dd->webview->pos().x(); int iy = dd->webview->pos().y(); painter.translate(ix, iy); painter.scale(scale, scale); dd->webview->page()->mainFrame()->render(&painter, QWebFrame::ContentsLayer, QRegion(-ix / scale, -iy / scale, w / scale, h / scale)); } return QPixmap::fromImage(result); }
//知识点:LCA/树链剖分 /* 使用重链剖分进行LCA 详见注释 */ #include<cstdio> #include<ctype.h> #include<algorithm> //======================================================== const int MARX = 5e5+10; struct edge { int u,v,ne; }a[2*MARX]; int head[MARX]; int num,n,m,root; int s[MARX],dep[MARX],fa[MARX],son[MARX],c[MARX];//Tree Chain Dxxxxx //======================================================== inline int read() { int fl=1,w=0;char ch=getchar(); while(!isdigit(ch) && ch!='-') ch=getchar(); if(ch=='-') fl=-1; while(isdigit(ch)){w=w*10+ch-'0',ch=getchar();} return fl*w; } inline void add(int u,int v) { a[++num].u=u,a[num].v=v; a[num].ne=head[u],head[u]=num; } void dfs1(int u,int fat)//求得每个点的,子树大小 , 重儿子 , 父亲 , 深度 ; { s[u]=1 , dep[u]=dep[fat]+1 , fa[u]=fat;//更新 for(int i=head[u],v=a[i].v ;i; i=a[i].ne,v=a[i].v) if(v!=fat) { dfs1(v,u); s[u]+=s[v];//回溯 if(s[son[u]] < s[v]) son[u]=v; } } void dfs2(int u,int fat)//求得每个点所在链,与链的顶端 { c[u]=fat; if(son[u]) dfs2(son[u],fat);//重链 else return; for(int i=head[u],v=a[i].v ;i; i=a[i].ne,v=a[i].v)//轻链 if(v!=fa[u] && v!=son[u]) dfs2(v,v); } int lca(int x,int y)//求得lca { for( ;c[x]!=c[y]; x=fa[c[x]])//循环将深度较大的点上移,直到两点在同一条链上 if(dep[c[x]] < dep[c[y]]) std::swap(x,y); return dep[x]<dep[y]?x:y;//返回深度较小的点 } //======================================================== signed main() { n=read(),m=read(),root=read(); for(int i=1;i<n;i++) { int u=read(),v=read(); add(u,v) , add(v,u); } dfs1(root,0);//初始化,进行剖分 dfs2(root,root); while(m--) { int u=read(),v=read(); printf("%d\n",lca(u,v)); } } //时间空间都不如树链剖分 //并且很难打,容易出锅的倍增LCA //详见注释 /* #include<cstdio> #include<algorithm> using namespace std; const int MARX = 5e5+10; int f[MARX][25],g[MARX][25]; int dep[MARX],head[MARX],lg[MARX]; int num; struct baka9 //存边 { int v; int ne; }a[2*MARX]; int lca(int a,int b) //倍增法上跳 { if(dep[a] < dep[b]) swap(a,b); while(dep[a] > dep[b]) //移到同一深度 a=f[a][ lg[dep[a]-dep[b]] -1]; if(a==b) return a; for(int k=lg[dep[a]]-1;k>=0;k--)//同时上跳 if(f[a][k] != f[b][k]) a=f[a][k],b=f[b][k]; return f[a][0]; } void dfs(int u,int fa) //dfs求深度,求向上2^n层的父亲 { dep[u]=dep[fa]+1; f[u][0]=fa; for(int i=1;(1<<i)<=dep[u];i++) f[u][i]=f[f[u][i-1]][i-1]; for(int i=head[u];i;i=a[i].ne) if(a[i].v != fa) dfs(a[i].v,u); } void add(int u,int v)//建图 { a[++num].v=v; a[num].ne=head[u]; head[u]=num; } int main() { int n,m,s; scanf("%d%d%d",&n,&m,&s); for(int i=1;i<n;i++)//建图 { int u,v; scanf("%d%d",&u,&v); add(u,v);add(v,u); } dfs(s,0); for(int i=1;i<=n;i++)//预处理log函数 lg[i]=lg[i-1]+(1<<lg[i-1]==i); for(int i=1;i<=m;i++) { int a,b; scanf("%d%d",&a,&b); printf("%d\n",lca(a,b)); } } */
#include <cppunit/extensions/HelperMacros.h> #include <Poco/Exception.h> #include "cppunit/BetterAssert.h" #include "model/GlobalID.h" using namespace std; namespace BeeeOn { class GlobalIDTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(GlobalIDTest); CPPUNIT_TEST(testToBytes); CPPUNIT_TEST(testFromBytes); CPPUNIT_TEST(testFromBytesInvalid); CPPUNIT_TEST_SUITE_END(); public: void testToBytes(); void testFromBytes(); void testFromBytesInvalid(); }; CPPUNIT_TEST_SUITE_REGISTRATION(GlobalIDTest); static string TEST_UUID = "1bffd7fe-fe95-41ba-a572-fb8cc2e4d002"; static const vector<uint8_t> TEST_BYTES = {0x1b, 0xff, 0xd7, 0xfe, 0xfe, 0x95, 0x41, 0xba, 0xa5, 0x72, 0xfb, 0x8c, 0xc2, 0xe4, 0xd0, 0x02}; void GlobalIDTest::testToBytes() { GlobalID id = GlobalID::parse(TEST_UUID); const vector<uint8_t> idBytes = id.toBytes(); CPPUNIT_ASSERT(idBytes == TEST_BYTES); } void GlobalIDTest::testFromBytes() { GlobalID id = GlobalID::fromBytes(TEST_BYTES); CPPUNIT_ASSERT_EQUAL(TEST_UUID, id.toString()); } void GlobalIDTest::testFromBytesInvalid() { vector<uint8_t> invalidBytes(8); CPPUNIT_ASSERT_THROW(GlobalID::fromBytes(invalidBytes), Poco::InvalidArgumentException); } }
// // Created by arnito on 4/06/17. // #include "Box.h" #include "../Resources.h" Box::Box(std::string texture,sf::Vector2f position, sf::Vector2i size, int frame, int id, int damage, int numFrames) : Entity(texture,position,size,frame,id,damage,numFrames){ _touched_floor = false; _reached_up = false; } Box::~Box(){ } bool Box::colisionMapBottom(sf::Image &image){ for(int i=(unsigned int)_position.x; i<(unsigned int)_position.x+_sizeSprite.x; i++){ sf::Vector2i pixel(i, (unsigned int)_position.y+_sizeSprite.y); if(pixel.x >=0 && pixel.x < image.getSize().x && pixel.y >=0 && pixel.y < image.getSize().y){ sf::Color c = image.getPixel(i, (unsigned int)_position.y+_sizeSprite.y); if(c == sf::Color::White) return true; } } return false; } void Box::update(const sf::Time& deltatime, const std::string colisionMap){ Entity::update(deltatime,colisionMap); sf::Image imageCol(*Resources::getImage(colisionMap)); bool colBottom = colisionMapBottom(imageCol); if(colBottom && !_touched_floor){ _upY = (int)_position.y-UP_AMOUNT; _touched_floor = true; } if(_touched_floor && !_reached_up){ _position.y -= deltatime.asSeconds()*270; if(_position.y <= _upY) _reached_up = true; } else if(!colBottom || _touched_floor) _position.y += deltatime.asSeconds()*270; setPosition(_position); if(_position.y>1024) _active = false; }
#include <iostream> #include <vector> #include <string> #include <fstream> #include <math.h> #include <string> using namespace std; // Complete the candies function below. long candies(int n, vector<int> arr) { int sum = 0; int count = 1; if (arr[0] < arr[1]) { count = 2; } for (int i = 0; i < arr.size(); i++) { if (arr[i] > arr[i + 1]) { count++; } else if (arr[i] < arr[i + 1]) { count--; } sum = sum + count; } return sum; } int candies() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); vector<int> arr(n); for (int i = 0; i < n; i++) { int arr_item; cin >> arr_item; cin.ignore(numeric_limits<streamsize>::max(), '\n'); arr[i] = arr_item; } long result = candies(n, arr); fout << result << "\n"; fout.close(); return 0; }
#pragma once #include "funcoesAuxiliares.h" struct sitaucaoDoNo{ bool visitado=false; }; template <typename T> struct GrafoIndirecionado{ Matriz<T> *arestas; sitaucaoDoNo *statusDe; GrafoIndirecionado(int nNos){ arestas=new Matriz<T>(nNos); statusDe=new sitaucaoDoNo[nNos]; } ListaEncadeada<T> *buscaCaminho(int noOrigem, int noMeta){ ListaEncadeada<int> *resultado=new ListaEncadeada<int>, *resultadoParcial=new ListaEncadeada<int>; int valorDeCorte=999; buscaProfundidade(--noOrigem, --noMeta, 0, resultadoParcial, resultado, valorDeCorte); // 99 arbitrário return resultado; } void adicionaAresta(int no1, int no2, T pesoDaAresta){ arestas->adiciona(--no1, --no2, pesoDaAresta); arestas->adiciona(no2, no1, pesoDaAresta); } void removeAresta(int no1, int no2){ arestas->adiciona(--no1, --no2, 0); arestas->adiciona(no2, no1, 0); } /** * Precisa ser um float para continuar * @param tamanhoDaColuna */ void imprime(int tDaColuna){ // tamanho da coluna ostringstream os; os << "%" << tDaColuna << "i"; const char * temp=os.str().c_str(); // cabecalho printf("(I = índices)\n"); printf("%s", "I|"); for(int coluna=0; coluna < arestas->numeroDeColunas; coluna++)printf(temp, coluna + 1); printf("\n--"); for(int coluna=0; coluna < arestas->numeroDeColunas * tDaColuna; coluna++)printf("-"); cout << endl; // ------------ for(int linha=0; linha < arestas->numeroDeLinhas; linha++){ printf("%i|", linha + 1); for(int coluna=0; coluna < arestas->numeroDeColunas; coluna++) printf(temp, arestas->matriz[linha * arestas->numeroDeColunas + coluna]); //cout << matriz[linha * numeroDeColunas + coluna] << " "; cout << endl; } cout << endl; } private: void buscaProfundidade(int noOrigem, int noMeta, int somaAtual, ListaEncadeada<int> *resultadoParcial, ListaEncadeada<int> *resultado, int &valorDeCorte){ // entra soma sempre 0 if(somaAtual > valorDeCorte) return; // cutoff, corte da arvofre de possibilidades else if(noOrigem == noMeta){ // encontrou a meta, faz backtrack, adiciona o resultado + caminho valorDeCorte=somaAtual; // muda o valor de corte para aumentar as chances de realiza-lo resultadoParcial->adicionaAoFinal(noOrigem + 1); // acrescenta no à lista de nos que esta navegando resultadoParcial->adicionaAoInicio(somaAtual); ListaEncadeada<int> *paraApagar=new ListaEncadeada<int>; resultado->inicio=resultadoParcial->copia()->inicio; resultadoParcial->removeAoInicio(); // Limpa o resultado resultadoParcial->removeAoFinal(); delete paraApagar; return; }else for(int noDestino=0; noDestino < arestas->numeroDeLinhas; noDestino++){ //navega todos os nos adjascentes if(arestaExiste(noOrigem, noDestino) && statusDe[noDestino].visitado == false){ // se ele vai visitar, se a aresta existe ... resultadoParcial->adicionaAoFinal(noOrigem + 1); // acrescenta no à lista de nos que esta navegando statusDe[noOrigem].visitado=true; buscaProfundidade(noDestino, noMeta, somaAtual + pegaPeso(noOrigem, noDestino), resultadoParcial, resultado, valorDeCorte); // vai somando ate chegar na meta statusDe[noOrigem].visitado=false; resultadoParcial->removeAoFinal(); // Depois de ter buscado e voltado, a busca ja nao importa mais e é removida, continua buscando... } }// percorreu todos ou esse noOrigem É TERMINAL // faz backtrack e continua ou acaba; } int pegaPeso(int no1, int no2){ return arestas->pega(no1, no2); } bool arestaExiste(int x, int y){ return arestas->pega(x, y) != 0; } };
#include <cstdlib> #include <iostream> #include <memory> #include <utility> #include <boost/asio.hpp> #include <boost/filesystem.hpp> #include <ostream> #include <fstream> #include "json.hpp" #include "Base64.h" #include "utility.h" #include "session.h" #include "server.h" #include "rsa.h" #include <osrng.h> #include "filters.h" #include "files.h" #include <base64.h> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); DWORD dwMode = 0; GetConsoleMode(hOut, &dwMode); dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; SetConsoleMode(hOut, dwMode); #endif try { int port = 32500; boost::asio::io_context io_context; server s(io_context, port); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ /** @file stdlib_string.cpp String functions. Functions common to the 'char' and 'uni_char' types are defined in stdlib_string_common.inl; that file is included several times, with proper #defines for function names and types, at the end of this file. (If you don't understand how this works then you need to read the code once more.) */ #include "core/pch.h" #ifdef HAVE_LTH_MALLOC # include "modules/memtools/happy-malloc.h" #endif /* These are abstractions that are used mostly by the parameterized code in stdlib_string_common.inl */ static inline size_t strlib_strlen(const char* s) { return op_strlen(s); } static inline size_t strlib_strlen(const uni_char* s) { return uni_strlen(s); } static inline char* strlib_strcpy(char* dest, const char* src) { return op_strcpy(dest, src); } static inline uni_char* strlib_strcpy(uni_char* dest, const uni_char* src) { return uni_strcpy(dest, src); } /* For these functions we have overloaded versions, and we can only map one of them to the system libraries */ #ifdef HAVE_UNI_STRSTR uni_char* uni_strstr(const uni_char* haystack, const uni_char* needle) { return const_cast<uni_char *>(real_uni_strstr(haystack, needle)); } #endif #ifdef HAVE_UNI_STRISTR const uni_char* uni_stristr(const uni_char* haystack, const uni_char* needle) { return real_uni_stristr(haystack, needle); } #endif #ifdef HAVE_UNI_STRCMP int uni_strcmp(const uni_char* str1, const uni_char* str2) { return real_uni_strcmp(str1, str2); } #endif #ifdef HAVE_UNI_STRICMP int uni_stricmp(const uni_char* str1, const uni_char* str2) { return real_uni_stricmp(str1, str2); } #endif #ifdef HAVE_UNI_STRNCMP int uni_strncmp(const uni_char* str1, const uni_char* str2, size_t n) { return real_uni_strncmp(str1, str2, n); } #endif #ifdef HAVE_UNI_STRNICMP int uni_strnicmp(const uni_char* str1, const uni_char* str2, size_t n) { return real_uni_strnicmp(str1, str2, n); } #endif /* These functions do not exist as parametrized versions */ #ifndef HAVE_UNI_STRTOK uni_char *uni_strtok(uni_char * s, const uni_char * delim) { uni_char **strtok_global_pp = &g_opera->stdlib_module.m_uni_strtok_datum; if (!s) s = *strtok_global_pp; // use previous pointer if (!*s) { *strtok_global_pp = s; // in case the string was empty initially return NULL; // the end has come } // may be in an area composed of delims, if so, skip those while (*s) { const uni_char *delims = delim; while (*delims && *s != *delims) delims++; if (!*delims) break; // stop at first non-delim s++; } // now we should be at the start of a token uni_char *token = s; while (*s) { const uni_char *delims = delim; while (*delims && *s != *delims) delims++; if (*delims) break; // stop at first delim s++; } // now we've found the end of the token if (*s) { (*s) = 0; *strtok_global_pp = s + 1; } else *strtok_global_pp = s; if (token == s) return NULL; // empty token else return token; } #endif // HAVE_UNI_STRTOK // Deprecate??? // Why not use op_strnicmp? (With suitable optimizations?) // // Warning: 7bit! (suitable for html-tags and attributes only, more or less) BOOL strni_eq(const char * str1, const char *str2, size_t len) { while (len-- && *str1) { char c = *str1; if (c >= 'a' && c <= 'z') { if (*str2 != (c & 0xDF)) return FALSE; } else if (*str2 != c) return FALSE; str1++, str2++; } return !*str2 || len == size_t(-1); } BOOL uni_stri_eq_upper(const uni_char* str1, const char* str2) { const unsigned char *unsigned_str2 = (const unsigned char *)str2; while ( *str1 ) { UnicodePoint c1 = *str1; OP_ASSERT( Unicode::ToUpper(*unsigned_str2) == *unsigned_str2 ); if( c1 != *unsigned_str2 && Unicode::ToUpper(c1) != *unsigned_str2 ) return FALSE; ++str1; ++unsigned_str2; } return (*unsigned_str2 == 0); } BOOL uni_stri_eq_lower(const uni_char* str1, const char* str2) { const unsigned char *unsigned_str2 = (const unsigned char *)str2; while ( *str1 ) { UnicodePoint c1 = *str1; OP_ASSERT( Unicode::ToLower(*unsigned_str2) == *unsigned_str2 ); if( c1 != *unsigned_str2 && Unicode::ToLower(c1) != *unsigned_str2 ) return FALSE; ++str1; ++unsigned_str2; } return (*unsigned_str2 == 0); } BOOL uni_strni_eq_lower(const uni_char* str1, const char* str2, size_t len) { const unsigned char *unsigned_str2 = (const unsigned char *)str2; while (len-- && *str1) { UnicodePoint c1 = *str1; OP_ASSERT( Unicode::ToLower(*unsigned_str2) == *unsigned_str2 ); if( c1 != *unsigned_str2 && Unicode::ToLower( c1 ) != *unsigned_str2 ) return FALSE; ++str1, ++unsigned_str2; if (*str1 == 0 && *unsigned_str2 != 0 && len >= 1) return FALSE; } return !*unsigned_str2 || len == size_t(-1); } BOOL uni_strni_eq_lower(const uni_char* str1, const uni_char* str2, size_t len) { while (len-- && *str1) { UnicodePoint c1 = *str1; UnicodePoint c2 = *str2; OP_ASSERT( Unicode::ToLower(c2) == c2 ); if( c1 != c2 && Unicode::ToLower( c1 ) != c2 ) return FALSE; ++str1, ++str2; if (*str1 == 0 && *str2 != 0 && len >= 1) return FALSE; } return !*str2 || len == size_t(-1); } BOOL uni_strni_eq_upper(const uni_char * str1, const char *str2, size_t len) { while (len-- && *str1) { UnicodePoint c1 = *str1; OP_ASSERT( Unicode::ToUpper(*(unsigned char*)str2) == *(unsigned char*)str2 ); if( c1 != *(unsigned char *)str2 && Unicode::ToUpper( c1 ) != *(unsigned char*)str2 ) return FALSE; ++str1, ++str2; if (*str1 == 0 && *(unsigned char*)str2 != 0 && len >= 1) return FALSE; } return !*str2 || len == size_t(-1); } BOOL uni_strni_eq_upper(const uni_char * str1, const uni_char *str2, size_t len) { while (len-- && *str1) { UnicodePoint c1 = *str1; UnicodePoint c2 = *str2; OP_ASSERT( Unicode::ToUpper(c2) == c2 ); if( c2 != c1 && Unicode::ToUpper( c1 ) != c2 ) return FALSE; ++str1, ++str2; if (*str1 == 0 && *str2 != 0 && len >= 1) return FALSE; } return !*str2 || len == size_t(-1); } BOOL uni_strni_eq_lower_ascii(const uni_char* str1, const uni_char* str2, size_t len) { while (len-- && *str1) { UnicodePoint c1 = *str1; UnicodePoint c2 = *str2; OP_ASSERT( c2 < 127 ); OP_ASSERT( Unicode::ToLower(c2) == c2 ); if( c1 != c2 && ( c1 < 'A' || c1 > 'Z' || c1 + 32 != c2 )) return FALSE; OP_ASSERT( Unicode::ToLower(c1) == c2 ); ++str1, ++str2; if (*str1 == 0 && *str2 != 0 && len >= 1) return FALSE; } return !*str2 || len == size_t(-1); } /* Functions that operate on 'char' */ extern "C" { #define CHAR_TYPE char #define CHAR2_TYPE char // Used for second parameter of some functions #define UCHAR_TYPE unsigned char #define UCHAR2_TYPE unsigned char // Used for second parameter of some functions #define CHARPARAM_TYPE int // Used when a character is passed through 'int' in the stdlib #undef CHAR_UNICODE #undef CHAR2_UNICODE #define STRLEN_NAME op_strlen #define STRCPY_NAME op_strcpy #define STRNCPY_NAME op_strncpy #define STRLCPY_NAME op_strlcpy #define STRCAT_NAME op_strcat #define STRNCAT_NAME op_strncat #define STRLCAT_NAME op_strlcat #define STRCMP_NAME op_strcmp #define STRNCMP_NAME op_strncmp #define STRICMP_NAME op_stricmp #define STRNICMP_NAME op_strnicmp #define STRDUP_NAME op_lowlevel_strdup #define STRCHR_NAME op_strchr #define STRRCHR_NAME op_strrchr #define STRSTR_NAME op_strstr #define STRISTR_NAME op_stristr #define STRSPN_NAME op_strspn #define STRCSPN_NAME op_strcspn #define STRPBRK_NAME op_strpbrk #define STRREV_NAME op_strrev #define STRUPR_NAME op_strupr #define STRLWR_NAME op_strlwr // Remove support for APIs not imported #ifndef STDLIB_STRREV # undef HAVE_STRREV # define HAVE_STRREV #endif #define HAVE_CONVERTING_STRDUP // not part of the op_ set #define HAVE_STR_EQ // not part of the op_ set #include "modules/stdlib/src/stdlib_string_common.inl" } // extern "C" /* Functions that operate on 'uni_char' */ #undef CHAR_TYPE #undef CHAR2_TYPE #define CHAR_TYPE uni_char #define CHAR2_TYPE uni_char #undef UCHAR_TYPE #undef UCHAR2_TYPE #define UCHAR_TYPE uni_char #define UCHAR2_TYPE uni_char #undef CHARPARAM_TYPE #define CHARPARAM_TYPE uni_char #undef CHAR_UNICODE #define CHAR_UNICODE #undef CHAR2_UNICODE #define CHAR2_UNICODE #undef STRLEN_NAME #undef STRCPY_NAME #undef STRNCPY_NAME #undef STRLCPY_NAME #undef STRCAT_NAME #undef STRNCAT_NAME #undef STRLCAT_NAME #undef STRCMP_NAME #undef STRNCMP_NAME #undef STRDUP_NAME #undef STRCHR_NAME #undef STRICMP_NAME #undef STRNICMP_NAME #undef STRRCHR_NAME #undef STRSTR_NAME #undef STRISTR_NAME #undef STRSPN_NAME #undef STRCSPN_NAME #undef STRPBRK_NAME #undef STRREV_NAME #define STRLEN_NAME uni_strlen #define STRCPY_NAME uni_strcpy #define STRNCPY_NAME uni_strncpy #define STRLCPY_NAME uni_strlcpy #define STRCAT_NAME uni_strcat #define STRNCAT_NAME uni_strncat #define STRLCAT_NAME uni_strlcat #define STRCMP_NAME uni_strcmp #define STRNCMP_NAME uni_strncmp #define STRICMP_NAME uni_stricmp #define STRNICMP_NAME uni_strnicmp #define STRDUP_NAME uni_lowlevel_strdup #define STRCHR_NAME uni_strchr #define STRRCHR_NAME uni_strrchr #define STRSTR_NAME uni_strstr #define STRISTR_NAME uni_stristr #define STRSPN_NAME uni_strspn #define STRCSPN_NAME uni_strcspn #define STRPBRK_NAME uni_strpbrk #define STR_EQ_NAME uni_str_eq #define STRREV_NAME uni_strrev /* Reset have variables using the UNI versions */ #undef HAVE_STRLEN #ifdef HAVE_UNI_STRLEN # define HAVE_STRLEN #endif #undef HAVE_STRCPY #ifdef HAVE_UNI_STRCPY # define HAVE_STRCPY #endif #undef HAVE_STRNCPY #ifdef HAVE_UNI_STRNCPY # define HAVE_STRNCPY #endif #undef HAVE_STRLCPY #ifdef HAVE_UNI_STRLCPY # define HAVE_STRLCPY #endif #undef HAVE_STRCAT #ifdef HAVE_UNI_STRCAT # define HAVE_STRCAT #endif #undef HAVE_STRNCAT #ifdef HAVE_UNI_STRNCAT # define HAVE_STRNCAT #endif #undef HAVE_STRLCAT #ifdef HAVE_UNI_STRLCAT # define HAVE_STRLCAT #endif #undef HAVE_STRCMP #ifdef HAVE_UNI_STRCMP # define HAVE_STRCMP #endif #undef HAVE_STRNCMP #ifdef HAVE_UNI_STRNCMP # define HAVE_STRNCMP #endif #undef HAVE_STRICMP #ifdef HAVE_UNI_STRICMP # define HAVE_STRICMP #endif #undef HAVE_STRNICMP #ifdef HAVE_UNI_STRNICMP # define HAVE_STRNICMP #endif #undef HAVE_STRDUP #ifdef HAVE_UNI_STRDUP # define HAVE_STRDUP #endif #undef HAVE_STRCHR #ifdef HAVE_UNI_STRCHR # define HAVE_STRCHR #endif #undef HAVE_STRRCHR #ifdef HAVE_UNI_STRRCHR # define HAVE_STRRCHR #endif #undef HAVE_STRSTR #ifdef HAVE_UNI_STRSTR # define HAVE_STRSTR #endif #undef HAVE_STRISTR #ifdef HAVE_UNI_STRISTR # define HAVE_STRISTR #endif #undef HAVE_STRSPN #ifdef HAVE_UNI_STRSPN # define HAVE_STRSPN #endif #undef HAVE_STRCSPN #ifdef HAVE_UNI_STRCSPN # define HAVE_STRCSPN #endif #undef HAVE_STRPBRK #ifdef HAVE_UNI_STRPBRK # define HAVE_STRPBRK #endif #undef HAVE_STR_EQ #undef HAVE_STRREV #ifdef HAVE_UNI_STRREV # define HAVE_STRREV #endif #define HAVE_STRCASE // Remove support for APIs not imported #ifndef STDLIB_STRREV # undef HAVE_STRREV # define HAVE_STRREV #endif #include "modules/stdlib/src/stdlib_string_common.inl" /* Functions that operate on 'uni_char' on the first parameter and 'char' on the second parameter or return type. Note these all use uni_whatever names */ #undef CHAR_TYPE #undef CHAR2_TYPE #define CHAR_TYPE uni_char #define CHAR2_TYPE char #undef UCHAR_TYPE #undef UCHAR2_TYPE #define UCHAR_TYPE uni_char #define UCHAR2_TYPE unsigned char #undef CHAR_UNICODE #define CHAR_UNICODE #undef CHAR2_UNICODE #undef HAVE_STRLEN #undef HAVE_STRCPY #undef HAVE_STRNCPY #undef HAVE_STRLCPY #undef HAVE_STRCAT #undef HAVE_STRNCAT #undef HAVE_STRLCAT #undef HAVE_STRCMP #undef HAVE_STRNCMP #undef HAVE_STRICMP #undef HAVE_STRNICMP #undef HAVE_STRDUP #undef HAVE_STRCHR #undef HAVE_STRRCHR #undef HAVE_STRSTR #undef HAVE_STRISTR #undef HAVE_STRSPN #undef HAVE_STRCSPN #undef HAVE_STRPBRK #undef HAVE_STR_EQ #undef HAVE_STRREV #define HAVE_STRLEN #define HAVE_STRCPY #define HAVE_STRNCPY #define HAVE_STRLCPY #define HAVE_STRCAT #define HAVE_STRNCAT #define HAVE_STRLCAT #define HAVE_STRDUP #define HAVE_STRCHR #define HAVE_STRRCHR #define HAVE_STRSPN #define HAVE_STRCSPN #define HAVE_STRPBRK #define HAVE_STRREV #undef HAVE_CONVERTING_STRDUP #define CONVERTING_STRDUP_NAME uni_down_strdup #include "modules/stdlib/src/stdlib_string_common.inl" /* Functions that operate on 'char' on the first parameter and 'uni_char' on the second parameter or return type. Note these all use uni_whatever names */ #undef CHAR_TYPE #undef CHAR2_TYPE #define CHAR_TYPE char #define CHAR2_TYPE uni_char #undef UCHAR_TYPE #undef UCHAR2_TYPE #define UCHAR_TYPE unsigned char #define UCHAR2_TYPE uni_char #undef CHAR_UNICODE #undef CHAR2_UNICODE #define CHAR2_UNICODE #define HAVE_STRLEN #define HAVE_STRCPY #define HAVE_STRNCPY #define HAVE_STRCAT #define HAVE_STRNCAT #define HAVE_STRLCAT #define HAVE_STRCMP #define HAVE_STRNCMP #define HAVE_STRICMP #define HAVE_STRNICMP #define HAVE_STRDUP #define HAVE_STRCHR #define HAVE_STRRCHR #define HAVE_STRSTR #define HAVE_STRISTR #define HAVE_STRSPN #define HAVE_STRCSPN #define HAVE_STRPBRK #define HAVE_STR_EQ #undef CONVERTING_STRDUP_NAME #define CONVERTING_STRDUP_NAME uni_up_strdup #undef HAVE_STRLCPY #undef STRLCPY_NAME #define STRLCPY_NAME uni_cstrlcpy #include "modules/stdlib/src/stdlib_string_common.inl" extern "C" { #undef op_isdigit #undef op_isxdigit #undef op_isspace #undef op_isupper #undef op_islower #undef op_isalnum #undef op_isalpha #undef op_iscntrl #undef op_ispunct int op_isdigit(int c) { return uni_isdigit(c); } int op_isxdigit(int c) { return uni_isxdigit(c); } int op_isspace(int c) { return uni_isspace(c); } int op_isupper(int c) { return uni_isupper(c); } int op_islower(int c) { return uni_islower(c); } int op_isalnum(int c) { return uni_isalnum(c); } int op_isalpha(int c) { return uni_isalpha(c); } int op_iscntrl(int c) { return uni_iscntrl(c); } int op_ispunct(int c) { return uni_ispunct(c); } int op_isprint(int c) { // FIXME: This is a halfway decent kludge, but we really need something better. return c < 256 && !op_iscntrl(c); } }
//By SCJ #include<bits/stdc++.h> using namespace std; #define endl '\n' #define INF 0x3f3f3f3f #define maxn 10004 int a[maxn],dp[maxn],LIS1[maxn],LIS2[maxn]; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; while(cin>>n) { memset(dp,INF,sizeof(dp)); for(int i=0;i<n;++i) cin>>a[i]; int ma=0; for(int i=0;i<n;++i) { int d=lower_bound(dp,dp+ma,a[i])-dp; if(d==ma) ma++; dp[d]=a[i]; LIS1[i]=d; } memset(dp,INF,sizeof(dp)); for(int i=n-1;i>=0;--i) { int d=lower_bound(dp,dp+ma,a[i])-dp; if(d==ma) ma++; dp[d]=a[i]; LIS2[i]=d; } int ans=0; for(int i=0;i<n;++i) ans=max(ans,min(LIS1[i],LIS2[i])*2+1); cout<<ans<<endl; } }
#include "laboratorio.h" laboratorio::laboratorio(){ this->cont=0; } void laboratorio::capturar_final(const computadora &c){ if(cont<5){ this->arreglo[cont]=c; cont++; } else{ cout<<"Arreglo lleno"<<endl; } } void laboratorio::mostrar_elementos(){ cout<<left; cout<<setw(19)<<"Sistema Operativo"; cout<<setw(19)<<"Tarjeta Grafica"; cout<<setw(10)<<"Precio"; cout<<setw(17)<<"Cantidad de Ram"<<endl; for(size_t i=0;i<cont;i++){ computadora &c=arreglo[i]; cout<<c; cout<<"\n"; } }
#include <iostream> #include <string> #include "Student.h" int main() { Student students[5]; students[0] = Student("Tom", 85); students[1] = Student("Alice", 71); students[2] = Student("Jack", 93); students[3] = Student("Mary", 65); students[4] = Student("Sue", 40); for(int i = 0; i < 5; i++){ students[i].print(); } }
#pragma once #include <string> #include <map> #if 0 namespace flex_typeclass_plugin { void setOutdir( const char outdir[]); } // namespace flex_typeclass_plugin #endif // 0
class PrintMinNumberSolver { public: string PrintMinNumber(vector<int> numbers) { if (numbers.size() == 0) return ""; vector<string> nums{}; for_each(numbers.begin(), numbers.end(), [&nums](int a) { nums.emplace_back(to_string(a)); }); sort(nums.begin(), nums.end(), [](string& a, string& b) { return a + b < b + a; }); string res{}; for_each(nums.begin(), nums.end(), [&res](string str) { res += str; }); return res; } void test() { vector<vector<int>> test_cases = { {3, 32, 321}, {1}, {} }; for (auto& i : test_cases) { cout << i << " ==> " << PrintMinNumber(i) << endl; } } };
#include "consumermgr.h" #include "config.h" #include "bnlogif.h" #include <unistd.h> #include <sys/time.h> #include "producermgr.h" ConsumerMgr* ConsumerMgr::pConsumerMgr = new ConsumerMgr(); ConsumerMgr* ConsumerMgr::Instance() { return pConsumerMgr; } ConsumerMgr::ConsumerMgr() { } ConsumerMgr::~ConsumerMgr() { } int ConsumerMgr::MakeCSMHanderPool() { int nPoolSize = Config::Instance()->m_conumercfg.m_poolsize; int i = 0; for(; i < nPoolSize; i++) { CSMHANDLER * pHandler = new CSMHANDLER; if(NULL == pHandler) { break; } Consumer * pCon = new Consumer(); if(NULL == pCon) { delete pHandler; pHandler = NULL; break; } pHandler->pCsm = pCon; pHandler->nCsmStatus = STATUS_IDLE; m_CsmPtr2Index[pCon] = i; m_vCsm.push_back(pHandler); } return i; } Consumer * ConsumerMgr::getConsumer(string& market) { std::vector<Producer* > vecProducer = ProducerMgr::Instance()->GetProducers(); if(!vecProducer.size()) return NULL; printf("Jerry: getConsumer itervec size is %d\n", vecProducer.size()); std::vector<Producer* >::iterator itervec = vecProducer.begin(); market = (*itervec)->getBsdrMarket(); printf("Jerry: getConsumer market is %s\n", market.c_str()); unsigned int minInUse = 0; //bool hasfound = false; std::map<string, int>::iterator iterforfoundBsdrInMap; for(; itervec != vecProducer.end(); itervec++) { iterforfoundBsdrInMap = market2inuse.find((*itervec)->getBsdrMarket()); if(iterforfoundBsdrInMap == market2inuse.end()) { market =(*itervec)->getBsdrMarket(); break; }else { if(itervec == vecProducer.begin()) { minInUse = iterforfoundBsdrInMap->second + 1; market = iterforfoundBsdrInMap->first; continue; } if(iterforfoundBsdrInMap->second < minInUse-1) { minInUse = iterforfoundBsdrInMap->second+1; market = iterforfoundBsdrInMap->first; } } } printf("Jerry : find selected bsdr %s\n", market.c_str()); std::lock_guard<std::mutex> lck(m_mutex); std::vector<CSMHANDLER *>::iterator iter = m_vCsm.begin(); //std::string pSelectedBsdr; for(; iter != m_vCsm.end(); iter++) { if(STATUS_IDLE == (*iter)->nCsmStatus) { (*iter)->nCsmStatus = STATUS_BUY; int nNum = 0; // Jerry std::map<string, int>::iterator itermap = market2inuse.find(market); if(itermap == market2inuse.end()) { market2inuse[market] = 0; } else { nNum = itermap->second + 1; nNum = nNum % Config::Instance()->m_consumerNum; itermap->second = nNum; } (*iter)->pCsm->setProNum(nNum); return (*iter)->pCsm; } } Consumer * ret = NULL; int nIncrement = Config::Instance()->m_conumercfg.m_increment; int i = 0; while(i < nIncrement) { CSMHANDLER * pHandler = new CSMHANDLER; if(NULL == pHandler) { break; } Consumer * pCon = new Consumer(); if(NULL == pCon) { delete pHandler; pHandler = NULL; break; } pHandler->pCsm = pCon; if(NULL == ret) { ret = pCon; int nNum = 0; std::map<string, int>::iterator itermap = market2inuse.find(market); if(itermap == market2inuse.end()) { market2inuse[market] = 0; } else { nNum = itermap->second + 1; nNum = nNum % Config::Instance()->m_consumerNum; itermap->second = nNum; } pCon->setProNum(nNum); pHandler->nCsmStatus = STATUS_BUY; } else { pHandler->nCsmStatus = STATUS_IDLE; } m_CsmPtr2Index[pCon] = m_vCsm.size(); m_vCsm.push_back(pHandler); i++; } return ret; } void ConsumerMgr::ReleaseCsm(Consumer * pCsm) { if(NULL == pCsm) { return; } std::map<Consumer *, int>::iterator iter = m_CsmPtr2Index.find(pCsm); if(iter == m_CsmPtr2Index.end()) { return; } if(iter->second > m_vCsm.size() - 1) { return; } m_vCsm[iter->second]->nCsmStatus = STATUS_IDLE; } // int ConsumerMgr::MakeCSMPool() // { // int nPoolSize = Config::Instance()->m_conumercfg.m_poolsize; // int i = 0; // for(; i < nPoolSize; i++) // { // Consumer * pCon = new Consumer(); // if(NULL == pCon) // { // break; // } // m_vecCsm.push_back(pCon); // } // return i; // } // Consumer * ConsumerMgr::GetCsm(std::string market) // { // Consumer * pRet = NULL; // std::lock_guard<std::mutex> lck(m_vecCmMtx); // if(m_vecCsm.size() > 0) // { // pRet = m_vecCsm[0]; // m_vecCsm.erase(m_vecCsm.begin()); // int nNum = 0; // std::map<string, int>::iterator itermap = market2inuse.find(market); // if(itermap == market2inuse.end()) // { // market2inuse[market] = 0; // } // else // { // nNum = itermap->second + 1; // nNum = nNum % Config::Instance()->m_consumerNum; // itermap->second = nNum; // } // pRet->setProNum(nNum); // return pRet; // } // int nIncrement = Config::Instance()->m_conumercfg.m_increment; // int i = 0; // while(i < nIncrement) // { // Consumer * pCon = new Consumer(); // if(NULL == pCon) // { // break; // } // if(NULL == pRet) // { // pRet = pCon; // int nNum = 0; // std::map<string, int>::iterator itermap = market2inuse.find(market); // if(itermap == market2inuse.end()) // { // market2inuse[market] = 0; // } // else // { // nNum = itermap->second + 1; // nNum = nNum % Config::Instance()->m_consumerNum; // itermap->second = nNum; // } // pCon->setProNum(nNum); // } // else // { // m_vecCsm.push_back(pCon); // } // i++; // } // return pRet; // } // void ConsumerMgr::putCsm(Consumer * pCsm) // { // if(NULL == pCsm) // { // return; // } // std::lock_guard<std::mutex> lck(m_vecCmMtx); // m_vecCsm.push_back(pCsm); // } // void ConsumerMgr::onInterest(const InterestFilter& filter, const Interest& interest) // { // _LOG_INFO("recieve bsdr name pubish interest:" << interest); // Name dataName(interest.getName()); // Name::Component comBsdrMarket = dataName.get(POS_MARKET_BSDR_NAME_PUB); // std::string strBsdrMarket = comBsdrMarket.toUri(); // time_t tm = ::time(NULL); // int * pStatus = new int[Config::Instance()->m_consumerNum]; // if(NULL == pStatus) // { // return; // } // for(int j= 0; j < Config::Instance()->m_consumerNum + 1; j++) // { // pStatus[j] = 0; // } // std::lock_guard<std::mutex> lck(m_vecMutex); // for(int i = 0; i < m_vecConsumer.size(); ) // { // if(strBsdrMarket == m_vecConsumer[i]->m_market) // { // if(m_vecConsumer[i]->m_consumerNum > Config::Instance()->m_consumerNum) // { // delete m_vecConsumer[i]; // m_vecConsumer.erase(m_vecConsumer.begin() + i); // continue; // } // else // { // pStatus[m_vecConsumer[i]->m_consumerNum] = 1; // } // } // i++; // } // for(int k = 1; k < Config::Instance()->m_consumerNum + 1; k++) // { // if(0 == pStatus[k]) // { // Consumer * pConsumer = new Consumer(strBsdrMarket, k); // if(NULL == pConsumer) // { // break; // } // m_vecConsumer.push_back(pConsumer); // } // } // } // void ConsumerMgr::onRegisterFailed(const Name& profix, const std::string& reason) // { // _LOG_ERROR("onRegisterFailed:" << reason); // if(m_pface != nullptr) // { // m_pface->shutdown(); // } // }
// Copyright (c) 2016 Agustin Berge // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <pika/preprocessor/cat.hpp> #include <type_traits> /// This macro creates a boolean unary meta-function such that for /// any type X, has_name<X>::value == true if and only if X is a /// class type and has a nested type member x::name. The generated /// trait ends up in a namespace where the macro itself has been /// placed. #define PIKA_HAS_XXX_TRAIT_DEF(Name) \ template <typename T, typename Enable = void> \ struct PIKA_PP_CAT(has_, Name) \ : std::false_type \ { \ }; \ \ template <typename T> \ struct PIKA_PP_CAT(has_, Name)<T, std::void_t<typename T::Name>> : std::true_type \ { \ }; \ \ template <typename T> \ using PIKA_PP_CAT(PIKA_PP_CAT(has_, Name), _t) = typename PIKA_PP_CAT(has_, Name)<T>::type; \ \ template <typename T> \ inline constexpr bool PIKA_PP_CAT(PIKA_PP_CAT(has_, Name), _v) = \ PIKA_PP_CAT(has_, Name)<T>::value; \ /**/
// chunk_manager.h #pragma once #include "math/vec3.h" #include "chunk.h" #include "world.h" #include "octree.h" #include <vector> using namespace leap::system; namespace leap { namespace world { class ChunkManager final { public: ChunkManager(); ~ChunkManager(); Rval init(); void new_terrain(); Chunk* get_chunk(const math::vec3& pos); const std::vector<Chunk>& get_chunks() const { return loaded_chunks_; } std::vector<Chunk>& get_chunks() { return loaded_chunks_; } private: std::vector<Chunk> loaded_chunks_; std::unique_ptr<octree::Node<std::size_t>> octree_; }; }//namespace }//namespace
/* * OtsuHand.hpp * * Created on: 2017年3月15日 * Author: lcy */ #ifndef OTSUHAND_HPP_ #define OTSUHAND_HPP_ #include <opencv2/opencv.hpp> class OtsuHand { public: OtsuHand() {} cv::Mat& start(cv::Mat &src); cv::Mat& justRGB(cv::Mat &src); private: void SkinRGB( cv::Mat &src); cv::Mat dst; }; #endif /* OTSUHAND_HPP_ */
#ifndef _DRAWER_H_ #define _DRAWER_H_ #include "bmp.h" #include "misc.h" //************************************************************ // Interfejs dla metod rysujacych. class Drawer{ public: Drawer() : bitmap(nullptr) {} Drawer(JiMP2::BMP &bmp) : bitmap(&bmp) {} virtual ~Drawer(){ bitmap = nullptr; } virtual void drawPoint(Point P, Colour clr) = 0; virtual void drawLine(Point A, Point B, Colour clr) = 0; virtual void drawCircle(Point S, uint16_t r, Colour clr) = 0; virtual void drawDisk(Point S, uint16_t r, Colour clr) = 0; virtual void drawArc(Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr) = 0; virtual void drawCircularSector(Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr) = 0; virtual void drawEllipse(Point S, uint16_t a, uint16_t b, Colour clr) = 0; virtual void drawRectangle(Point A, Point B, Colour clr) = 0; virtual void drawRegularPolygon(Point S, int n, fp_t side_length, Colour clr) = 0; void setBitmap(JiMP2::BMP &bmp){ bitmap = &bmp; } class DrawingException : public std::exception {}; protected: JiMP2::BMP *bitmap; }; //************************************************************ class DrawerImplementation : public Drawer{ public: DrawerImplementation() : Drawer() {} DrawerImplementation(JiMP2::BMP &bmp) : Drawer(bmp) {} virtual void drawPoint(Point P, Colour clr); virtual void drawLine(Point A, Point B, Colour clr); virtual void drawCircle(Point S, uint16_t r, Colour clr); virtual void drawDisk(Point S, uint16_t r, Colour clr); virtual void drawArc(Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr); virtual void drawCircularSector(Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr); virtual void drawEllipse(Point S, uint16_t a, uint16_t b, Colour clr); virtual void drawRectangle(Point A, Point B, Colour clr); virtual void drawRegularPolygon(Point S, int n, fp_t side_length, Colour clr); }; //************************************************************ #endif //_DRAWER_H_
#include <bits/stdc++.h> #define ll long long #define ull unsigned long long #define FOR(i,n) for(ll i=0;i<n;i++) #define FOR1(i,n) for(ll i=1;i<n;i++) #define FORn1(i,n) for(ll i=1;i<=n;i++) #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define mod 1000000007; using namespace std; vector<ll> sieve(ll n) { vector<ll> v; bool prime[n+1]; memset(prime, true, sizeof(prime)); for (ll p=2; p*p<=n; p++) { if (prime[p] == true) { for (ll i=p*p; i<=n; i += p) prime[i] = false; } } for (ll p=2; p<=n; p++) if (prime[p]) v.push_back(p); return v; } int main() { // your code goes here fast; ll n,m; cin>>n>>m; ll tmp=n+m; vector<ll> v=sieve(tmp); cout<<v.size(); return 0; }
#pragma once #include <iberbar/Gui/Widget.h> #include <iberbar/Gui/RenderElement.h> #include <iberbar/Utility/Xml/Base.h> #include <iberbar/Utility/Color.h> namespace iberbar { namespace Gui { struct UXmlParserContext; __iberbarGuiApi__ void XmlReadProc_Object( Xml::CNodeA* pXmlNode, CObject* pObject ); __iberbarGuiApi__ void XmlReadProc_Widget( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ void XmlReadProc_Widget_Button( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ void XmlReadProc_Widget_CheckBox( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ void XmlReadProc_Widget_RadioBox( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ void XmlReadProc_Widget_ListBox( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ void XmlReadProc_Widget_EditBox( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ void XmlReadProc_Widget_ProgressBar( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CWidget* pWidget, CRenderElement* pRenderElement ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget( const char* strType ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget_Button( const char* strType ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget_CheckBox( const char* strType ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget_RadioBox( const char* strType ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget_ListBox( const char* strType ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget_EditBox( const char* strType ); __iberbarGuiApi__ CWidget* XmlCreateProc_Widget_ProgressBar( const char* strType ); __iberbarGuiApi__ void XmlReadProc_Element( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CRenderElement* pElement ); __iberbarGuiApi__ void XmlReadProc_Element_ColorRect( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CRenderElement* pElement ); __iberbarGuiApi__ void XmlReadProc_Element_StateTexture( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CRenderElement* pElement ); __iberbarGuiApi__ void XmlReadProc_Element_StateLabel( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CRenderElement* pElement ); __iberbarGuiApi__ void XmlReadProc_Element_EditBoxText( const UXmlParserContext* pContext, Xml::CNodeA* pXmlNode, CRenderElement* pElement ); __iberbarGuiApi__ CRenderElement* XmlCreateProc_Element( const char* strType ); __iberbarGuiApi__ CRenderElement* XmlCreateProc_Element_ColorRect( const char* strType ); __iberbarGuiApi__ CRenderElement* XmlCreateProc_Element_StateTexture( const char* strType ); __iberbarGuiApi__ CRenderElement* XmlCreateProc_Element_StateLabel( const char* strType ); __iberbarGuiApi__ CRenderElement* XmlCreateProc_Element_EditBoxText( const char* strType ); __iberbarGuiApi__ int XmlAttributeConvertToWidgetState( const char* strStateName ); __iberbarGuiApi__ CColor4B XmlAttributeConvertToColor4B( const char* strColor ); __iberbarGuiApi__ CRect2f XmlAttributeConvertToUV( const char* strUV ); } }
#ifndef T_GEOMETRY_HPP #define T_GEOMETRY_HPP #include "../model.hpp" /* this is actually a bad design. I can either write public functions: makeCube, makeUVSphere, makeCylinder, makePyramid something like that */ class CubeModel : public Model { public: //this will give you a one-by-one cube CubeModel(const glm::vec3 translation = glm::vec3(0.0f), const glm::vec3 scale = glm::vec3(1.0f), const glm::quat rotation = glm::quat(glm::vec3(0.0f))); //void SetColor(glm::vec4 color); }; //basically we need to write the use the different mesh property class isoSphere : public Model { public: isoSphere(float radius); }; #endif /* EOF */
#include<bits/stdc++.h> using namespace std; const int maxn = 1e4+4; vector<int>g[maxn]; int f[maxn],n,m,a,b; bool visit[maxn][maxn]; void init(){ for(int i=1;i<=n;++i)f[i]=i; } int find(int x){ int root=x,j; while(root!=f[root])root=f[root]; while(x!=root){ j = f[x]; f[x]=root; x = j; } return root; } void join(int x,int y){ int xx=find(x),yy=find(y); if(xx!=yy)f[xx]=yy; } bool scc(){ for(int i=2;i<=n;++i)if(f[i]!=f[1])return false; return true; }//判断图的连通性 bool eulerjudeg(){ int num = 0; for(int i=1;i<=n;++i)if(g[i].size()&1)num++; if(!num||(num==2&&g[1].size()&1))return true; return false; }//根据欧拉路径的性质,且要满足1为起点 typedef pair<int,int> pa; stack<int> path; stack<pa >s; void dfs(){ s.push(pa(1,0)); int i; while(!s.empty()){ a = s.top().first; i = s.top().second; s.pop(); for(;i<g[a].size();++i){ b=g[a][i]; if(!visit[a][b]){ visit[a][b]=visit[b][a]=true; s.push(pa(a,i+1));//优化 s.push(pa(b,0)); break; } } if(i==g[a].size())path.push(a); } }//需要利用栈来模拟dfs,不然会出现运行错误的情况 int main(){ scanf("%d%d",&n,&m); init(); for(int i=0;i<m;++i){ scanf("%d%d",&a,&b); g[b].push_back(a); g[a].push_back(b); join(a,b); } for(int i=1;i<=n;++i)find(i);//刷新并查集 if(scc()&&eulerjudeg()){ for(int i=1;i<=n;++i)sort(g[i].begin(),g[i].end()); //利用dfs的性质,将顶点排序后,取出的数自动满足字典序 dfs(); while(!path.empty()){ a = path.top(); path.pop(); cout<<a<<" "; }cout<<endl; }else printf("-1\n"); }
// HD-SEN0018 test #include <SoftwareSerial.h> const int PIN_SENSOR = 11; const int PIN_STATE = 10; const int PIN_RX = 2; const int PIN_TX = 3; SoftwareSerial serial(PIN_RX, PIN_TX); void setup() { Serial.begin(9600); serial.begin(9600); } void loop() { static int oldSensor = -1; int sensor = digitalRead(PIN_SENSOR); if (sensor > 0) { if (oldSensor != sensor) { serial.write( (byte)12 ); serial.write( (byte)1 ); Serial.write( (byte)1 ); } } else { if (oldSensor != sensor) { serial.write( (byte)12 ); serial.write( (byte)0 ); Serial.write( (byte)0 ); } } oldSensor = sensor; }
#ifndef CSUBSCRIBER_H #define CSUBSCRIBER_H #include "chandler.h" class CSubscriber { ros::NodeHandle nh; ros::NodeHandle nh_private; ros::Subscriber sub_cloud; ros::Subscriber sub_image; ros::Subscriber sub_transform; dynamic_reconfigure::Server<lidar_camera_offline_calibration::CalibrationConfig> server; dynamic_reconfigure::Server<lidar_camera_offline_calibration::CalibrationConfig>::CallbackType f; public: CSubscriber(); void run(); bool IsInitialized(); void ShowImages(); void setImageConfig(int i, int x); void setPointCloudConfig(int i, float x); bool showLock(); bool showUnLock(); public: private: bool m_bInitialized; CHandler m_Handler; }; #endif // CSUBSCRIBER_H
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4; -*- * * Copyright (C) 2007-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #if defined(POSIX_SELECTOR_SELECT) || defined(POSIX_SELECTOR_SELECT_FALLBACK) #include "platforms/posix/posix_selector.h" // PosixSelector, PosixSelectListener #include "platforms/posix/net/posix_network_address.h" // PosixNetworkAddress #include "platforms/posix/posix_signal_watcher.h" // PosixSignalListener #include "modules/util/simset.h" // AutoDeleteHead, Link #ifdef POSIX_OK_NETADDR #define IF_NETADDR(X) , X #else #define IF_NETADDR(X) /* skip it */ #endif // POSIX_OK_NETADDR class SelectListenerCarrier : public Link { public: const int m_file; PosixSelector::Type m_type; PosixSelectListener *m_ear; #ifdef POSIX_OK_NETADDR PosixNetworkAddress *m_address; #endif SelectListenerCarrier(int fd, PosixSelector::Type mode, PosixSelectListener *listener IF_NETADDR(PosixNetworkAddress *connect)) : m_file(fd), m_type(mode), m_ear(listener) IF_NETADDR(m_address(connect)) { OP_ASSERT(m_file >= 0 && m_ear); } ~SelectListenerCarrier() { OP_ASSERT(!InList()); #ifdef POSIX_OK_NETADDR OP_DELETE(m_address); #endif OP_ASSERT(m_file >= 0); } SelectListenerCarrier* Suc() { return static_cast<SelectListenerCarrier*>(Link::Suc()); } bool Carries(const PosixSelectListener *whom) { return whom == m_ear; } bool Carries(const PosixSelectListener *whom, int fd) { return whom == m_ear && fd == m_file; } }; class SelectData { public: fd_set m_read; fd_set m_write; fd_set m_except; SelectData() { FD_ZERO(&m_read); FD_ZERO(&m_write); FD_ZERO(&m_except); } void Set(int fd, unsigned int mode) { FD_SET(fd, &m_except); if (mode & PosixSelector::READ) FD_SET(fd, &m_read); if (mode & PosixSelector::WRITE) FD_SET(fd, &m_write); } unsigned int Check(int fd, bool& error) { unsigned int mode = 0; if (FD_ISSET(fd, &m_read)) mode |= PosixSelector::READ; if (FD_ISSET(fd, &m_write)) mode |= PosixSelector::WRITE; error = FD_ISSET(fd, &m_except); return mode; } }; class SimplePosixSelector : public PosixSelector, public AutoDeleteHead, public PosixLogger { private: SelectListenerCarrier *First() { return static_cast<SelectListenerCarrier *>(Head::First()); } /** Flag set during reporting. * * Set true by Work() to tell Delete() when it's not safe to really do * deletions. Work() takes care of actually chasing up the deletions * after it's set this back to false. */ bool m_reporting; /** Delete or mark for deletion. * * Used by Detach() to "remove" an item from the list. However, if called * during reporting of select()'s results, the item is merely marked for * later removal, by clearing its m_ear (which is typically points to an * object that's about to be deleted anyway). This avoids assorted problems * with entries in the list being deleted as a side-effect of call-backs * while Work() is iterating over the list; instead, such detached entries * are marked for deletion. */ void Delete(SelectListenerCarrier *whom); /** Purge entries marked for deletion while m_reporting was true. */ void Purge() { SelectListenerCarrier *run = First(); while (run) { SelectListenerCarrier *next = run->Suc(); if (!run->m_ear) Delete(run); run = next; } } public: SimplePosixSelector() : PosixLogger(ASYNC), m_reporting(false) { Log(CHATTY, "%010p: Started simple selector\n", this); } ~SimplePosixSelector(); // PosixSelector API: virtual bool Poll(double timeout); virtual void Detach(const PosixSelectListener *whom, int fd); virtual void Detach(const PosixSelectListener *whom); virtual void SetMode(const PosixSelectListener * listener, Type mode); virtual void SetMode(const PosixSelectListener * listener, int fd, Type mode); virtual OP_STATUS Watch(int fd, Type mode, PosixSelectListener *listener, const class OpSocketAddress *connect=0, bool accepts=false); DEPRECATED(virtual OP_STATUS Watch(int fd, Type mode, unsigned long interval, PosixSelectListener *listener, const class OpSocketAddress *connect=0)); }; #ifdef POSIX_SELECTOR_SELECT // static OP_STATUS PosixSelector::Create(PosixSelector * &selector) { OP_ASSERT(g_opera && !g_posix_selector); // Expect to be a singleton. selector = OP_NEW(SimplePosixSelector, ()); return selector ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } #endif // POSIX_SELECTOR_SELECT #ifdef POSIX_SELECTOR_SELECT_FALLBACK // static OP_STATUS PosixSelector::CreateWithFallback(PosixSelector * &selector) { if (OpStatus::IsError(PosixSelector::Create(selector))) { OP_ASSERT(g_opera && !g_posix_selector); // Expect to be a singleton. selector = OP_NEW(SimplePosixSelector, ()); return selector ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } return OpStatus::OK; } #endif // POSIX_SELECTOR_SELECT_FALLBACK SimplePosixSelector::~SimplePosixSelector() { Log(CHATTY, "%010p: Shutting down simple selector\n", this); // Give all listeners fair warning before we shut down. while (SelectListenerCarrier *run = First()) { run->Out(); // makes it safe for OnDetach() to delete or otherwise Detach m_ear run->m_ear->OnDetach(run->m_file); // May Out()/delete other list entries. OP_DELETE(run); } } void SimplePosixSelector::Delete(SelectListenerCarrier *whom) { Log(VERBOSE, "%010p: Disconnecting listener %010p\n", this, whom->m_ear); whom->m_type = NONE; if (m_reporting) whom->m_ear = 0; else { whom->Out(); OP_DELETE(whom); } } void SimplePosixSelector::Detach(const PosixSelectListener *whom) { OP_ASSERT(whom); SelectListenerCarrier *run = First(); while (run) { SelectListenerCarrier *next = run->Suc(); if (run->Carries(whom)) Delete(run); run = next; } } void SimplePosixSelector::Detach(const PosixSelectListener *whom, int fd) { OP_ASSERT(whom && fd >= 0); SelectListenerCarrier *run = First(); while (run) { SelectListenerCarrier *next = run->Suc(); if (run->Carries(whom, fd)) Delete(run); run = next; } } void SimplePosixSelector::SetMode(const PosixSelectListener * whom, Type mode) { OP_ASSERT(whom); for (SelectListenerCarrier *run = First(); run; run = run->Suc()) if (run->Carries(whom)) { Log(SPEW, "%010p: Adjusting %010p listener (file %d) mode %d -> %d\n", this, whom, run->m_file, (int)run->m_type, (int)mode); run->m_type = mode; } } void SimplePosixSelector::SetMode(const PosixSelectListener * whom, int fd, Type mode) { OP_ASSERT(whom && fd >= 0); for (SelectListenerCarrier *run = First(); run; run = run->Suc()) if (run->Carries(whom, fd)) { Log(SPEW, "%010p: Adjusting %010p listener (file %d=%d) mode %d -> %d\n", this, whom, fd, run->m_file, (int)run->m_type, (int)mode); run->m_type = mode; } } OP_STATUS SimplePosixSelector::Watch(int fd, Type mode, unsigned long interval, PosixSelectListener *listener, const OpSocketAddress *connect /* = 0 */) { return Watch(fd, mode, listener, connect); } OP_STATUS SimplePosixSelector::Watch(int fd, Type mode, PosixSelectListener *listener, const OpSocketAddress *connect /* = 0 */, bool /* ignored = false */) { Log(VERBOSE, "%010p: Watching %d with %010p in mode %d.\n", this, fd, listener, (int)mode); if (!listener) return OpStatus::ERR_NULL_POINTER; #ifdef _DEBUG /* Check for duplicated listeners. * * From this code's point of view, there's no problem supporting duplicates; * however, particularly if OpSocket::{Pause,Continue}Recv() calls are out * of balance, this very likely is a mistake by the caller. In particular, * the next call to Detach() shall kill all duplicates, not just the one * most recently added. That behaviour could easily change, if someone * comes up with a plausible use-case. */ for (SelectListenerCarrier *run = First(); run; run = run->Suc()) if (run->Carries(listener, fd)) OP_ASSERT(!"Duplicating listener on same file handle"); #endif #ifdef POSIX_OK_NETADDR PosixNetworkAddress *local = 0; if (connect) RETURN_IF_ERROR(PrepareSocketAddress(local, connect, fd, listener)); #else OP_ASSERT(connect == 0 || !"Import API_POSIX_NETADDR to " "activate PosixSelector's connect functionality."); #endif SelectListenerCarrier *lug = OP_NEW(SelectListenerCarrier, (fd, mode, listener IF_NETADDR(local))); if (lug == 0) { #ifdef POSIX_OK_NETADDR OP_DELETE(local); #endif return OpStatus::ERR_NO_MEMORY; } lug->Into(this); return OpStatus::OK; } bool SimplePosixSelector::Poll(double timeout) { OP_ASSERT(!m_reporting); // Recursive call: not supported. See documentation. if (Empty()) return false; // nothing to do, I don't care if you do want to wait for it. SelectData data; SelectListenerCarrier *run; #ifdef POSIX_OK_NETADDR m_reporting = true; // so Delete() merely clears m_ear, if called run = First(); while (run) { SelectListenerCarrier *next = run->Suc(); if (run->m_address && run->m_ear) OpStatus::Ignore(ConnectSocketAddress(run->m_address, run->m_file, run->m_ear)); run = next; } m_reporting = false; Purge(); #endif // POSIX_OK_NETADDR int max_fd = 0; for (run = First(); run; run = run->Suc()) { OP_ASSERT(run->InList() && run->m_file >= 0 && run->m_ear); // NB: Set(, 0) ensures still we get error reports, even when mode is NONE. data.Set(run->m_file, #ifdef POSIX_OK_NETADDR /* Pending connections get a write notification: */ run->m_address ? WRITE : #endif run->m_type); if (run->m_file > max_fd) max_fd = run->m_file; } timeval wait = { 0, 0 }, *pause = &wait; if (timeout < 0) pause = NULL; else if (timeout > 0) { wait.tv_sec = timeout / 1000; wait.tv_usec = (timeout - 1000 * wait.tv_sec) * 1000; } int res = select(max_fd + 1, &data.m_read, &data.m_write, &data.m_except, pause); if (res < 0 && errno != EINTR) PError("select", errno, Str::S_ERR_SELECT_FAILED, "Failed to discover whether data is available"); else if (res > 0) { m_reporting = true; // make Delete() merely clear m_ear for (run = First(); run; run = run->Suc()) if (run->m_ear) // It might have been Delete()d by someone else's call-back. { int err = 0; bool has_err; unsigned int mode = data.Check(run->m_file, has_err); /* NB: run->m_ear->On*() may Detach() list entries or SetMode(); * either way, run->m_type changes. */ if (mode & READ & run->m_type) run->m_ear->OnReadReady(run->m_file); if (mode & WRITE & run->m_type) { OP_ASSERT(run->m_ear); // Delete() clears m_type when clearing m_ear. #ifdef POSIX_OK_NETADDR if (run->m_address) { /* If connect() was non-blocking, i.e. it returned e.g. * EINPROGRESS, we did not delete the address, but * selected the socket for writing. So now we need to * determine if connect was successful. */ OP_DELETE(run->m_address); run->m_address = 0; socklen_t len = sizeof(int); if (-1 == getsockopt(run->m_file, SOL_SOCKET, SO_ERROR, &err, &len)) err = errno; if (err) has_err = true; else run->m_ear->OnConnected(run->m_file); } else #endif // POSIX_OK_NETADDR run->m_ear->OnWriteReady(run->m_file); } if (run->m_ear && has_err) // Do we have any way to find out *what* the error was ? run->m_ear->OnError(run->m_file, err); } m_reporting = false; // allow Delete() to do its job properly Purge(); Log(SPEW, "%010p: Processed select notifications.\n", this); return true; } return false; } #endif // POSIX_SELECTOR_SELECT || POSIX_SELECTOR_SELECT_FALLBACK
// // Created by 钟奇龙 on 2019-05-06. // #include <iostream> #include <vector> #include <string> using namespace std; bool isCross(string s1,string s2,string aim){ if(aim.size() != s1.size() + s2.size()) return false; vector<vector<bool>> dp(s1.size()+1,vector<bool> (s2.size()+1)); dp[0][0] = true; for(int i=1; i<s1.size(); ++i){ if(s1[i-1] != aim[i-1]){ break; } dp[i][0] = true; } for(int j=1; j<s2.size(); ++j){ if(s2[j-1] != aim[j-1]){ break; } dp[0][j] = true; } for(int i=1; i<=s1.size(); ++i){ for(int j=1; j<=s2.size(); ++j){ if((dp[i-1][j] && s1[i-1] == aim[i+j-1]) || (dp[i][j-1] && s2[j-1] == aim[i+j-1])){ dp[i][j] = true; } } } return dp[s1.size()][s2.size()]; } int main(){ string s1 = "AB"; string s2 = "12"; cout<<isCross(s1,s2,"1A2B")<<endl; return 0; }
#ifndef __Calculator__ #define __Calculator__ #include <iostream> class Calculator { public: Calculator(); ~Calculator() = default; /* c++11 */ void SetNumbersAndSymbol(double x, double y, char ch); double ArithmeticOperations(); private: double m_x; double m_y; char m_symbol; }; #endif
#include "../include/mvm0/parser.hh" #include "../include/mvm0/defs.hh" #include <cassert> #include <fstream> #include <sstream> namespace mvm0 { namespace { bool is_wspace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } std::string str_trim(const std::string &str) { std::size_t bpos = 0; while (bpos < str.length() && is_wspace(str[bpos])) ++bpos; if (bpos == str.length()) return ""; std::size_t epos = str.length() - 1; while (is_wspace(str[epos])) --epos; return std::string(str.begin() + bpos, str.begin() + epos + 1); } std::vector<std::string> str_split(const std::string &str, char sep) { std::vector<std::string> res; std::istringstream is(str); std::string val; while (std::getline(is, val, sep)) res.push_back(val); return res; } int parse_arg(const std::string &val, const ROM &code, Ins &ins) { assert(!val.empty()); if (val[0] >= '0' && val[0] <= '9') return std::atoi(val.c_str()); if (val[0] == 'r') return std::atoi(val.c_str() + 1); else if (val == "sp") return 15; assert(val[0] == '@'); auto it = code.smap.find(val.substr(1)); assert(it != code.smap.end()); std::size_t sym_idx = it->second; ins.use_sym = sym_idx; return static_cast<int>(MEM_CODE_START + code.sym_defs[sym_idx]); } } // namespace ROM parse_is(std::istream &is) { ROM res; std::size_t ins_idx = 0; std::size_t sym_idx = 0; std::string line; std::string sym; while (std::getline(is, line, '\n')) { line = str_trim(line); if (line.empty()) continue; if (line[0] == '@') { sym = line.substr(1); res.syms.push_back(sym); res.smap.emplace(sym, sym_idx++); res.sym_defs.push_back(ins_idx); } else { Ins ins; ins.name = line; ins.def_sym = sym.empty() ? SYM_NONE : sym_idx - 1; ins.use_sym = SYM_NONE; ++ins_idx; res.ins.push_back(ins); sym.clear(); } } for (auto &ins : res.ins) { auto args = str_split(ins.name, ' '); ins.name = args[0]; for (std::size_t i = 1; i < args.size(); ++i) ins.args.push_back(parse_arg(args[i], res, ins)); } return res; } ROM parse_file(const std::string &path) { std::ifstream is(path); return parse_is(is); } } // namespace mvm0
#include "mini/RandomChance/randomchancetile.h" RandomChanceTile::RandomChanceTile(int number, bool unique, QWidget* parent) :QPushButton(parent) { this->number = number; this->unique = unique; } RandomChanceTile::~RandomChanceTile() { } bool RandomChanceTile::getUnique() { if(this->unique) return true; return false; }
#include <stdio.h> //reindel john a. raņeses float max(float q,float w,float e,float r,float t) { float maximum; if(q>w && q>e && q>r && q>t) maximum=q; else if(w>q && w>e && w>r && w>t) maximum=w; else if(e>q && e>w && e>r && e>t) maximum=e; else if(r>q && r>w && r>e && r>t) maximum=r; else maximum=t; return(maximum); } float min(float a,float s,float d,float f,float g) { float minimum; if(a<s && a<d && a<f && a<g) minimum=a; else if(s<a && s<d && s<f && s<g) minimum=s; else if(d<a && d<s && d<f && d<g) minimum=d; else if(f<a && f<s && f<d && f<g) minimum=f; else minimum=g; return(minimum); } int main() { float n1,n2,n3,n4,n5,mx,mn; printf("enter 5 numbers\n"); printf("enter 1st number: "); scanf("%f",&n1); printf("enter 2nd number: "); scanf("%f",&n2); printf("enter 3rd number: "); scanf("%f",&n3); printf("enter 4th number: "); scanf("%f",&n4); printf("enter 5th number: "); scanf("%f",&n5); printf("the maximum number is %.2f\n",mx = max (n1,n2,n3,n4,n5)); printf("the minimum number is %.2f\n",mn = min (n1,n2,n3,n4,n5)); return 0; }
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls.Navigation/1.3.1/Navigator.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Controls{struct Navigator__DeferSwitch;}}} namespace g{namespace Fuse{namespace Navigation{struct RouterPage;}}} namespace g{ namespace Fuse{ namespace Controls{ // private sealed class Navigator.DeferSwitch :614 // { uType* Navigator__DeferSwitch_typeof(); void Navigator__DeferSwitch__ctor__fn(Navigator__DeferSwitch* __this); void Navigator__DeferSwitch__New1_fn(Navigator__DeferSwitch** __retval); struct Navigator__DeferSwitch : uObject { int GotoMode; int Operation; uStrong< ::g::Fuse::Navigation::RouterPage*> Page; void ctor_(); static Navigator__DeferSwitch* New1(); }; // } }}} // ::g::Fuse::Controls
#include "shape_list.h" ShapeList::~ShapeList() { for (auto& obj : object_list) { delete obj; } } void ShapeList::add_object(Hitable* obj) { object_list.push_back(obj); } bool ShapeList::cast_ray(const Ray& r, float t_min, float t_max, HitDesc& d) { HitDesc temp_d; bool hit_object = false; double closest_object_hit = t_max; for (auto& object : object_list) { if (object->hit(r, t_min, closest_object_hit, temp_d)) { hit_object = true; closest_object_hit = temp_d.t; d = temp_d; } } return hit_object; }
#include <Arduino.h> //Test Routine Program - By Stezipoo #include <SoftPWMServo.h> //#include <Servo.h> //create servo objects //Servo steering; //Servo throttle; const int PIN_STR = 9; const int PIN_THR = 7; const int PIN_IN_STR = 13; const int PIN_IN_THR = 12; //Servo ServoSTR; //Servo ServoTHR; void setup() { Serial.begin(9600); delay(250); pinMode(PIN_IN_STR, INPUT); pinMode(PIN_IN_THR, INPUT); //pinMode(PIN_STR, OUTPUT); //pinMode(PIN_THR, OUTPUT); //ServoSTR.attach(PIN_STR); //ServoTHR.attach(PIN_THR); } /* printIMU to serial port */ void printData(float ax, float ay, float az, float gx, float gy, float gz, unsigned long time, int str, int thr ) { Serial.printf("%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%lu,%d,%d\n", ax, ay, az, gx, gy, gz, millis(), str, thr); } void loop() { //unsigned long THR_VAL = 0; unsigned long STR_VAL = pulseIn(PIN_IN_STR, HIGH, 25000); // Read the pulse width of unsigned long THR_VAL = pulseIn(PIN_IN_THR, HIGH, 25000); // each channel SoftPWMServoServoWrite(PIN_STR, STR_VAL); SoftPWMServoServoWrite(PIN_THR, THR_VAL); //ServoSTR.writeMicroseconds(STR_VAL); //ServoTHR.writeMicroseconds(THR_VAL); printData(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, millis(), STR_VAL, THR_VAL); delay(10); }
#include "fhandle.h" int main() { FHandle f; while(true) { f.input(">> "); cout << endl << f(0) << endl << endl; } return 0; }
#include "Client.h" static inline QByteArray IntToArray(qint32 source); Client::Client(QObject *parent) : QObject(parent) { socket = new QTcpSocket(this); } bool Client::connectToHost(QString host) { socket->connectToHost(host, 1024); return socket->waitForConnected(); } bool Client::writeData(QByteArray data) { if(socket->state() == QAbstractSocket::ConnectedState) { socket->write(IntToArray(data.size())); //write size of data socket->write(data); //write the data itself return socket->waitForBytesWritten(); } else return false; } QByteArray IntToArray(qint32 source) //Use qint32 to ensure that the number have 4 bytes { //Avoid use of cast, this is the Qt way to serialize objects QByteArray temp; QDataStream data(&temp, QIODevice::ReadWrite); data << source; return temp; }
#ifndef BASE_MANAGER_H #define BASE_MANAGER_H #include <deque> #include <mutex> #include <string> #include "BaseConfig.h" #include "Command.h" #include "Client.h" #include "Order.h" #include "Server.h" #include "inventory/InventoryManager.h" #include "State.h" #include "Update.h" class BaseManager { public: // Constructor. Creates inventory and server objects. // @param inventory_file The file that stores the current inventory // contents BaseManager ( std::string inventory_file ); // Start the inventory server void run(); private: // Callback function that the inventory server will use for processing new // messages on its socket. Depending on the message type, it will call one // of the below specialized handle_* functions. std::string handle_input ( std::string input ); // Handle a command std::string handle_command ( const Command& command ); // Add a new order to the queue bool handle_order ( const Order& order ); // Update the inventory levels std::string handle_update ( const Update& update ); // Process all items currently in the queue; dispense product as necessary. // Must be called with access_mutex held. void process_queue(); // Listen for a heartbeat from the mobile platform and set an error if // anything goes wrong void listen_heartbeat(); // Mutex for guarding the inventory, queue, and state variables std::mutex access_mutex; // The current inventory InventoryManager inventory; // The inventory server. It will listen for incoming requests and add them // to the queue for later processing. Server server; // The bluetooth connection to the mobile base Client mobile_client; // The queue of current orders. Should not be accessed unless holding // access_mutex. std::deque<Order> queue; // Mobile platform state. current_state is what is being reported by robie. // expected_state is what the base is expecting. Should not be accessed // unless holding access_mutex. State current_state; State expected_state; // User configuration BaseConfig config; }; #endif
#include <bits/stdc++.h> using namespace std; typedef pair <int, int> dist_node; typedef pair <int, int> edge; const int MAXF=110; const int MAX = 510; const int INF = 1 << 30; int run, fire, inter; vector<int> station; vector<edge> g [MAX]; vector<edge> maxm; int d[MAX]; //distancias; int sta[MAX]; void connect(int a, int b, int we) { g[a].push_back(edge(b,we)); g[b].push_back(edge(a,we)); } void ini() { station.clear();maxm.clear(); memset(d,0,sizeof d); memset(sta,0,sizeof sta); for(int i = 0; i < MAX; ++i)g[i].clear(); } void dijkstra(int s) { int n = inter; int d1[MAX]; for(int i = 0; i <= n; ++i){ d1[i] = INF; } priority_queue<dist_node, vector<dist_node>, greater<dist_node> > q; d1[s] = 0; q.push(dist_node(0, s)); while(!q.empty()){ int dist = q.top().first; int cur = q.top().second; q.pop(); if(dist > d1[cur]) continue; for(int i = 0; i < g[cur].size(); ++i){ int next = g[cur][i].first; int w_extra = g[cur][i].second; if(d1[cur] + w_extra < d1[next]){ d1[next] = d1[cur] + w_extra; q.push(dist_node(d[next],next)); } } } for(int i = 0; i <= n; ++i){ d[i] = min(d[i],d1[i]); } } void dijkstra2(int s) { int n = inter; int d1[MAX]; for(int i = 0; i <= n; ++i){ d1[i] = INF; } priority_queue<dist_node, vector<dist_node>, greater<dist_node> > q; d1[s] = 0; q.push(dist_node(0, s)); while(!q.empty()){ int dist = q.top().first; int cur = q.top().second; q.pop(); if(dist > d1[cur]) continue; for(int i = 0; i < g[cur].size(); ++i){ int next = g[cur][i].first; int w_extra = g[cur][i].second; if(d1[cur] + w_extra < d1[next]){ if(d[next] > d1[cur] + w_extra) d1[next] = d1[cur] + w_extra; else d1[next] = d[next]; q.push(dist_node(d1[next],next)); } } } int ma = -INF; for(int i = 0; i < n; ++i){ if(ma < d1[i]){ ma=d1[i]; } } maxm.push_back(edge(ma,s)); } int maxstation () { int pos=-1, tam = INF; for(int i = 0; i < maxm.size(); ++i){ //cout<<maxm[i].first<<endl; if(tam> maxm[i].first){ pos = maxm[i].second; tam = maxm[i].first; } } return pos; } int main() { ios_base::sync_with_stdio(false); while(cin>>run){ for(; run > 0; --run){ ini(); cin>>fire>>inter; for(int t = 0; t < fire; ++t){ int f; cin>>f; station.push_back(f-1); sta[f-1] = 1; } string l;getline(cin,l); while(getline(cin,l)) { // cout << l; if(l == "")break; int a,b,we; stringstream ss(l); ss>>a>>b>>we; connect(a-1,b-1,we); } /*for(int t = 0; t < inter; ++t){ int a,b,we ; cin>>a>>b>>we; connect(a-1,b-1,we); }*/ for(int i = 0; i <= inter; ++i){ d[i] = INF; } for(int i = 0; i < fire; ++i){ dijkstra(station[i]); } for(int i = 0; i < inter; ++i){ if(sta[i] == 1)continue; dijkstra2(i); } int ans = maxstation()+1; if(ans == 0)ans = 1; cout<<ans<<"\n"; if(run != 1)cout<<"\n"; } } return 0; }
#include <Tanker/Admin/Admin.hpp> #include <Tanker/Crypto/Format/Format.hpp> #include <Tanker/Errors/Errc.hpp> #include <Tanker/Errors/Exception.hpp> #include <Tanker/Errors/ServerErrc.hpp> #include <Tanker/Log/Log.hpp> #include <Tanker/Network/AConnection.hpp> #include <Tanker/Serialization/Serialization.hpp> #include <Tanker/Trustchain/Action.hpp> #include <Tanker/Trustchain/Actions/Nature.hpp> #include <Tanker/Trustchain/Actions/TrustchainCreation.hpp> #include <Tanker/Trustchain/Block.hpp> #include <Tanker/Trustchain/TrustchainId.hpp> #include <cppcodec/base64_rfc4648.hpp> #include <nlohmann/json.hpp> #include <tconcurrent/coroutine.hpp> #include <tconcurrent/future.hpp> #include <tconcurrent/promise.hpp> #include <Tanker/Tracer/ScopeTimer.hpp> #include <algorithm> #include <iterator> using namespace Tanker::Errors; using Tanker::Trustchain::Actions::Nature; TLOG_CATEGORY(Admin); namespace Tanker { namespace Admin { namespace { // FIXME Duplicated in Client.cpp std::map<std::string, ServerErrc> const serverErrorMap{ {"internal_error", ServerErrc::InternalError}, {"invalid_body", ServerErrc::InvalidBody}, {"invalid_origin", ServerErrc::InvalidOrigin}, {"trustchain_is_not_test", ServerErrc::TrustchainIsNotTest}, {"trustchain_not_found", ServerErrc::TrustchainNotFound}, {"device_not_found", ServerErrc::DeviceNotFound}, {"device_revoked", ServerErrc::DeviceRevoked}, {"too_many_attempts", ServerErrc::TooManyAttempts}, {"verification_needed", ServerErrc::VerificationNeeded}, {"invalid_passphrase", ServerErrc::InvalidPassphrase}, {"invalid_verification_code", ServerErrc::InvalidVerificationCode}, {"verification_code_expired", ServerErrc::VerificationCodeExpired}, {"verification_code_not_found", ServerErrc::VerificationCodeNotFound}, {"verification_method_not_set", ServerErrc::VerificationMethodNotSet}, {"verification_key_not_found", ServerErrc::VerificationKeyNotFound}, {"group_too_big", ServerErrc::GroupTooBig}, {"invalid_delegation_signature", ServerErrc::InvalidDelegationSignature}, }; } Admin::Admin(Network::ConnectionPtr cx, std::string idToken) : _cx(std::move(cx)), _idToken(std::move(idToken)) { _cx->connected = [this]() { _taskCanceler.add(tc::async_resumable([this]() -> tc::cotask<void> { TC_AWAIT(authenticateCustomer(_idToken)); connected(); })); }; } tc::cotask<void> Admin::start() { tc::promise<void> prom; auto fut = prom.get_future(); this->connected = ([prom = std::move(prom)]() mutable { prom.set_value({}); prom = tc::promise<void>(); }); _cx->connect(); TC_AWAIT(std::move(fut)); connected = nullptr; } tc::cotask<void> Admin::authenticateCustomer(std::string const& idToken) { auto const message = nlohmann::json{ {"idToken", idToken}, }; TC_AWAIT(emit("authenticate customer", message)); } tc::cotask<Trustchain::TrustchainId> Admin::createTrustchain( std::string const& name, Crypto::SignatureKeyPair const& keyPair, bool isTest, bool storePrivateKey) { FUNC_TIMER(Net); Trustchain::Block block{}; block.nature = Nature::TrustchainCreation; block.payload = Serialization::serialize( Trustchain::Actions::TrustchainCreation{keyPair.publicKey}); block.trustchainId = Trustchain::TrustchainId(block.hash()); auto message = nlohmann::json{ {"is_test", isTest}, {"name", name}, {"root_block", cppcodec::base64_rfc4648::encode(Serialization::serialize(block))}, }; if (storePrivateKey) message["private_signature_key"] = keyPair.privateKey; TC_AWAIT(emit("create trustchain", message)); TC_RETURN(block.trustchainId); } tc::cotask<void> Admin::deleteTrustchain( Trustchain::TrustchainId const& trustchainId) { auto const message = nlohmann::json{ {"id", trustchainId}, }; TC_AWAIT(emit("delete trustchain", message)); } tc::cotask<void> Admin::update(Trustchain::TrustchainId const& trustchainId, std::optional<std::string> oidcClientId, std::optional<std::string> oidcProvider) { auto request = nlohmann::json{{"id", trustchainId}}; if (oidcClientId) request["oidc_client_id"] = oidcClientId.value(); if (oidcProvider) request["oidc_provider"] = oidcProvider.value(); TC_AWAIT(emit("update trustchain", request)); } tc::cotask<VerificationCode> Admin::getVerificationCode( Trustchain::TrustchainId const& tcid, Email const& email) { auto const msg = nlohmann::json({{"email", email}, {"trustchain_id", tcid}}); auto const answer = TC_AWAIT(emit("get verification code", msg)); auto it = answer.find("verification_code"); if (it == answer.end()) { throw Errors::formatEx(Errors::Errc::InvalidVerification, "could not find verification code for {}", email); } TC_RETURN(it->get<std::string>()); } tc::cotask<nlohmann::json> Admin::emit(std::string const& eventName, nlohmann::json const& data) { auto const stringmessage = TC_AWAIT(_cx->emit(eventName, data.dump())); TDEBUG("emit({}) -> {}", eventName, stringmessage); auto const message = nlohmann::json::parse(stringmessage); auto const error_it = message.find("error"); if (error_it != message.end()) { auto const code = error_it->at("code").get<std::string>(); auto const message = error_it->at("message").get<std::string>(); auto const serverErrorIt = serverErrorMap.find(code); if (serverErrorIt == serverErrorMap.end()) throw Errors::formatEx( ServerErrc::UnknownError, "code: {}, message: {}", code, message); throw Errors::Exception(serverErrorIt->second, message); } TC_RETURN(message); } } }