text
stringlengths
8
6.88M
#include "sdlwrap.h" #include "GameState.h" #include "StopWatch.h" #include "Sound.h" #include <SDL_timer.h> void load_media() { textures("player_pistol").load("gfx/Player/pistol.png"); sounds("pistol_shot").load("sfx/pistol_shot.mp3"); textures("player_shotgun").load("gfx/Player/shotgun.png"); sounds("shotgun_shot").load("sfx/shotgun_shot.mp3"); textures("player_uzi").load("gfx/Player/uzi.png"); sounds("uzi_shot1").load("sfx/uzi_shot1.mp3"); sounds("uzi_shot2").load("sfx/uzi_shot2.mp3"); textures("crosshair"). load("gfx/crosshair.png"); textures("reload"). load("gfx/reload.png"); textures("bullet").load("gfx/bullet.png"); textures("zombie"). load("gfx/Zombie/idle.png"); textures("zombie_attack0").load("gfx/Zombie/Attack/1.png"); textures("zombie_attack1").load("gfx/Zombie/Attack/2.png"); textures("zombie_attack2").load("gfx/Zombie/Attack/3.png"); textures("zombie_attack3").load("gfx/Zombie/Attack/4.png"); textures("zombie_attack4").load("gfx/Zombie/Attack/5.png"); textures("zombie_attack5").load("gfx/Zombie/Attack/6.png"); textures("zombie_death0").load("gfx/Zombie/Death/1.png"); textures("zombie_death1").load("gfx/Zombie/Death/2.png"); textures("zombie_death2").load("gfx/Zombie/Death/3.png"); textures("zombie_death3").load("gfx/Zombie/Death/4.png"); textures("zombie_death4").load("gfx/Zombie/Death/5.png"); textures("zombie_death5").load("gfx/Zombie/Death/6.png"); textures("zombie_death6").load("gfx/Zombie/Death/7.png"); textures("zombie_death7").load("gfx/Zombie/Death/8.png"); sounds("zombie_attack").load("sfx/zombie_attack.mp3"); textures("wolf_move0").load("gfx/Werewolf/Alive/1.png"); textures("wolf_move1").load("gfx/Werewolf/Alive/2.png"); textures("wolf_move2").load("gfx/Werewolf/Alive/3.png"); textures("wolf_move3").load("gfx/Werewolf/Alive/4.png"); textures("wolf_move4").load("gfx/Werewolf/Alive/5.png"); textures("wolf_move5").load("gfx/Werewolf/Alive/6.png"); textures("wolf_attack0").load("gfx/Werewolf/Attack/1.png"); textures("wolf_attack1").load("gfx/Werewolf/Attack/2.png"); textures("wolf_attack2").load("gfx/Werewolf/Attack/3.png"); textures("wolf_attack3").load("gfx/Werewolf/Attack/4.png"); textures("wolf_attack4").load("gfx/Werewolf/Attack/5.png"); textures("wolf_attack5").load("gfx/Werewolf/Attack/6.png"); textures("wolf_attack6").load("gfx/Werewolf/Attack/7.png"); textures("wolf_attack7").load("gfx/Werewolf/Attack/8.png"); textures("wolf_teleport0").load("gfx/Werewolf/Teleportation/1.png"); textures("wolf_teleport1").load("gfx/Werewolf/Teleportation/2.png"); textures("wolf_teleport2").load("gfx/Werewolf/Teleportation/3.png"); sounds("wolf_attack"). load("sfx/wolf_attack.mp3"); sounds("wolf_teleport").load("sfx/wolf_teleport.mp3"); music("weather").load("sfx/weather.mp3"); } int main(int, char*[]) { if(!init_sdl()) { return -1; } load_media(); currentStateID() = GState::intro; currentState().reset(new StateIntro); StopWatch fpsCapper; while(currentStateID() != GState::exit) { fpsCapper.start(); currentState()->handle_events(); currentState()->handle_logic(); change_state(); currentState()->handle_render(); if(fpsCapper.get_ticks() < minSpf) { SDL_Delay(minSpf - fpsCapper.get_ticks()); } } close_sdl(); }
//使用するヘッダーファイル #include "GameL\DrawTexture.h" #include "GameL\HitBoxManager.h" #include "GameHead.h" #include "ObjBubble.h" #include "ObjBlock.h" #include "UtilityModule.h" #include "GameL\Audio.h" //使用するネームスペース using namespace GameL; CObjBubble::CObjBubble(float x, float y) { m_x = x; m_y = y; } //イニシャライズ void CObjBubble::Init() { m_vx = -1.0f; m_vy = 0.0f; m_damage = 2; //移動ベクトルの正規化 UnitVec(&m_vx, &m_vy); //当たり判定用hitBox作成 Hits::SetHitBox(this, m_x, m_y, 35, 35, ELEMENT_BUBBLE, OBJ_BUBBLE, 1); } //アクション void CObjBubble::Action() { //主人公と泡で角度を取る CObjHero* obj = (CObjHero*)Objs::GetObj(COBJ_HERO); CObjBlock*b = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); //主人公が存在する場合、誘導角度の計算する if (obj != nullptr) { float x = obj->GetX() - m_x- b->GetScrollX(); float y = obj->GetY() - m_y- b->GetScrollY(); float ar = GetAtan2Angle(x, -y); //弾丸の現在の向いている角度を取る float br = GetAtan2Angle(m_vx, -m_vy); //主人公機と敵機角度があまりにもかけ離れたら if (ar - br > 20) { //移動方向を主人公機の方向にする m_vx = cos(3.14 / 180 * ar); m_vy = -sin(3.14 / 180 * ar); } float yy = m_vy; float xx = m_vx; float r = 3.14 / 180.0f; //角度1° if (ar < br) { //移動方向にに+1°加える m_vx = xx * cos(r) - yy * sin(r); m_vy = yy * cos(r) + xx * sin(r); } else { //移動方向にに-1°加える m_vx = xx * cos(-r) - yy * sin(-r); m_vy = yy * cos(-r) + xx * sin(-r); } UnitVec(&m_vx, &m_vy); } //移動ベクトルを座標に加算する m_x += m_vx * 5.0f; m_y += m_vy * 5.0f; //HitBoxの内容を更新 CHitBox*hit = Hits::GetHitBox(this); hit->SetPos(m_x, m_y); CObjBlock*block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); //HitBoxの位置を変更 hit->SetPos(m_x + block->GetScrollX(), m_y + block->GetScrollY()); //ブロックに当たると削除 /*if (m_hit_right == true || m_hit_left == true || m_hit_up == true || m_hit_down == true) { Audio::Start(5); //音 this->SetStatus(false); Hits::DeleteHitBox(this); return; }*/ //画面外に出たら破棄する処理 if (m_x + block->GetScrollX() > 800.0f || m_x + block->GetScrollX() < -45.0f && m_y + block->GetScrollY() > 600.0f || m_y + block->GetScrollY() < 45.0f) { this->SetStatus(false); Hits::DeleteHitBox(this); return; } //主人公オブジェクトと接触したら誘導弾丸削除 if (hit->CheckObjNameHit(COBJ_HERO) != nullptr) { Audio::Start(9); //音 hit->SetInvincibility(true);//当たり判定無効 this->SetStatus(false); Hits::DeleteHitBox(this); return; } //剣が当たったら泡削除 if (hit->CheckElementHit(ELEMENT_ATTACK) == true) { Audio::Start(7); //音 this->SetStatus(false); Hits::DeleteHitBox(this); return; } //完全に領域外に出たら破棄する /*bool Check = CheckWindow(m_x, m_y, -32.0f, -32.0f, 800.0f, 600.0f); if (Check == false) { this->SetStatus(false); //自身に削除命令を出す。 Hits::DeleteHitBox(this); //敵機弾丸が所有するHitBoxに削除する。 }*/ } //ドロー void CObjBubble::Draw() { //描写カラー情報 float c[4] = { 1.0f,1.0f,1.0f,1.0f }; RECT_F src;//描写元切り取り位置 RECT_F dst;//描写先表示位置 //切り取り位置の設定 src.m_top = 0.0f; src.m_left = 0.0f; src.m_right = 35.0f; src.m_bottom = 35.0f; CObjBlock*block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); //表示位置の設定 dst.m_top = 0.0f +m_y + block->GetScrollY(); dst.m_left = 0.0f +m_x + block->GetScrollX(); dst.m_right = 35.0f +m_x + block->GetScrollX(); dst.m_bottom = 35.0f +m_y + block->GetScrollY(); float r = 0.0f; //主人公機と誘導弾丸で角度を取る CObjHero* obj = (CObjHero*)Objs::GetObj(COBJ_HERO); //主人公機が存在する場合、誘導角度の計算する if (obj != nullptr) { float x = obj->GetX() - m_x; float y = obj->GetY() - m_y; r = GetAtan2Angle(x, -y); } //0番目に登録したグラフィックをsrc・dst・cの情報を元に描写 Draw::Draw(21, &src, &dst, c, r); }
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Triad National Security, LLC. This file is part of the // Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms // in the LICENSE file found in the top-level directory of this distribution. // ////////////////////////////////////////////////////////////////////////////// #include "post_process.h" #include <iostream> #include <fstream> //template<class Scalar> post_process::post_process(const Teuchos::RCP<const Epetra_Comm>& comm, Mesh *mesh, const int index, SCALAR_OP s_op, bool restart, const int eqn_id, const std::string basename, double precision): comm_(comm), mesh_(mesh), index_(index), s_op_(s_op), restart_(restart), eqn_id_(eqn_id), basename_(basename), precision_(precision) { scalar_val_ = 0.; std::vector<Mesh::mesh_lint_t> node_num_map(mesh_->get_node_num_map()); overlap_map_ = Teuchos::rcp(new Epetra_Map(-1, node_num_map.size(), &node_num_map[0], 0, *comm_)); if( 1 == comm_->NumProc() ){ node_map_ = overlap_map_; }else{ #ifdef MESH_64 node_map_ = Teuchos::rcp(new Epetra_Map(Create_OneToOne_Map64(*overlap_map_))); #else node_map_ = Teuchos::rcp(new Epetra_Map(Epetra_Util::Create_OneToOne_Map(*overlap_map_))); #endif } importer_ = Teuchos::rcp(new Epetra_Import(*overlap_map_, *node_map_)); ppvar_ = Teuchos::rcp(new Epetra_Vector(*node_map_)); std::string ystring=basename_+std::to_string(index_); mesh_->add_nodal_field(ystring); if ( (0 == comm_->MyPID()) && (s_op_ != NONE) ){ filename_ = ystring+".dat"; std::ofstream outfile; if( restart_ ){ outfile.open(filename_, std::ios::app ); }else{ outfile.open(filename_); } outfile.close(); } if ( 0 == comm_->MyPID()) std::cout<<"Post process created for variable "<<index_<<" with name "<<ystring<<std::endl<<std::endl; //exit(0); }; post_process::~post_process(){}; void post_process::process(const int i, const double *u, const double *uold, const double *uoldold, const double *gradu, const double &time, const double &dt, const double &dtold) { #ifdef MESH_64 Mesh::mesh_lint_t gid_node = node_map_->GID64(i); #else Mesh::mesh_lint_t gid_node = node_map_->GID(i); #endif int lid_overlap = overlap_map_->LID(gid_node); std::vector<double> xyz(3); xyz[0]=mesh_->get_x(lid_overlap); xyz[1]=mesh_->get_y(lid_overlap); xyz[2]=mesh_->get_z(lid_overlap); (*ppvar_)[i] = (*postprocfunc_)(u, uold, uoldold, gradu, &xyz[0], time, dt, dtold, eqn_id_); }; void post_process::update_mesh_data(){ Epetra_Vector *temp = new Epetra_Vector(*overlap_map_); temp->Import(*ppvar_, *importer_, Insert); int num_nodes = overlap_map_->NumMyElements(); std::vector<double> ppvar(num_nodes,0.); #pragma omp parallel for for (int nn=0; nn < num_nodes; nn++) { ppvar[nn]=(*temp)[nn]; } std::string ystring=basename_+std::to_string(index_); mesh_->update_nodal_data(ystring, &ppvar[0]); }; void post_process::update_scalar_data(double time){ scalar_reduction();//not sure if we need this here if ( (0 == comm_->MyPID()) && (s_op_ != NONE) ){ std::ofstream outfile; outfile.open(filename_, std::ios::app ); outfile << std::setprecision(precision_) //<< std::setprecision(std::numeric_limits<double>::digits10 + 1) <<time<<" "<<scalar_val_<<std::endl; outfile.close(); } }; double post_process::get_scalar_val(){ return scalar_val_; }; void post_process::scalar_reduction(){ scalar_val_ = 0.; switch(s_op_){ case NONE: return; case NORM1: ppvar_->Norm1(&scalar_val_); break; case NORM2: ppvar_->Norm2(&scalar_val_); break; case NORMRMS:{ Epetra_Vector *temp = new Epetra_Vector(*ppvar_); temp->PutScalar((double)1.); ppvar_->NormWeighted(*temp,&scalar_val_); break; } case NORMINF: ppvar_->NormInf(&scalar_val_); break; case MAXVALUE: ppvar_->MaxValue(&scalar_val_); break; case MINVALUE: ppvar_->MinValue(&scalar_val_); break; case MEANVALUE: ppvar_->MeanValue(&scalar_val_); break; default: return; } };
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2007 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** @author Lasse Magnussen lasse@opera.com */ #ifndef MODULES_DOM_DOMIO_H #define MODULES_DOM_DOMIO_H #if defined(DOM_GADGET_FILE_API_SUPPORT) || defined(WEBSERVER_SUPPORT) #include "modules/dom/src/domobj.h" #include "modules/dom/src/domevents/domeventtarget.h" #include "modules/util/opfile/opfile.h" #include "modules/util/adt/bytebuffer.h" #include "modules/util/adt/opvector.h" #include "modules/webserver/webserver_callbacks.h" #include "modules/ecmascript_utils/esasyncif.h" #include "modules/gadgets/OpGadget.h" #include "modules/windowcommander/OpWindowCommander.h" class DOM_GadgetFile; class DOM_FileList; class DOM_WebServer; class WebserverFileSandbox; class WebserverBodyObject_Base; class WebserverFolderSelector; class OpPersistentStorageListener; class WebserverResourceDescriptor_Base; /************************************************************************/ /* class DOM_IO */ /************************************************************************/ class DOM_IO : public DOM_Object #ifdef SELFTEST ,public OpPersistentStorageListener #endif // SELFTESTS { public: static OP_STATUS Make(DOM_IO *&new_obj, DOM_Runtime *origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_IO || DOM_Object::IsA(type); } #ifdef SELFTEST // from OpPersistentStorageListener OP_STATUS SetPersistentData(const uni_char* section, const uni_char* key, const uni_char* value) { return OpStatus::OK; } const uni_char* GetPersistentData(const uni_char* section, const uni_char* key) { return NULL; } OP_STATUS DeletePersistentData(const uni_char* section, const uni_char* key) { return OpStatus::OK; } OP_STATUS GetPersistentDataItem(UINT32 idx, OpString& key, OpString& data) { return OpStatus::ERR; } OP_STATUS GetStoragePath(OpString& storage_path); #endif // SELFTEST private: DOM_IO() : m_persistentStorageListener(NULL) {} OP_STATUS Initialize(); void InstallFileObjectsL(); #ifdef WEBSERVER_SUPPORT OP_STATUS InstallWebserverObjects(); #endif // WEBSERVER_SUPPORT OpPersistentStorageListener *m_persistentStorageListener; public: static BOOL AllowIOAPI(FramesDocument* frm_doc); /**< Returns TRUE if the opera.io object should be present for the specified FramesDocument's runtime. */ static BOOL AllowFileAPI(FramesDocument* frm_doc); }; #endif //defined(DOM_GADGET_FILE_API_SUPPORT) || defined(WEBSERVER_SUPPORT) #endif // !MODULES_DOM_DOMIO_H
#include "SAT.h" #include "Graph.h" #include "point.h" #include "random.h" #include "test.h" #include <iostream> #include <ctime> using namespace std; int main() { //input parameters deciding the size,pairs and blocks int size,pairs,blocks; cin>>size>>pairs>>blocks; //use random to generate Random random(size,pairs,blocks); random.generate(); Graph graph(size,pairs,blocks,"random.txt"); graph.printgraph(cout); //solve the sat problem SAT sat(graph); cout<<"Computing..."<<endl; clock_t start =clock(); sat.computeroute(); clock_t end = clock(); cout<<"run time of algorthm: "<<(double) (end - start) / CLOCKS_PER_SEC<<" s"<<endl; //cout<<(double) (end - start) / CLOCKS_PER_SEC<<endl; //output the solution Graph output = sat.GetSolution(); output.printgraph(cout); //test if it is valid cout<<"testing"<<endl; Test test(output); if (test.check()) cout<<"valid"<<endl; else cout<<"invalid"<<endl; return 0; }
#include <iostream> #include <vector> #include <string> #include <cstring> using namespace std; const int MAX_BUDGET = 2147483647 - 1; // n : 초밥 종류 (1<=n<=20) // m : 예산 (1<=m<=1,000,000,000) // price : 초밥 가격 (<=20000 / 100의 배수) // pref : 초밥 선호도 (1<=pref<=20) int n, m, price[20], pref[20]; //int cache[100000000]; //int cache2[100000000]; int cache3[20000 / 100 + 1]; // budget 만큼 예산을 써서 얻을 수 있는 최대 선호도 합 /* int sushi(int budget) { // 메모이제이션 int& ret = cache[budget]; if(ret != -1) return ret; ret = 0; for(int i=0; i<n; i++) { if(budget < price[i]) continue; ret = max(ret, sushi(budget - price[i]) + pref[i]); } return ret; } // 반복적 동적 계획법 int sushi2() { int ret = 0; for(int budget=1; budget<=m; budget++) { cache2[budget] = 0; for(int d=0; d<n; d++) { if(budget >= price[d]) cache2[budget] = max(cache2[budget], cache2[budget - price[d]] + pref[d]); } ret = max(ret, cache2[budget]); } return ret; } */ // 반복적 동적 계획법 : cache size 줄이기 int sushi3() { int ret = 0; cache3[0] = 0; for(int budget=1; budget<=m; budget++) { int cand = 0; for(int dish=0; dish<n; dish++) { if(budget >= price[dish]) cand = max(cand, cache3[(budget - price[dish])%201] + pref[dish]); } cache3[budget % 201] = cand; ret = max(ret, cand); } return ret; } int main() { int testCase; cin >> testCase; if(testCase < 1 || testCase > 5) exit(-1); //memset(cache, -1, sizeof(cache)); for(int i=0; i<testCase; i++) { cin >> n >> m; if(n < 1 || n > 20 || m < 1 || m > 2147483647) exit(-1); m /= 100; // 예산을 100으로 나눠준다. for(int j=0; j<n; j++) { cin >> price[j] >> pref[j]; price[j] /= 100; // 가격도 100으로 나눠놓음. } //cout << sushi(m) << endl; //cout << sushi2() << endl; cout << sushi3() << endl; } return 0; }
#ifndef MOREINFOPIONEER_H #define MOREINFOPIONEER_H #include "data_types/pioneer.h" #include "data_types/relation.h" #include "services/pioneerservice.h" #include "services/relationservice.h" #include "ui/mainwindow.h" #include <QDialog> /* ------------------------------------------------------------ * This window is only displaying * information about the selected pioneer * ------------------------------------------------------------ */ namespace Ui { class MoreInfoPioneer; } class MoreInfoPioneer : public QDialog { Q_OBJECT public: explicit MoreInfoPioneer(QWidget *parent = 0); ~MoreInfoPioneer(); void setPioneer(Pioneer pioneer); // Sets information in MoreInfo window to the currently selected Pioneer private slots: void on_pushButton_close_clicked(); // Close window void getRelationList(Pioneer pioneer); // Sets relation info in MoreInfo window to the currently selected Pioneer private: Ui::MoreInfoPioneer *ui; RelationService relationService; vector<Relation> relation; }; #endif // MOREINFOPIONEER_H
/** * Nana Configuration * Nana C++ Library(http://www.nanapro.org) * Copyright(C) 2003-2016 Jinhao(cnjinhao@hotmail.com) * * 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) * * @file _GUI/Config.h * * @brief Provide switches to enable 3rd-party libraries for a certain feature. * * External libraries: * - NANA_LIBPNG, USE_LIBPNG_FROM_OS * - NANA_LIBJPEG, USE_LIBJPEG_FROM_OS * * Messages: * - VERBOSE_PREPROCESSOR, STOP_VERBOSE_PREPROCESSOR */ #pragma once #include "Config.h" //The basic configurations are ignored when NANA_IGNORE_CONF is defined. //The NANA_IGNORE_CONF may be specified by CMake generated makefile. #ifndef NANA_IGNORE_CONF // Here defines some flags that tell Nana what features will be supported. //Support of std::thread //Boost.Thread is preferred. //NANA_ENABLE_MINGW_STD_THREADS_WITH_MEGANZ is only available on MinGW when STD_THREAD_NOT_SUPPORTED is defined. //if NANA_ENABLE_MINGW_STD_THREADS_WITH_MEGANZ is enabled, Boost.Thread will be replaced with meganz's mingw-std-threads. //https://github.com/meganz/mingw-std-threads //#define NANA_ENABLE_MINGW_STD_THREADS_WITH_MEGANZ /////////////////// //Support of PCM playback // //#define NANA_ENABLE_AUDIO /////////////////// //Support for PNG // Define the NANA_ENABLE_PNG to enable the support of PNG. // //#define NANA_ENABLE_PNG //! //#define USE_LIBPNG_FROM_OS // Un-Comment it to use libpng from operating system. #if defined(NANA_ENABLE_PNG) #if !defined(USE_LIBPNG_FROM_OS) #define NANA_LIBPNG #endif #endif /////////////////// //Support for JPEG // Define the NANA_ENABLE_JPEG to enable the support of JPEG. // //#define NANA_ENABLE_JPEG //! //#define USE_LIBJPEG_FROM_OS // Un-Comment it to use libjpeg from operating system. #if defined(NANA_ENABLE_JPEG) #if !defined(USE_LIBJPEG_FROM_OS) #define NANA_LIBJPEG #endif #endif #if !defined(VERBOSE_PREPROCESSOR) //#define VERBOSE_PREPROCESSOR #endif #if !defined(STOP_VERBOSE_PREPROCESSOR) #define STOP_VERBOSE_PREPROCESSOR #endif #endif // NANA_IGNORE_CONFIG
// SimpleGraphic Engine // (c) David Gowor, 2014 // // Render Font Header // // ======= // Classes // ======= // Font class r_font_c { public: r_font_c(class r_renderer_c* renderer, char* fontName); ~r_font_c(); int StringWidth(int height, const char* str); int StringCursorIndex(int height, const char* str, int curX, int curY); void Draw(scp_t pos, int align, int height, col4_t col, const char* str); void FDraw(scp_t pos, int align, int height, col4_t col, const char* fmt, ...); void VDraw(scp_t pos, int align, int height, col4_t col, const char* fmt, va_list va); private: int StringWidthInternal(struct f_fontHeight_s* fh, const char* str); const char* StringCursorInternal(struct f_fontHeight_s* fh, const char* str, int curX); void DrawTextLine(scp_t pos, int align, int height, col4_t col, const char* str); class r_renderer_c* renderer; int numFontHeight; struct f_fontHeight_s* fontHeights[32]; int maxHeight; int* fontHeightMap; };
#include "stdafx.h" #include "ball.h" Ball::Ball(int radius, int speed, float direction) : radius(radius) , speed(speed) , direction(direction) , image(sf::CircleShape(radius)) { image.setOrigin(radius, radius); lastCollision = -1; } sf::CircleShape Ball::getImage() { return image; } void Ball::setPosition(float x, float y) { this->x = x; this->y = y; image.setPosition(x, y); } int Ball::getLastCollision() { return lastCollision; } void Ball::setLastCollision(int collision) { lastCollision = collision; } int Ball::getX() { return x; } int Ball::getY() { return y; } void Ball::setX(float x) { this->x = x; image.setPosition(x, y); } void Ball::setY(float y) { this->y = y; image.setPosition(x, y); } sf::Vector2f Ball::getLeftEdgeCoordinates() { return sf::Vector2f(x - radius, y); } sf::Vector2f Ball::getRightEdgeCoordinates() { return sf::Vector2f(x + radius, y); } sf::Vector2f Ball::getTopEdgeCoordinates() { return sf::Vector2f(x, y - radius); } sf::Vector2f Ball::getBottomEdgeCoordinates() { return sf::Vector2f(x, y + radius); } float Ball::getDirection() { return direction; } void Ball::setDirection(float direction) { this->direction = direction; } bool Ball::isOutOfLeftBound() { return x < -radius; } bool Ball::isOutOfRightBound(int boundX) { return x > boundX + radius; } bool Ball::hasCollided(Collidable* obj) { return obj->intersects(getLeftEdgeCoordinates()) || obj->intersects(getRightEdgeCoordinates()) || obj->intersects(getTopEdgeCoordinates()) || obj->intersects(getBottomEdgeCoordinates()); } void Ball::move() { float offsetX = speed * sin(direction*PI / 180); float offsetY = speed * -cos(direction*PI / 180); image.move(offsetX, offsetY); sf::Vector2f newPosition = image.getPosition(); this->x = newPosition.x; this->y = newPosition.y; } int Ball::getSpeed() { return speed; }
// // environment.h // Total Control // // Created by Parker Lawrence on 1/9/16. // Copyright (c) 2016 Parker Lawrence. All rights reserved. // #ifndef __Total_Control__environment__ #define __Total_Control__environment__ #include <stdio.h> #include "vox.h" #include "render.h" #include "generators.h" #include "glm/gtx/string_cast.hpp" class Environment { private: std::vector<std::pair<Location*,Structure*>> loadqueue; std::vector<GeomTerrain*> bakequeue; std::vector<Structure> structures; glm::vec4 view = glm::vec4(0,0,0,1); pthread_t loadingthread; Generator gen; bool testerbool = true; public: bool keepexecution = true; Environment(); void loadnextchunk(); void draw(ShaderVNC*); void cluein(double,double,double); Structure* getStruct(std::string targetid); void checkup(); void cleanup(); }; void* loaderthread(void*); #endif /* defined(__Total_Control__environment__) */
#ifndef tmptools__coretools__selector__hpp #define tmptools__coretools__selector__hpp namespace tmp { template <bool B> struct selector {}; //typedef selector<true> true_type; //typedef selector<false> false_type; } // tmp #endif // tmptools__coretools__selector__hpp
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2009-2010. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _IOVTKGDCM_DICOMPATIENTDBWRITERSERVICE_HPP_ #define _IOVTKGDCM_DICOMPATIENTDBWRITERSERVICE_HPP_ #include <string> #include <boost/filesystem/path.hpp> #include <io/IWriter.hpp> #include "ioVtkGdcm/config.hpp" namespace fwData { class PatientDB; class Patient; } namespace ioVtkGdcm { class IOVTKGDCM_CLASS_API DicomPatientDBWriterService : public ::io::IWriter { public : fwCoreServiceClassDefinitionsMacro ( (DicomPatientDBWriterService)( ::io::IWriter) ) ; /** * @brief constructor * */ IOVTKGDCM_API DicomPatientDBWriterService() throw(); /** * @brief destructor */ IOVTKGDCM_API virtual ~DicomPatientDBWriterService() throw(); protected: /// Override IOVTKGDCM_API virtual void starting() throw(::fwTools::Failed); /// Override IOVTKGDCM_API virtual void stopping() throw(::fwTools::Failed); /// Override IOVTKGDCM_API void updating() throw(::fwTools::Failed); /// Override virtual void updating( ::boost::shared_ptr< const ::fwServices::ObjectMsg > _msg ) throw(::fwTools::Failed) {} ; /// Override IOVTKGDCM_API void info(std::ostream &_sstream ) ; /// Override IOVTKGDCM_API virtual std::vector< std::string > getSupportedExtensions() ; /// Override IOVTKGDCM_API virtual std::string getSelectorDialogTitle(); /// Override IOVTKGDCM_API virtual void configureWithIHM(); /// Return path type managed by the service, here FOLDER IOVTKGDCM_API ::io::IOPathType getIOPathType() const; private : void savePatientDB( const ::boost::filesystem::path patientDBPath, ::boost::shared_ptr< ::fwData::PatientDB > _pPatientDB ); }; } // namespace ioVtkGdcm #endif //_IOVTKGDCM_DICOMPATIENTDBWRITERSERVICE_HPP_
struct KeyFrame { //for the animation's convience, we need the datatype cooperates with time float timeStamp; std::map<std::string, JointTransform> transforms; // std::vector<JointTransform> transforms; }; class JointAnim : public OBJproperty { protected: std::vector<KeyFrame> keyframes; public: virtual ~JointAnim() override; virtual bool load(const aiScene *scene) override; virtual bool push2GPU(void) override; }; //gota decide whether to class JointTransform { public: glm::vec3 translation; glm::quat rotation; glm::vec3 scale; std::string joint_name; JointTransform(const std::string& name = "", const glm::vec3& t = glm::vec3(0.0f), const glm::quat& r = glm::quat(glm::vec3(0.0f)), const glm::vec3& s = glm::vec3(1.0f)); const glm::mat4 getLocalTransform(); static JointTransform interpolate(const JointTransform& a, const JointTransform& b, float progression); static glm::vec3 interpolate(const glm::vec3& a, const glm::vec3& b, float progression); }; JointTransform::JointTransform(const std::string& name, const glm::vec3& t, const glm::quat& r, const glm::vec3& s) { this->joint_name = name; this->translation = t; this->rotation = r; this->scale = s; } JointTransform JointTransform::interpolate(const JointTransform &a, const JointTransform &b, float progression) { assert(a.joint_name == b.joint_name); glm::vec3 trans = (1-progression) * a.translation + progression * b.translation; glm::vec3 scale = (a.scale != b.scale) ? ((1-progression) * a.scale + progression * b.scale) : a.scale; glm::quat quaternion = glm::slerp(a.rotation, b.rotation, progression); return JointTransform(a.joint_name, trans, quaternion, scale); } glm::vec3 JointTransform::interpolate(const glm::vec3 &a, const glm::vec3 &b, float progression) { return (1-progression) * a + progression * b; } struct Animation { double seconds; //you r gonna have memory problem with it. std::vector<KeyFrame> keyframes; }; static bool need_interpolate(const double current_time, double& prev_frame, double& next_frame, const std::set<double>& timestamps) { std::set<double>::const_iterator itr = timestamps.lower_bound(current_time); if (itr == timestamps.end() || *itr == current_time) return false; next_frame = *itr; //this only happens when we don't have 0 frame and we inserted 0. We also want avoid this prev_frame = (itr != timestamps.begin()) ? (*(--itr)) : current_time; if (prev_frame == current_time) return false; else if (next_frame > current_time && current_time > prev_frame) return true; else return false; } int Model::loadAnimations(const aiScene* scene) { // std::cout << "I am here, with " << scene->mNumAnimations << " animations" << std::endl; // this->animations.resize(scene->mNumAnimations); for (uint i = 0; i < scene->mNumAnimations; i++) { aiAnimation *anim = scene->mAnimations[i]; Animation local_anim; std::set<double> global_timestamps; std::map<double, KeyFrame> all_keyframes; //XXX: so not true!!! it is harmless to insert the 0 timestamp // KeyFrame first_frame; // first_frame.timeStamp = 0; // for (auto bone_itr = this->bones.cbegin(); bone_itr != this->bones.end(); bone_itr++) // first_frame.transforms[bone_itr->first] = JointTransform(bone_itr->first); // all_keyframes[0.0] = first_frame; // local_anim.seconds = anim->mTicksPerSecond * anim->mDuration; // global_timestamps.insert(0); for (uint k = 0; k < anim->mNumChannels; k++) { std::set<double> timestamps; aiNodeAnim *bone_anim = anim->mChannels[k]; std::string bone_name = bone_anim->mNodeName.C_Str(); //now I need to interpolate keyframes for (uint itt = 0; itt < bone_anim->mNumPositionKeys; itt++) { // double current_time = bone_anim->mPositionKeys[itt].mTime; double current_time = value_at_precision(bone_anim->mPositionKeys[itt].mTime, 2); aiVector3D value = bone_anim->mPositionKeys[itt].mValue; KeyFrame& keyframe = all_keyframes[current_time]; keyframe.timeStamp = current_time; keyframe.transforms[bone_name] = JointTransform(bone_name, glm::vec3(value.x, value.y, value.z)); global_timestamps.insert(current_time); timestamps.insert(current_time); } for (uint itr = 0; itr < bone_anim->mNumRotationKeys; itr++) { // double current_time = bone_anim->mPositionKeys[itr].mTime; double current_time = value_at_precision(bone_anim->mRotationKeys[itr].mTime, 2); aiQuaternion value = bone_anim->mRotationKeys[itr].mValue; KeyFrame& keyframe = all_keyframes[current_time]; keyframe.timeStamp = current_time; JointTransform& batframe = keyframe.transforms[bone_name]; batframe.joint_name = bone_name; batframe.rotation = glm::quat(value.w, value.x, value.y ,value.z); double next_tstamp, prev_tstamp; if (need_interpolate(current_time, prev_tstamp, next_tstamp, timestamps)) { glm::vec3 last_transform = all_keyframes[prev_tstamp].transforms[bone_name].translation; glm::vec3 next_transform = all_keyframes[next_tstamp].transforms[bone_name].translation; batframe.translation = JointTransform::interpolate(last_transform, next_transform, (current_time - prev_tstamp)/(next_tstamp - prev_tstamp) ); if (glm::isnan(batframe.translation)[0]) std::cerr << "lol, found a bug" << std::endl; } global_timestamps.insert(current_time); timestamps.insert(current_time); } for (uint its = 0; its < bone_anim->mNumScalingKeys; its++) { // double current_time = bone_anim->mPositionKeys[its].mTime; double current_time = value_at_precision(bone_anim->mScalingKeys[its].mTime, 2); aiVector3D value = bone_anim->mScalingKeys[its].mValue; KeyFrame& keyframe = all_keyframes[current_time]; keyframe.timeStamp = current_time; JointTransform& batframe = keyframe.transforms[bone_name]; batframe.joint_name = bone_name; batframe.scale = glm::vec3(value.x, value.y, value.z); double next_tstamp, prev_tstamp; if (need_interpolate(current_time, prev_tstamp, next_tstamp, timestamps)) { JointTransform& last_transform = all_keyframes[prev_tstamp].transforms[bone_name]; JointTransform& next_transform = all_keyframes[next_tstamp].transforms[bone_name]; batframe = JointTransform::interpolate(last_transform, next_transform, (current_time - prev_tstamp)/(next_tstamp - prev_tstamp) ); } global_timestamps.insert(current_time); timestamps.insert(current_time); } // std::cout << bone_anim->mNumPositionKeys << " translations, "; // std::cout << bone_anim->mNumRotationKeys << " rotations, and "; // std::cout << bone_anim->mNumScalingKeys << " scales\n"; // (void)bone_anim->mNumPositionKeys; // (void)bone_anim->mNumRotationKeys; // (void)bone_anim->mNumScalingKeys; } /* std::cerr << "number of keyframes for this model: " << all_keyframes.size() << std::endl; for (auto itr = all_keyframes.begin(); itr != all_keyframes.end(); itr++) { std::cerr << "current timestamp" << itr->first << std::endl; for (auto itj = itr->second.transforms.begin(); itj != itr->second.transforms.end(); itj++) { std::cerr << "\tbone: " << itj->first << "\t" << glm::to_string(itj->second.translation); std::cerr << '\t' << glm::to_string(itj->second.rotation) <<'\t' << glm::to_string(itj->second.scale) << std::endl; } } */ //copy constructor is called this->animations[std::string(anim->mName.C_Str())] = local_anim; } }
/*==================================================================== Copyright(c) 2018 Adam Rankin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ====================================================================*/ // Local includes #include "pch.h" #include "AppView.h" #include "Common.h" #include "Debug.h" #include "DirectXHelper.h" #include "HoloInterventionCore.h" #include "IConfigurable.h" #include "IEngineComponent.h" #include "ILocatable.h" #include "IStabilizedComponent.h" // System includes #include "GazeSystem.h" #include "ImagingSystem.h" #include "NetworkSystem.h" #include "NotificationSystem.h" #include "RegistrationSystem.h" #include "SplashSystem.h" #include "TaskSystem.h" #include "ToolSystem.h" // UI includes #include "Icons.h" // Physics includes #include "PhysicsAPI.h" // Sound includes #include "SoundAPI.h" // Rendering includes #include "ModelRenderer.h" #include "NotificationRenderer.h" #include "SliceRenderer.h" #include "MeshRenderer.h" #include "VolumeRenderer.h" // Input includes #include "SpatialInput.h" #include "VoiceInput.h" // STL includes #include <iomanip> #include <regex> #include <string> // Windows includes #include <windows.graphics.directx.direct3d11.interop.h> // Intellisense includes #include "Log.h" #include <WindowsNumerics.h> using namespace Concurrency; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::Data::Xml::Dom; using namespace Windows::Foundation::Collections; using namespace Windows::Foundation::Numerics; using namespace Windows::Foundation; using namespace Windows::Graphics::DirectX; using namespace Windows::Graphics::Holographic; using namespace Windows::Media::SpeechRecognition; using namespace Windows::Perception::Spatial::Surfaces; using namespace Windows::Perception::Spatial; using namespace Windows::Storage; using namespace Windows::System::Threading; using namespace Windows::UI::Input::Spatial; namespace HoloIntervention { //---------------------------------------------------------------------------- // Loads and initializes application assets when the application is loaded. HoloInterventionCore::HoloInterventionCore(const std::shared_ptr<DX::DeviceResources>& deviceResources) : m_deviceResources(deviceResources) { m_deviceResources->RegisterDeviceNotify(this); } //---------------------------------------------------------------------------- HoloInterventionCore::~HoloInterventionCore() { m_deviceResources->RegisterDeviceNotify(nullptr); UnregisterHolographicEventHandlers(); if (m_locatabilityIcon != nullptr) { m_icons->RemoveEntry(m_locatabilityIcon->GetId()); } } //---------------------------------------------------------------------------- void HoloInterventionCore::SetHolographicSpace(HolographicSpace^ holographicSpace) { UnregisterHolographicEventHandlers(); m_holographicSpace = holographicSpace; // Engine components m_debug = std::make_unique<Debug>(*m_sliceRenderer.get(), m_deviceResources); m_modelRenderer = std::make_unique<Rendering::ModelRenderer>(m_deviceResources, m_timer, *m_debug.get()); m_sliceRenderer = std::make_unique<Rendering::SliceRenderer>(m_deviceResources, m_timer, *m_debug.get()); m_debug->SetModelRenderer(m_modelRenderer.get()); m_debug->SetSliceRenderer(m_sliceRenderer.get()); m_notificationRenderer = std::make_unique<Rendering::NotificationRenderer>(m_deviceResources); m_volumeRenderer = std::make_unique<Rendering::VolumeRenderer> (m_deviceResources, m_timer); m_physicsAPI = std::make_unique<Physics::PhysicsAPI>(m_deviceResources, m_timer); m_meshRenderer = std::make_unique<Rendering::MeshRenderer> (m_deviceResources, *m_physicsAPI); m_icons = std::make_unique<UI::Icons>(*m_modelRenderer.get()); m_soundAPI = std::make_unique<Sound::SoundAPI>(); m_spatialInput = std::make_unique<Input::SpatialInput>(); m_voiceInput = std::make_unique<Input::VoiceInput> (*m_soundAPI.get(), *m_icons.get()); m_icons->AddEntryAsync(L"satellite.cmo", L"satellite").then([this](std::shared_ptr<UI::Icon> entry) { m_locatabilityIcon = entry; entry->SetUserRotation(Math::PI_2<float>, Math::PI<float>, 0.0); entry->GetModel()->RenderDefault(); }); // Systems (apps-specific behaviour), eventually move to separate project and have engine DLL m_notificationSystem = std::make_unique<System::NotificationSystem>(*m_notificationRenderer.get()); m_networkSystem = std::make_unique<System::NetworkSystem> (*this, *m_notificationSystem.get(), *m_voiceInput.get(), *m_icons.get(), *m_debug.get()); m_registrationSystem = std::make_unique<System::RegistrationSystem>(*this, *m_networkSystem.get(), *m_physicsAPI.get(), *m_notificationSystem.get(), *m_modelRenderer.get(), *m_spatialInput.get(), *m_icons.get(), *m_debug.get(), m_timer); m_toolSystem = std::make_unique<System::ToolSystem>(*this, *m_notificationSystem.get(), *m_registrationSystem.get(), *m_modelRenderer.get(), *m_networkSystem.get(), *m_icons.get()); m_gazeSystem = std::make_unique<System::GazeSystem> (*m_notificationSystem.get(), *m_physicsAPI.get(), *m_modelRenderer.get()); m_imagingSystem = std::make_unique<System::ImagingSystem> (*this, *m_registrationSystem.get(), *m_notificationSystem.get(), *m_sliceRenderer.get(), *m_volumeRenderer.get(), *m_networkSystem.get(), *m_debug.get()); m_splashSystem = std::make_unique<System::SplashSystem> (*m_sliceRenderer.get()); m_taskSystem = std::make_unique<System::TaskSystem> (*this, *m_notificationSystem.get(), *m_networkSystem.get(), *m_toolSystem.get(), *m_registrationSystem.get(), *m_modelRenderer.get(), *m_icons.get()); m_engineComponents.push_back(m_modelRenderer.get()); m_engineComponents.push_back(m_sliceRenderer.get()); m_engineComponents.push_back(m_volumeRenderer.get()); m_engineComponents.push_back(m_meshRenderer.get()); m_engineComponents.push_back(m_soundAPI.get()); m_engineComponents.push_back(m_notificationSystem.get()); m_engineComponents.push_back(m_spatialInput.get()); m_engineComponents.push_back(m_voiceInput.get()); m_engineComponents.push_back(m_physicsAPI.get()); m_engineComponents.push_back(m_icons.get()); m_engineComponents.push_back(m_networkSystem.get()); m_engineComponents.push_back(m_gazeSystem.get()); m_engineComponents.push_back(m_toolSystem.get()); m_engineComponents.push_back(m_registrationSystem.get()); m_engineComponents.push_back(m_imagingSystem.get()); m_engineComponents.push_back(m_splashSystem.get()); m_engineComponents.push_back(m_taskSystem.get()); ReadConfigurationAsync().then([this](bool result) { if (!result) { LOG_ERROR("Unable to initialize system. Loading of configuration failed."); Log::instance().EndSessionAsync(); } RegisterVoiceCallbacks(); }); m_soundAPI->InitializeAsync().then([this](task<HRESULT> initTask) { HRESULT hr(S_OK); try { hr = initTask.get(); } catch (Platform::Exception^ e) { m_notificationSystem->QueueMessage(L"Unable to initialize audio system. See log."); OutputDebugStringW((L"Audio Error" + e->Message)->Data()); } }); // Use the default SpatialLocator to track the motion of the device. m_locator = SpatialLocator::GetDefault(); for (auto& system : m_locatables) { system->OnLocatabilityChanged(m_locator->Locatability); } m_locatabilityChangedToken = m_locator->LocatabilityChanged += ref new Windows::Foundation::TypedEventHandler<SpatialLocator^, Object^> (std::bind(&HoloInterventionCore::OnLocatabilityChanged, this, std::placeholders::_1, std::placeholders::_2)); m_cameraAddedToken = m_holographicSpace->CameraAdded += ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraAddedEventArgs^> (std::bind(&HoloInterventionCore::OnCameraAdded, this, std::placeholders::_1, std::placeholders::_2)); m_cameraRemovedToken = m_holographicSpace->CameraRemoved += ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraRemovedEventArgs^> (std::bind(&HoloInterventionCore::OnCameraRemoved, this, std::placeholders::_1, std::placeholders::_2)); m_attachedReferenceFrame = m_locator->CreateAttachedFrameOfReferenceAtCurrentHeading(); // Initialize the notification system with a bogus frame to grab sensor data HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame(); SpatialCoordinateSystem^ currentCoordinateSystem = m_attachedReferenceFrame->GetStationaryCoordinateSystemAtTimestamp(holographicFrame->CurrentPrediction->Timestamp); SpatialPointerPose^ pose = SpatialPointerPose::TryGetAtTimestamp(currentCoordinateSystem, holographicFrame->CurrentPrediction->Timestamp); m_notificationSystem->Initialize(pose); m_physicsAPI->InitializeSurfaceObserverAsync(currentCoordinateSystem).then([this](task<bool> initTask) { bool result(false); try { result = initTask.get(); } catch (const std::exception&) { LOG_ERROR("Unable to initialize surface observers. Mesh data not available."); result = false; } if (!result) { // TODO : add more robust error handling m_notificationSystem->QueueMessage("Unable to initialize surface observer."); } LoadAppStateAsync().then([this](bool result) { if (!result) { LOG_ERROR("Unable to load app state. Starting new session."); } LOG(LogLevelType::LOG_LEVEL_INFO, "Engine loading..."); uint32 componentsReady(0); bool engineReady(true); auto messageId = m_notificationSystem->QueueMessage(L"Loading ... 0%"); double lastValue = 0.0; do { componentsReady = 0; engineReady = true; std::this_thread::sleep_for(std::chrono::milliseconds(16)); for (auto& component : m_engineComponents) { #if defined(_DEBUG) if (!component->IsReady()) { std::string name(typeid(*component).name()); std::wstring wname(name.begin(), name.end()); m_debug->UpdateValue(L"not-ready-comp", wname); } #endif engineReady = engineReady && component->IsReady(); if (component->IsReady()) { componentsReady++; } } if ((double)componentsReady / m_engineComponents.size() * 100 == lastValue) { continue; } lastValue = (double)componentsReady / m_engineComponents.size() * 100; m_notificationSystem->RemoveMessage(messageId); std::wstringstream wss; wss << L"Loading ... " << std::fixed << std::setprecision(1) << lastValue << L"%"; messageId = m_notificationSystem->QueueMessage(wss.str()); } while (!engineReady); m_engineReady = true; }).then([this]() { LOG(LogLevelType::LOG_LEVEL_INFO, "Engine loaded."); m_splashSystem->EndSplash(); m_voiceInput->EnableVoiceAnalysis(true); }); }); } //---------------------------------------------------------------------------- void HoloInterventionCore::UnregisterHolographicEventHandlers() { if (m_holographicSpace != nullptr) { if (m_cameraAddedToken.Value != 0) { m_holographicSpace->CameraAdded -= m_cameraAddedToken; m_cameraAddedToken.Value = 0; } if (m_cameraRemovedToken.Value != 0) { m_holographicSpace->CameraRemoved -= m_cameraRemovedToken; m_cameraRemovedToken.Value = 0; } } if (m_locator != nullptr) { m_locator->LocatabilityChanged -= m_locatabilityChangedToken; } } //---------------------------------------------------------------------------- // Updates the application state once per frame. HolographicFrame^ HoloInterventionCore::Update() { if (!m_engineUserEnabled) { return nullptr; } HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame(); HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction; m_deviceResources->EnsureCameraResources(holographicFrame, prediction); SpatialCoordinateSystem^ hmdCoordinateSystem = m_attachedReferenceFrame->GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp); DX::CameraResources* cameraResources(nullptr); if (!m_deviceResources->UseHolographicCameraResources<bool>([this, holographicFrame, prediction, hmdCoordinateSystem, &cameraResources](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap) { for (auto cameraPose : prediction->CameraPoses) { cameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get(); if (cameraResources == nullptr) { return false; } auto result = cameraResources->Update(m_deviceResources, cameraPose, hmdCoordinateSystem); } return true; })) { // Camera resources failed LOG_ERROR("Camera update failed. Skipping frame."); return nullptr; } // Time-based updates m_timer.Tick([&]() { SpatialPointerPose^ headPose = SpatialPointerPose::TryGetAtTimestamp(hmdCoordinateSystem, prediction->Timestamp); if (!m_engineReady) { // Show our welcome screen until the engine is ready! m_splashSystem->Update(m_timer, hmdCoordinateSystem, headPose); m_sliceRenderer->Update(headPose, cameraResources); m_notificationSystem->Update(headPose, m_timer); } else { m_voiceInput->Update(m_timer); if (headPose != nullptr) { m_volumeRenderer->Update(cameraResources, hmdCoordinateSystem, headPose); } m_imagingSystem->Update(m_timer, hmdCoordinateSystem); m_toolSystem->Update(m_timer, hmdCoordinateSystem); m_networkSystem->Update(m_timer); m_taskSystem->Update(hmdCoordinateSystem, m_timer); m_physicsAPI->Update(hmdCoordinateSystem); if (headPose != nullptr) { m_registrationSystem->Update(hmdCoordinateSystem, headPose, prediction->CameraPoses->GetAt(0)); m_gazeSystem->Update(m_timer, hmdCoordinateSystem, headPose); m_icons->Update(m_timer, headPose); m_soundAPI->Update(m_timer, hmdCoordinateSystem); m_sliceRenderer->Update(headPose, cameraResources); m_notificationSystem->Update(headPose, m_timer); } m_modelRenderer->Update(cameraResources); } m_debug->Update(hmdCoordinateSystem); }); SpatialPointerPose^ headPose = SpatialPointerPose::TryGetAtTimestamp(hmdCoordinateSystem, prediction->Timestamp); SetHolographicFocusPoint(prediction, holographicFrame, hmdCoordinateSystem, headPose); return holographicFrame; } //---------------------------------------------------------------------------- bool HoloInterventionCore::Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame) { if (m_timer.GetFrameCount() == 0 || !m_engineUserEnabled || holographicFrame == nullptr) { return false; } // Lock the set of holographic camera resources, then draw to each camera in this frame. return m_deviceResources->UseHolographicCameraResources<bool> ([this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap) -> bool { holographicFrame->UpdateCurrentPrediction(); HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction; SpatialCoordinateSystem^ currentCoordinateSystem = m_attachedReferenceFrame->GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp); bool atLeastOneCameraRendered = false; for (auto cameraPose : prediction->CameraPoses) { DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get(); const auto context = m_deviceResources->GetD3DDeviceContext(); const auto depthStencilView = pCameraResources->GetDepthStencilView(); ID3D11RenderTargetView* const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() }; context->OMSetRenderTargets(1, targets, depthStencilView); context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent); context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); pCameraResources->Update(m_deviceResources, cameraPose, currentCoordinateSystem); bool activeCamera = pCameraResources->Attach(m_deviceResources); if (activeCamera) { if (m_engineReady) { m_meshRenderer->Render(); m_modelRenderer->Render(); m_sliceRenderer->Render(); m_volumeRenderer->Render(); if (m_notificationSystem->IsShowingNotification()) { m_notificationRenderer->Render(); } } else { // Show our welcome screen until it is ready! m_sliceRenderer->Render(); if (m_notificationSystem->IsShowingNotification()) { m_notificationRenderer->Render(); } } atLeastOneCameraRendered = true; } } return atLeastOneCameraRendered; }); } //---------------------------------------------------------------------------- task<bool> HoloInterventionCore::SaveAppStateAsync() { if (m_physicsAPI == nullptr) { return task_from_result(false); } return create_task([this]() { uint32 timer(0); while (!m_physicsAPI->IsReady() && timer < 5000) //(wait for 5s) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); timer += 100; } if (timer >= 5000) { return task_from_result(false); } return m_physicsAPI->SaveAppStateAsync(); }); } //---------------------------------------------------------------------------- task<bool> HoloInterventionCore::LoadAppStateAsync() { return create_task([this]() { while (m_physicsAPI == nullptr || m_registrationSystem == nullptr || !m_physicsAPI->IsReady() || !m_registrationSystem->IsReady()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return m_physicsAPI->LoadAppStateAsync().then([this](bool result) { if (!result) { return task_from_result(result); } // Registration must follow spatial due to anchor store return m_registrationSystem->LoadAppStateAsync(); }); }); } //---------------------------------------------------------------------------- uint64 HoloInterventionCore::GetCurrentFrameNumber() const { return m_timer.GetFrameCount(); } //---------------------------------------------------------------------------- void HoloInterventionCore::OnDeviceLost() { m_meshRenderer->ReleaseDeviceDependentResources(); m_physicsAPI->ReleaseDeviceDependentResources(); m_modelRenderer->ReleaseDeviceDependentResources(); m_sliceRenderer->ReleaseDeviceDependentResources(); m_notificationRenderer->ReleaseDeviceDependentResources(); m_volumeRenderer->ReleaseDeviceDependentResources(); } //---------------------------------------------------------------------------- void HoloInterventionCore::OnDeviceRestored() { m_notificationRenderer->CreateDeviceDependentResourcesAsync(); m_meshRenderer->CreateDeviceDependentResources(); m_modelRenderer->CreateDeviceDependentResources(); m_sliceRenderer->CreateDeviceDependentResources(); m_volumeRenderer->CreateDeviceDependentResourcesAsync(); m_physicsAPI->CreateDeviceDependentResourcesAsync(); } //---------------------------------------------------------------------------- void HoloInterventionCore::RegisterLocatable(ILocatable* locatable) { if (std::find(begin(m_locatables), end(m_locatables), locatable) == end(m_locatables)) { m_locatables.push_back(locatable); } } //---------------------------------------------------------------------------- void HoloInterventionCore::UnregisterLocatable(ILocatable* locatable) { std::vector<ILocatable*>::iterator it = std::find(begin(m_locatables), end(m_locatables), locatable); if (it != end(m_locatables)) { m_locatables.erase(it); } } //---------------------------------------------------------------------------- void HoloInterventionCore::RegisterConfigurable(IConfigurable* component) { if (std::find(begin(m_configurables), end(m_configurables), component) == end(m_configurables)) { m_configurables.push_back(component); } } //---------------------------------------------------------------------------- void HoloInterventionCore::UnregisterConfigurable(IConfigurable* component) { std::vector<IConfigurable*>::iterator it = std::find(begin(m_configurables), end(m_configurables), component); if (it != end(m_configurables)) { m_configurables.erase(it); } } //---------------------------------------------------------------------------- void HoloInterventionCore::OnLocatabilityChanged(SpatialLocator^ sender, Object^ args) { m_locatability = sender->Locatability; for (auto& locatable : m_locatables) { locatable->OnLocatabilityChanged(sender->Locatability); } if (m_locatabilityIcon == nullptr) { return; } switch (sender->Locatability) { case SpatialLocatability::Unavailable: { m_locatabilityIcon->GetModel()->SetColour(1.0, 0.0, 0.0); m_notificationSystem->RemoveMessage(m_locatabilityMessage); m_locatabilityMessage = m_notificationSystem->QueueMessage(L"Warning! Positional tracking is unavailable."); } break; case SpatialLocatability::PositionalTrackingActivating: case SpatialLocatability::OrientationOnly: case SpatialLocatability::PositionalTrackingInhibited: // Gaze-locked content still valid m_locatabilityIcon->GetModel()->SetColour(1.0, 1.0, 0.0); m_notificationSystem->RemoveMessage(m_locatabilityMessage); m_locatabilityMessage = m_notificationSystem->QueueMessage(L"Re-acquiring positional tracking..."); break; case SpatialLocatability::PositionalTrackingActive: m_locatabilityIcon->GetModel()->RenderDefault(); m_notificationSystem->RemoveMessage(m_locatabilityMessage); m_locatabilityMessage = m_notificationSystem->QueueMessage(L"Positional tracking is active.", 1.0); break; } } //---------------------------------------------------------------------------- void HoloInterventionCore::OnCameraAdded( HolographicSpace^ sender, HolographicSpaceCameraAddedEventArgs^ args ) { Deferral^ deferral = args->GetDeferral(); HolographicCamera^ holographicCamera = args->Camera; create_task([this, deferral, holographicCamera]() { m_deviceResources->AddHolographicCamera(holographicCamera); // Holographic frame predictions will not include any information about this camera until the deferral is completed. deferral->Complete(); }); } //---------------------------------------------------------------------------- void HoloInterventionCore::OnCameraRemoved( HolographicSpace^ sender, HolographicSpaceCameraRemovedEventArgs^ args ) { create_task([this]() { // TODO: Asynchronously unload or deactivate content resources (not back buffer // resources) that are specific only to the camera that was removed. }); m_deviceResources->RemoveHolographicCamera(args->Camera); } //---------------------------------------------------------------------------- void HoloInterventionCore::RegisterVoiceCallbacks() { Input::VoiceInputCallbackMap callbacks; m_debug->RegisterVoiceCallbacks(callbacks); m_gazeSystem->RegisterVoiceCallbacks(callbacks); m_networkSystem->RegisterVoiceCallbacks(callbacks); m_physicsAPI->RegisterVoiceCallbacks(callbacks); m_toolSystem->RegisterVoiceCallbacks(callbacks); m_imagingSystem->RegisterVoiceCallbacks(callbacks); m_registrationSystem->RegisterVoiceCallbacks(callbacks); m_taskSystem->RegisterVoiceCallbacks(callbacks); m_meshRenderer->RegisterVoiceCallbacks(callbacks); callbacks[L"end session"] = [this](SpeechRecognitionResult ^ result) { Log::instance().EndSessionAsync(); m_notificationSystem->QueueMessage(L"Log session ended."); }; callbacks[L"save config"] = [this](SpeechRecognitionResult ^ result) { m_physicsAPI->SaveAppStateAsync().then([this](bool result) { if (!result) { // Physics API didn't save m_notificationSystem->QueueMessage("Unable to save anchors. Continuing."); } WriteConfigurationAsync().then([this](bool result) { if (result) { m_notificationSystem->QueueMessage(L"Save successful."); } else { m_notificationSystem->QueueMessage(L"Save failed."); } }); }); }; callbacks[L"hide all"] = [this](SpeechRecognitionResult ^ result) { m_engineUserEnabled = false; }; callbacks[L"show all"] = [this](SpeechRecognitionResult ^ result) { m_engineUserEnabled = true; }; m_voiceInput->CompileCallbacksAsync(callbacks).then([this](task<bool> compileTask) { bool result; try { result = compileTask.get(); m_voiceInput->SwitchToCommandRecognitionAsync(); } catch (const std::exception& e) { LOG(LogLevelType::LOG_LEVEL_ERROR, std::string("Failed to compile voice callbacks: ") + e.what()); m_notificationSystem->QueueMessage(L"Unable to initialize voice input system. Critical failure."); } }); } //---------------------------------------------------------------------------- void HoloInterventionCore::SetHolographicFocusPoint(HolographicFramePrediction^ prediction, HolographicFrame^ holographicFrame, SpatialCoordinateSystem^ currentCoordinateSystem, SpatialPointerPose^ pose) { float maxPriority(PRIORITY_NOT_ACTIVE); IStabilizedComponent* winningComponent(nullptr); for (auto component : m_engineComponents) { IStabilizedComponent* stabilizedComponent = dynamic_cast<IStabilizedComponent*>(component); if (stabilizedComponent != nullptr && stabilizedComponent->GetStabilizePriority() > maxPriority) { maxPriority = stabilizedComponent->GetStabilizePriority(); winningComponent = stabilizedComponent; } } if (winningComponent == nullptr) { LOG(LogLevelType::LOG_LEVEL_WARNING, "No component returned a stabilization request."); return; } for (auto cameraPose : prediction->CameraPoses) { HolographicCameraRenderingParameters^ renderingParameters = holographicFrame->GetRenderingParameters(cameraPose); float3 focusPointPosition = winningComponent->GetStabilizedPosition(pose); float3 focusPointVelocity = winningComponent->GetStabilizedVelocity(); #if defined(_DEBUG) std::string className(typeid(*winningComponent).name()); std::wstring wClassName(begin(className), end(className)); m_debug->UpdateValue(L"WinComp", wClassName); #endif try { renderingParameters->SetFocusPoint( currentCoordinateSystem, focusPointPosition, -pose->Head->ForwardDirection, focusPointVelocity ); } catch (Platform::Exception^ e) { LOG(LogLevelType::LOG_LEVEL_ERROR, e->Message); } } } //---------------------------------------------------------------------------- task<bool> HoloInterventionCore::WriteConfigurationAsync() { // Backup current file return create_task(ApplicationData::Current->LocalFolder->TryGetItemAsync(L"configuration.xml")).then([this](IStorageItem ^ item) { if (item == nullptr) { return task_from_result((StorageFile^) nullptr); } else { StorageFile^ file = dynamic_cast<StorageFile^>(item); auto Calendar = ref new Windows::Globalization::Calendar(); Calendar->SetToNow(); auto fileName = L"configuration_" + Calendar->YearAsString() + L"-" + Calendar->MonthAsNumericString() + L"-" + Calendar->DayAsString() + L"T" + Calendar->HourAsPaddedString(2) + L"h" + Calendar->MinuteAsPaddedString(2) + L"m" + Calendar->SecondAsPaddedString(2) + L"s.xml"; return create_task(file->CopyAsync(ApplicationData::Current->LocalFolder, fileName, Windows::Storage::NameCollisionOption::GenerateUniqueName)); } }).then([this](task<StorageFile^> copyTask) { try { copyTask.wait(); } catch (Platform::Exception^ e) { WLOG_ERROR(L"Unable to backup existing configuration. Data loss may occur. Error: " + e->Message); } // Create new document auto doc = ref new XmlDocument(); // Add root node auto elem = doc->CreateElement(L"HoloIntervention"); doc->AppendChild(elem); auto docElem = doc->DocumentElement; // Populate document std::vector<task<bool>> tasks; for (auto comp : m_configurables) { tasks.push_back(comp->WriteConfigurationAsync(doc)); } return when_all(begin(tasks), end(tasks)).then([this, doc](std::vector<bool> results) { // Write document to disk return create_task(ApplicationData::Current->LocalFolder->CreateFileAsync(L"configuration.xml", CreationCollisionOption::ReplaceExisting)).then([this, doc](StorageFile ^ file) { auto xmlAsString = std::wstring(doc->GetXml()->Data()); // Custom formatting // After every > add two \r\n xmlAsString = std::regex_replace(xmlAsString, std::wregex(L">"), L">\r\n\r\n"); xmlAsString = std::regex_replace(xmlAsString, std::wregex(L"\" "), L"\"\r\n "); xmlAsString.insert(0, L"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"); return create_task(Windows::Storage::FileIO::WriteTextAsync(file, ref new Platform::String(xmlAsString.c_str()))).then([this](task<void> writeTask) { try { writeTask.wait(); } catch (const std::exception& e) { LOG_ERROR(std::string("Unable to write to file: ") + e.what()); return false; } return true; }); }); }); }); } //---------------------------------------------------------------------------- task<bool> HoloInterventionCore::ReadConfigurationAsync() { if (m_configurables.size() == 0) { return task_from_result(true); } return create_task(ApplicationData::Current->LocalFolder->TryGetItemAsync(L"configuration.xml")).then([this](IStorageItem ^ file) { if (file == nullptr) { // If the user specific file doesn't exist, copy the default from the installed location return create_task(Package::Current->InstalledLocation->GetFileAsync(L"Assets\\Data\\configuration.xml")).then([this](task<StorageFile^> getTask) { StorageFile^ file; try { file = getTask.get(); } catch (Platform::Exception^) { // Not local, not installed... what happened!? assert(false); } return create_task(file->CopyAsync(ApplicationData::Current->LocalFolder, L"configuration.xml")).then([this](task<StorageFile^> copyTask) { try { return copyTask.get(); } catch (Platform::Exception^) { return (StorageFile^) nullptr; } }); }); } else { return task_from_result(dynamic_cast<StorageFile^>(file)); } }).then([this](task<StorageFile^> fileTask) { StorageFile^ file; try { file = fileTask.get(); } catch (Platform::Exception^) { // Not local, not installed... what happened!? task_from_result(false); } if (file == nullptr) { return task_from_result(false); } return LoadXmlDocumentAsync(file).then([this](task<XmlDocument^> docTask) { XmlDocument^ doc; try { doc = docTask.get(); } catch (Platform::Exception^) { // Not local, not installed... what happened!? return task_from_result(false); } // Read application level configuration Platform::String^ xpath = L"/HoloIntervention"; if (doc->SelectNodes(xpath)->Length != 1) { // No configuration found, use defaults LOG_ERROR(L"Config file does not contain \"HoloIntervention\" tag. Invalid configuration file."); return task_from_result(false); } auto node = doc->SelectNodes(xpath)->Item(0); std::wstring outValue; if (!GetAttribute(L"LogLevel", node, outValue) || Log::WStringToLogLevel(outValue) == LogLevelType::LOG_LEVEL_UNKNOWN) { LOG_WARNING("Log level not found in configuration file. Defaulting to LOG_LEVEL_INFO."); Log::instance().SetLogLevel(LogLevelType::LOG_LEVEL_INFO); } else { Log::instance().SetLogLevel(Log::WStringToLogLevel(outValue)); } std::shared_ptr<bool> hasError = std::make_shared<bool> (false); // Run in order, as some configurations may rely on others auto readConfigTask = create_task([this, hasError, doc]() { *hasError = *hasError || !m_configurables[0]->ReadConfigurationAsync(doc).get(); }); for (uint32 i = 1; i < m_configurables.size(); ++i) { readConfigTask = readConfigTask.then([this, hasError, doc, i]() { *hasError = *hasError || !m_configurables[i]->ReadConfigurationAsync(doc).get(); }); } return readConfigTask.then([hasError]() { return !(*hasError); }); }); }); } }
#include "chesslib.h" int King::attack(char* p) { if(deskout(p) > 0) return(0); int x = p[0] - pos[0]; int y = p[1] - pos[1]; if(x < 0) x = -x; if(y < 0) y = -y; if((x <2) && (y<2)) return(1); return(0); }; int Alfil ::attack(char* p) { if(deskout(p) > 0) return(0); int x = p[0] - pos[0]; int y = p[1] - pos[1]; if(x < 0) x = -x; if(y < 0) y = -y; if(((x + y) == 4) && ( x == y)) return(2); return(0); }; int Sultan::attack(char* s) { if(Alfil::attack(s) > 0) return(2); if(King::attack(s) > 0) return(1); return(0); };
#include <iostream> #include <sstream> #include "readf.cpp" using namespace std; int main(int argc, const char *argv[]) { string line; if(line.empty()) cout << "yeah" << endl; getline(cin,line); //line += " "; istringstream in(line); readfile(in); return 0; }
#pragma once #include <memory> namespace detail_uninit { template<typename T> struct alignment_of_impl; template<typename T, std::size_t size_diff> struct helper { static const std::size_t value = size_diff; }; template<typename T> struct helper<T,0> { static const std::size_t value = alignment_of_impl<T>::value; }; template<typename T> struct alignment_of_impl { struct big { T x; char c; }; static const std::size_t value = helper<big, sizeof(big) - sizeof(T)>::value; }; } // end detail_uninit template<typename T> struct alignment_of : detail_uninit::alignment_of_impl<T> {}; template<std::size_t Len, std::size_t Align> struct aligned_storage { union type { unsigned char data[Len]; struct __align__(Align) { } align; }; }; template<typename T> class uninitialized { private: typename aligned_storage<sizeof(T), alignment_of<T>::value>::type storage; __device__ inline const T* ptr() const { return reinterpret_cast<const T*>(storage.data); } __device__ inline T* ptr() { return reinterpret_cast<T*>(storage.data); } public: // copy assignment __device__ inline uninitialized<T> &operator=(const T &other) { T& self = *this; self = other; return *this; } __device__ inline T& get() { return *ptr(); } __device__ inline const T& get() const { return *ptr(); } __device__ inline operator T& () { return get(); } __device__ inline operator const T&() const { return get(); } inline __device__ void construct() { ::new(ptr()) T(); } template<typename Arg> inline __device__ void construct(const Arg &a) { ::new(ptr()) T(a); } template<typename Arg1, typename Arg2> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2) { ::new(ptr()) T(a1,a2); } template<typename Arg1, typename Arg2, typename Arg3> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3) { ::new(ptr()) T(a1,a2,a3); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4) { ::new(ptr()) T(a1,a2,a3,a4); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4, const Arg5 &a5) { ::new(ptr()) T(a1,a2,a3,a4,a5); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4, const Arg5 &a5, const Arg6 &a6) { ::new(ptr()) T(a1,a2,a3,a4,a5,a6); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4, const Arg5 &a5, const Arg6 &a6, const Arg7 &a7) { ::new(ptr()) T(a1,a2,a3,a4,a5,a6,a7); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4, const Arg5 &a5, const Arg6 &a6, const Arg7 &a7, const Arg8 &a8) { ::new(ptr()) T(a1,a2,a3,a4,a5,a6,a7,a8); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4, const Arg5 &a5, const Arg6 &a6, const Arg7 &a7, const Arg8 &a8, const Arg9 &a9) { ::new(ptr()) T(a1,a2,a3,a4,a5,a6,a7,a8,a9); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> inline __device__ void construct(const Arg1 &a1, const Arg2 &a2, const Arg3 &a3, const Arg4 &a4, const Arg5 &a5, const Arg6 &a6, const Arg7 &a7, const Arg8 &a8, const Arg9 &a9, const Arg10 &a10) { ::new(ptr()) T(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10); } inline __device__ void destroy() { T& self = *this; self.~T(); } };
#include "Archiver.h" // Change to your path const path from = "./"; const path to = "./archived/"; // And default images path is "./assets/" , "./archived/assets/" const path imgPath = "assets/"; int main(int argc, const char* argv[]) { cout << "Current Path: " << current_path() << "\n"; if (argc < 2) { cout << "Usage: tools/ta a.md b.md c.md \n" << "From: " << from << "\n" << "To: " << to << "\n" << "You can change the paths setting in source code.\n"; return 0; } vector<string> mdFileNames(argc-1); for (int i = 0; i < argc-1; i++) { mdFileNames[i] = argv[i+1]; } Archiver a(mdFileNames, from, to, imgPath); a.Run(); return 0; }
#ifndef NET_NETADDRESS_HPP #define NET_NETADDRESS_HPP #include <string> #include <vector> #include <cstring> #include <netdb.h> #include <arpa/inet.h> #include <sys/socket.h> #include "../core/Exception.hpp" #include "../core/Stringable.hpp" namespace net { //Union for storing address union u_address { sockaddr_in ipv4; sockaddr_in6 ipv6; }; class NetAddress : public Stringable { public: NetAddress(const sockaddr_in &ipv4); NetAddress(const sockaddr_in6 &ipv6); NetAddress(const std::string &ip, int port = 0); void port(short p); int family() const; unsigned int port() const; std::string address() const; const sockaddr* sockaddr_ptr() const; sockaddr_in get_sockaddr_ipv4() const; sockaddr_in6 get_sockaddr_ipv6() const; virtual std::string to_string() const override; protected: u_address m_netaddress; }; std::vector<NetAddress> get_hosts_by_name(const std::string &name); } #endif
#ifndef MACOPAUTOUPDATEPI_H #define MACOPAUTOUPDATEPI_H #ifdef AUTO_UPDATE_SUPPORT #include "adjunct/autoupdate/pi/opautoupdatepi.h" class MacOpAutoUpdatePI : public OpAutoUpdatePI { public: virtual ~MacOpAutoUpdatePI() {} virtual OP_STATUS GetOSName(OpString& os); virtual OP_STATUS GetOSVersion(OpString& version); virtual OP_STATUS GetArchitecture(OpString& arch); virtual OP_STATUS GetPackageType(OpString& package); virtual OP_STATUS GetGccVersion(OpString& gcc); virtual OP_STATUS GetQTVersion(OpString& qt); virtual OP_STATUS ExtractInstallationFiles(uni_char *package) { return OpStatus::OK; } virtual BOOL ExtractionInBackground() { return FALSE; } }; #endif // AUTO_UPDATE_SUPPORT #endif // MACOPAUTOUPDATEPI_H
// // Created by dylan on 3-3-2020. // Hpp file containing the function declarations for the picture class // Takes a given picture and turns it into an object that it can draw on the window // #ifndef PICTURE_HPP #define PICTURE_HPP #include "drawable.hpp" class picture : public drawable { public: //Constructor for the picture object picture(sf::Vector2f position, std::string filename); //Draw function used to draw the sprite of the picture on the window void draw( sf::RenderWindow & window)const override; //Contains function used to check if the given point is inside the sprite bool contains(const sf::Vector2i & point) override; //Function that instantly moves the sprite to the target location //Do note that it puts the middle point of the sprite on the sprite on the target location void jump(sf::Vector2f target) override; //Function that writes the picture type to a txt file void writeType(std::ofstream & output) override; //Function that writes the name of the picture to the txt file void writeSpecific(std::ofstream & output) override; private: std::string filename; sf::Texture texture; sf::Sprite sprite; }; #endif
// // write_float_image.cpp // PlaneMap // // Created by Yimeng Zhang on 5/25/14. // Copyright (c) 2014 Yimeng Zhang. All rights reserved. // #include "write_float_image.h" #include <stdint.h> #include <cstdio> void write_float_image(GLuint fbo, GLsizei width, GLsizei height, const char * imagepath, bool append){ // printf("Writing image %s\n", imagepath); glBindFramebuffer(GL_FRAMEBUFFER, fbo); uint16_t width16 = (uint16_t)width; uint16_t height16 = (uint16_t)height; unsigned int imageSize = width16*height16*3; float *data = new float[imageSize]; glReadPixels(0,0,width,height,GL_RGB,GL_FLOAT,data); FILE *file; if (!append) { file = fopen(imagepath,"wb"); } else { file = fopen(imagepath,"ab"); // append } if (!file) {printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath); getchar(); return; } // write width and height fwrite(&width16, sizeof(uint16_t), 1, file); fwrite(&height16, sizeof(uint16_t), 1, file); fwrite(data,sizeof(float),imageSize,file); fclose (file); delete [] data; return; }
#include <iostream> int get_fibonacci_last_digit_naive(int n) { if (n <= 1) return n; int previous = 0; int current = 1; for (int i = 0; i < n - 1; ++i) { int tmp_previous = previous; previous = current; current = tmp_previous + current; } return current % 10; } int get_fibonacci_last_digit(int n) { if (n < 0) return 0; if (n <= 1) return n; int previous = 0; int current = 1; for (int i = 0; i < n - 1; ++i) { int tmp_previous = previous; previous = current; current = (tmp_previous + current) % 10; } return current; } #ifdef UNITTESTS #define CATCH_CONFIG_MAIN #include "../../catch.hpp" TEST_CASE("Fibonacci Last Digit negative numbers", "[fibonacci]") { REQUIRE(get_fibonacci_last_digit(-1) == 0); REQUIRE(get_fibonacci_last_digit(std::numeric_limits<int>::max() + 1) == 0); } TEST_CASE("Fibonacci Last Digit corner cases", "[fibonacci]") { REQUIRE(get_fibonacci_last_digit(0) == 0); REQUIRE(get_fibonacci_last_digit(1) == 1); REQUIRE(get_fibonacci_last_digit(std::numeric_limits<int>::max()) == 3); } TEST_CASE("Fibonacci Last Digit must be correct", "[fibonacci]") { REQUIRE(get_fibonacci_last_digit(3) == 2); REQUIRE(get_fibonacci_last_digit(331) == 9); REQUIRE(get_fibonacci_last_digit(327305) == 5); } #else int main() { int n; std::cin >> n; int c = get_fibonacci_last_digit(n); std::cout << c << '\n'; } #endif
#include "Utils/GenerateName.h" #include <crossguid/guid.hpp> using namespace xg; using namespace Rocket; String Rocket::GenerateName() { auto id = newGuid(); return id.str(); }
/* Copyright (c) 2019-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "TestResult.hpp" namespace Ishiko { std::string ToString(TestResult result) { std::string str; switch (result) { case TestResult::unknown: str = "unknown"; break; case TestResult::passed: str = "passed"; break; case TestResult::passedButMemoryLeaks: str = "memory leak detected"; break; case TestResult::exception: str = "exception"; break; case TestResult::failed: str = "failed"; break; case TestResult::skipped: str = "skipped"; break; default: str = "UNEXPECTED OUTCOME ENUM VALUE"; break; } return str; } }
#include <iostream> #include <queue> #include <deque> #include <algorithm> #include <string> #include <vector> #include <stack> #include <set> #include <map> #include <math.h> #include <string.h> #include <bitset> #include <cmath> using namespace std; vector<int> use; vector<int> temp[102]; vector<queue<int>> will; int check[101]; int remain; const int INF = -1; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, k, ret = 0; cin >> n >> k; remain = n; for (int i = 0; i < k; i++) { use.push_back(0); cin >> use[i]; temp[use[i]].push_back(i); } for (int i = 1; i <= k; i++) { if (temp[i].size()) { queue<int> q; for (auto x : temp[i]) { q.push(x); } q.push(INF); will.push_back(q); } } for (int i = 0; i < k; i++) { for (auto x : will) cout << x.front() << " "; cout << endl; int j = 0; for (auto x : will) { if (!x.empty() && x.front() == i) { cout << x.front() << endl; will[j].pop(); if (!check[j] && remain > 0) remain--, check[j] = true; else { ret++; int maximum = 0, index; int k = 0; for (auto x : will) { if (check[k]) { if (maximum < x.front()) maximum = x.front(), index = k; } check[k] = false; } check[j] = true; } } j++; } } cout << ret; return 0; }
#ifndef GAME_SETTINGS_H #define GAME_SETTINGS_H // TODO: Add suitable settings // TODO: Load settings from file somewhere namespace Platy { namespace Game { class Settings { public: Settings() = delete; ~Settings() = default; static void Init(); ///////////////// // Setters ///////////////// static void SetGamePadDeadZone(const float& aValue); ///////////////// // Getters ///////////////// static const float& GetGamePadDeadZone(); private: static float myGamePadAxisDeadZone; }; } } #endif
#include "StepGenerator.hpp" #include <sys/time.h> #include <cmath> #include <boost/random/uniform_real_distribution.hpp> #define PI 3.14159265359 StepGenerator::StepGenerator() { timeval tv; gettimeofday(&tv, NULL); rng.seed(1000000*tv.tv_sec + tv.tv_usec); } void StepGenerator::generateNext(position& next, position last) { double theta = generateAngle(0,2*PI); double phi = generateAngle(0,PI); next.x = last.x + cos(theta) * sin(phi); next.y = last.y + sin(theta) * sin(phi); next.z = last.z + cos(phi); } double StepGenerator::generateAngle(double lowBound, double highBound) { boost::random::uniform_real_distribution<> uniformDistribution(lowBound, highBound); return uniformDistribution(rng); }
/** ****************************************************************************** * Copyright (c) 2020 - ~, SCUT-RobotLab Development Team * @file motor_AK80.h * @author Mentos Seetoo 1356046979@qq.com * @brief Driver for T-Motor A-Series Dynamic Module(AK80-6, AK80-9), which is * highly intergrated with internal gear and controller, on embedded * platform. Extension package of 'motor.h'. * @date 2020-07-11 * @version 1.0 * @par Change Log: * <table> * <tr><th>Date <th>Version <th>Author <th>Description * <tr><td>2020-07-11 <td> 1.0 <td>Mentos Seetoo <td>Creator * </table> * ============================================================================== How to use this library ============================================================================== @usage 1. Construct a new object of 'Motor_AK80_9'. 2. Optionally call `setZero_cmd()` & `set_pid()`. 3. MUST call `enterCtrlMode_cmd()` once and send by CAN before control loop. 4. Use `pack_cmd()` & `unpack_cmd()` to pack/unpack CAN meaasge data. - To view more details about this dynamic module, please read 'AK80-6_Cook_Book_v1.pdf' following in the folder. @warning - Standard C++11 required! - Unsafe under multithreading. ****************************************************************************** * @attention * * if you had modified this file, please make sure your code does not have many * bugs, update the version Number, write dowm your name and the date, the most * important is make sure the users will have clear and definite understanding * through your new brief. * * <h2><center>&copy; Copyright (c) 2020 - ~, SCUT-RobotLab Development Team. * All rights reserved.</center></h2> ****************************************************************************** */ #pragma once /* Includes ------------------------------------------------------------------*/ #include <stdint.h> #include <math.h> #ifdef __cplusplus /* Private macros ------------------------------------------------------------*/ /* Private type --------------------------------------------------------------*/ struct _AKParamRange_t { float P_MIN; float P_MAX; float V_MIN; float V_MAX; float T_MIN; float T_MAX; float KP_MIN; float KP_MAX; float KD_MIN; float KD_MAX; _AKParamRange_t(float p_min, float p_max, float v_min, float v_max, \ float t_min, float t_max, float kp_min, float kp_max, \ float kd_min, float kd_max):P_MIN(p_min), P_MAX(p_max),\ V_MIN(v_min), V_MAX(v_max), T_MIN(t_min), T_MAX(t_max), \ KP_MIN(kp_min), KP_MAX(kp_max), KD_MIN(kd_min), KD_MAX(kd_max){} }; static int float_to_uint(float x, float x_min, float x_max, int bits) { /* Converts a float to an unsigned int, given range and number of bits */ float span = x_max - x_min; float offset = x_min; return (int) ((x-offset)*((float)((1<<bits)-1))/span); } static float uint_to_float(int x_int, float x_min, float x_max, int bits){ /* converts unsigned int to float, given range and number of bits */ float span = x_max - x_min; float offset = x_min; return ((float)x_int)*span/((float)((1<<bits)-1)) + offset; } /* Exported function declarations --------------------------------------------*/ class Motor_AK80_9 { private: const _AKParamRange_t PARAM = //!< Parameter range for specific model _AKParamRange_t(-95.5, 95.5, -30, 30, -18, 18, 0, 500, 0, 5); float position_des, velocity_des, torque_ff; //!< Desire value & feed forward torque. float Kp, Kd; //!< internal pid controller. bool is_ctrlMode; //!< motor only works under control mode. int32_t ID; public: float position_fb, velocity_fb, torque_fb; //!< Feed back value. Motor_AK80_9(uint8_t id, float p_gain, float d_gain) { ID = id; is_ctrlMode = false; Kp = fminf(fmaxf(PARAM.KP_MIN, p_gain), PARAM.KP_MAX); Kd = fminf(fmaxf(PARAM.KD_MIN, d_gain), PARAM.KD_MAX); }; void set_pid(float p_gain, float d_gain) { Kp = fminf(fmaxf(PARAM.KP_MIN, p_gain), PARAM.KP_MAX); Kd = fminf(fmaxf(PARAM.KD_MIN, d_gain), PARAM.KD_MAX); } /* Be careful of the input array. */ void pack_cmd(uint8_t _package[],float p_des, float v_des, float t_ff) { if(is_ctrlMode) { //Constrain position_des = fminf(fmaxf(PARAM.P_MIN, p_des), PARAM.P_MAX); velocity_des = fminf(fmaxf(PARAM.V_MIN, v_des), PARAM.V_MAX); torque_ff = fminf(fmaxf(PARAM.T_MIN, t_ff), PARAM.T_MAX); //Convert float to uint. int p_int = float_to_uint(position_des, PARAM.P_MIN, PARAM.P_MAX, 16); int v_int = float_to_uint(velocity_des, PARAM.V_MIN, PARAM.V_MAX, 12); int t_int = float_to_uint(torque_ff, PARAM.T_MIN, PARAM.T_MAX, 12); int kp_int = float_to_uint(Kp, PARAM.KP_MIN, PARAM.KP_MAX, 12); int kd_int = float_to_uint(Kd, PARAM.KD_MIN, PARAM.KD_MAX, 12); //Pack _package[0] = p_int >> 8; _package[1] = p_int & 0xff; _package[2] = v_int >> 4; _package[3] = ((v_int&0xF)<<4)|(kp_int>>8); _package[4] = kp_int&0xFF; _package[5] = kd_int >> 4; _package[6] = ((kd_int&0xF)<<4)|(t_int>>8); _package[7] = t_int&0xff; } else { for(uint8_t i = 0; i < 8; i++) _package[i] = 0; } } void unpack_reply(uint8_t _package[]) { //Unpack int p_int = (_package[1] << 8)|_package[2]; int v_int = (_package[3] << 4)|(_package[4] >> 4); int i_int = ((_package[4] & 0x0f) << 8)|_package[5]; //Convert int to float position_fb = uint_to_float(p_int, PARAM.P_MIN, PARAM.P_MAX, 16); velocity_fb = uint_to_float(v_int, PARAM.V_MIN, PARAM.V_MAX, 12); torque_fb = uint_to_float(i_int, PARAM.T_MIN, PARAM.T_MAX, 12); } void setZero_cmd(uint8_t _package[]) { const uint8_t temp[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0XFE}; for(uint8_t i = 0; i < 8; i++) _package[i] = temp[i]; } void enterCtrlMode_cmd(uint8_t _package[]) { const uint8_t temp[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,0XFC }; for(uint8_t i = 0; i < 8; i++) _package[i] = temp[i]; is_ctrlMode = true; } }; #endif /************************ COPYRIGHT(C) SCUT-ROBOTLAB **************************/
#ifndef COPY_NODE_H_ #define COPY_NODE_H_ #include <SOP/SOP_Node.h> #include "G_Global_IO.h" class GIO_Load:public SOP_Node { public: static OP_Node *myConstructor(OP_Network *,const char*,OP_Operator *); static PRM_Template myTemplateList[]; GIO_Load(OP_Network *,const char*,OP_Operator *); virtual ~GIO_Load() {} void loadData(g_global_io &io,char *path); void forkTheData(g_global_io &io,GU_Detail *gdp); void setIntAttrib(g_global_io &io,GU_Detail *gdp); void setFloatAttrib(g_global_io &io,GU_Detail *gdp); void setIntVecAttrib(g_global_io &io,GU_Detail *gdp); void setFltVecAttrib(g_global_io &io,GU_Detail *gdp); protected: virtual OP_ERROR cookMySop(OP_Context &context); }; #endif
// // Created by Masayuki IZUMI on 5/14/16. // #include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/filters/statistical_outlier_removal.h> #include "pctools/utils.hpp" using namespace pctools; int main (int argc, char** argv) { pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZRGBA>); std::string pcd_file = argv[1]; pcl::io::loadPCDFile(pcd_file, *cloud); std::cerr << "Cloud before filtering: " << std::endl; std::cerr << *cloud << std::endl; removeOutlier(cloud, *cloud_filtered, 50, 1.0); std::cerr << "Cloud after filtering: " << std::endl; std::cerr << *cloud_filtered << std::endl; pcl::visualization::PCLVisualizer viewer("viewer"); std::vector<int> viewports; splitVisualizer(viewer, 2, 1, viewports); viewer.addPointCloud(cloud, "input", viewports[0]); viewer.addPointCloud(cloud_filtered, "filtered", viewports[1]); while (!viewer.wasStopped()) { viewer.spinOnce(100); } return (0); }
#ifndef AREA_NAVIGATION_ROS_H #define AREA_NAVIGATION_ROS_H #include <string> #include <ros/ros.h> #include <tf/tf.h> #include <actionlib/server/simple_action_server.h> #include <area_navigation/area_navigation.h> #include <area_navigation/structs.h> // ROS messages #include <navigation_sign_msgs/NavigationSigns.h> #include <std_msgs/Float32.h> #include <area_navigation/AreaNavigationAction.h> // ROS services #include <heading_control/Switch.h> #include <robot_distance_monitor/Reset.h> #include <robot_heading_monitor/Reset.h> #include <motion_control/Switch.h> #include <motion_control/Params.h> #include <motion_control/DriveMode.h> class AreaNavigationROS { public: // Constructor / destructor AreaNavigationROS(ros::NodeHandle&); ~AreaNavigationROS(); void loadParameters(); void run(); private: // ROS ros::NodeHandle nh_; ros::Subscriber navigation_signs_subscriber_; ros::Subscriber distance_monitor_subscriber_; ros::Subscriber heading_monitor_subscriber_; ros::Publisher desired_heading_publisher_; ros::Publisher desired_velocity_publisher_; ros::ServiceClient heading_control_switch_service_client_; ros::ServiceClient heading_monitor_reset_service_client_; ros::ServiceClient distance_monitor_reset_service_client_; ros::ServiceClient motion_control_switch_service_client_; ros::ServiceClient motion_control_params_service_client_; ros::ServiceClient motion_control_drive_mode_service_client_; actionlib::SimpleActionServer<area_navigation::AreaNavigationAction> area_navigation_server_; // subscriber callbacks void navigationSignsCallback(const navigation_sign_msgs::NavigationSigns::ConstPtr& msg); void distanceMonitorCallback(const std_msgs::Float32::ConstPtr& msg); void headingMonitorCallback(const std_msgs::Float32::ConstPtr& msg); void desiredHeadingCallback(const std_msgs::Float32::ConstPtr& msg); // ROS service, topic names std::string navigation_signs_topic_; std::string distance_monitor_topic_; std::string heading_monitor_topic_; std::string desired_heading_topic_; std::string desired_velocity_topic_; std::string heading_control_switch_service_; std::string reset_distance_monitor_service_; std::string reset_heading_monitor_service_; std::string motion_control_switch_service_; std::string motion_control_params_service_; std::string motion_control_drive_mode_service_; int controller_frequency_; // corridor navigation AreaNavigation area_navigation_; // data caching // 1. detected navigation signs std::vector<NavigationSign> navigation_signs_; // 2. monitors double monitored_distance_; double monitored_heading_; // action server callbacks void AreaNavigationExecute(const area_navigation::AreaNavigationGoalConstPtr& goal); // ROS related helper functions void resetMonitors(); void resetHeadingMonitor(); void resetDistanceMonitor(); void reset(); void enableHeadingController(); void disableHeadingController(); void enableMotionController(); void disableMotionController(); void setMotionControllerParams(double inflation_radius); void setMotionControllerDriveMode(int drive_mode); NavigationSign navigationSignROSToNavigationSign(navigation_sign_msgs::NavigationSign nav_sign_ros); }; #endif
#include<iostream> using namespace std; int main() { int age; char gender, martialStatus; cout<<"THE DEPARTMENT OF DEFENSE | ELIGIBLITY TEST\n"; cout<<"ENTER YOUR GENDER ('X' for male and 'Y' for female)"<<endl; cin>>gender; cout<<"ENTER YOUR MARTIAL STATUS ('M' for married and 'S' for single)"<<endl; cin>>martialStatus; cout<<"ENTER YOUR AGE"<<endl; cin>>age; if(gender == 'x' || 'X' && martialStatus == 'S' || 's' && age < 27 && age > 17) cout<<"\nCONGRATULATIONS!!! YOU'RE ELIGIBLE FOR THIS JOB."<<endl; return 1; }
#include <iostream> using namespace std; int main() { int n, cur, init; string s; cin >> n >> s; cur = 0; init = 0; for(char ch : s) { if(ch == '+') cur++; if(ch == '-') { cur--; if(cur < 1) { cur = 0; init++; } } } cout << cur << endl; }
/////////////////////////////////////// // // Computer Graphics TSBK03 // Conrad Wahlén - conwa099 // /////////////////////////////////////// #ifndef _TEST // ==== Includes ==== #include "Program.h" // ==== Main Program ==== int main(int argc, char *argv[]) { Program program; return program.Execute(); } #else #include <gtest/gtest.h> // ==== Main Program ==== int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); printf("Press enter to quit..."); getchar(); return result; } #endif
#ifndef LogVol_ShieldingPSDCone_h #define LogVol_ShieldingPSDCone_h 1 /*! @file LogVol_ShieldingPSDCone.hh @brief Defines mandatory user class LogVol_ShieldingPSDCone. @date August, 2015 @author Flechas (D. C. Flechas dcflechasg@unal.edu.co) @version 2.0 In this header file, the 'physical' setup is defined: materials, geometries and positions. This class defines the experimental hall used in the toolkit. */ #include "globals.hh" #include "G4VSolid.hh" #include "G4LogicalVolume.hh" /* units and constants */ #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" #include "G4NistManager.hh" class G4VisAttributes; class G4Material; /*! @brief This mandatory user class defines the geometry. It is responsible for @li Construction of geometry \sa Construct() */ class LogVol_ShieldingPSDCone : public G4LogicalVolume { public: //! Constructor LogVol_ShieldingPSDCone(G4String fname="ShieldingPSDCone_log",G4double fIrad=5.56/2.0*mm,G4double fOrad=33.40/2.0*mm,G4double fheight=29.76*mm,G4double fang=34.9*deg,G4Material* fmaterial=(G4NistManager::Instance())->FindOrBuildMaterial("G4_Pb")); //! Destructor ~LogVol_ShieldingPSDCone(); inline void SetName(G4String pname) {Name = pname;}; inline void SetOuterRadius(G4double prad) {OuterRadius = prad;}; inline void SetInnerRadius(G4double prad) {InnerRadius = prad;}; inline void SetHeight(G4double pheigth) {Height = pheigth;}; inline void SetAngOpening(G4double pangop) {AngOp = pangop;}; private: void ConstructSolidVol_ShieldingPSDCone(void); void SetSolidVol_ShieldingPSDCone(void); private: // General solid volume G4VSolid* ShieldingPSDCone_solid; //! Name G4String Name; // Dimensions G4double AngOp; G4double Height; G4double OuterRadius; G4double InnerRadius; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif
#pragma once #include "Core/Core.h" #include "Render/DrawBasic/FrameBuffer.h" #include <vulkan/vulkan.h> typedef struct GLFWwindow GLFWwindow; namespace Rocket { class VulkanFrameBuffer { public: void Connect( VkDevice device, VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkRenderPass renderPass, const Vec<VkImageView>& swapChainImageViews); void Initialize(); void Finalize(); void CreateColorResources(); void CreateDepthResources(); void CreateFramebuffers(); void SetWindowHandle(GLFWwindow* handle) { windowHandle = handle; } void SetMsaaSample(VkSampleCountFlagBits msaa) { msaaSamples = msaa; } public: Vec<VkFramebuffer> swapChainFramebuffers; VkImage colorImage; VkDeviceMemory colorImageMemory; VkImageView colorImageView; VkImage depthImage; VkDeviceMemory depthImageMemory; VkImageView depthImageView; VkDevice device; VkRenderPass renderPass; Vec<VkImageView> swapChainImageViews; VkPhysicalDevice physicalDevice; VkSurfaceKHR surface; VkSurfaceFormatKHR surfaceFormat; VkExtent2D extent = {}; VkSampleCountFlagBits msaaSamples = VK_SAMPLE_COUNT_1_BIT; GLFWwindow* windowHandle; }; }
#ifndef _TRACER_H_ #define _TRACER_ #include "Scene.h" #include "init.h" #include <opencv2/opencv.hpp> class Tracer { public: Tracer(); Vector trace(Ray ray,int step); Color check(Color c); void render(); void savepic(const char* file); void init(char* file); void ins(char* file); Scene *scene; Vector viewPoint; Vector picPoint; cv::Mat pic; //Color pic[PIXEL_W][PIXEL_H]; }; #endif
#ifndef MAT44_H #define MAT44_H #include<cmath> #include<array> #include<cstdio> #define PI 3.14159265 using namespace std; class mat44 { public: mat44(); // Construtor ~mat44(); // Destrutor // Ponteiro público para os elementos da matrix const float *mptr; // Principais métodos void identity(); // Carrega a matriz identidade void rotatex(int degrees); // Multiplica a esquerda por uma matriz de rotação void rotatey(int degrees); // Multiplica a esquerda por uma matriz de rotação void rotatez(int degrees); // Multiplica a esquerda por uma matriz de rotação void translate(float dx, float dy, float dz); // Multiplica a esquerda por uma matriz de translação void scale(float sx, float sy, float sz); // Multiplica a esquerda por uma matriz de escala const float* multleft(const float *mtl); void print(); // Imprime no console a matriz atual private: array <float, 16> m; // Matriz (vetor) principal array <float, 16> maux; // // Matriz (vetor) auxiliar }; void mat44::identity() { m = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; mptr = m.data(); } void mat44::rotatex(int degrees) { float rads = degrees*PI/180; float c = cos(rads); float s = sin(rads); maux = {m[0], m[1], m[2], m[3], c*m[4]-s*m[8], c*m[5]-s*m[9], c*m[6]-s*m[10], c*m[7]-s*m[11], s*m[4]+c*m[8], s*m[5]+c*m[9], s*m[6]+c*m[10], s*m[7]+c*m[11], m[12], m[13], m[14], m[15] }; m=maux; } void mat44::rotatey(int degrees){ float rads = degrees*PI/180; float c = cos(rads); float s = sin(rads); maux = {c*m[0]+s*m[8], c*m[1]+s*m[9], c*m[2]+s*m[10], c*m[3]+s*m[11], m[4], m[5], m[6], m[7], -s*m[0]+c*m[8], -s*m[1]+c*m[9], -s*m[2]+c*m[10], -s*m[3]+c*m[11], m[12], m[13], m[14], m[15] }; m=maux; } void mat44::rotatez(int degrees) { float rads = degrees*PI/180; float c = cos(rads); float s = sin(rads); maux = {c*m[0]-s*m[4], c*m[1]-s*m[5], c*m[2]-s*m[6], c*m[3]-s*m[7], s*m[0]+c*m[4], s*m[1]+c*m[5], s*m[2]+c*m[6], s*m[3]+c*m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15] }; m=maux; } void mat44::translate(float dx, float dy, float dz) { maux = {m[0]+dx*m[12], m[1]+dx*m[13], m[2]+dx*m[14], m[3]+dx*m[15], m[4]+dy*m[12], m[5]+dy*m[13], m[6]+dy*m[14], m[7]+dy*m[15], m[8]+dz*m[12], m[9]+dz*m[13], m[10]+dz*m[14],m[11]+dz*m[15], m[12], m[13], m[14], m[15] }; m=maux; } void mat44::scale(float sx, float sy, float sz){ maux = {sx*m[0], sx*m[1], sx*m[2], sx*m[3], sy*m[4], sy*m[5], sy*m[6], sy*m[7], sz*m[8], sz*m[9], sz*m[10], sz*m[11], m[12], m[13], m[14], m[15] }; m=maux; } const float* mat44::multleft(const float *mtl) { maux[0] = mtl[0]*m[0] + mtl[1]*m[4] + mtl[2]*m[8] + mtl[3]*m[12]; maux[1] = mtl[0]*m[1] + mtl[1]*m[5] + mtl[2]*m[9] + mtl[3]*m[13]; maux[2] = mtl[0]*m[2] + mtl[1]*m[6] + mtl[2]*m[10] + mtl[3]*m[14]; maux[3] = mtl[0]*m[3] + mtl[1]*m[7] + mtl[2]*m[11] + mtl[3]*m[15]; maux[4] = mtl[4]*m[0] + mtl[5]*m[4] + mtl[6]*m[8] + mtl[7]*m[12]; maux[5] = mtl[4]*m[1] + mtl[5]*m[5] + mtl[6]*m[9] + mtl[7]*m[13]; maux[6] = mtl[4]*m[2] + mtl[5]*m[6] + mtl[6]*m[10] + mtl[7]*m[14]; maux[7] = mtl[4]*m[3] + mtl[5]*m[7] + mtl[6]*m[11] + mtl[7]*m[15]; maux[8] = mtl[8]*m[0] + mtl[9]*m[4] + mtl[10]*m[8] + mtl[11]*m[12]; maux[9] = mtl[8]*m[1] + mtl[9]*m[5] + mtl[10]*m[9] + mtl[11]*m[13]; maux[10] = mtl[8]*m[2] + mtl[9]*m[6] + mtl[10]*m[10] + mtl[11]*m[14]; maux[11] = mtl[8]*m[3] + mtl[9]*m[7] + mtl[10]*m[11] + mtl[11]*m[15]; maux[12] = mtl[12]*m[0] + mtl[13]*m[4] + mtl[14]*m[8] + mtl[15]*m[12]; maux[13] = mtl[12]*m[1] + mtl[13]*m[5] + mtl[14]*m[9] + mtl[15]*m[13]; maux[14] = mtl[12]*m[2] + mtl[13]*m[6] + mtl[14]*m[10] + mtl[15]*m[14]; maux[15] = mtl[12]*m[3] + mtl[13]*m[7] + mtl[14]*m[11] + mtl[15]*m[15]; const float *multesq = maux.data(); return multesq; } void mat44::print() { printf("%4.1f %4.1f %4.1f %4.1f\n", m[0], m[1], m[2], m[3]); printf("%4.1f %4.1f %4.1f %4.1f\n", m[4], m[5], m[6], m[7]); printf("%4.1f %4.1f %4.1f %4.1f\n", m[8], m[9], m[10], m[11]); printf("%4.1f %4.1f %4.1f %4.1f\n", m[12], m[13], m[14], m[15]); } mat44::mat44() { identity(); } mat44::~mat44() { //destrutor } #endif // MAT44_H
#include "stdafx.h" #include "pong.hpp" #include "menu.hpp" #include "ball.h" #include "paddle.h" #include "Wall.h" #include "scoreboard.h" #include <SFML/Audio.hpp> using namespace std; #define MAX_SCORE 10 int end(sf::RenderWindow& window, char* endText) { window.setMouseCursorVisible(true); sf::Text mainText(endText, font, 75); setTextOrig(&mainText); mainText.setPosition(windowWidth * .5, windowHeight * .3); sf::Text playAgainButton("Play Again", font); setTextOrig(&playAgainButton); playAgainButton.setPosition(windowWidth * .5, windowHeight * .5); sf::Text mainMenuButton("Main Menu", font); setTextOrig(&mainMenuButton); mainMenuButton.setPosition(windowWidth * .5, windowHeight * .6); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::MouseButtonPressed) { sf::Vector2i mousePosition = sf::Mouse::getPosition(window); if (isClicked(playAgainButton, mousePosition)) { return OPTION_PLAY; } else if (isClicked(mainMenuButton, mousePosition)) { return OPTION_MENU; } } else if (event.type == sf::Event::Closed) { window.close(); exit(0); } } window.clear(); window.draw(mainText); window.draw(playAgainButton); window.draw(mainMenuButton); window.display(); } return OPTION_EXIT; } #define PADDLE_WIDTH 20; #define PADDLE_HEIGHT 100; int play(sf::RenderWindow& window) { window.setMouseCursorVisible(false); sf::Vector2i windowCenter(windowWidth / 2, windowHeight / 2); extern int gameLevel; int ballSpeed = (gameLevel == LEVEL_EASY) ? 10 : 15; int ballRadius = 10; float ballInitDirection = 270; Ball ball(ballRadius, ballSpeed, ballInitDirection); ball.setPosition((float)windowCenter.x, (float)windowCenter.y); // Define paddle size int paddleWidth = 10; int paddleHeight = 100; int paddleMaxY = windowHeight - paddleHeight / 2; int paddleMinY = paddleHeight / 2; int userPaddleX = windowWidth - 50; Paddle userPaddle(paddleWidth, paddleHeight, userPaddleX, windowCenter.y); int compPaddleX = 50; Paddle compPaddle(paddleWidth, paddleHeight, compPaddleX, windowCenter.y); sf::Font mfont; mfont.loadFromFile("arial.ttf"); Scoreboard scoreboard(mfont); scoreboard.setPosition(windowWidth*0.5, windowHeight*0.05); // 10-90 110-190 210-290 310-390 410-490 510-590 int lineLength = 60; int lineDistance = 40; int numberOfLines = windowHeight-200 / (lineLength + lineDistance); int yPos = 60; // so that the first line starts at y=10 and there be a space at the top and bottom sf::VertexArray centerLine(sf::Lines, numberOfLines*2); for (int i = 0; i < 12; i++) { yPos += (i % 2 == 0) ? lineDistance : lineLength; centerLine[i].position = sf::Vector2f(windowCenter.x, yPos); centerLine[i].color = sf::Color::White; } sf::SoundBuffer buf; if (!buf.loadFromFile("sound.wav")) { printf("sound failure"); } sf::Sound sound; sound.setBuffer(buf); sf::Clock clock; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); exit(0); } } if (clock.getElapsedTime().asMilliseconds() > 13.f) { if (scoreboard.getScores()[USER] == MAX_SCORE || scoreboard.getScores()[COMPUTER] == MAX_SCORE) { char* endText = (scoreboard.getScores()[USER] == MAX_SCORE) ? "You Win!" : "You Lose!"; return end(window, endText); } //ball.move(); // Check if ball is in goal if (ball.isOutOfLeftBound() || ball.isOutOfRightBound(windowWidth)) { if (ball.isOutOfRightBound(windowWidth)) { scoreboard.incrementScore(COMPUTER); } else { scoreboard.incrementScore(USER); } ball.setPosition(windowCenter.x, windowCenter.y); ball.setDirection(ballInitDirection); userPaddle.setPosition(userPaddleX, windowCenter.y); compPaddle.setPosition(compPaddleX, windowCenter.y); } // Check collision with the walls or paddles if (ball.getBottomEdgeCoordinates().y >= windowHeight || ball.getTopEdgeCoordinates().y <= 0) { float ballDirection = (ball.getDirection() <= 180) ? 180 - ball.getDirection(): 540 - ball.getDirection(); ball.setDirection(ballDirection); sound.play(); } else if (ball.hasCollided(&userPaddle)) { float newDirection = (ball.getY() - userPaddle.getY())*-0.45 + 270; ball.setDirection(newDirection); sound.play(); } else if (ball.hasCollided(&compPaddle)) { float newDirection = (ball.getY() - compPaddle.getY())*0.45 + 90; ball.setDirection(newDirection); sound.play(); } // Move user paddle according to the cursor position int mouseY = sf::Mouse::getPosition().y; int userY = userPaddle.getY(); if (mouseY != userY) { if (mouseY >= paddleMaxY) { userPaddle.setTargetY(paddleMaxY); } else if (mouseY <= paddleMinY) { userPaddle.setTargetY(paddleMinY); } else { userPaddle.setTargetY(mouseY); } } // Move AI paddle int compY = compPaddle.getY(); int compPaddleSpeed = 10; float projectionDistance = (LEVEL_EASY) ? .4 : .5; if (ball.getX() <= windowWidth * projectionDistance) { float projectionY = -gameLevel * ball.getSpeed() * 10 * cos(ball.getDirection()*PI / 180) + ball.getY(); if (abs(compY - projectionY) >= 50) { if (compY <= projectionY && compPaddle.getY() + 5 <= paddleMaxY) { compPaddle.addTargetY(compPaddleSpeed); } else if (compY >= projectionY && compY - 5 >= paddleMinY) { compPaddle.addTargetY(-compPaddleSpeed); } } } else { if (compY <= windowHeight * .45) { compPaddle.addTargetY(compPaddleSpeed); } else if (compY >= windowHeight * .55) { compPaddle.addTargetY(-compPaddleSpeed); } } userPaddle.move(); compPaddle.move(); ball.move(); clock.restart(); } window.clear(); window.draw(centerLine); window.draw(ball.getImage()); window.draw(userPaddle.getImage()); window.draw(compPaddle.getImage()); window.draw(scoreboard.getImage()); window.display(); } return OPTION_EXIT; }
#include "ClassificationResult.hpp" void ClassificationResult::operator>>(Counters &counters) {} /** * @brief Copies reference to tracked vector */ void ClassificationResult::operator<<(std::shared_ptr<TrackedObject> obj) { this->classified.push_back(obj); } std::vector<std::shared_ptr<TrackedObject>>ClassificationResult::GetClassified() { return this->classified; }
#ifndef ROTATION_H #define ROTATION_H #include <algorithm> #include <cmath> #include <limits> ////////////////////////////////////////////////////////////////// // math functions needed for rotation conversion. // dot and cross production template<typename T> inline T DotProduct(const T x[3], const T y[3]) { return (x[0] * y[0] + x[1] * y[1] + x[2] * y[2]); } template<typename T> inline void CrossProduct(const T x[3], const T y[3], T result[3]) { result[0] = x[1] * y[2] - x[2] * y[1]; result[1] = x[2] * y[0] - x[0] * y[2]; result[2] = x[0] * y[1] - x[1] * y[0]; } ////////////////////////////////////////////////////////////////// // Converts from a angle anxis to quaternion : template<typename T> inline void AngleAxisToQuaternion(const T *angle_axis, T *quaternion) { const T &a0 = angle_axis[0]; const T &a1 = angle_axis[1]; const T &a2 = angle_axis[2]; const T theta_squared = a0 * a0 + a1 * a1 + a2 * a2; if (theta_squared > T(std::numeric_limits<double>::epsilon())) { const T theta = sqrt(theta_squared); const T half_theta = theta * T(0.5); const T k = sin(half_theta) / theta; quaternion[0] = cos(half_theta); quaternion[1] = a0 * k; quaternion[2] = a1 * k; quaternion[3] = a2 * k; } else { // in case if theta_squared is zero const T k(0.5); quaternion[0] = T(1.0); quaternion[1] = a0 * k; quaternion[2] = a1 * k; quaternion[3] = a2 * k; } } template<typename T> inline void QuaternionToAngleAxis(const T *quaternion, T *angle_axis) { const T &q1 = quaternion[1]; const T &q2 = quaternion[2]; const T &q3 = quaternion[3]; const T sin_squared_theta = q1 * q1 + q2 * q2 + q3 * q3; // For quaternions representing non-zero rotation, the conversion // is numercially stable if (sin_squared_theta > T(std::numeric_limits<double>::epsilon())) { const T sin_theta = sqrt(sin_squared_theta); const T &cos_theta = quaternion[0]; // If cos_theta is negative, theta is greater than pi/2, which // means that angle for the angle_axis vector which is 2 * theta // would be greater than pi... const T two_theta = T(2.0) * ((cos_theta < 0.0) ? atan2(-sin_theta, -cos_theta) : atan2(sin_theta, cos_theta)); const T k = two_theta / sin_theta; angle_axis[0] = q1 * k; angle_axis[1] = q2 * k; angle_axis[2] = q3 * k; } else { // For zero rotation, sqrt() will produce NaN in derivative since // the argument is zero. By approximating with a Taylor series, // and truncating at one term, the value and first derivatives will be // computed correctly when Jets are used.. const T k(2.0); angle_axis[0] = q1 * k; angle_axis[1] = q2 * k; angle_axis[2] = q3 * k; } } template<typename T> inline void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3]) { const T theta2 = DotProduct(angle_axis, angle_axis); if (theta2 > T(std::numeric_limits<double>::epsilon())) { // Away from zero, use the rodriguez formula // // result = pt costheta + // (w x pt) * sintheta + // w (w . pt) (1 - costheta) // // We want to be careful to only evaluate the square root if the // norm of the angle_axis vector is greater than zero. Otherwise // we get a division by zero. // const T theta = sqrt(theta2); const T costheta = cos(theta); const T sintheta = sin(theta); const T theta_inverse = 1.0 / theta; const T w[3] = {angle_axis[0] * theta_inverse, angle_axis[1] * theta_inverse, angle_axis[2] * theta_inverse}; // Explicitly inlined evaluation of the cross product for // performance reasons. /*const T w_cross_pt[3] = { w[1] * pt[2] - w[2] * pt[1], w[2] * pt[0] - w[0] * pt[2], w[0] * pt[1] - w[1] * pt[0] };*/ T w_cross_pt[3]; CrossProduct(w, pt, w_cross_pt); const T tmp = DotProduct(w, pt) * (T(1.0) - costheta); // (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) * (T(1.0) - costheta); result[0] = pt[0] * costheta + w_cross_pt[0] * sintheta + w[0] * tmp; result[1] = pt[1] * costheta + w_cross_pt[1] * sintheta + w[1] * tmp; result[2] = pt[2] * costheta + w_cross_pt[2] * sintheta + w[2] * tmp; } else { // Near zero, the first order Taylor approximation of the rotation // matrix R corresponding to a vector w and angle w is // // R = I + hat(w) * sin(theta) // // But sintheta ~ theta and theta * w = angle_axis, which gives us // // R = I + hat(w) // // and actually performing multiplication with the point pt, gives us // R * pt = pt + w x pt. // // Switching to the Taylor expansion near zero provides meaningful // derivatives when evaluated using Jets. // // Explicitly inlined evaluation of the cross product for // performance reasons. /*const T w_cross_pt[3] = { angle_axis[1] * pt[2] - angle_axis[2] * pt[1], angle_axis[2] * pt[0] - angle_axis[0] * pt[2], angle_axis[0] * pt[1] - angle_axis[1] * pt[0] };*/ T w_cross_pt[3]; CrossProduct(angle_axis, pt, w_cross_pt); result[0] = pt[0] + w_cross_pt[0]; result[1] = pt[1] + w_cross_pt[1]; result[2] = pt[2] + w_cross_pt[2]; } } #endif // rotation.h
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back typedef pair<int,ll> pl; int main() { ll d,g; cin >> d >> g; vector<pl> pc; rep(i,d) { ll p,c; cin >> p >> c; pc.pb(make_pair(p,c)); } ll res = 1001; for (int b = 0; b < (1 << d); ++b) { ll tmp = g, cnt = 0; for (int i = 0; i < d; ++i) { if ((b >> i) & 1) { int point = 100 * (i+1); tmp -= pc[i].second + pc[i].first * point; cnt += pc[i].first; } } cout << "cnt:" << res << endl; if (tmp <= 0) { res = min(cnt, res); continue; } printf("time: %d, tmp: %d\n", b, tmp); for (int i = d-1; i >= 0; --i) { cout << "in" << endl; bool flag = false; if (!((b >> i) & 1)) { cout << i << endl; for (int j = 0; j < pc[i].first; ++j) { tmp -= 100 * (i+1); cnt++; if (tmp <= 0) { res = min(cnt, res); flag = true; break; } } } if (flag) { break; } tmp -= pc[i].second; if (tmp <= 0) { res = min(cnt, res); flag = true; break; } } } cout << res << endl; }
#include <cstdio> #include <iostream> #include <vector> using namespace std; struct ListNode{ int val; ListNode *next; ListNode():next(NULL){} }; ListNode *merge(ListNode *head1, ListNode *head2){ ListNode *res = NULL; if(head1 == NULL) return head2; if(head2 == NULL) return head1; if(head1->val < head2->val){ res = head1; head1 = head1->next; }else{ res = head2; head2 = head2->next; } ListNode *p = res; // Don't forget the first node should be assigned! while(head1 != NULL && head2 !=NULL){ if(head1->val head2->val){ p->next = head1; head1=head1->next; } else{ p->next = head2; head2=head2->next; } p=p->next; } //Still remains some! if(head1 != NULL) p->next =head1; else if(head2 != NULL) p->next = head2; return res; } ListNode *mergeSort(ListNode * head){ if(head == NULL || head->next == NULL) return head; else{ ListNode *slow = head; ListNode *fast = head; while(fast->next !=NULL && fast->next->next !=NULL){ slow = slow->next; fast = fast->next->next; } fast = slow; slow = slow->next; fast->next = NULL; fast = mergeSort(head); slow = mergeSort(slow); return merge(fast,slow); } } int main(){ ListNode *head=NULL; int i; while(cin >> i){ ListNode *p = new ListNode; p->val = i; p->next = head; head = p; } ListNode *ans = mergeSort(head); // ListNode *ans = merge(head,head2); while(ans!=NULL){ cout << ans->val << " "; ans = ans->next; } }
// -*- C++ -*- /*! * @file RTWiimote.cpp * @brief WiiリモコンのRTコンポーネント * @date $Date$ * * $Id$ */ #include "RTWiimote.h" // デバッグ情報の表示 //#define DEBUG_SHOW_INPUT_DATA //#define DEBUG_SHOW_OUTPUT_DATA // Module specification // <rtc-template block="module_spec"> static const char* rtwiimote_spec[] = { "implementation_id", "RTWiimote", "type_name", "RTWiimote", "description", "Wiirimote RTComponent", "version", "1.0.0", "vendor", "Keisuke SUZUKI, AIST", "category", "Category", "activity_type", "PERIODIC", "kind", "DataFlowComponent", "max_instance", "1", "language", "C++", "lang_type", "compile", "exec_cxt.periodic.rate", "1.0", // Configuration variables "conf.default.beep", "beep.wav", "" }; // </rtc-template> /*! * @brief constructor * @param manager Maneger Object */ RTWiimote::RTWiimote(RTC::Manager* manager) // <rtc-template block="initializer"> : RTC::DataFlowComponentBase(manager), m_ledIn("led", m_led), m_rumbleIn("rumble", m_rumble), m_speakerIn("speaker", m_speaker), m_buttonOut("button", m_button), m_accelerationOut("acceleration", m_acceleration), m_update_ageOut("update_age", m_update_age), m_pitchOut("pitch", m_pitch), m_rollOut("roll", m_roll) // </rtc-template> { // Registration: InPort/OutPort/Service // <rtc-template block="registration"> // Set InPort buffers registerInPort("led", m_ledIn); registerInPort("rumble", m_rumbleIn); registerInPort("speaker", m_speakerIn); // Set OutPort buffer registerOutPort("button", m_buttonOut); registerOutPort("acceleration", m_accelerationOut); registerOutPort("update_age", m_update_ageOut); registerOutPort("pitch", m_pitchOut); registerOutPort("roll", m_rollOut); // Set service provider to Ports // Set service consumers to Ports // Set CORBA Service Ports // </rtc-template> } /*! * @brief destructor */ RTWiimote::~RTWiimote() { } RTC::ReturnCode_t RTWiimote::onInitialize() { // <rtc-template block="bind_config"> // Bind variables and configuration variable bindParameter("beep", m_conf_varname, "beep.wav"); _tprintf(_T("Start RTwiimote!\n")); //最初につながったリモコンを探す while(!remote.Connect(wiimote::FIRST_AVAILABLE)){ _tprintf(_T("Connecting to a WiiRemote.\n")); Sleep(1000); } _tprintf(_T("connected.\n")); _tprintf(_T("Battery: %3u%%"), remote.BatteryPercent); //ボタンと加速度のイベント更新を伝える remote.SetReportType(wiimote::IN_BUTTONS_ACCEL); // </rtc-template> return RTC::RTC_OK; } /* RTC::ReturnCode_t RTWiimote::onFinalize() { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onStartup(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onShutdown(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onActivated(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onDeactivated(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ RTC::ReturnCode_t RTWiimote::onExecute(RTC::UniqueId ec_id) { unsigned char ledRead; bool rumbleRead; bool speakerRead; //バッテリーの容量を更新する _tprintf(_T("\b\b\b\b\b %3u%%"), remote.BatteryPercent); // 入力の更新がない場合はSleepする while(remote.RefreshState() == NO_CHANGE) { Sleep(1); } // LEDの入力ポートに新しい入力があった場合,LEDを点灯 if(m_ledIn.isNew()) { m_ledIn.read(); ledRead = m_led.data; #ifdef DEBUG_SHOW_INPUT_DATA printf("led : %x\n",ledRead); #endif remote.SetLEDs(ledRead); } // バイブレータの入力ポートに新しい入力があった場合,振動させる if(m_rumbleIn.isNew()){ m_rumbleIn.read(); rumbleRead = m_rumble.data; #ifdef DEBUG_SHOW_INPUT_DATA printf("rumble : %x\n",rumbleRead); #endif remote.SetRumble(rumbleRead); } // スピーカの入力ポートに新しい入力があった場合,スピーカから音を出す if(m_speakerIn.isNew()){ m_speakerIn.read(); speakerRead = m_speaker.data; #ifdef DEBUG_SHOW_INPUT_DATA printf("speaker : %x\n",speakerRead); #endif // ここにスピーカON/OFFの処理を書く(未対応) } static unsigned short old_button; // ボタン入力に変化があった場合のみボタン情報を出力 if(old_button != (remote.Button.ALL & remote.Button.Bits)) { m_button.data = remote.Button.Bits; m_buttonOut.write(); #ifdef DEBUG_SHOW_OUTPUT_DATA printf("button : %x\n",(remote.Button.ALL & remote.Button.Bits)); #endif } old_button = remote.Button.ALL & remote.Button.Bits; // 加速度情報を出力 m_acceleration.data.length(3); m_acceleration.data[0] = remote.Acceleration.X; m_acceleration.data[1] = remote.Acceleration.Y; m_acceleration.data[2] = remote.Acceleration.Z; m_accelerationOut.write(); #ifdef DEBUG_SHOW_OUTPUT_DATA printf("AcceX : %f\n",remote.Acceleration.X); printf("AcceY : %f\n",remote.Acceleration.Y); printf("AcceZ : %f\n",remote.Acceleration.Z); #endif // その他情報を出力 m_update_age.data = remote.Acceleration.Orientation.UpdateAge; m_pitch.data = remote.Acceleration.Orientation.Pitch; m_roll.data = remote.Acceleration.Orientation.Roll; m_update_ageOut.write(); m_pitchOut.write(); m_rollOut.write(); #ifdef DEBUG_SHOW_OUTPUT_DATA printf("Update Age : %d\n",remote.Acceleration.Orientation.UpdateAge); printf("Pitch : %f\n",remote.Acceleration.Orientation.Pitch); printf("Roll : %f\n",remote.Acceleration.Orientation.Roll); #endif return RTC::RTC_OK; } /* RTC::ReturnCode_t RTWiimote::onAborting(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onError(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onReset(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onStateUpdate(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ /* RTC::ReturnCode_t RTWiimote::onRateChanged(RTC::UniqueId ec_id) { return RTC::RTC_OK; } */ extern "C" { void RTWiimoteInit(RTC::Manager* manager) { coil::Properties profile(rtwiimote_spec); manager->registerFactory(profile, RTC::Create<RTWiimote>, RTC::Delete<RTWiimote>); } };
/***************************************************************** Name :binomial_heap Author :srhuang Email :lukyandy3162@gmail.com History : 20200108 delete 20200107 decrease key and fix minNode bug 20200107 find 20191226 reconstruct 20191218 Initial Version *****************************************************************/ #include <iostream> #include <vector> #define DEBUG (1) #define SCALE (13) using namespace std; using namespace std::chrono; /*==============================================================*/ //Global area //Left-Child Right-sibling struct Node{ int data; Node *parent=NULL; Node *child=NULL; Node *sibling=NULL; // the height for the subtree // 1<<degree (2^degree) int degree=0; }; class BinomialHeap{ //core operation Node *treeUnion(Node *n1, Node *n2); //must be the same degree void heapUnion(bool isinsert); //handle with tree union //preorder traversal void preorderTraversal(Node *current); //preorder find Node *preorderFind(Node *current, int key); public: Node *minNode=NULL; Node *head=NULL; //five operations BinomialHeap(); BinomialHeap(int *arr, int size); Node *insert(int input); int extract_min(); int minimum(); void merge(BinomialHeap &bh); //decrease-key and delete Node *decrease_key(Node *input, int new_val); void delete_key(Node *input); //find Node *find(int key); //dump elements void dump(void); }; BinomialHeap::BinomialHeap() { } //core operation Node *BinomialHeap::treeUnion(Node *n1, Node *n2) { //check if the same degree if(n1->degree != n2->degree) return NULL; //compare to find new root Node *less = (n1->data < n2->data)? n1 : n2; Node *greater = (n1 == less)? n2 : n1; //adjust the pointers and degree if(less->sibling == greater){ less->sibling = greater->sibling; } greater->parent = less; greater->sibling = less->child; less->child = greater; less->degree++; return less; } //core operation void BinomialHeap::heapUnion(bool isinsert) { Node *pre = NULL; Node *current = head; Node *next = current->sibling; //tree union for current and next if needed while(next){ if((current->degree != next->degree) || (next->sibling && next->sibling->degree == current->degree)) { //the degree of the first two trees is not the same //or //the degree of the first three trees are the same, //we just deal with the last two. pre = current; current = next; //in the case of insertion , just break if no carry if(isinsert) break; }else{ //tree union current = treeUnion(current, next); if(pre){ pre->sibling = current; }else{ head = current; } } next = current->sibling; }//while //keep tracking the min node current = head; minNode = head; while(current){ minNode = (current->data < minNode->data) ? current : minNode; current = current->sibling; } } //Initialize BinomialHeap::BinomialHeap(int *arr, int size) { for(int i=0; i<size; i++){ insert(arr[i]); } } //insert Node *BinomialHeap::insert(int input) { Node *newNode = new Node(); newNode->data = input; //insert into the head if(head){ newNode->sibling = head; } head = newNode; //adjust the binomial heap heapUnion(true); return newNode; } //extract_min int BinomialHeap::extract_min() { if(NULL==head) return -1; Node *target = minNode; int result = minNode->data; //find the previous binomial tree Node *pre = NULL; Node *current = head; while(current){ if(current == minNode) break; pre = current; current = current->sibling; } //remove it if(minNode == head){ head = minNode->sibling; }else{ pre->sibling = minNode->sibling; } //update the minNode current = head; minNode = head; while(current){ minNode = (current->data < minNode->data) ? current : minNode; current = current->sibling; } //reverse the sibling list //and update min Node of new BH pre = NULL; current = target->child; Node *next = NULL; Node *tempMinNode = current; while(current){ //update the minNode if(current->data < tempMinNode->data) tempMinNode = current; next = current->sibling; current->parent = NULL; current->sibling = pre; pre = current; current = next; } //create the new BH if(NULL != pre){ BinomialHeap bh; bh.head = pre; bh.minNode = tempMinNode; //merge with updating the min Node merge(bh); } //delete the min Node delete target; target = NULL; return result; } //minimum int BinomialHeap::minimum() { if(NULL==head) return -1; return minNode->data; } //merge void BinomialHeap::merge(BinomialHeap &bh) { if(NULL == head){ head = bh.head; minNode = bh.minNode; return; } if(NULL == bh.head){ return; } //類似 merge sort 的作法 Node *h1 = head; Node *h2 = bh.head; Node *current; //pick the new head and set current node if(h1->degree > h2->degree){ current = head = h2; h2 = h2->sibling; }else{ current = head = h1; h1 = h1->sibling; } //until one of them is running out. while(h1 && h2){ if(h1->degree > h2->degree){ current->sibling = h2; current = h2; h2 = h2->sibling; }else{ current->sibling = h1; current = h1; h1 = h1->sibling; } } //if h1 has last elements if(h1){ current->sibling = h1; } //if h2 has last elements if(h2){ current->sibling = h2; } //adjust the binomial heap heapUnion(false); } //decrease key Node *BinomialHeap::decrease_key(Node *input, int new_val) { if(NULL == input) return NULL; if(input->data <= new_val) return input; input->data = new_val; Node *current = input; Node *parent = current->parent; while(parent && parent->data > current->data) { //swap int temp = current->data; current->data = parent->data; parent->data = temp; //bottom-up current = parent; parent = current->parent; } return current; } //delete void BinomialHeap::delete_key(Node *input) { if(NULL == input) return; Node *current = input; Node *parent = current->parent; while(parent) { //swap int temp = current->data; current->data = parent->data; parent->data = temp; //bottom-up current = parent; parent = current->parent; } //extract min minNode = current; extract_min(); } //binary tree preorder find Node *BinomialHeap::preorderFind(Node *current, int key) { if(NULL == current){ return NULL; } if(key == current->data){ return current; } Node *result = NULL; result = preorderFind(current->child, key); if(NULL != result){ return result; } if(current->parent){ //parent of root is not NULL result = preorderFind(current->sibling, key); } return result; } //find Node *BinomialHeap::find(int key) { if(NULL == head) return NULL; Node *current = head; Node *result = NULL; while(current){ //preorder find result = preorderFind(current, key); if(result){ return result; } current = current->sibling; } return result; } //binomial tree preorder traversal void BinomialHeap::preorderTraversal(Node *current) { if(NULL == current){ return; } cout << " " << current->data; preorderTraversal(current->child); if(current->parent){ //parent of root is not NULL preorderTraversal(current->sibling); } } //dump elements void BinomialHeap::dump(void) { if(NULL == head) return; cout << "Dump the heap : " << endl; Node *current = head; while(current){ cout << "B(" << current->degree << ") = "; //preorder traversal preorderTraversal(current); cout << endl; current = current->sibling; } } /*==============================================================*/ //Function area int *random_case(int base, int number) { int *result = new int[number]; //generate index ordered arrary for(int i=0; i<number; i++){ result[i] = base + i; } //swap each position srand(time(NULL)); for(int i=0; i<number-1; i++){ int j = i + rand() / (RAND_MAX / (number-i)); //swap int t=result[i]; result[i] = result[j]; result[j]=t; } return result; } /*==============================================================*/ int main(int argc, char const *argv[]){ int n=SCALE; int size; //generate data int *random_data = random_case(1, n); #if DEBUG cout << "Generate Data :"; for(int i=0; i<n; i++){ cout << random_data[i] << " "; } cout << endl; #endif // Initialize from the array cout << "\n\tInitialize from the array" << endl; BinomialHeap myHeap(random_data, n); myHeap.dump(); cout << "minimum :" << myHeap.minimum() << endl; // Insert the new element cout << "\n\tInsert the new element" << endl; Node *temp = myHeap.insert(6); myHeap.dump(); // Test minimum and extract min cout << "\n\tTest minimum and extract min" << endl; cout << "minimum :" << myHeap.minimum() << endl; cout << "extract_min :" << myHeap.extract_min() << endl; myHeap.dump(); cout << "minimum :" << myHeap.minimum() << endl; // Test decrease-key and delete cout << "\n\tTest decrease-key and delete" << endl; myHeap.dump(); int decrease_value = 7; Node *decrease_node = myHeap.decrease_key(myHeap.find(7), 4); cout << "decrease-key from " << decrease_value << " to " << decrease_node->data << endl; myHeap.dump(); cout << "\nBefore delete" << endl; myHeap.dump(); myHeap.delete_key(myHeap.find(6)); myHeap.delete_key(myHeap.find(4)); cout << "After delete" << endl; myHeap.dump(); // Find the value cout << "\n\tFind the value" << endl; int find_value = 7; Node *find_node = myHeap.find(find_value); cout << "Find Node :"; if(NULL != find_node){ cout << find_node->data << endl; }else{ cout << "NULL" << endl; } // Merge the two heap cout << "\n\tMerge the two heap" << endl; n=13; int *random_data2 = random_case(20, n); #if DEBUG cout << "Generate Data2 :"; for(int i=0; i<n; i++){ cout << random_data2[i] << " "; } cout << endl; #endif BinomialHeap myHeap2(random_data2, n); myHeap2.dump(); myHeap.merge(myHeap2); myHeap.dump(); // Heap sort cout << "\n\tHeap sort" << endl; cout << "Heap sort :"; while(myHeap.head){ cout << myHeap.extract_min() << " "; } cout << endl; return 0; } /*==============================================================*/
#ifndef WINDOW_CPP #define WINDOW_CPP #include "Window.h" using namespace std; Window::Window(){ id = 0; idle = 0; totalIdle = 0; timeTilOpen = 0; idleForFive = false; } Window::Window(int id){ this->id = id; idle = 0; totalIdle = 0; timeTilOpen = 0; idleForFive = false; } bool operator==(const Window& window, const Window& window2) { if(window.id != window2.id) { return false; } return true; } Window::~Window(){} #endif
// // Created by LBYPatrick on 2/6/2018. // #include "util.hpp" void util::RemoveLetter(string &original_string, char letter) { string temp_buffer; bool is_in_quote = false; for (char i : original_string) { if (i == '\"') { is_in_quote = !is_in_quote; continue; } else if (i != letter || is_in_quote) temp_buffer += i; } original_string = temp_buffer; } void util::ReportError(string message) { printf("[ERROR] %s\n", message.c_str()); } void util::RemoveFile(string filename) { remove(filename.c_str()); } void util::AppendStringVector(vector <string> &left, vector <string> &right) { left.insert(end(left), begin(right), end(right)); } void util::ShowHelp(vector <Help> option_list) { size_t left_len = 0; string print_buffer; //Get max option length for better formatting for (auto & element : option_list) { left_len = element.option.length() > left_len ? element.option.length() : left_len; } for (auto & elelment : option_list) { print_buffer += elelment.option; for (int i = elelment.option.length(); i < left_len; ++i) { print_buffer += ' '; } print_buffer += " : "; print_buffer += elelment.description + "\n"; } printf("%s", print_buffer.c_str()); } void util::PercentageBar(int current, int total) { int barLength = 50; int leftPercent = double(current) / double(total) * barLength; int rightPercent = barLength - leftPercent; string print_buffer = "\r["; for (int i = 0; i < leftPercent - 1; i++) { print_buffer += "="; } print_buffer += ">"; for (int i = 0; i < rightPercent; i++) { print_buffer += " "; } print_buffer += string("] ") + std::to_string(current) + string("/") + std::to_string(total); if (current == total) print_buffer += "\n"; printf(print_buffer.c_str()); } bool util::IsFileExist(string filename) { vector <string> file_list = GetFileList(); for (string &file : file_list) { if (filename == file) return true; } return false; } vector <string> util::SysExecute(string cmd) { ifstream reader; vector <string> return_buffer; string read_buffer; #if DEBUG_CMDOUT printf("CMD: %s\n", cmd.c_str()); #endif system((cmd + "> output.data").c_str()); reader.open("output.data"); while (getline(reader, read_buffer)) { return_buffer.push_back(read_buffer); } reader.close(); RemoveFile("output.data"); #if DEBUG_CMDOUT printf("Output: \n"); for (string & i : return_buffer) { printf("\t%s\n", i.c_str()); } #endif return return_buffer; } vector <string> util::ReadFile(string path) { return util::ReadFile(path, true); } vector <string> util::ReadFile(string path, bool is_parsed) { ifstream reader; string in; vector <string> out; reader.open(path); if (!reader.is_open()) return out; while (getline(reader, in)) { out.push_back(in); } return out; /* ifstream r(path.c_str()); stringstream read_buffer; vector<string> file_buffer; if (!r.is_open()) { return vector<string>(); } read_buffer << r.rdbuf(); r.close(); if (!is_parsed) return { read_buffer.str() }; else { string temp = read_buffer.str(); vector<int> results = util::SearchString(temp, '\n'); bool is_newline_head = false; //Quit if it's a file without "\n" if (results.size() == 0) { return { temp }; } if (results[0] == 0) { file_buffer.push_back(""); file_buffer.push_back(SubString(temp, 1, results[1])); is_newline_head = true; } else { file_buffer.push_back(SubString(temp, 0, results[0])); } for (int i = is_newline_head; i < results.size(); ++i) { if (i + 1 <= (results.size() - 1)) { file_buffer.push_back(SubString(temp, results[i] + 1, results[i + 1])); } else { if (results[i] == temp.size() - 1) {break;} file_buffer.push_back(SubString(temp, results[i] + 1, results.size())); } } } return file_buffer; */ } int util::Search(string str, vector <string> match_list, bool precise) { for (int i = 0; i < match_list.size(); ++i) { if (precise && match_list[i] == str) { return i; } else if (!precise && str.find(match_list[i]) != string::npos) { return i; } } return -1; } int util::Search(string str, vector <string> match_list) { return Search(str, match_list, false); } YAML util::GetYaml(string line) { YAML out; if (line.find(':') == -1) { return YAML(); } out.level = line.find_first_not_of(' '); out.left = SubString(line, out.level, line.find(':')); out.right = SubString(line, line.find(':') + 1, line.find_last_not_of(' ') + 1); //Remove Trailing & starting spaces out.left = SubString(out.left, 0, out.left.find_last_not_of(' ') + 1); out.right = SubString(out.right, out.right.find_first_not_of(' '), out.right.size()); if (out.left.find('\"') != -1) { out.left = SubString(out.left, 1, out.left.size() - 1); } if (out.right.find('\"') != -1) { out.right = SubString(out.right, 1, out.right.size() - 1); } return out; } string util::SubString(string str, int left, int stop) { size_t length = stop - left; //Out-of-bound fix if (left < 0) left = 0; if (stop > str.size()) stop = str.size(); return str.substr(left, length); } string util::GetMachineIP() { vector <string> result = SysExecute( R"(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')"); return !result.empty() ? result[0] : string(); } bool util::IsProcessAlive(string pid) { vector <string> cmd_buffer = SysExecute("ps -p " + pid); return cmd_buffer.size() > 1; } bool util::IsTheSame(string str, string key, bool is_precise, bool is_case_sensitive) { if (!is_case_sensitive) { for (char &i : str) { i = toupper(i); } for (char &i : key) { i = toupper(i); } } if (is_precise) { return str == key; } else { return (str.find(key) != -1) || (key.find(str) != -1); } } vector <string> util::GetFileList(string directory) { vector <string> console_buffer = SysExecute("ls -p " + directory + " -1"); vector <string> output_buffer; for (string &line : console_buffer) { if (line.find_last_of('/') == -1 && line.find("output.data") == -1) { output_buffer.push_back(line); } } return output_buffer; } vector <string> util::GetFolderList(string directory) { vector <string> console_buffer = SysExecute("ls -p " + directory + " -1"); vector <string> output_buffer; for (string &line : console_buffer) { if (line.find_last_of('/') != -1) { output_buffer.push_back(SubString(line, 0, line.size() - 1)); } } return output_buffer; } vector <string> util::GetFolderList() { return GetFolderList("./"); } vector <string> util::GetFileList() { return GetFileList("./"); } bool util::WriteFile(string filename, vector <string> content) { ofstream o; string buf; o.open(filename); if (!o.is_open()) return false; for (const auto &i : content) { buf += i + "\n"; } o.write(buf.c_str(), buf.size()); o.close(); return true; } vector <size_t> util::SearchString(string str, char key) { return SearchString(str, key, 0, str.size()); } vector <size_t> util::SearchString(string str, char key, size_t left, size_t stop) { size_t length = stop - left; vector<size_t> r; for(size_t i = left; i < stop; i+=1) { if(str[i] == key) { r.push_back(i); } } return r; } void util::QuickSort::Sort(vector <SortItem> &arr, size_t low, size_t high) { if (low < high) { size_t pivot = Partition(arr, low, high); Sort(arr, low, pivot); Sort(arr, pivot + 1, high); } } /** * Overloaded Sort method #1: When user passes a raw size_t array with bounds * @param arr * @return vector containing indexes of sorted items */ vector <size_t> util::QuickSort::Sort(vector <long long> &arr, size_t low, size_t high) { vector <SortItem> new_arr; vector <size_t> r; //Reserve space for efficiency new_arr.reserve(high - low + 1); r.reserve(high - low + 1); for (size_t i = low; i <= high; ++i) { new_arr.push_back({i, arr[i]}); } Sort(new_arr, low, high); for (auto &element : new_arr) { r.push_back(element.old_index); } return r; } /** * Overloaded Sort method #1: When user passes a raw size_t array without bounds * @param arr * @return vector containing indexes of sorted items */ vector <size_t> util::QuickSort::Sort(vector <long long> &arr) { return Sort(arr, 0, arr.size() - 1); } /** * Sort using Hoare Partition Scheme * @param arr Array (By reference) * @param low lower index. * @param high High index. * @return Index of pivot */ size_t util::QuickSort::Partition(vector <SortItem> &arr, size_t low, size_t high) { long long pivot = arr[low].key; size_t left_index = low - 1, right_index = high + 1; while (true) { do { left_index += 1; } while (arr[left_index].key < pivot); do { right_index -= 1; } while (arr[right_index].key > pivot); if (left_index >= right_index) { return right_index; } std::swap(arr[left_index], arr[right_index]); } }
#ifndef HIRAGANA_H #define HIRAGANA_H #include "mot.h" class Hiragana : public Mot { public: Hiragana( const string & inHiraKata, const string & inRoumaji ); virtual ~Hiragana(); }; #endif
#include <iostream> #include <limits.h> using namespace std; typedef long long ll; int n, q, l, r, a[100001]; ll subSum(int l, int r) { ll maxTillNow = LONG_MIN, currSum = 0; bool reverse = false; int i = 1; while (i <= n) { if (i == l && reverse == false) { i = r; reverse = true; } currSum += a[i]; if (currSum < 0) currSum = 0; else if (currSum > maxTillNow) maxTillNow = currSum; if (i == l) { reverse = false; i = r; } if (reverse == true) i--; else i++; } return maxTillNow; } int main() { cin >> n >> q; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 0; i < q; i++) { cin >> l >> r; cout << subSum(l, r) << endl; } }
#ifndef PREFMODEL_H #define PREFMODEL_H #include <QObject> #include <sharedpreferences.h> class PrefModel : public QObject { Q_OBJECT Q_PROPERTY(QStringList model READ model NOTIFY modelChanged) public: explicit PrefModel(QObject *parent = nullptr); QStringList model() const; public slots: void save(const QString &key, const QVariant &value); void remove(int index); signals: void modelChanged(); private: SharedPreferences *prefs; }; #endif // PREFMODEL_H
/* * Copyright (c) 2020, Mohamed Ammar <mamar452@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <fstream> #include <string> #include <map> #include <vector> #include "MRKCommon.h" #include "MRKXCPPStructs.h" namespace MRK { struct MRKCodeStream { mrks ofstream Stream; mrku32 IndentCount; bool IsDirty; mrks string ClassPath; MRKXCPPClass* Class; }; class MRKCodeWriter { private: mrks map<mrks string, MRKCodeStream> m_OpenedStreams; MRKCodeStream* m_CurrentStream; mrks string m_ParentDir; mrks ofstream m_InitializeStream; mrks vector<mrks string> m_CodeClassPaths; mrks vector<mrks string> m_RegParams; mrks vector<mrks string> m_Images; void WriteLine(mrks string line); mrks string Replicate(char c, mrku32 times); mrks string Replicate(mrks string c, mrku32 times); void Increment(); void Decrement(); mrks string Replace(mrks string orig, mrks string from, mrks string to); void RegParam(mrks string& param); public: MRKCodeWriter(mrks string dir); void OpenClass(MRKXCPPClass* clazz); void WriteMethod(MRKXCPPMethod* method, bool sttic); void WriteField(MRKXCPPField* field); void CloseClass(); void CloseWriter(); }; }
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <stb_image.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "shader.h" #include "camera.h" #include "object.h" #include <iostream> void framebuffer_size_callback(GLFWwindow *window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void processInput(GLFWwindow *window); const unsigned int SCREEN_WIDTH = 800; const unsigned int SCREEN_HEIGHT = 600; Camera camera(glm::vec3(0.0f, 0.0f, 5.0f)); float lastX = SCREEN_WIDTH/2.0f; float lastY = SCREEN_HEIGHT/2.0f; bool firstMouse = true; float deltaTime = 0.0f; float lastFrame = 0.0f; GLFWwindow* init() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow *window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Scene", NULL, NULL); if(window == NULL) { std::cerr << "Failed to create GLFW window!" << std::endl; return nullptr; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cerr << "Failed to initialize GLAD!" << std::endl; return nullptr; } glEnable(GL_DEPTH_TEST); return window; } void verticesSetup(int verticesNum, unsigned int VAO[], unsigned int VBO[], int bufLength, int attribNum, int lengths[], int sizes[], float* verticesArray[]) { glGenVertexArrays(verticesNum, VAO); glGenBuffers(verticesNum, VBO); for(int i=0; i<verticesNum; i++) { glBindVertexArray(VAO[i]); glBindBuffer(GL_ARRAY_BUFFER, VBO[i]); glBufferData(GL_ARRAY_BUFFER, sizes[i], verticesArray[i], GL_STATIC_DRAW); int offset = 0; for(int j=0; j<attribNum; j++) { glVertexAttribPointer(j, lengths[j], GL_FLOAT, GL_FALSE, bufLength*sizeof(float), (void*)(offset*sizeof(float))); glEnableVertexAttribArray(j); offset += lengths[j]; } } } bool loadTexture(unsigned int& texture, const char* path) { 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); int width, height, nrChannels; unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0); if(data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cerr << "Failed to load texture!" << std::endl; return false; } stbi_image_free(data); return true; } int main() { GLFWwindow *window = init(); if(!window) { glfwTerminate(); return -1; } Shader shader("vshader.vs", "fshader.fs"); // vertices float verticesPlane[] ={ -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, }; float verticesCube[] = { // front 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // back 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // left 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, // right 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // top 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, // down 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }; float verticesPyramid[] = { // front 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f, // back 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f, // left 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f, // right 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f, // down 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }; float verticesDiamond[] = { // front up 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, 2.0f, 0.5f, 0.5f, 1.0f, // back up 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 2.0f, 0.5f, 0.5f, 1.0f, // left up 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, 2.0f, 0.5f, 0.5f, 1.0f, // right up 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 2.0f, 0.5f, 0.5f, 1.0f, // front down 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 1.0f, // back down 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 1.0f, // left down 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 1.0f, // right down 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 1.0f, }; float* verticesArray[] ={verticesCube, verticesPyramid, verticesDiamond, verticesPlane}; int sizes[] ={sizeof(verticesCube), sizeof(verticesPyramid), sizeof(verticesDiamond), sizeof(verticesPlane)}; int lengths[] ={3, 2}; unsigned int VAO[4], VBO[4]; verticesSetup(4, VAO, VBO, 5, 2, lengths, sizes, verticesArray); // object Cube cube(2.0f, (float)glfwGetTime(), 36, 5, verticesCube, glm::vec3(3.0f, 0.0f, 0.0f), glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 1.0f, 1.0f)); Pyramid pyramid(18, 5, verticesPyramid, glm::vec3(0.0f, 0.0f, -2.0f), glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 1.5f, 1.0f)); Diamond diamond(24, 5, verticesDiamond, glm::vec3(-2.0f, 0.0f, 0.0f), glm::vec3(-0.5f, -1.0f, -0.5f), glm::vec3(1.0f, 1.0f, 1.0f)); Plane front(FRONT_FACE, 6, 5, verticesPlane, glm::vec3(0.0f, 0.0f, 10.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(10.0f, 5.0f, 1.0f)); Plane back(BACK_FACE, 6, 5, verticesPlane, glm::vec3(0.0f, 0.0f, -10.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(10.0f, 5.0f, 1.0f)); Plane left(LEFT_FACE, 6, 5, verticesPlane, glm::vec3(-10.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(10.0f, 5.0f, 1.0f)); Plane right(RIGHT_FACE, 6, 5, verticesPlane, glm::vec3(10.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(10.0f, 5.0f, 1.0f)); Plane top(TOP_FACE, 6, 5, verticesPlane, glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(10.0f, 10.0f, 1.0f)); Plane down(DOWN_FACE, 6, 5, verticesPlane, glm::vec3(0.0f, -5.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(10.0f, 10.0f, 1.0f)); // texture unsigned int background, texture1, texture2, texture3; if(!loadTexture(background, "texture/background.jpg") || !loadTexture(texture1, "texture/marble.jpg") || !loadTexture(texture2, "texture/interesting.jpg") || !loadTexture(texture3, "texture/rgb.jpg")) { glfwTerminate(); return -1; } while(!glfwWindowShouldClose(window)) { float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; processInput(window); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, background); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, texture2); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, texture3); shader.use(); // draw background shader.setInt("texture1", 0); glDisable(GL_DEPTH_TEST); glBindVertexArray(VAO[3]); shader.setMat4("projection", glm::mat4(1.0f)); shader.setMat4("view", glm::mat4(1.0f)); shader.setMat4("model", glm::mat4(1.0f)); glDrawArrays(GL_TRIANGLES, 0, 6); glEnable(GL_DEPTH_TEST); // draw objects glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCREEN_WIDTH / (float)SCREEN_HEIGHT, 0.1f, 100.0f); shader.setMat4("projection", projection); glm::mat4 view = camera.GetViewMatrix(); shader.setMat4("view", view); // draw planes shader.setInt("texture1", 1); glBindVertexArray(VAO[3]); glm::mat4 model = front.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 6); model = back.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 6); model = left.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 6); model = right.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 6); model = top.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 6); model = down.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 6); // draw pyramid shader.setInt("texture1", 3); glBindVertexArray(VAO[1]); model = pyramid.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 18); // draw diamond shader.setInt("texture1", 3); glBindVertexArray(VAO[2]); model = diamond.model(0.0f); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 24); // draw cube shader.setInt("texture1", 3); glBindVertexArray(VAO[0]); model = cube.model(2.0f*currentFrame); if(cube.collide(diamond) || cube.collide(pyramid)) { shader.setInt("texture1", 2); } shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(2, VAO); glDeleteBuffers(2, VBO); glfwTerminate(); return 0; } void framebuffer_size_callback(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow *window) { if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyboard(FORWARD, deltaTime); } if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera.ProcessKeyboard(BACKWARD, deltaTime); } if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera.ProcessKeyboard(LEFT, deltaTime); } if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera.ProcessKeyboard(RIGHT, deltaTime); } if(glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { camera.ProcessKeyboard(UP, deltaTime); } if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) { camera.ProcessKeyboard(DOWN, deltaTime); } } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if(firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos-lastX; float yoffset = lastY-ypos; lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); }
// Copyright 2013 (c) 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) // This test case demonstrates the issue described in #878: `future::unwrap` // triggers assertion #include <pika/future.hpp> #include <pika/init.hpp> #include <pika/testing.hpp> #include <exception> #include <utility> int pika_main() { pika::lcos::local::promise<pika::future<int>> promise; pika::future<pika::future<int>> future = promise.get_future(); std::exception_ptr p; try { //promise.set_value(42); throw pika::error::bad_parameter; } catch (...) { p = std::current_exception(); } PIKA_TEST(p); promise.set_exception(std::move(p)); PIKA_TEST(future.has_exception()); pika::future<int> inner(std::move(future)); PIKA_TEST(inner.has_exception()); return pika::finalize(); } int main(int argc, char* argv[]) { PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv), 0, "pika main exited with non-zero status"); return 0; }
#include<iostream> using namespace std; int main() { typedef int INT32; INT32 n = 20; cout << n << "is"<<sizeof(n)<<endl; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_MODEL_LINEAR_GROUP_PROPS_H_ #define BAJKA_MODEL_LINEAR_GROUP_PROPS_H_ #include "geometry/Point.h" #include "util/ReflectionMacros.h" #include "IGroupProperties.h" #include "Align.h" namespace Model { struct IModel; /** * */ struct LinearGroupProperties : public IGroupProperties { C__ (void) LinearGroupProperties () : hAlign (HA_CENTER), vAlign (VA_CENTER) {} virtual ~LinearGroupProperties () {} HAlign pe_ (hAlign); VAlign pe_ (vAlign); E_ (LinearGroupProperties) }; } /* namespace Model */ # endif /* LAYOUT_H_ */
#ifndef OtherUnderscoreEXTRA_HPP #define OtherUnderscoreEXTRA_HPP #include <QObject> class OtherUnderscoreExtraPrivate; class OtherUnderscoreExtra : public QObject { Q_OBJECT public: OtherUnderscoreExtra(); ~OtherUnderscoreExtra(); private: OtherUnderscoreExtraPrivate* const d; }; #endif
#pragma once #include <bits/stdc++.h> #include "hdf5.h" #include "Utils.h" namespace dyablo { struct Attribute { std::string name; std::string type; std::string center; hid_t handle; }; constexpr size_t CoordSize = 3; // Coordinates are stored as 3-float even in 2D /** * Class storing info about dyablo snapshots * * A general note : The strategy here is to never store arrays directly in * ram except for coordinates and connectivity for rapid lookup. * Future optimization might include streaming or partial buffering * but we do this for the moment to avoid any memory explosion for big runs * * @todo buffer storing for probing ? Maybe do a region extraction as in yt ? * @todo I'm pretty sure probeLocation can be written in a nice templated without * having to explicitely define the template when calling it ... * @todo Time series * @todo Improve getRefinementCriterion by enabling the user to provide a lambda for * the calculation * @todo Finish getBlock when iOct writing has been corrected * @todo switch static allocation of the selecters for probe/get to a heap allocation * to avoid segfaults when having large datasets * @todo How to detach EOS stuff from hardcoding ? -> Maybe the whole thing * should be directly based on the dyablo code to reuse modules as possible **/ class Snapshot { private: /** * Hdf5 related stuff **/ std::string name; //!< Name of the set std::map<std::string, hid_t> handles; //!< Map of all the opened file handles std::vector<hid_t> data_handles; //!< List of all the opened dataset handles hid_t connectivity; //!< Handle to connectivity dataset hid_t coordinates; //!< Handle to coordinates dataset std::map<std::string, Attribute> attributes; //!< Map of attributes std::vector<int> index_buffer; //!< Connectivity info (HEAVY !) std::vector<float> vertex_buffer; //!< Coordinates info (HEAVY !) int nDim; //!< Number of dimensions of the dataset int nElems; //!< Number of indices per cell int nCells; //!< Number of cells stored in the file int nVertices; //!< Number of vertices stored in the file float time; //!< Current time of the snapshot static std::map<std::string, hid_t> type_corresp; //!< Mapping between type names and hid equivalents bool show_progress_bars; public: Snapshot() = default; ~Snapshot(); void close(); void print(); /** Snapshot reading/construction from Hdf5 **/ void setName(std::string name); void setTime(float time); void setNDim(int nDim); void addH5Handle(std::string handle, std::string filename); void setConnectivity(std::string handle, std::string xpath, int nCells); void setCoordinates(std::string handle, std::string xpath, int nVertices); void addAttribute(std::string handle, std::string xpath, std::string name, std::string type, std::string center); /** Cell info and access **/ int getCellFromPosition(Vec v); BoundingBox getCellBoundingBox(uint iCell); Vec getCellCenter(uint iCell); Vec getCellSize(uint iCell); float getCellVolume(uint iCell); float getTime(); /** Vector access * @note: Please use thes for large query as most of them are made in parallel **/ std::vector<int> getCellsFromPositions(std::vector<Vec> v); std::vector<Vec> getCellCenter(std::vector<uint> iCells); std::vector<Vec> getCellSize(std::vector<uint> iCells); std::vector<float> getCellVolume(std::vector<uint> iCells); std::vector<Vec> getUniqueCells(std::vector<Vec> pos); /** Domain info **/ int getNCells(); int getNDim(); bool hasAttribute(std::string attribute); BoundingBox getDomainBoundingBox(); /** Generic attribute probing methods **/ template<typename T> T probeLocation(Vec pos, std::string attribute); template<typename T> std::vector<T> probeLocation(std::vector<Vec> pos, std::string attribute); template<typename T> std::vector<T> probeCells(std::vector<uint> iCells, std::string attribute); /** High-level probing methods **/ float probeDensity(Vec pos); float probePressure(Vec pos); float probeTotalEnergy(Vec pos); float probeMach(Vec pos); Vec probeMomentum(Vec pos); Vec probeVelocity(Vec pos); int probeLevel(Vec pos); int probeRank(Vec pos); int probeOctant(Vec pos); // Integrated quantities float getTotalMass(); float getTotalEnergy(); float getTotalInternalEnergy(double gamma); float getTotalKineticEnergy(); float getMaxMach(); float getAverageMach(); float getRefinementCriterion(Vec pos); std::vector<float> getRefinementCriterion(std::vector<Vec> pos); // Vector functions std::vector<float> probeDensity(std::vector<Vec> pos); std::vector<float> probePressure(std::vector<Vec> pos); std::vector<float> probeTotalEnergy(std::vector<Vec> pos); std::vector<float> probeMach(std::vector<Vec> pos); std::vector<Vec> probeMomentum(std::vector<Vec> pos); std::vector<Vec> probeVelocity(std::vector<Vec> pos); std::vector<int> probeLevel(std::vector<Vec> pos); std::vector<int> probeRank(std::vector<Vec> pos); std::vector<int> probeOctant(std::vector<Vec> pos); // By cell std::vector<float> getDensity(std::vector<uint> iCells); std::vector<float> getPressure(std::vector<uint> iCells); std::vector<float> getTotalEnergy(std::vector<uint> iCells); std::vector<float> getMach(std::vector<uint> iCells); std::vector<Vec> getMomentum(std::vector<uint> iCells); std::vector<Vec> getVelocity(std::vector<uint> iCells); std::vector<int> getLevel(std::vector<uint> iCells); std::vector<int> getRank(std::vector<uint> iCells); std::vector<int> getOctant(std::vector<uint> iCells); std::vector<int> getBlock(uint iOct); // Static variable for vectorized reading static int vec_size; }; }
#include <iostream> #include <stack> #include <math.h> using namespace std; struct arr{ long n; long mn; }; int T, n, k, res = 0; int **a; arr *b; stack<int> sr,sl; void nhap(){ int i, j; cin >> T; b = new arr[T]; a = new int*[T]; for(i = 0; i < T; i++){ cin >> b[i].n >> b[i].mn; a[i] = new int[b[i].n]; for(j = 0; j < b[i].n; j++) cin >> a[i][j]; } } void exch(int &a, int &b){ int r = a; a = b; b = r; } void quicksort(int ii, int left, int right){ sl.push(left); sr.push(right); int x, l, r, i, j; while(!sl.empty()){ l = sl.top(); sl.pop(); r = sr.top(); sr.pop(); x = a[ii][(l+r)/2]; i = l; j = r; do{ while(x > a[ii][i]) i++; while(x < a[ii][j]) j--; if(i <= j) exch(a[ii][i++], a[ii][j--]); } while(i < j); if(l < j){ sl.push(l); sr.push(j); } if(i < r){ sl.push(i); sr.push(r); } } } void solve(){ long i, j, d = 0, res, resum; for(i = 0; i < T; i++){ quicksort(i, 0, b[i].n-1); d = 0; resum = 0; for(j = 0; j < b[i].n - 1; j++) if(a[i][j] == a[i][j+1] - 1){ d++; } else if(d > 0){ ++d; res = sqrt(2*d-1); while(!((res*(res-1)/2 + 1) <= d && (res*(res+1)/2 >= d))){ res++; } resum = resum +(res-1)*b[i].mn; d = 0; } if(d > 0){ ++d; res = sqrt(2*d-1); while(!((res*(res-1)/2 + 1) <= d && (res*(res+1)/2 >= d))){ res++; } resum = resum +(res-1)*b[i].mn; } cout << b[i].n*b[i].mn + resum << endl; } } int main(){ nhap(); solve(); for(int i = 0; i < T; i++) delete []a[i]; delete []a; delete []b; return 0; }
#include <iostream> using namespace std; class Loc { int longitude; int latitude; public: Loc(); Loc(int lg, int lt); Loc(const Loc& loc1); friend ostream& operator <<(ostream& outs, const Loc& loc1); friend istream& operator >>(istream& ins, Loc& loc1); friend Loc operator +(const Loc& loc1, const Loc& loc2); friend Loc operator +(const Loc& loc1, int x); friend Loc operator +(int x, const Loc& loc1); void operator ++(int); void operator ++(); };
#include "Item.h" Item::Item(int isbn, string title) : _isbn(isbn), _title(title) { } Item::~Item() { } int Item::getIsbn() const { return _isbn; } string Item::getTitle() const { return _title; } bool Item::matches(string keyword) const { return (_title.find(keyword) != string::npos); } string Item::toString() const { stringstream s; s << "Item={" << "isbn=" << _isbn << ",title=" << _title << "}"; return s.str(); }
#include "Wire.h" #include "I2Cdev.h" #include "MPU6050.h" #include "math.h" int l1 = 6, l2 = 7, r1 = 5, r2 = 4;//Motor Pins IN1, IN2, IN3, IN4 from L298N Driver double kp = 20, kd = 0.014, ki = 28; float sampleTime = 0.005, targetAngle = - 0.5; MPU6050 mpu; int in; int16_t accY, accZ, gyroX; volatile int mSpeed, gRate; volatile float aAngle, gAngle, presAngle, prevAngle = 0, error, errorSum = 0; void motors(int leftMotorSpeed, int rightMotorSpeed) { if (leftMotorSpeed >= 0) { analogWrite(l1, leftMotorSpeed); digitalWrite(l2, LOW); } else { analogWrite(l1, 255 + leftMotorSpeed); digitalWrite(l2, HIGH); } if (rightMotorSpeed >= 0) { analogWrite(r1, rightMotorSpeed); digitalWrite(r2, LOW); } else { analogWrite(r1, 255 + rightMotorSpeed); digitalWrite(r2, HIGH); } } void init_PID() { cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B OCR1A = 9999;// set compare match register to set sample time 5ms TCCR1B |= (1 << WGM12);// turn on CTC mode TCCR1B |= (1 << CS11);// Set CS11 bit for prescaling by 8 TIMSK1 |= (1 << OCIE1A);// enable timer compare interrupt sei(); // enable global interrupts } void setup() { Serial.begin(9600); pinMode(l1, OUTPUT); pinMode(l2, OUTPUT); pinMode(r1, OUTPUT); pinMode(r2, OUTPUT); mpu.initialize(); mpu.setYAccelOffset(1593); mpu.setZAccelOffset(963); mpu.setXGyroOffset(40); init_PID(); in=0; } void loop() { if (in == 1) { accY = mpu.getAccelerationY(); accZ = mpu.getAccelerationZ(); gyroX = mpu.getRotationX(); mSpeed = constrain(mSpeed, -255, 255); motors(mSpeed, mSpeed); } if (in == 0) { digitalWrite(LED_BUILTIN, LOW); delay(500); digitalWrite(LED_BUILTIN, HIGH); delay(250); } } ISR(TIMER1_COMPA_vect) { if (Serial.read() == 0) in = 0; if (Serial.read() == 1) in = 1; aAngle = (atan2(accY, accZ) * RAD_TO_DEG) - 18; gRate = map(gyroX, -32768, 32767, -250, 250); gAngle = (float)gRate * sampleTime; presAngle = 0.9934 * (prevAngle + gAngle) + 0.0066 * aAngle; error = presAngle - targetAngle; errorSum = errorSum + error; errorSum = constrain(errorSum, -300, 300); mSpeed = kp * (error) + ki * (errorSum) * sampleTime - kd * (presAngle - prevAngle) / sampleTime; prevAngle = presAngle; }
#ifndef TUTORIALOBJECT_H #define TUTORIALOBJECT_H #include "Lib.h" #include <vector> namespace gnGame { // チュートリアル用のオブジェクトのクラス class TutorialObject : public Object{ public: ~TutorialObject() = default; virtual void onUpdate() = 0; }; /// <summary> /// 移動のオブジェクト /// </summary> class MoveIntro : public TutorialObject { public: MoveIntro(const Vector2& _pos); ~MoveIntro() = default; void onUpdate() override; private: Sprite sprite; }; /// <summary> /// ジャンプのオブジェクト /// </summary> class JumpIntro : public TutorialObject { public: JumpIntro(const Vector2& _pos); ~JumpIntro() = default; void onUpdate() override; private: Sprite sprite; }; /// <summary> /// ショットのオブジェクト /// </summary> class ShotIntro : public TutorialObject { public: ShotIntro(const Vector2& _pos); ~ShotIntro() = default; void onUpdate() override; private: Sprite sprite; }; using TutorialObjectPtr = std::shared_ptr<TutorialObject>; class TutorialObjectList { public: static TutorialObjectList* getIns(); public: void addObject(TutorialObjectPtr _object); void update(); void clear(); private: TutorialObjectList() : tutorialObjectList() {}; TutorialObjectList(const TutorialObjectList&); TutorialObjectList& operator= (const TutorialObjectList&); private: std::vector<TutorialObjectPtr> tutorialObjectList; }; } #endif // !TUTORIALOBJECT_H
#include <iostream> #include "TreeNode.h" #include "BinarySearchTree.h" using namespace std; template <typename T> bool equal(const TreeNode<T>* tree_a, const TreeNode<T>* tree_b) { if (!tree_a && !tree_b) { return true; } else if (tree_a && tree_b) { return (tree_a->get_value() == tree_b->get_value()) && equal(tree_a->get_left(), tree_b->get_left()) && equal(tree_a->get_right(), tree_b->get_right()); } else { return false; } } template <typename T> bool is_subtree(const TreeNode<T>* super, const TreeNode<T>* sub) { if (!super) { return false; } else if (super->get_value() == sub->get_value()) { return equal(super, sub); } else { return (is_subtree(super->get_left(), sub) || is_subtree(super->get_right(), sub)); }; } int main() { BinarySearchTree<int> tree1 {}; for (auto i : {4, 6, 7, 2, 1, 3}) { tree1.add(i); } BinarySearchTree<int> tree2 {}; for (auto i : {2, 1, 3}) { tree2.add(i); } BinarySearchTree<int> tree3 {}; for (auto i : {2, 4, 1}) { tree3.add(i); } cout << is_subtree(tree1.get_head(), tree2.get_head()) << endl; cout << is_subtree(tree1.get_head(), tree3.get_head()) << endl; }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int n, w, l, T; vector< pair<int, int> > p; struct Tp { int r, i; bool operator<(const Tp& B)const { return r > B.r; } } a[1111111]; int ansx[111111], ansy[111111]; bool ByI(const Tp& A, const Tp & B){ return A.i < B.i; } int main() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); cin >> T; for (int _ = 1; _ <= T; _++) { cin >> n >> w >> l; for (int i = 0; i < n; i++) { cin >> a[i].r; a[i].i = i; } sort(a, a + n); p.clear(); p.push_back(make_pair(a[0].r, a[0].r)); ansx[a[0].i] = 0; ansy[a[0].i] = 0; for (int i = 1, j = 1; i < n;) { if (j >= (int)p.size()) { int ri = p.back().first; if (ri + a[i].r <= l) { p.push_back(make_pair(ri + a[i].r + a[i].r, a[i].r)); ansx[a[i].i] = 0; ansy[a[i].i] = ri + a[i].r; i++; continue; } else { j = 0; continue; } } else { if ( (j == 0 && p[j].second + a[i].r + a[i].r > w) || (j != 0 && p[j].second + a[i].r + a[i].r > p[j - 1].second) ) { j++; continue; } else { int pr = ((j == 0)? 0 : (p[j-1].first)); if (pr + a[i].r * (j != 0) > l) { j++; continue; } int ll = p[j].first - pr; ansx[a[i].i] = p[j].second + a[i].r; ansy[a[i].i] = pr + a[i].r * (j != 0); if (a[i].r == ll) { p[j].second += a[i].r + a[i].r; } else { p.insert(p.begin() + j, make_pair(pr + a[i].r + a[i].r * (j != 0), p[j].second + a[i].r + a[i].r)); } i++; continue; } } throw 666; } sort(a, a + n, ByI); printf("Case #%d:", _); for (int i = 0; i < n; i++) { printf(" %d %d", ansx[i], ansy[i]); for (int j = 0; j < i; j++) { LL r1 = sqr(LL(ansx[i]) - ansx[j]) + sqr(LL(ansy[i]) - ansy[j]); if (r1 < sqr(LL(a[i].r) + a[j].r)) { cout << endl << endl; cout << i << " " << j << endl; cout << ansx[i] << " " << ansy[i] << " " << a[i].r << endl; cout << ansx[j] << " " << ansy[j] << " " << a[j].r << endl; cout << r1 << endl; throw 555; } } if (ansx[i] < 0 || ansx[i] > w || ansy[i] < 0 || ansy[i] > l) { cout << endl; cout << w << " " << l << endl; throw 666; } } puts(""); } return 0; }
#ifndef _ROS_SERVICE_mav_ctrl_motors_h #define _ROS_SERVICE_mav_ctrl_motors_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace asctec_hl_comm { static const char MAV_CTRL_MOTORS[] = "asctec_hl_comm/mav_ctrl_motors"; class mav_ctrl_motorsRequest : public ros::Msg { public: bool startMotors; mav_ctrl_motorsRequest(): startMotors(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_startMotors; u_startMotors.real = this->startMotors; *(outbuffer + offset + 0) = (u_startMotors.base >> (8 * 0)) & 0xFF; offset += sizeof(this->startMotors); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_startMotors; u_startMotors.base = 0; u_startMotors.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->startMotors = u_startMotors.real; offset += sizeof(this->startMotors); return offset; } const char * getType(){ return MAV_CTRL_MOTORS; }; const char * getMD5(){ return "6076998c2a5ec9144368e0457caa79ef"; }; }; class mav_ctrl_motorsResponse : public ros::Msg { public: bool motorsRunning; mav_ctrl_motorsResponse(): motorsRunning(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_motorsRunning; u_motorsRunning.real = this->motorsRunning; *(outbuffer + offset + 0) = (u_motorsRunning.base >> (8 * 0)) & 0xFF; offset += sizeof(this->motorsRunning); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_motorsRunning; u_motorsRunning.base = 0; u_motorsRunning.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->motorsRunning = u_motorsRunning.real; offset += sizeof(this->motorsRunning); return offset; } const char * getType(){ return MAV_CTRL_MOTORS; }; const char * getMD5(){ return "246eeab4e06271d99512461f49c049e7"; }; }; class mav_ctrl_motors { public: typedef mav_ctrl_motorsRequest Request; typedef mav_ctrl_motorsResponse Response; }; } #endif
#include <iostream> #include <fstream> #include <string> #include <vector> #include <conio.h> #include <stack> #include <algorithm> using namespace std; enum brace_type { ORIENTED_OPEN = '<', ORIENTED_CLOSE = '>', REGULAR_OPEN = '{', REGULAR_CLOSE = '}' }; // Типы скобок enum mnogestvo_type { ORIENTED, REGULAR }; // Типы множеств enum element_type { SINGLE, MNOGESTVO }; // Тип эл-та: множество или объект class Mnogestvo; class Element; class Operations; class Element { private: element_type _type; // Тип эл-та public: string value; // Един-ое знач. эл-та Mnogestvo * mnogestvo; // Един-ое знач. множества Element(element_type); ~Element(); const element_type type() const; void setValue(string &); void setValue(Mnogestvo *); string toString() const; bool operator<(const Element &) const; }; class Mnogestvo { private: vector<Element> elements; // Вектор для элементов множества mnogestvo_type _type; // Тип множества Element * _getElementPtr(string &, unsigned int &, unsigned int); bool _checkBalance(string &); public: bool isSorted; bool isCorrect; Mnogestvo(mnogestvo_type); Mnogestvo(string &); ~Mnogestvo(); const mnogestvo_type type() const; void pushElement(Element *); void show(int); int size(); void sort(); string toString(); bool hasElement(string &); friend class Operations; }; class Operations { public: Mnogestvo * symDifference(Mnogestvo *, Mnogestvo *); }; Mnogestvo::Mnogestvo(mnogestvo_type typ) { // Конструктор множ. _type = typ; // typ - его тип isSorted = true; } Mnogestvo::Mnogestvo(string & strok) { // Конструктор множ. _type = REGULAR; // strok - строка множества isSorted = true; isCorrect = true; if (!_checkBalance(strok)) { cerr << " Ne pravilno (proverte sootvetstvie skobok): " << strok << endl; isCorrect = false; } else { unsigned int start = 1; while (start < strok.length() - 1) { Element * el = _getElementPtr(strok, start, strok.length() - 1); if (el != NULL) pushElement(el); else break; } if (strok != toString()) { cerr << "Ne pravily vvod" << endl; cerr << " Polycheno: " << strok << endl; cerr << " Analiziryemyi kak: " << toString() << endl; isCorrect = false; } } } Mnogestvo::~Mnogestvo() { /* TODO: fix memleaks vector<Element>::iterator i; for (i=elements.begin(); i < elements.end(); ++i) elements.erase(i); */ } const mnogestvo_type Mnogestvo::type() const { return _type; // Возвращение типа множества } bool Mnogestvo::_checkBalance(string & line) { stack<char> braces; for (unsigned int i = 1; i < line.length() - 1; ++i) { if (line[i] == REGULAR_OPEN) { braces.push(REGULAR_OPEN); } else if (line[i] == REGULAR_CLOSE) { if (braces.empty() || (!braces.empty() && braces.top() != REGULAR_OPEN)) return false; else braces.pop(); } else if (line[i] == ORIENTED_OPEN) { braces.push(ORIENTED_OPEN); } else if (line[i] == ORIENTED_CLOSE) { if (braces.empty() || (!braces.empty() && braces.top() != ORIENTED_OPEN)) return false; else braces.pop(); } } return braces.empty(); } Element * Mnogestvo::_getElementPtr(string & line, unsigned int & begin, unsigned int end) { // Получения укозателя элемента // begin, end - выравнивание позиций для получения след. эл-та Mnogestvo * mnogestvo; if (line[begin] == REGULAR_OPEN) { mnogestvo = new Mnogestvo(REGULAR); } else if (line[begin] == ORIENTED_OPEN) { mnogestvo = new Mnogestvo(ORIENTED); } Element * element = NULL; if ((line[begin] >= '0' && line[begin] <= '9') || (line[begin] >= 'A' && line[begin] <= 'z')) { string ch; while (line[begin] != ',' && begin < end) { ch = ch + line[begin]; ++begin; } ++begin; element = new Element(SINGLE); element->setValue(ch); } else if (line[begin] == ORIENTED_OPEN) { unsigned int i = begin; int braces = 0; while (line[i] != ORIENTED_CLOSE || braces != 1) { if (line[i] == ORIENTED_OPEN) ++braces; else if (line[i] == ORIENTED_CLOSE) --braces; ++i; } element = new Element(MNOGESTVO); Mnogestvo * mnogestvo; mnogestvo = new Mnogestvo(ORIENTED); ++begin; while (begin < i) mnogestvo->pushElement(_getElementPtr(line, begin, i)); element->setValue(mnogestvo); begin = i + 2; } else if (line[begin] == REGULAR_OPEN) { unsigned int i = begin; int braces = 0; while (line[i] != REGULAR_CLOSE || braces != 1) { if (line[i] == REGULAR_OPEN) ++braces; else if (line[i] == REGULAR_CLOSE) --braces; ++i; } element = new Element(MNOGESTVO); Mnogestvo * mnogestvo; mnogestvo = new Mnogestvo(REGULAR); ++begin; while (begin < i) mnogestvo->pushElement(_getElementPtr(line, begin, i)); element->setValue(mnogestvo); begin = i + 2; } else { begin = end; } return element; } void Mnogestvo::pushElement(Element * el) { // Добовления нового эл-та во множество elements.push_back(*el); // el - укозатель на новый эл-т isSorted = false; } void Mnogestvo::show(int dert = 0) { // dert - глубина подмножества vector<Element>::const_iterator i; for (i = elements.begin(); i != elements.end(); ++i) { for (int d = 0; d <= dert; ++d) cout << " "; if (i->type() == SINGLE) { cout << "Element: " << i->value << endl; } else { cout << "Mnogestvo (" << (i->mnogestvo->type() == REGULAR ? "regular" : "oriented") << ", " << (i->mnogestvo->isSorted ? "sorted" : "unsorted") << "): " << endl; i->mnogestvo->show(dert + 1); } } } int Mnogestvo::size() { return elements.size(); // Возвращения размера множества } void Mnogestvo::sort() { if (isSorted) return; if (type() == REGULAR) { std::sort(elements.begin(), elements.end()); } else { vector<Element>::iterator i; // рекурсивная сортировка for (i = elements.begin(); i < elements.end(); ++i) if (i->type() == MNOGESTVO) i->mnogestvo->sort(); } isSorted = true; } string Mnogestvo::toString() { // Возвращения множества как строка string mnogestvo = ""; vector<Element>::iterator i; for (i = elements.begin(); i != elements.end(); ++i) { mnogestvo += i->toString(); if (i + 1 != elements.end()) mnogestvo += ','; } if (type() == REGULAR) mnogestvo = (char)REGULAR_OPEN + mnogestvo + (char)REGULAR_CLOSE; else mnogestvo = (char)ORIENTED_OPEN + mnogestvo + (char)ORIENTED_CLOSE; return mnogestvo; } bool Mnogestvo::hasElement(string & elemS) { // Проверка элемента на присутствие в множестве vector<Element>::iterator i; // elemS - строковое предстовление для поиска for (i = elements.begin(); i < elements.end(); ++i) if (i->toString() == elemS) return true; return false; } Element::Element(element_type dez) { // Конструктор эл-та _type = dez; // dez - element type value = ""; mnogestvo = NULL; } Element::~Element() { /* if (_type==Mnogestvo) delete mnogestvo;; */ } void Element::setValue(string & dia) { value = dia; // dia - строковое знач. } void Element::setValue(Mnogestvo * sif) { // Набор эл-то во множество mnogestvo = new Mnogestvo(sif->type()); // sif - преднозначенный для множества *mnogestvo = *sif; } const element_type Element::type() const { return _type; // Тип возврощающего элемента } string Element::toString() const { // Пердстовление эл-та возврощений как строка if (type() == SINGLE) return value; else return mnogestvo->toString(); } bool Element::operator<(const Element & reil) const { // Оператор, проверяющий явл. ли эл-т меньше чем другой // reil - связь со знач. переменной if (type() == MNOGESTVO) mnogestvo->sort(); if (reil.type() == MNOGESTVO) reil.mnogestvo->sort(); if (type() == SINGLE && reil.type() == SINGLE) return value < reil.value; else if (type() == MNOGESTVO && reil.type() == MNOGESTVO) return toString() < reil.toString(); else if (type() == SINGLE && reil.type() == MNOGESTVO) return true; else return false; } Mnogestvo * Operations::symDifference(Mnogestvo * levoe, Mnogestvo * pravoe) { // Вычисления симметричного различия множества levoe->sort(); // levoe & pravoe - указатели на два множества pravoe->sort(); vector<string> elements; vector<string>::iterator j; string result; vector<Element>::iterator i; string t = ""; for (i = levoe->elements.begin(); i < levoe->elements.end(); ++i) { t = i->toString(); if (!pravoe->hasElement(t)) elements.push_back(t); } bool already = false; for (i = pravoe->elements.begin(); i < pravoe->elements.end(); ++i) { t = i->toString(); if (!levoe->hasElement(t)) { for (j = elements.begin(); j < elements.end(); ++j) if (*j == t) { already = true; break; } if (!already) elements.push_back(t); } } result = (char)REGULAR_OPEN; for (j = elements.begin(); j < elements.end(); ++j) result += *j + ','; if (result.length() != 1) result = result.substr(0, result.length() - 1); result += REGULAR_CLOSE; Mnogestvo * mnogestvo = new Mnogestvo(result); return mnogestvo; } int main() { ifstream in("input.txt"); //Зарание согласовать путь string mnogestvoExpression; Operations * psycho = new Operations; Mnogestvo * result = new Mnogestvo(REGULAR); while (getline(in, mnogestvoExpression)) { unsigned int pos = mnogestvoExpression.find("="); if (pos != string::npos) { mnogestvoExpression = mnogestvoExpression.substr(pos + 1); Mnogestvo * mnogestvo = new Mnogestvo(mnogestvoExpression); if (!mnogestvo->isCorrect) { cout << "Nepravilnyi vvod. Exit!" << endl; return 0; } result = psycho->symDifference(result, mnogestvo); delete mnogestvo; } } cout << "Rezultat= " << result->toString() << endl; _getch(); return 0; }
#include<iostream> #include<string.h> using namespace std; class Base{ protected: int id; public: virtual void whogetsinvoked(){ cout<<"In BASE " <<"\n"; } }; class Derived : public Base{ public: void whogetsinvoked(){ cout<<"In Derived"<<"\n"; } }; class Derived1 : public Derived{ public: void whogetsinvoked(){ cout<<"In Derived1"<<"\n"; id=2; } }; int main(){ Base *test= new Derived1(); test->whogetsinvoked(); return 0; }
// // Created by 史浩 on 2019-12-03. // #include "OffscreenSurface.h" OffscreenSurface::OffscreenSurface(EGLCore *eglCore,int width,int height) : BaseEGLSurface(eglCore) { createOffscreenSurface(width,height); } void OffscreenSurface::release() { releaseEglSurface(); }
// Created on: 2016-10-20 // Created by: Irina KRYLOVA // Copyright (c) 2016 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 _XCAFView_Object_HeaderFile #define _XCAFView_Object_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <gp_Pln.hxx> #include <gp_Pnt.hxx> #include <TColgp_HArray1OfPnt.hxx> #include <TCollection_HAsciiString.hxx> #include <XCAFView_ProjectionType.hxx> class XCAFView_Object; DEFINE_STANDARD_HANDLE(XCAFView_Object, Standard_Transient) //! Access object for saved view class XCAFView_Object : public Standard_Transient { public: Standard_EXPORT XCAFView_Object(); Standard_EXPORT XCAFView_Object(const Handle(XCAFView_Object)& theObj); void SetName(Handle(TCollection_HAsciiString) theName) { myName = theName; } Handle(TCollection_HAsciiString) Name() { return myName; } void SetType(XCAFView_ProjectionType theType) { myType = theType; } XCAFView_ProjectionType Type() { return myType; } void SetProjectionPoint(const gp_Pnt& thePoint) { myProjectionPoint = thePoint; } gp_Pnt ProjectionPoint() { return myProjectionPoint; } void SetViewDirection(const gp_Dir& theDirection) { myViewDirection = theDirection; } gp_Dir ViewDirection() { return myViewDirection; } void SetUpDirection(const gp_Dir& theDirection) { myUpDirection = theDirection; } gp_Dir UpDirection() { return myUpDirection; } void SetZoomFactor(Standard_Real theZoomFactor) { myZoomFactor = theZoomFactor; } Standard_Real ZoomFactor() { return myZoomFactor; } void SetWindowHorizontalSize(Standard_Real theSize) { myWindowHorizontalSize = theSize; } Standard_Real WindowHorizontalSize() { return myWindowHorizontalSize; } void SetWindowVerticalSize(Standard_Real theSize) { myWindowVerticalSize = theSize; } Standard_Real WindowVerticalSize() { return myWindowVerticalSize; } void SetClippingExpression(Handle(TCollection_HAsciiString) theExpression) { myClippingExpression = theExpression; } Handle(TCollection_HAsciiString) ClippingExpression() { return myClippingExpression; } void UnsetFrontPlaneClipping() { myFrontPlaneClipping = Standard_False; } Standard_Boolean HasFrontPlaneClipping() { return myFrontPlaneClipping; } void SetFrontPlaneDistance(Standard_Real theDistance) { myFrontPlaneDistance = theDistance; myFrontPlaneClipping = Standard_True; } Standard_Real FrontPlaneDistance() { return myFrontPlaneDistance; } void UnsetBackPlaneClipping() { myBackPlaneClipping = Standard_False; } Standard_Boolean HasBackPlaneClipping() { return myBackPlaneClipping; } void SetBackPlaneDistance(Standard_Real theDistance) { myBackPlaneDistance = theDistance; myBackPlaneClipping = Standard_True; } Standard_Real BackPlaneDistance() { return myBackPlaneDistance; } void SetViewVolumeSidesClipping(Standard_Boolean theViewVolumeSidesClipping) { myViewVolumeSidesClipping = theViewVolumeSidesClipping; } Standard_Boolean HasViewVolumeSidesClipping() { return myViewVolumeSidesClipping; } void CreateGDTPoints(const Standard_Integer theLenght) { if (theLenght > 0) myGDTPoints = new TColgp_HArray1OfPnt(1, theLenght); } Standard_Boolean HasGDTPoints() { return (!myGDTPoints.IsNull()); } Standard_Integer NbGDTPoints() { if (myGDTPoints.IsNull()) return 0; return myGDTPoints->Length(); } void SetGDTPoint(const Standard_Integer theIndex, const gp_Pnt& thePoint) { if (myGDTPoints.IsNull()) return; if (theIndex > 0 && theIndex <= myGDTPoints->Length()) myGDTPoints->SetValue(theIndex, thePoint); } gp_Pnt GDTPoint(const Standard_Integer theIndex) { if (myGDTPoints.IsNull()) return gp_Pnt(); if (theIndex > 0 && theIndex <= myGDTPoints->Length()) return myGDTPoints->Value(theIndex); else return gp_Pnt(); } DEFINE_STANDARD_RTTIEXT(XCAFView_Object,Standard_Transient) private: Handle(TCollection_HAsciiString) myName; XCAFView_ProjectionType myType; gp_Pnt myProjectionPoint; gp_Dir myViewDirection; gp_Dir myUpDirection; Standard_Real myZoomFactor; Standard_Real myWindowHorizontalSize; Standard_Real myWindowVerticalSize; Handle(TCollection_HAsciiString) myClippingExpression; Standard_Boolean myFrontPlaneClipping; Standard_Real myFrontPlaneDistance; Standard_Boolean myBackPlaneClipping; Standard_Real myBackPlaneDistance; Standard_Boolean myViewVolumeSidesClipping; Handle(TColgp_HArray1OfPnt) myGDTPoints; // Point for each GDT to describe position of GDT frame in View. }; #endif // _XCAFView_Object_HeaderFile
// belt buckle - no idea what this is used for class Helper_Base_EP1; class BeltBuckle_DZE : Helper_Base_EP1 { scope = 2; model = "\z\addons\dayz_epoch\models\skull.p3d"; displayName = "Belt Buckle"; accuracy = 1000; hiddenSelections[] = {"camo1"}; hiddenSelectionsTextures[] = {"#(argb,8,8,3)color(1,0.5,0.5,0.5,ca)"}; }; class WorkBench_DZ: BuiltItems { scope = 2; destrType = "DestructTree"; cost = 100; offset[] = {0,1.5,0}; model = "\z\addons\dayz_epoch\models\workbench.p3d"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; armor = 400; displayName = $STR_EPOCH_WORKBENCH; vehicleClass = "DayZ Epoch Buildables"; maintainBuilding[] = {{"PartWoodLumber",1}}; constructioncount = 1; removeoutput[] = {{"PartWoodPlywood",1},{"PartWoodLumber",2}}; requireplot = 0; nounderground = 0; }; class FuelPump_DZ: BuiltItems { scope = 2; destrType = "DestructNo"; cost = 100; offset[] = {0,2,0}; model = "\ca\Structures_E\Ind\Ind_FuelStation\Ind_FuelStation_Feed_ep1.p3d"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; armor = 400; displayName = $STR_EPOCH_FUELPUMP; vehicleClass = "DayZ Epoch Buildables"; constructioncount = 2; removeoutput[] = {{"fuel_pump_kit",1}}; requireplot = 0; nounderground = 0; }; class FireBarrel_DZ: Land_Fire_barrel { cost = 100; offset[] = {0,2,0.5}; displayName = $STR_EPOCH_FIREBARREL; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; armor = 400; vehicleClass = "DayZ Epoch Buildables"; constructioncount = 2; removeoutput[] = {{"ItemFireBarrel_kit",1}}; nounderground = 0; }; class Sign_1L_Noentry_EP1; class Plastic_Pole_EP1_DZ: Sign_1L_Noentry_EP1 { destrType = "DestructTree"; armor = 2000; // static hasDriver = 0; simulation = "house"; weapons[] = {}; magazines[] = {}; irTarget = 0; type = 1; threat[] = {0,0,0}; maxSpeed = 0; coefInside = 4; coefInsideHeur = 4; scope = 2; offset[] = {0,2.5,0.3}; displayName = $STR_EPOCH_PLAYER_246; vehicleClass = "DayZ Epoch Buildables"; removeoutput[] = {{"plot_pole_kit",1}}; requireplot = 0; nounderground = 0; }; class Land_covering_hut_EP1; class CanvasHut_DZ: Land_covering_hut_EP1 { armor = 200; scope = 2; offset[] = {0,2.5,1}; displayName = $STR_EPOCH_CANVASSUNSHADE; vehicleClass = "DayZ Epoch Buildables"; removeoutput[] = {{"sun_shade_kit",1}}; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; }; class Park_bench1; class ParkBench_DZ: Park_bench1 { scope = 2; offset[] = {0,1.5,0.5}; displayName = $STR_EPOCH_WOODBENCH; vehicleClass = "DayZ Epoch Buildables"; removeoutput[] = {{"park_bench_kit",1}}; }; class Land_Misc_deerstand; class DeerStand_DZ: Land_Misc_deerstand { armor = 300; scope = 2; offset[] = {0,5,0}; displayName = $STR_EPOCH_DEERSTAND; vehicleClass = "DayZ Epoch Buildables"; removeoutput[] = {{"deer_stand_kit",1}}; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; }; class Land_Wall_Gate_Ind1_L; class MetalGate_DZ: Land_Wall_Gate_Ind1_L { armor = 400; scope = 2; offset[] = {0,6,1}; displayName = $STR_EPOCH_RUSTYGATE; vehicleClass = "DayZ Epoch Buildables"; removeoutput[] = {{"rusty_gate_kit",1}}; }; class Fence_corrugated_plate; class Fence_corrugated_DZ: Fence_corrugated_plate { armor = 600; scope = 2; offset[] = {0,3,1}; removeoutput[] = {{"ItemCorrugated",1}}; displayName = $STR_EPOCH_CORRUGATEDFENCE; vehicleClass = "DayZ Epoch Buildables"; nounderground = 0; }; class Wall_FenW2_6_EP1; class StickFence_DZ: Wall_FenW2_6_EP1 { destrType = "DestructTree"; armor = 200; scope = 2; offset[] = {0,4.5,0.5}; displayName = $STR_EPOCH_STICKFENCE; vehicleClass = "DayZ Epoch Buildables"; removeoutput[] = {{"stick_fence_kit",1}}; }; class ASC_EU_LHVOld; class LightPole_DZ: ASC_EU_LHVOld { armor = 200; scope = 2; offset[] = {0,2.5,0}; displayName = $STR_EPOCH_LIGHTPOLE; vehicleClass = "DayZ Epoch Buildables"; maintainBuilding[] = {{"ItemLightBulb",1}}; removeoutput[] = {{"light_pole_kit",1}}; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; }; class Land_Misc_Scaffolding; class Scaffolding_DZ: Land_Misc_Scaffolding { armor = 100; destrType = "DestructBuilding"; scope = 2; displayName = $STR_EPOCH_SCAFFOLDING; vehicleClass = "DayZ Epoch Buildables"; constructioncount = 6; animated = 0; irTarget = 0; accuracy = 0.3; transportAmmo = 0; transportRepair = 0; transportFuel = 0; typicalCargo[] = {}; offset[] = {0,9,3}; cost = 0; removeoutput[] = {{"ItemScaffoldingKit",1}}; }; class Hedgehog_DZ: BuiltItems { scope = 2; destrType = "DestructNo"; cost = 100; offset[] = {0,1.5,0.55}; model = "\ca\misc\jezek_kov"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; armor = 400; displayName = $STR_BUILT_HEDGEHOG; vehicleClass = "DayZ Epoch Buildables"; constructioncount = 1; removeoutput[] = {{"ItemTankTrap",1}}; nounderground = 0; //Remove vanilla dismantle action class UserActions {delete Dismantle;}; }; class MetalPanel_DZ: BuiltItems { scope = 2; destrType = "DestructTree"; cost = 100; offset[] = {0,2.5,0.5}; model = "\ca\structures\wall\wall_indcnc2_3.p3d"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; armor = 4000; displayName = $STR_EPOCH_METALPANEL; vehicleClass = "DayZ Epoch Buildables"; constructioncount = 6; removeoutput[] = {{"metal_panel_kit",1}}; }; class Fort_RazorWire : BuiltItems { scope = 2; animated = 0; vehicleClass = "DayZ Epoch Buildables"; model = "\ca\misc\Fort_Razorwire"; icon = "\Ca\misc\data\icons\I_drutkolczasty_CA.paa"; offset[] = {0,1.5,0.5}; accuracy = 0.3; mapSize = 3; displayName = $STR_EPOCH_WIRE; destrType = "DestructTent"; armor = 100; GhostPreview = "Fort_RazorWirePreview"; nounderground = 0; }; class USMC_WarfareBMGNest_M240; class M240Nest_DZ: USMC_WarfareBMGNest_M240 { destrType = "DestructBuilding"; armor = 450; scope = 2; offset[] = {0,3.5,0}; displayName = $STR_EPOCH_M240NEST; vehicleClass = "DayZ Epoch Buildables"; transportMaxMagazines = 25; transportMaxWeapons = 4; transportMaxBackpacks = 1; constructioncount = 10; removeoutput[] = {{"m240_nest_kit",1}}; }; class WoodGate_DZ: BuiltItems { scope = 2; destrType = "DestructTree"; offset[] = {0,1.5,0.5}; model = "\ca\structures\Wall\Gate_wood2_5"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; armor = 100; displayName = "Wood Panel"; vehicleClass = "DayZ Epoch Buildables"; class AnimationSources { class DoorR { source = "User"; animPeriod = 1; initPhase = 0; }; }; class UserActions { class CloseDoor { position = ""; displayName = "Close Door"; radius = 1.5; onlyForPlayer = 0; condition = "this animationPhase 'DoorR' == 1"; statement = "this animate ['DoorR', 0];"; }; class OpenDoor { position = ""; displayName = "Open Door"; radius = 1.5; onlyForPlayer = 0; condition = "this animationPhase 'DoorR' == 0"; statement = "this animate ['DoorR', 1];"; }; }; }; class Notebook; class Notebook_DZ: Notebook { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_NOTEBOOK; constructioncount = 1; offset[] = {0,2,2}; removeoutput[] = {{"notebook_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Water_Pump_DZ: Land_pumpa { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_WATERPUMP; constructioncount = 1; offset[] = {0,2,0}; removeoutput[] = {{"water_pump_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class MAP_Misc_Greenhouse; class Greenhouse_DZ: MAP_Misc_Greenhouse { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_GREENHOUSE; constructioncount = 1; offset[] = {0,3,2}; removeoutput[] = {{"greenhouse_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class MAP_F_postel_panelak2; class Bed_DZ: MAP_F_postel_panelak2 { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_BED; constructioncount = 1; offset[] = {0,2,0}; removeoutput[] = {{"bed_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class MAP_stul_hospoda; class Table_DZ: MAP_stul_hospoda { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_TABLE; constructioncount = 1; offset[] = {0,2,0}; removeoutput[] = {{"table_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Office_Chair_DZ: BuiltItems { scope = 2; model = "\z\addons\dayz_epoch_v\base_building\storage\office_chair"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_CHAIR; constructioncount = 1; offset[] = {0,2,1}; removeoutput[] = {{"office_chair_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Land_MBG_Garage_Single_D; class Garage_Green_DZ: Land_MBG_Garage_Single_D { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_GARAGE_GREEN; constructioncount = 3; offset[] = {0,6,2}; removeoutput[] = {{"garage_green_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Land_MBG_Garage_Single_A; class Garage_White_DZ: Land_MBG_Garage_Single_A { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_GARAGE_WHITE; constructioncount = 3; offset[] = {0,6,2}; removeoutput[] = {{"garage_white_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Land_MBG_Garage_Single_B; class Garage_Brown_DZ: Land_MBG_Garage_Single_B { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_GARAGE_BROWN; constructioncount = 3; offset[] = {0,6,2}; removeoutput[] = {{"garage_brown_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Land_MBG_Garage_Single_C; class Garage_Grey_DZ: Land_MBG_Garage_Single_C { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_GARAGE_GREY; constructioncount = 3; offset[] = {0,6,2}; removeoutput[] = {{"garage_grey_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class HeliHCivil; class Helipad_Civil_DZ: HeliHCivil { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_HELIPAD_CIVIL; constructioncount = 1; offset[] = {0,4,0}; removeoutput[] = {{"helipad_civil_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class HeliHRescue; class Helipad_Rescue_DZ: HeliHRescue { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_HELIPAD_RESCUE; constructioncount = 1; offset[] = {0,4,0}; removeoutput[] = {{"helipad_rescue_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class MAP_Heli_H_army; class Helipad_Army_DZ: MAP_Heli_H_army { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_HELIPAD_ARMY; constructioncount = 1; offset[] = {0,4,0}; removeoutput[] = {{"helipad_army_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class MAP_Heli_H_cross; class Helipad_Cross_DZ: MAP_Heli_H_cross { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_HELIPAD_CROSS; constructioncount = 1; offset[] = {0,4,0}; removeoutput[] = {{"helipad_cross_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Sr_border; class Helipad_ParkBorder_DZ: Sr_border { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_HELIPAD_PARKBORDER; constructioncount = 1; offset[] = {0,4,0}; removeoutput[] = {{"helipad_parkborder_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; }; class Loudspeaker; class CCTV_DZ: Loudspeaker { scope = 2; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 2; displayName = $STR_EPOCH_CCTV; constructioncount = 2; offset[] = {0,4,0}; removeoutput[] = {{"cctv_kit",1}}; vehicleClass = "DayZ Epoch Buildables"; };
#include<bits/stdc++.h> using namespace std; queue<int>Q; queue<int>Q1; main() { int n, m, a, i, index; while(cin>>n>>m) { for(i=1; i<=n; i++) { cin>>a; Q.push(a); Q1.push(i); } while(!Q.empty()) { a= Q.front(); if(a<=m) { Q.pop(); index = Q1.front(); Q1.pop(); } else { Q.pop(); a = a-m; Q.push(a); i = Q1.front(); Q1.pop(); Q1.push(i); } } cout<<index<<endl; } return 0; }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int N = 1024; vector<int> g[N], sons[N]; int was[N], pr[N], IT; vector<int> req[N]; vector<pair<int, int> > forroot[N]; int n; int fs(int x) { if (pr[x] != x) pr[x] = fs(pr[x]); return pr[x]; } void dfs(int x) { was[x] = 1; for (int i = 0; i < g[x].size(); ++i) { int y = g[x][i]; if (was[y]) continue; dfs(y); pr[fs(y)] = x; } for (int i = 0; i < req[x].size(); ++i) { int y = req[x][i]; if (was[y] != 2) continue; forroot[fs(y)].push_back(make_pair(x, y)); } was[x] = 2; } int used[N]; int f[N], G[N]; int F[N][N]; vector<int> csons[N]; int fath[N]; int num[N]; inline void update(int& holder, int value) { if (holder < value) holder = value; } void rec(int x) { used[x] = IT; G[x] = 0; csons[x].clear(); int sons = 0; for (int i = 0; i < g[x].size(); ++i) { int y = g[x][i]; if (used[y] == IT) continue; rec(y); update(f[1 << sons], G[y]); num[y] = sons++; csons[x].push_back(y); fath[y] = x; } int lim = (1 << sons); for (int i = 0; i < forroot[x].size(); ++i) { int cx = forroot[x][i].first; int cy = forroot[x][i].second; //cerr << x << " " << cx << " " << cy << endl; int fx = fs(cx); int fy = fs(cy); int nx = num[fx]; int ny = num[fy]; if (cx == x) update(f[1 << ny], F[fy][cy] + 1); if (cy == x) update(f[1 << nx], F[fx][cx] + 1); update(f[(1 << nx) + (1 << ny)], F[fx][cx] + F[fy][cy] + 1); } for (int msk = 0; msk < lim; ++msk) { for (int i = 0; i < sons; ++i) { if (msk & (1 << i)) { update(f[msk], f[msk ^ (1 << i)] + f[1 << i]); for (int j = i + 1; j < sons; ++j) if (msk & (1 << j)) update(f[msk], f[msk ^ (1 << i) ^ (1 << j)] + f[(1 << i) + (1 << j)]); } } update(G[x], f[msk]); } for (int i = 0; i < n; ++i) { if (fath[fs(i)] == x) { F[x][i] = F[fs(i)][i] + f[(lim - 1) ^ (1 << num[fs(i)])]; } if (fath[i] == x) { F[x][i] = G[i]; } } for (int i = 0; i < csons[x].size(); ++i) { pr[fs(csons[x][i])] = x; } memset(f, 0, sizeof(f)); } int main() { freopen("in", "r", stdin); //freopen(".out", "w", stdout); int T; scanf("%d", &T); while (T--) { scanf("%d", &n); memset(f, 0, sizeof(f)); for (int i = 0; i < n; ++i) { used[i] = false; forroot[i].clear(); g[i].clear(); sons[i].clear(); req[i].clear(); was[i] = 0; G[i] = 0; for (int j = 0; j < n; ++j) F[i][j] = 0; } for (int i = 1; i < n; ++i) { int x, y; scanf("%d%d", &x, &y); --x; --y; g[x].push_back(y); g[y].push_back(x); } int m; scanf("%d", &m); while (m--) { int x, y; scanf("%d%d", &x, &y); --x; --y; req[x].push_back(y); req[y].push_back(x); } ++IT; for (int i = 0; i < n; ++i) pr[i] = i; dfs(0); for (int i = 0; i < n; ++i) pr[i] = i; rec(0); printf("%d\n", G[0]); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Arjan van Leeuwen */ #ifndef QUICK_ADDRESS_DROPDOWN_H #define QUICK_ADDRESS_DROPDOWN_H #include "adjunct/quick_toolkit/widgets/QuickTextWidget.h" #include "adjunct/quick/widgets/OpAddressDropDown.h" #include "modules/widgets/OpEdit.h" /** @brief An autocompleting dropdown for urls */ class QuickAddressDropDown : public QuickEditableTextWidgetWrapper<OpAddressDropDown> { typedef QuickEditableTextWidgetWrapper<OpAddressDropDown> Base; IMPLEMENT_TYPEDOBJECT(Base); public: virtual ~QuickAddressDropDown() { RemoveOpWidgetListener(*GetOpWidget()); } // The wrapped OpAddressDropDown needs to listen to itself to be able to // show the menu window. virtual OP_STATUS Init() { RETURN_IF_ERROR(Base::Init()); return AddOpWidgetListener(*GetOpWidget()); } // Implement QuickTextWidget virtual OP_STATUS SetText(const OpStringC& text) { return Base::GetOpWidget()->edit->SetText(text.CStr()); } protected: virtual unsigned GetDefaultMinimumWidth() { return Base::GetCharWidth(GetOpWidget(),70); } virtual unsigned GetDefaultPreferredWidth() { return WidgetSizes::Infinity; } }; #endif // QUICK_ADDRESS_DROPDOWN_H
#include "stdafx.h" #include "SequenceQuestion.h" using namespace qp; using namespace std; using Sequence = CSequenceQuestion::Sequence; CSequenceQuestion::CSequenceQuestion(const string & description, double score, const Sequence & sequence) :CQuestion(description, score) { if (sequence.size() < 3) { throw invalid_argument("minimal sequence length is 3"); } bool emptyNodeExists = (find(sequence.begin(), sequence.end(), "") != sequence.end()); if (emptyNodeExists) { throw invalid_argument("sequence node cannot be empty"); } set<string> uniqueNodes(sequence.begin(), sequence.end()); if (sequence.size() != uniqueNodes.size()) { throw invalid_argument("sequence contain duplicate nodes"); } m_sequence = sequence; } const Sequence & CSequenceQuestion::GetSequence()const { return m_sequence; } size_t CSequenceQuestion::GetSequenceLength()const { return m_sequence.size(); }
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; #define ll long long #define fi first #define se second #define pb push_back #define ALL(v) v.begin(), v.end() #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a)) #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a)) #define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a)) #define FOREACH(a, b) for (auto&(a) : (b)) #define REP(i, n) FOR(i, 0, n) #define REPN(i, n) FORN(i, 1, n) #define dbg(x) cout << (#x) << " is " << (x) << endl; #define dbg2(x, y) cout << (#x) << " is " << (x) << " and " << (#y) << " is " << y << endl; #define dbgarr(x, sz) \ for (int asdf = 0; asdf < (sz); asdf++) cout << x[asdf] << ' '; \ cout << endl; #define dbgarr2(x, rose, colin) \ for (int asdf2 = 0; asdf2 < rose; asdf2++) { \ dbgarr(x[asdf2], colin); \ } #define dbgitem(x) \ for (auto asdf = x.begin(); asdf != x.end(); asdf++) cout << *asdf << ' '; \ cout << endl; const int mod = 1e9 + 7; int n, m; bool A[100000], B[100000]; struct Solution { pair<vi, vi> solve() { vi order, turns; // dbg(n); for (int i = n - 1, j = m - 1, p = -1; i != -1 || j != -1;) { // p = prev card (from bottom) if (i == -1) { order.push_back(j + n), p = B[j--]; continue; } if (j == -1) { order.push_back(i), p = A[i--]; continue; } if (A[i] == p) order.push_back(i--); else if (B[j] == p) order.push_back(j-- + n); else if (A[i] == 0) // none equal p order.push_back(i--), p = 0; else order.push_back(j + n), p = B[j--]; } reverse(order.begin(), order.end()); int p = -1; for (int i = 0; i != n + m; ++i) { // p = prev card (from top) int x = order[i] < n ? A[order[i]] : B[order[i] - n]; if (x != p && p != -1) turns.push_back(i - 1); p = x; } if (p == 1) turns.push_back(n + m - 1); // turn them all to down return {order, turns}; } }; void print(vector<int>& nums, ofstream& fout) { for (auto num : nums) fout << num + 1 << " "; fout << endl; } int main() { ifstream fin; ios::sync_with_stdio(false); fin.open("input.txt"); fin >> n; REP(i, n) fin >> A[i]; fin >> m; REP(i, m) fin >> B[i]; ofstream fout; fout.open("output.txt"); Solution test; auto res = test.solve(); print(res.first, fout); fout << res.second.size() << endl; print(res.second, fout); }
#include<iostream> using namespace std; int binCloseSearch(int arr[],int l, int r,int x){ int mid=l+(r-l)/2; if(arr[mid]==x) return mid; else if(arr[mid]>arr[mid+1]){ if(x==arr[mid+1]) return mid+1; else if(x>arr[mid+1]){ binCloseSearch(arr,mid+2,r,x); } else{ binCloseSearch(arr,l,mid-1,x); } } else if(arr[mid]<arr[mid-1]){ if(x==arr[mid-1]) return m-1; else if(x<arr[mid-1]) binCloseSearch(arr,l,mid-2,x); else { binCloseSearch(arr,mid+1,r,x); } } else{ if(x>arr[mid]) binCloseSearch(arr,mid+1,r,x); else{ binCloseSearch(arr,l,mid-1,x); } } return -1; }
#include<bits/stdc++.h> using namespace std; main() { int n, s; while(cin>>n>>s) { int i, j=0, sum, array[200], f, t; for(i=1; i<=n; i++) { cin>>f>>t; sum = f+t; array[j] = sum; j++; } int max=0; for(int k=0; k<j; k++) { if(array[k]>max) max = array[k]; } if(max>=s) cout<<max<<endl; else cout<<s<<endl; } return 0; }
#ifndef RVSPECTORUS_H #define RVSPECTORUS_H #include "rvtorus.h" class RVSpecTorus : public RVTorus { public: RVSpecTorus(double smallRadius = 1.0, double bigRadius = 4.0); void setTorusTex(QString leftImage, QString rightImage, QString frontImage, QString backImage, QString topImage, QString bottomImage); }; #endif // RVSPECTORUS_H
#include<iostream> #include<fstream> #include<stdio.h> #include<vector> using namespace std; vector<long> flag_big; long getO(long t) { long result=1; while((t=long(t/10)) != 0) result *=10; return result; } long C(int base) { if(base <2) return 0; else { switch(base) { case 2: return 1; case 3: return 3; case 4: return 6; } } } void setflag(long b) { flag_big.push_back(b); } bool getflag(long b) { for(long k=0;k<flag_big.size();k++) { if(flag_big[k] == b) return false; } return true; } int main() { ofstream output("C-small-attempt0.out"); int n; long a[100],b[100]; //bool flag[10001]; ifstream fin("C-small-attempt0.in"); fin >> n; for(int i=0;i<n;i++) { long ar,br; fin>>ar; fin>>br; a[i]=ar; b[i]=br; } fin.close(); //for(int i=0;i<5001;i++) //flag[i]=true; for(int i=0;i<n;i++) { long count=0; int count_num; for(int j=a[i];j<=b[i];j++) { count_num=1; if(getflag(j)){ setflag(j); output<<j<<endl; long temp=(long)(j / 10); long remain = j % 10; long O=getO(j); long current = remain*O+temp; while(getflag(current)) { if(current>=a[i] && current<=b[i]){ count_num++; } setflag(current); temp=(long)(current / 10); remain = current % 10; current = remain*O+temp; } } count+=C(count_num); } output << "Case #"<<i+1<<": "<<count<<endl; //for(int s=0;s<10001;s++) //flag[s]=true; flag_big.clear(); } output.close(); return 0; }
#include "collisionEvent.h" collisionEvent::collisionEvent(GameObject a, GameObject b) { this->a = a; this->b = b; } GameObject collisionEvent::getObjA() { return a; } GameObject collisionEvent::getObjB() { return b; } eventType collisionEvent::getType() { return collisionEvent_type; } char collisionEvent::getKeyPress(){ return NULL; }
#include "bird.h" #include "timerlist.h" #include "dino.h" #include "game.h" #include "gameover.h" #include <QTimer> #include <QObject> #include <QGraphicsScene> #include <QGraphicsPixmapItem> #include <QGraphicsItem> #include <QList> #include <typeinfo> #include <math.h> #include <QDebug> extern Game *game; Bird::Bird(double moveSpeed, QString path1, QString path2): QObject(), QGraphicsPixmapItem() { this->path1 = path1; this->path2 = path2; int randomY = rand() % 3; setPosition(1300, randomY); this->moveSpeed = moveSpeed; initFly(); moveTimer = new QTimer(); // add Timer to list. Used to terminate all Timers if colliding allTimers->addToList(moveTimer); connect(moveTimer, SIGNAL(timeout()), this, SLOT(move())); moveTimer->start(35); } void Bird::setPosition(int x, int y) { if (y == 0) { setPos(x, 280); } else if (y == 1) { setPos(x, 330); } else if (y == 2) { setPos(x, 380); } } void Bird::setImage(QString path) { setPixmap(QPixmap(path)); setScale(0.70); } void Bird::initFly() { QTimer *timer = new QTimer(); allTimers->addToList(timer); connect(timer, SIGNAL(timeout()), this, SLOT(fly())); timer->start(160); } void Bird::fly() { if (counter % 2 == 0) { setImage(path1); } else { setImage(path2); } counter++; } void Bird::move() { // if bird collides with dino QList<QGraphicsItem *> items = collidingItems(); for (int i = 0; i < items.size(); i++) { if (typeid (*(items[i])) == typeid (Dino)) { QString path = ":/Image/dinoDead0000.png"; if(game->isChangeColor) { path = ":/Image/dinoDeadNegative0000.png"; } game->player->setImage(path); QList<QTimer *> timers = allTimers->getList(); GameOver *go = new GameOver(); scene()->addWidget(go->getLabel()); scene()->addWidget(go->getButton()); for (QTimer *timer : timers) { timer->stop(); } game->player->clearFocus(); } } setPos(x() - moveSpeed, y()); if (pos().x() + boundingRect().width() < 0) { scene()->removeItem(this); delete this; } }
#include<stdio.h> #include<stdlib.h> #include<conio.h> using namespace std; struct qnode { struct qnode *next,*prev; unsigned pagenumber; }; struct queue { unsigned count; unsigned totalframe; struct qnode *front,*rear; }; struct hash { unsigned capacity; struct qnode **arr; }; void dequeue(struct queue *q); struct qnode *createnode(unsigned pageno) { struct qnode *temp = (qnode *) malloc (sizeof(qnode)); temp->pagenumber = pageno; temp->next = temp->prev = NULL; return temp; } struct queue *createqueue(unsigned totalframe) { struct queue *q = (queue *) malloc ( sizeof(queue)); q->count = 0; q->front = q->rear = NULL; q->totalframe = totalframe; return q; } struct hash *createhash(unsigned capacity) { struct hash *h = (hash *) malloc(sizeof(hash)); h->capacity = capacity; h->arr = (qnode **)malloc(h->capacity * sizeof(qnode *)); for(int i=0;i<h->capacity;++i) h->arr[i] = NULL; return h; } int allframefull(queue *queue) { return queue->count == queue->totalframe; } int allframeempty(queue *queue) { return queue->rear == NULL; } void enqueue(struct queue *q,struct hash *h,unsigned pagenumber) { if(allframefull(q)) { h->arr[q->rear->pagenumber] = NULL; dequeue(q); } struct qnode *temp = createnode(pagenumber); temp->next = q->front; if(allframeempty(q)) { q->front = q->rear = temp; } q->front->prev = temp; q->front = temp; //hash it and incr the count h->arr[pagenumber] = temp; q->count++; } void dequeue(struct queue *q) { if(allframeempty(q)) return; if(q->front == q->rear) { q->front = NULL; } struct qnode *temp = q->rear; q->rear = q->rear->prev; q->rear->next = NULL; free(temp); q->count--; } void requestpage(struct queue *q,struct hash *h,unsigned pgno) { struct qnode *reqpage = h->arr[pgno]; if(reqpage == NULL) { enqueue(q,h,pgno); } else if(reqpage != q->front) { reqpage->prev->next = reqpage->next; if(reqpage->next) { reqpage->next->prev = reqpage->prev; } if(q->rear == reqpage) { q->rear = q->rear->prev; q->rear->next = NULL; } reqpage->next = q->front; reqpage->next->prev = reqpage; reqpage->prev = NULL; q->front = reqpage; } } int main() { // Let cache can hold 4 pages queue* q = createqueue( 4 ); // Let 10 different pages can be requested (pages to be // referenced are numbered from 0 to 9 hash* hash = createhash( 10 ); // Let us refer pages 1, 2, 3, 1, 4, 5 requestpage( q, hash, 1); requestpage( q, hash, 2); requestpage( q, hash, 3); requestpage( q, hash, 1); requestpage( q, hash, 4); requestpage( q, hash, 5); // Let us print cache frames after the above referenced pages printf ("%d ", q->front->pagenumber); printf ("%d ", q->front->next->pagenumber); printf ("%d ", q->front->next->next->pagenumber); printf ("%d ", q->front->next->next->next->pagenumber); getch(); }
#pragma once #include "Defines.h" #include <string> using namespace std; class BasePeer { public: BasePeer(int input_buffer_size); ~BasePeer(); SOCKET getPeerSocket(); void InitializeSocket(); int GetLastErrorCode(); void Close(SOCKET handle); bool Bind(short port); bool Listen(int max_connections); SOCKET Connect(string remote_address, short port); int Send(SOCKET handle, unsigned char* buffer, int length); bool Update(); void SetCallbacks(void (*on_recv)(SOCKET handle, unsigned char* buffer, int length), void(*on_connect)(SOCKET handle), void(*on_disconnect)(SOCKET handle)); private: int max_connections_; SOCKET socket_handle_; struct sockaddr_in socketAddr_; int input_buffer_size_; unsigned char* input_buffer_; bool is_listening_; fd_set main_fds_; fd_set read_fds_; //unsigned integer to keep track of maximum fd value, required for select() unsigned short max_fds_; void (*on_connect_callback) (SOCKET fd); void (*on_recv_callback) (SOCKET fd, unsigned char* buffer, int length); void (*on_disconnect_callback) (SOCKET fd); int Poll(); bool UpdateServer(); bool UpdateClient(); int RecvFromConnection(SOCKET handle); void HandleNewConnection(); void PrintError(const char* pcMessagePrefix); };
#ifndef ECLAT_H #define ECLAT_H #include <bitset> #include <unordered_map> #include <vector> const int MAX_ITEM_LEN = 100; const int MAX_INPUT_LINE = 3200; using namespace std; using std::bitset; using std::unordered_map; class Eclat { private: unordered_map<int, bitset<MAX_INPUT_LINE>> inverted_list; vector<bitset<MAX_ITEM_LEN>> L1_item; vector<bitset<MAX_INPUT_LINE>> L1_index; int ans = 0; double min_sup = 0; public: Eclat(bitset<MAX_ITEM_LEN> input[], int line_ans, double sup); ~Eclat(); void genL1(); void genFreq(vector<bitset<MAX_ITEM_LEN>> Lk_item, vector<bitset<MAX_INPUT_LINE>> Lk_index, int num); void getResult(); }; #endif
#include<iostream> #include<vector> #include<algorithm> #include<set> #include<string> using namespace std; class Solution { public: string getHint(string secret, string guess) { //基本思想:第一次遍历用multiset将secret每个出现过的数字保存起来,第二次遍历看guess中数字是否存在于multiset计算countB string res; int countA=0; int countB=0; multiset<char> Set; for(int i=0;i<secret.size();i++) { if(secret[i]==guess[i]) countA++; else Set.insert(secret[i]); } for(int i=0;i<secret.size();i++) { if(secret[i]==guess[i]) continue; multiset<char>::iterator pos = Set.find(guess[i]); if(pos!=Set.end()) { countB++; Set.erase(pos); } } res+=to_string(countA); res.push_back('A'); res+=to_string(countB); res.push_back('B'); return res; } }; class Solution1 { public: string getHint(string secret, string guess) { //基本思想:桶思想,bukets存储secret和guess中所有数字出现次数,如果出现在secret该数字出现次数++,如果出现在guess该数字出现次数-- //当bukets[guess[i]-'0']>0说明该数字在secret中出现过,guess[i]又出现过,所以countB++ //当bukets[secret[i]-'0']<0说明该数字在guess中出现过,secret[i]又出现过,所以countB++ string res; int countA=0; int countB=0; int[10] bukets={0}; for(int i=0;i<secret.size();i++) { if(secret[i]==guess[i]) countA++; else { //bukets[guess[i]-'0']>0说明数字guess[i]在secret中出现过,guess[i]又出现过,所以countB++ if(bukets[guess[i]-'0']>0) countB++; //bukets[secret[i]-'0']<0说明数字secret[i]在guess中出现过,secret[i]又出现过,所以countB++ if(bukets[secret[i]-'0']<0) countB++; bukets[guess[i]-'0']--; bukets[secret[i]-'0']++; } } res+=to_string(countA); res.push_back('A'); res+=to_string(countB); res.push_back('B'); return res; } }; int main() { Solution solute; string secret="1807"; string guess="7810"; cout<<solute.getHint(secret,guess)<<endl; return 0; }
#include "pch.h" #include "RenderDevice.h" namespace Hourglass { RenderDevice g_RenderDev; ComPtr<ID3D11InputLayout> g_InputLayouts[kVertexDeclCount]; ComPtr <ID3D11BlendState> g_BlendState[kBlendStateCount]; ComPtr<ID3D11SamplerState> g_SamplerState[kSamplerStateCount]; RenderShader g_RenderShaders[kRenderShaderCount]; ComPtr<ID3D11ComputeShader> g_ComputeShaders[kComputeShaderCount]; }
// RsaToolbox #include "Vna.h" using namespace RsaToolbox; // Qt #include <QCoreApplication> #include <QDir> void main() { Vna vna(ConnectionType::VisaTcpConnection, "127.0.0.1"); // Start from instrument preset vna.preset(); vna.pause(); // Get Trc1 interface VnaTrace trc1 = vna.trace("Trc1"); // Set Parameter // for single-ended ports. // Example: S21 trc1.setSParameter(2, 1); // Set S-Parameter // for balanced ports // Note: Balanced ports must // be defined in channel. // See channel example. // Type options: // SingleEnded // Differential // Common // Example: Sdd21 BalancedPort port1(1, BalancedPort::Type::Differential); BalancedPort port2(2, BalancedPort::Type::Differential); // trc1.setSParameter(port2, port1); // Set impedance trace // for single ended ports // Example: Z-S11 trc1.setImpedance(1, 1); // Set impedance trace // for balanced ports // Example: Z-Sdd11 // trc1.setImpedance(port1, port1); // Set display format // Options: // DecibelMagnitude, // Phase, // SmithChart, // PolarChart, // Vswr, // UnwrappedPhase, // Magnitude, // InverseSmithChart, // Real, // Imaginary, // Delay trc1.setFormat(TraceFormat::DecibelMagnitude); // Save data to csv locally. // Data is as displayed (e.g. dB) QDir src(SOURCE_DIR); trc1.saveCsvLocally(src.filePath("formatted_data.csv")); // Save complex data to csv locally // Data is complex regardless of // the format of the trace. // ComplexFormat: // DecibelDegrees // MagnitudeDegrees // RealImaginary trc1.saveComplexCsvLocally(src.filePath("complex_data.csv"), ComplexFormat::DecibelDegrees); }
#include <memory> int main() { std::unique_ptr<int> u(new int(0)); return *u; }
#include "Berserker.h" Berserker::Berserker(string nom, int force) : Personnage(nom), _force(force) { } Berserker::~Berserker() { } void Berserker::sePresenter() const { Personnage::sePresenter(); cout << "J'ai également " << _force << " points de force" << endl; cout << "Ma devise : l'attaque est la meilleure des défenses" << endl << endl; } void Berserker::attaquer(Personnage* cible) const { cible->recevoirDegats(_force); }
/* -*- 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. */ #ifndef DOM_EXTENSIONS_EXTENSIONMANAGER_H #define DOM_EXTENSIONS_EXTENSIONMANAGER_H #ifdef EXTENSION_SUPPORT #include "modules/dom/src/domruntime.h" #include "modules/util/OpHashTable.h" #include "modules/dom/src/extensions/domextensionsupport.h" #include "modules/dom/src/extensions/domextensionmenuitem.h" class DOM_ExtensionBackground; /** DOM_ExtensionManager - tracking active extensions. In order to support communication between a window and its background extension, an extension is notified when a new window is activated. This is recorded via the 'extension manager', which the opera.* object of DOM environments within the window will see. If found, it can then set up the connection and start communicating. When the environments on the window's side disappear, they unregister via this manager, causing the association between the window and extension to be dropped. The extension manager cuts across DOM environments, and the single instance is kept at the DOM module level. It may not end up being the long-term solution for brokering UI window <-> extension communication. */ class DOM_ExtensionManager : public OpHashTableForEachListener { public: static OP_STATUS Make(DOM_ExtensionManager *&new_obj); virtual ~DOM_ExtensionManager(); OP_STATUS AddExtensionContext(Window *window, DOM_Runtime *runtime, DOM_ExtensionBackground **background); /**< Create and add the correct extension context (opera.extension.*) to the opera object of the corresponding runtime. No context will be added if the window is not associated with a gadget. @param window the window. @param runtime the runtime of this background extension context. @param[out] background the background extension object. @return OpStatus::OK on success, OpStatus::ERR_NO_MEMORY on OOM condition. */ void RemoveExtensionContext(DOM_ExtensionSupport *support); /**< Remove the background process' extension context and notify the extension contexts of all other environments associated to the given extension background object that it's being shutdown (so they can dispatch disconnection events and the such). */ void RemoveExtensionContext(DOM_EnvironmentImpl *environment); /**< Remove the extension context associated with the given environment. This is called by the environment itself when shutting down. */ DOM_ExtensionSupport *GetExtensionSupport(OpGadget *gadget); /**< Get the extension support for the given gadget. */ static void Shutdown(DOM_ExtensionManager *manager); /**< Perform clean up and shut down; run upon module shutdown. */ static OP_STATUS Init(); /**< Create and initialise the singleton extension manager instance */ // From OpHashTableForEachListener virtual void HandleKeyData(const void *key, void *data); #ifdef DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT OP_STATUS AppendExtensionMenu(OpWindowcommanderMessages_MessageSet::PopupMenuRequest::MenuItemList& menu_items, OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element); /**< Fills a vector of menu items which extensions(via ContextMenu API) requested * to add to the context menu. * * @param menu_items List of menu items to which the menu items will be added. * @param document_context Context in which the menu has been requested. * @param document Document for which the menu has been requested. * @param element Element for which the menu has been requested. May be NULL. * @return * OpStatus::OK * OpStatus::ERR_NO_MEMORY */ #endif // DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT private: class ExtensionBackgroundInfoElement { public: ExtensionBackgroundInfoElement(DOM_ExtensionSupport *extension_support) : m_extension_support(extension_support) { } OpVector<DOM_EnvironmentImpl> m_connections; /**< The environments associated with this extension background that * may need something done when the extension background shuts down * (e.g. sending ondisconnect events to the DOM_ExtensionPageContext). */ OpSmartPointerWithDelete<DOM_ExtensionSupport> m_extension_support; }; OpPointerHashTable<OpGadget, ExtensionBackgroundInfoElement> m_extensions; /**< Mapping from a gadget to the background process' extension context. */ }; #endif // EXTENSION_SUPPORT #endif // DOM_EXTENSIONS_EXTENSIONMANAGER_H
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10550" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int start,one,two,three; while( ~scanf("%d %d %d %d",&start,&one,&two,&three) ){ if( start == 0 && one == 0 && two == 0 && three == 0 ) break; int ans = 120; while( start != one ){ start--; if( start == -1 ) start = 39; ans++; } while( start != two ){ start++; if( start == 40 ) start = 0; ans++; } while( start != three ){ start--; if( start == -1 ) start = 39; ans++; } printf("%d\n",ans*9 ); } return 0; }
RENDER_PLANET(RenderTrianglePlanet); // Returns size_in_tris int InitTrianglePlanetMesh(DrawItem &draw_item) { const int splits = 5; // configurable const int size_in_tris = 1 << splits; const int size_in_verts = size_in_tris + 1; const int verts_total = size_in_verts * (size_in_verts + 1) / 2 + size_in_verts * 3; const int indices_total = (size_in_tris * size_in_tris) * 3 + size_in_tris * 2 * 3 * 3; Vec3 verts[verts_total]; { int n = 0; double ydiv = 1.0 / size_in_tris; double div = 1.0 / (size_in_verts - 1); for (int x = 0; x < size_in_verts; x++) verts[n++] = V3(x*div, 0.0f, 1.0f); for (int y = 0; y < size_in_verts - 1; ++y) { int row_in_verts = size_in_verts - y; double xdiv = 1.0 / (row_in_verts - 1); verts[n++] = V3(0.0f, y*ydiv, 1.0f); for (int x = 0; x < row_in_verts; ++x) verts[n++] = V3(x*xdiv, y*ydiv, 0.0f); verts[n++] = V3(1.0f, y*ydiv, 1.0f); } verts[n++] = V3(0.0f, 1.0f, 1.0f); verts[n++] = V3(0.0f, 1.0f, 0.0f); verts[n++] = V3(1.0f, 1.0f, 1.0f); assert(n == verts_total); } uint32_t indices[indices_total]; { int n = 0; uint32_t v0 = 0; uint32_t v1 = size_in_verts + 1; #define TRI(a, b, c) indices[n++] = a; indices[n++] = b; indices[n++] = c; for (int x = 0; x < size_in_tris; x++) { TRI(v0, v1, v0 + 1); TRI(v0 + 1, v1, v1 + 1); v0++; v1++; } v0 += 1; v1 += 2; for (int y = 0; y < size_in_tris; ++y) { int row_in_tris = size_in_tris - y; for (int x = 0; x < row_in_tris + 1; ++x) { TRI(v0, v1, v0 + 1); TRI(v0 + 1, v1, v1 + 1); v0++; v1++; } TRI(v0, v1, v0 + 1); v0 += 2; v1 += 1; } #undef TRI assert(v0 < verts_total); assert(v1 == verts_total); assert(n == indices_total); } VertexFormat vf = {}; AddVertexAttribute(vf, 0, 3, GL_FLOAT, false); GLuint vertex_buffer = CreateVertexBuffer(sizeof(verts), verts); GLuint index_buffer = CreateIndexBuffer(sizeof(indices), indices); GLuint vertex_array = CreateVertexArray(vertex_buffer, vf, index_buffer); draw_item.vertex_array = vertex_array; draw_item.primitive_mode = GL_TRIANGLES; draw_item.index_type = GL_UNSIGNED_INT; draw_item.first = 0; draw_item.count = indices_total; draw_item.draw_arrays = false; return size_in_tris; } void ProcessTriangle(Planet &planet, const Node &tri, const CameraInfo &cam, int lod) { if (lod == 0) { // No more splitting PlanetAddLeafNode(planet, tri); return; } Vec3d mid_n = Normalize(tri.p[0] + tri.p[1] + tri.p[2]); Vec3d mid = mid_n * planet.radius; Vec3d p[4]; for (int i = 0; i < 3; i++) { float height = planet.hmap_gen.GetHeightAt(tri.p[i], 0, 1); p[i] = tri.p[i] + Normalize(tri.p[i]) * height; } float height = planet.hmap_gen.GetHeightAt(mid, 0, 1); p[3] = mid + mid_n * height; AABB box = AABB::CreateEmpty(); for (int i = 0; i < 4; i++) { box.AddPoint(p[i]); } if (!cam.BoxInsideFrustum(box)) { return; } if (box.DistanceToPoint(cam.position) > 1.7*box.Diameter()) { PlanetAddLeafNode(planet, tri); return; } // Do split #define VERT(i, j) Normalize(tri.p[i] + tri.p[j]) * planet.radius #define TRI(a, b, c, id) (Node){verts[a], verts[b], verts[c], {}, id} Vec3d verts[] = { tri.p[0], VERT(0, 1), tri.p[1], VERT(0, 2), VERT(1, 2), tri.p[2] }; ProcessTriangle(planet, TRI(0, 1, 3, MakeChildID(tri.id, 0)), cam, lod - 1); ProcessTriangle(planet, TRI(1, 2, 4, MakeChildID(tri.id, 1)), cam, lod - 1); ProcessTriangle(planet, TRI(3, 1, 4, MakeChildID(tri.id, 2)), cam, lod - 1); ProcessTriangle(planet, TRI(3, 4, 5, MakeChildID(tri.id, 3)), cam, lod - 1); #undef VERT #undef TRI } // // Render triangle planet // RENDER_PLANET(RenderTrianglePlanet) { ListResize(planet.nodes, 0); #define VERT(x, y, z) Normalize(V3d(x, y, z)) * planet.radius #define TRI(a, b, c, id) (Node){verts[a], verts[b], verts[c], {}, id} #if 1 // kelvin structure Vec3d verts[] = { VERT( 0, 2, -1), // 0 VERT( 1, 2, 0), // 1 VERT( 0, 2, 1), // 2 VERT(-1, 2, 0), // 3 VERT( 0, 1, -2), // 4 VERT(-1, 0, -2), // 5 VERT( 0, -1, -2), // 6 VERT( 1, 0, -2), // 7 VERT( 2, 1, 0), // 8 VERT( 2, 0, -1), // 9 VERT( 2, -1, 0), // 10 VERT( 2, 0, 1), // 11 VERT(-2, 1, 0), // 12 VERT(-2, 0, 1), // 13 VERT(-2, -1, 0), // 14 VERT(-2, 0, -1), // 15 VERT( 0, 1, 2), // 16 VERT( 1, 0, 2), // 17 VERT( 0, -1, 2), // 18 VERT(-1, 0, 2), // 19 VERT( 0, -2, 1), // 20 VERT( 1, -2, 0), // 21 VERT( 0, -2, -1), // 22 VERT(-1, -2, 0), // 23 {}, // 24 {}, // 25 {}, // 26 {}, // 27 {}, // 28 {}, // 29 {}, // 30 {}, // 31 }; int id = 0; #define TRIANGLE(a, b, c) \ ProcessTriangle(planet, TRI(a, b, c, MakeRootID(id++)), cam, planet.max_lod) #define QUAD(a, b, c, d) \ TRIANGLE(a, b, d); TRIANGLE(d, b, c) #define HEX(a, b, c, d, e, f, mid) \ verts[mid] = Normalize(verts[a] + verts[d]) * planet.radius; \ TRIANGLE(a, b, mid); TRIANGLE(b, c, mid); \ TRIANGLE(c, d, mid); TRIANGLE(d, e, mid); \ TRIANGLE(e, f, mid); TRIANGLE(f, a, mid) QUAD( 0, 1, 2, 3); QUAD( 4, 5, 6, 7); QUAD( 8, 9, 10, 11); QUAD(12, 13, 14, 15); QUAD(16, 17, 18, 19); QUAD(20, 21, 22, 23); HEX( 0, 4, 7, 9, 8, 1, 24); HEX( 1, 8, 11, 17, 16, 2, 25); HEX( 2, 16, 19, 13, 12, 3, 26); HEX( 3, 12, 15, 5, 4, 0, 27); HEX( 7, 6, 22, 21, 10, 9, 28); HEX(11, 10, 21, 20, 18, 17, 29); HEX(19, 18, 20, 23, 14, 13, 30); HEX(15, 14, 23, 22, 6, 5, 31); #undef QUAD #else // cube Vec3d verts[] = { VERT(-1, -1, -1), // 0 VERT( 1, -1, -1), // 1 VERT( 1, 1, -1), // 2 VERT(-1, 1, -1), // 3 VERT(-1, -1, 1), // 4 VERT( 1, -1, 1), // 5 VERT( 1, 1, 1), // 6 VERT(-1, 1, 1), // 7 }; ProcessTriangle(planet, TRI(0, 1, 3, MakeRootID(0)), cam, planet.max_lod); ProcessTriangle(planet, TRI(3, 1, 2, MakeRootID(1)), cam, planet.max_lod); ProcessTriangle(planet, TRI(5, 4, 6, MakeRootID(2)), cam, planet.max_lod); ProcessTriangle(planet, TRI(6, 4, 7, MakeRootID(3)), cam, planet.max_lod); ProcessTriangle(planet, TRI(4, 0, 7, MakeRootID(4)), cam, planet.max_lod); ProcessTriangle(planet, TRI(7, 0, 3, MakeRootID(5)), cam, planet.max_lod); ProcessTriangle(planet, TRI(1, 5, 2, MakeRootID(6)), cam, planet.max_lod); ProcessTriangle(planet, TRI(2, 5, 6, MakeRootID(7)), cam, planet.max_lod); ProcessTriangle(planet, TRI(3, 2, 7, MakeRootID(8)), cam, planet.max_lod); ProcessTriangle(planet, TRI(7, 2, 6, MakeRootID(9)), cam, planet.max_lod); ProcessTriangle(planet, TRI(4, 5, 0, MakeRootID(10)), cam, planet.max_lod); ProcessTriangle(planet, TRI(0, 5, 1, MakeRootID(11)), cam, planet.max_lod); #endif #undef VERT #undef TRI PlanetFinishHeightMaps(planet); Planet::RenderComponent &component = planet.render.triangle; component.uniforms.proj.value.m4 = cam.projection; component.uniforms.view.value.m4 = cam.view; for (int i = 0; i < planet.nodes.num; ++i) { Node &tri = planet.nodes.data[i]; TextureRect rect = GetHeightMapForNode(planet, tri); planet.textures.height_map.texture = rect.texture; component.uniforms.height_map.corners.value.v2[0] = rect.corners[0]; component.uniforms.height_map.corners.value.v2[1] = rect.corners[1]; for (int j = 0; j < 3; ++j) { Vec3d p = tri.p[j] - cam.position; Vec3d n = Normalize(tri.p[j]); component.uniforms.p.value.v3[j] = V3(p); component.uniforms.n.value.v3[j] = V3(n); } float skirt_size = planet.max_skirt_size; int depth = GetDepth(tri.id) - 1 - rect.depth_diff; if (depth > 0) skirt_size /= (2 << depth); component.uniforms.skirt_size.value.f[0] = skirt_size; Draw(component.patch); } }
// // NodoBB.h // Arboles // // Created by Daniel on 20/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #ifndef __Arboles__NodoBB__ #define __Arboles__NodoBB__ #include <iostream> template <class T> class NodoB; template <class T> std::ostream & operator <<(std::ostream &, NodoB<T> &); template <class T> class NodoB{ private: T info; NodoB<T> * izquierdo; NodoB<T> * derecho; public: NodoB(); NodoB(T info); ~NodoB(); T getInfo(); void setInfo(T value); NodoB<T>* getIzquierdo(); NodoB<T>* getDerecho(); void setIzquierdo(NodoB<T> * value); void setDerecho(NodoB<T> * value); friend std::ostream & operator << <>(std::ostream &, NodoB<T> &); }; template <class T> NodoB<T>::NodoB(){ this->izquierdo = this->derecho = nullptr; } template <class T> NodoB<T>::NodoB(T info){ this-> info = info; this->izquierdo = this->derecho = nullptr; } template <class T> NodoB<T>::~NodoB(){ izquierdo = derecho = nullptr; } template <class T> T NodoB<T>::getInfo(){ return info; } template <class T> void NodoB<T>::setInfo(T value){ info = value; } template <class T> NodoB<T>* NodoB<T>::getIzquierdo(){ return izquierdo; } template <class T> NodoB<T>* NodoB<T>::getDerecho(){ return derecho; } template <class T> void NodoB<T>::setIzquierdo(NodoB<T> *value){ izquierdo = value; } template <class T> void NodoB<T>::setDerecho(NodoB<T> *valor){ derecho = valor; } template <class T> std::ostream & operator <<(std::ostream & os, NodoB<T> & NodoB){ os << NodoB.info; return os; } #endif /* defined(__Arboles__NodoBBB__) */
/* Copyright (c) 2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "DirectoryComparisonTestCheck.hpp" #include "FileComparisonTestCheck.hpp" #include "Test.hpp" #include <Ishiko/FileSystem.hpp> using namespace Ishiko; DirectoryComparisonTestCheck::DirectoryComparisonTestCheck() { } DirectoryComparisonTestCheck::DirectoryComparisonTestCheck(boost::filesystem::path outputDirectoryPath, boost::filesystem::path referenceDirectoryPath) : m_outputDirectoryPath(std::move(outputDirectoryPath)), m_referenceDirectoryPath(std::move(referenceDirectoryPath)) { } void DirectoryComparisonTestCheck::run(Test& test, const char* file, int line) { m_result = Result::failed; if (!FileSystem::Exists(m_outputDirectoryPath)) { // TODO: more info, check which files are added or missing test.fail(file, line); return; } if (!FileSystem::Exists(m_referenceDirectoryPath)) { // TODO: more info, check which files are added or missing test.fail(file, line); return; } Directory outputDirectory(m_outputDirectoryPath); Directory referenceDirectory(m_referenceDirectoryPath); // TODO: this is a qucik working implementation to be done with it but ideally I'd like the following behaviour. // 1. We only iterate through the each directory once. // 2. We first check if there are differences in files and then we consider extra or missing files. I think this is // more informative for the user in general. size_t outputFilesCount = outputDirectory.getRegularFilesCount(false); size_t referenceFilesCount = referenceDirectory.getRegularFilesCount(false); if (outputFilesCount != referenceFilesCount) { // TODO: more info, check which files are added or missing test.fail(file, line); return; } // TODO: limit the number of files bool allCheckPassed = true; referenceDirectory.forEachRegularFile( [this, &test, file, line, &allCheckPassed](const boost::filesystem::path& referenceFilePath) { boost::filesystem::path outputFilePath = m_outputDirectoryPath / referenceFilePath.filename(); std::shared_ptr<FileComparisonTestCheck> check = std::make_shared<FileComparisonTestCheck>(outputFilePath, referenceFilePath); // TODO: if I add this to the test then I get automatic reporting of each file check->run(test, file, line); if (check->result() == TestCheck::Result::failed) { allCheckPassed = false; } }, false); if (allCheckPassed) { m_result = Result::passed; } } const boost::filesystem::path& DirectoryComparisonTestCheck::outputDirectoryPath() const { return m_outputDirectoryPath; } void DirectoryComparisonTestCheck::setOutputDirectoryPath(const boost::filesystem::path& path) { m_outputDirectoryPath = path; } const boost::filesystem::path& DirectoryComparisonTestCheck::referenceDirectoryPath() const { return m_referenceDirectoryPath; } void DirectoryComparisonTestCheck::setReferenceDirectoryPath(const boost::filesystem::path& path) { m_referenceDirectoryPath = path; }
#pragma once #include "XPBDConstraints.h" #include <cuda_runtime.h> #include <nclgl\Vector4.h> #include <vector> struct CudaTextureWrapper { CudaTextureWrapper() : mem(NULL), tex(NULL), surface(NULL) {} cudaArray* mem; cudaTextureObject_t tex; cudaSurfaceObject_t surface; void allocate( cudaChannelFormatDesc& desc, uint width, uint height); void allocate3D( cudaChannelFormatDesc& desc, cudaExtent ce); }; class XPBD; class XPBD_ConstraintLayer { public: XPBD_ConstraintLayer(); ~XPBD_ConstraintLayer(); void Initialize(XPBD* parent, int step); void Release(); void GenerateData(Vector4* initial_positions); void ResetLambda(); bool Solve(int iterations, cudaTextureObject_t positions, cudaTextureObject_t positionstmp, cudaStream_t stream1, cudaStream_t stream2); //returns true if positions/positionstmp have swapped protected: void GenerateConstraints(Vector4* initial_positions); void GenerateCudaArrays(Vector4* initial_positions); XPBDDistanceConstraint BuildDistanceConstraint(const Vector4* positions, uint2 idxA, uint2 idxB, float k); XPBDBendingConstraint BuildBendingConstraint(const Vector4* positions, uint2 idxA, uint2 idxB, uint2 idxC, float k); XPBDBendDistConstraint BuildBendingDistanceConstraint(const Vector4* positions, uint2 idxA, uint2 idxB, uint2 idxC, float k_bend, float k_stretch); uint GetGridIdx(const uint2& grid_ref); uint2 GenGridRef(uint x, uint y); public: int m_NumX, m_NumY; float k_weft, k_warp, k_shear, k_bend; std::vector<XPBDDistanceConstraint> m_DistanceConstraints; std::vector<XPBDBendingConstraint> m_BendingConstraints; std::vector<XPBDBendDistConstraint> m_BendingDistanceConstraints; float* m_cuDistanceLambdaij; float* m_cuBendingLambdaij; XPBDDistanceConstraint* m_cuDistanceConstraints; XPBDBendingConstraint* m_cuBendingConstraints; XPBDBendDistConstraint* m_cuBendingDistanceConstraints; CudaTextureWrapper m_cuMipMapParticles; CudaTextureWrapper m_cuMipMapParticlesOld; #if XPBD_USE_BATCHED_CONSTRAINTS std::vector<uint2> m_DistanceConstraintBatches; std::vector<uint2> m_BendingConstraintBatches; std::vector<uint2> m_BendingDistanceConstraintBatches; #else float3* m_cuConstraintOutput; uint2* m_cuConstraintLookups; //Particle -> OutputLookups uint* m_cuConstraintOutputLookups; //Particle -> Constraint Output List #endif protected: XPBD* m_Parent; int m_Step; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2004 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" #ifdef _SUPPORT_PROXY_NTLM_AUTH_ #define SECURITY_WIN32 #include "modules/url/url2.h" #include "modules/url/url_man.h" #include "modules/formats/argsplit.h" #include "modules/formats/hdsplit.h" #include "modules/formats/base64_decode.h" #include "modules/formats/encoder.h" #include "modules/url/protocols/http1.h" #include "modules/url/protocols/http_req2.h" #include "modules/auth/auth_elm.h" #include "platforms/windows/auth/auth_ntlm.h" AuthScheme CheckAuthenticateName(const char *name); void ShutdownNTLMAUth() { NTLM_AuthElm::Terminate(); } BOOL SetUpNTLM_NegotiateL(BOOL proxy, HeaderList &headers, HTTP_Request *request, BOOL &set_waiting, AuthElm *auth_element, BOOL first_request) { BOOL ret = FALSE; set_waiting = FALSE; ParameterList *ntlm_params = NULL; ParameterList *negotiate_params = NULL; HeaderEntry *header = headers.GetHeaderByID((proxy ? HTTP_Header_Proxy_Authenticate : HTTP_Header_WWW_Authenticate),NULL); while(header) { ParameterList *params = header->GetParameters((PARAM_SEP_COMMA | PARAM_WHITESPACE_FIRST_ONLY | PARAM_STRIP_ARG_QUOTES | PARAM_NO_ASSIGN), KeywordIndex_Authentication);//FIXME:OOM-yngve Can return NULL due to OOM, should this be signalled? if(params && params->First()) { Parameters *param = params->First(); AuthScheme scheme = (AuthScheme) param->GetNameID(); switch(scheme) { case AUTH_SCHEME_HTTP_NEGOTIATE: if(!negotiate_params) { negotiate_params = params; } break; case AUTH_SCHEME_HTTP_NTLM: if(/*proxy && */!ntlm_params) { ntlm_params = params; } break; case AUTH_SCHEME_HTTP_UNKNOWN: case AUTH_SCHEME_HTTP_BASIC: break; default: { // Basic does not override NTLM, Digest and more advanced (known) methods do. ntlm_params = NULL; negotiate_params = NULL; HeaderEntry *next_header = headers.GetHeaderByID((proxy ? HTTP_Header_Proxy_Authenticate : HTTP_Header_WWW_Authenticate),NULL); while(next_header) { header = next_header; next_header = headers.GetHeaderByID(0, header); ParameterList *params = header->GetParameters((PARAM_SEP_COMMA | PARAM_WHITESPACE_FIRST_ONLY | PARAM_STRIP_ARG_QUOTES | PARAM_NO_ASSIGN), KeywordIndex_Authentication);//FIXME:OOM-yngve Can return NULL due to OOM, should this be signalled? if(params && params->First()) { Parameters *param = params->First(); AuthScheme scheme = (AuthScheme) param->GetNameID(); if(scheme == AUTH_SCHEME_HTTP_NEGOTIATE || scheme == AUTH_SCHEME_HTTP_NTLM) { header->Out(); delete header; } } } header = NULL; goto finished_ntlm_search; } } } header = headers.GetHeaderByID(0, header); } finished_ntlm_search:; if(ntlm_params || negotiate_params) { if(auth_element) { if(negotiate_params && (auth_element->GetScheme() & AUTH_SCHEME_HTTP_MASK) != AUTH_SCHEME_HTTP_NTLM) { if(negotiate_params->Cardinal() == 1) { set_waiting = TRUE; if(first_request) return FALSE; } else LEAVE_IF_ERROR(auth_element->Update_Authenticate(negotiate_params)); } if(ntlm_params && (auth_element->GetScheme() & AUTH_SCHEME_HTTP_MASK) != AUTH_SCHEME_HTTP_NEGOTIATE) { if(ntlm_params->Cardinal() == 1) { set_waiting = TRUE; if(first_request) return FALSE; } else LEAVE_IF_ERROR(auth_element->Update_Authenticate(ntlm_params )); } OpStringS8 auth_str; ANCHOR(OpStringS8, auth_str); LEAVE_IF_ERROR(auth_element->GetAuthString(auth_str, NULL, NULL)); if(proxy) request->SetProxyAuthorization(auth_str); else request->SetAuthorization(auth_str); ret = auth_str.HasContent(); set_waiting = TRUE; } } return ret; } PSecurityFunctionTable NTLM_AuthElm::SecurityInterface = 0; //SecPkgInfo *NTLM_AuthElm::SecurityPackages; //DWORD NTLM_AuthElm::NumOfPkgs; //DWORD NTLM_AuthElm::PkgToUseIndex; //const char * const Base64_Encoding_chars = // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; AuthElm *CreateNTLM_Element(authenticate_params &auth_params,const char *user_name, const char *user_password) { NTLM_AuthElm *elm = new NTLM_AuthElm(auth_params.scheme, (auth_params.proxy ? URL_HTTP : (URLType) auth_params.url.GetAttribute(URL::KType)), auth_params.port); if(!elm) return NULL; if(OpStatus::IsError(elm->Construct(user_name, user_password)) || OpStatus::IsError(elm->SetHost(auth_params.servername, auth_params.port)) ) { delete elm; return NULL; } return elm; } NTLM_AuthElm::NTLM_AuthElm(AuthScheme scheme, URLType a_urltype, unsigned short a_port) : AuthElm_Base(a_port, scheme, a_urltype) { gotten_credentials = FALSE; try_negotiate = try_ntml = FALSE; memset(&Credentials, 0, sizeof(Credentials)); memset(&SecurityContext, 0, sizeof(SecurityContext)); } NTLM_AuthElm::~NTLM_AuthElm() { last_challenge.Wipe(); if(SecurityInterface) { (*SecurityInterface->FreeCredentialHandle)(&Credentials); (*SecurityInterface->DeleteSecurityContext)(&SecurityContext); } } OP_STATUS NTLM_AuthElm::Construct(OpStringC8 a_user, OpStringC8 a_passwd) { RETURN_IF_ERROR(AuthElm_Base::Construct("", NULL)); RETURN_IF_ERROR(password.SetFromUTF8(a_passwd)); int pos = a_user.FindFirstOf('\\'); if(pos != KNotFound) { RETURN_IF_ERROR(domain.SetFromUTF8(a_user, pos)); pos ++; } else { domain.Set(""); pos = 0; } RETURN_IF_ERROR(user_name.SetFromUTF8(a_user+pos)); id.User = user_name.CStr();//UNI_L("Administrator"); id.UserLength = user_name.Length(); // uni_strlen(id.User); id.Domain = domain.CStr(); // UNI_L("HADES"); id.DomainLength = domain.Length(); // (id.Domain ? uni_strlen(id.Domain) : 0); id.Password = password.CStr(); // UNI_L("OperaQA"); id.PasswordLength = password.Length(); // uni_strlen(id.Password); id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; return OpStatus::OK; } OP_STATUS NTLM_AuthElm::Construct(NTLM_AuthElm *master) { if(master == NULL) return OpStatus::ERR_NULL_POINTER; SetId(master->GetId()); RETURN_IF_ERROR(AuthElm_Base::Construct(NULL, NULL)); RETURN_IF_ERROR(password.Set(master->password)); RETURN_IF_ERROR(domain.Set(master->domain)); RETURN_IF_ERROR(user_name.Set(master->user_name)); RETURN_IF_ERROR(SPN.Set(master->SPN)); Credentials = master->Credentials; memset(&master->Credentials, 0, sizeof(Credentials)); SecurityContext = master->SecurityContext; memset(&master->SecurityContext, 0, sizeof(SecurityContext)); gotten_credentials = master->gotten_credentials; master->gotten_credentials = FALSE; try_negotiate = master->try_negotiate; master->try_negotiate = FALSE; try_ntml = master->try_ntml; master->try_ntml = FALSE; id.User = user_name.CStr();//UNI_L("Administrator"); id.UserLength = user_name.Length(); // uni_strlen(id.User); id.Domain = domain.CStr(); // UNI_L("HADES"); id.DomainLength = domain.Length(); // (id.Domain ? uni_strlen(id.Domain) : 0); id.Password = password.CStr(); // UNI_L("OperaQA"); id.PasswordLength = password.Length(); // uni_strlen(id.Password); id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; return OpStatus::OK; } OP_STATUS NTLM_AuthElm::SetHost(ServerName *sn, unsigned short port) { SPN.Empty(); if(sn == NULL || !sn->UniName()) return OpStatus::OK; return SPN.AppendFormat(UNI_L("www/%s:%d/"), sn->UniName(), (port ? port : 80)); } void NTLM_AuthElm::Terminate() { /* if(SecurityPackages) { FreeContextBuffer(SecurityPackages); SecurityPackages = NULL; } */ SecurityInterface = NULL; } OP_STATUS NTLM_AuthElm::GetAuthString(OpStringS8 &ret_str, URL_Rep *url, #if defined(SSL_ENABLE_DELAYED_HANDSHAKE) && (!defined(_EXTERNAL_SSL_SUPPORT_) || defined(_USE_HTTPS_PROXY)) BOOL secure, #endif HTTP_Method http_method, HTTP_request_st* request, #ifdef HTTP_DIGEST_AUTH HTTP_Request_digest_data *auth_digest, HTTP_Request_digest_data *proxy_digest, #endif Upload_Base* upload_data, OpStringS8 &data) { return GetAuthString(ret_str,url, NULL); }; void NTLM_AuthElm::ClearAuth() { last_challenge.Empty(); ntlm_challenge.Empty(); if(gotten_credentials) { (*SecurityInterface->FreeCredentialHandle)(&Credentials); (*SecurityInterface->DeleteSecurityContext)(&SecurityContext); memset(&Credentials, 0, sizeof(Credentials)); memset(&SecurityContext, 0, sizeof(SecurityContext)); gotten_credentials = FALSE; } } OP_STATUS NTLM_AuthElm::GetAuthString(OpStringS8 &ret_str, URL_Rep *, HTTP_Request *http) { SECURITY_STATUS status; ret_str.Empty(); if(!SecurityInterface) { SecurityInterface = InitSecurityInterface(); if(!SecurityInterface) { Terminate(); return OpStatus::OK; } } TimeStamp stamp; BOOL initializing = FALSE; AuthScheme scheme = (GetScheme() & AUTH_SCHEME_HTTP_MASK); if(!gotten_credentials) { do{ status = (*SecurityInterface->AcquireCredentialsHandle)( NULL, (scheme == AUTH_SCHEME_HTTP_NTLM_NEGOTIATE || scheme == AUTH_SCHEME_HTTP_NEGOTIATE ? TEXT("Negotiate") : TEXT("NTLM")), SECPKG_CRED_OUTBOUND, 0, &id, 0, 0, &Credentials, &stamp ); if(status == SEC_E_OK) { if(scheme == AUTH_SCHEME_HTTP_NTLM_NEGOTIATE ) SetScheme(AUTH_SCHEME_HTTP_NEGOTIATE | (GetScheme() & AUTH_SCHEME_HTTP_PROXY)); break; // Success } // error if(scheme != AUTH_SCHEME_HTTP_NTLM_NEGOTIATE) // If we looked for NTLM or does not have NTLM, return return OpStatus::OK; // If we tried Negotiate, try NTLM SetScheme(AUTH_SCHEME_HTTP_NTLM | (GetScheme() & AUTH_SCHEME_HTTP_PROXY)); last_challenge.TakeOver(ntlm_challenge); } while(1); gotten_credentials = TRUE; initializing = TRUE; } DWORD ContextAttributes=0; SecBufferDesc BufferDescriptor; SecBuffer Buffer; PSecBufferDesc InputDescriptor = NULL; SecBufferDesc InputBufferDesc; SecBuffer InputBuffer; InputBuffer.BufferType = SECBUFFER_TOKEN; InputBuffer.cbBuffer = 0; InputBuffer.pvBuffer = NULL; InputBufferDesc.ulVersion = SECBUFFER_VERSION; InputBufferDesc.cBuffers = 1; InputBufferDesc.pBuffers = &InputBuffer; if(last_challenge.HasContent()) { unsigned long read_pos= 0, chlen = last_challenge.Length() ; BOOL warning=FALSE; unsigned char *buffer = new unsigned char[chlen]; if(buffer == NULL) { return OpStatus::OK; } unsigned long tlen = GeneralDecodeBase64((const unsigned char *) last_challenge.CStr(), chlen, read_pos, buffer, warning); OP_ASSERT(read_pos == chlen && !warning); InputBuffer.cbBuffer = tlen; InputBuffer.pvBuffer = buffer; InputDescriptor = &InputBufferDesc; } else { InputBuffer.cbBuffer = 0; InputBuffer.pvBuffer = new unsigned char[1]; if(InputBuffer.pvBuffer == NULL) { return OpStatus::OK; } ((unsigned char *)InputBuffer.pvBuffer)[0] = 0; InputDescriptor = &InputBufferDesc; } Buffer.cbBuffer = 0; Buffer.pvBuffer = NULL; Buffer.BufferType = SECBUFFER_TOKEN; BufferDescriptor.ulVersion = SECBUFFER_VERSION; BufferDescriptor.cBuffers = 1; BufferDescriptor.pBuffers = &Buffer; status = (*SecurityInterface->InitializeSecurityContext)( &Credentials, (!initializing ? &SecurityContext : NULL), SPN.CStr(), ISC_REQ_USE_DCE_STYLE |// ISC_REQ_DELEGATE | /*ISC_REQ_MUTUAL_AUTH | ISC_REQ_REPLAY_DETECT |*/ ISC_REQ_ALLOCATE_MEMORY | //ISC_REQ_SEQUENCE_DETECT | // ISC_REQ_CONFIDENTIALITY | ISC_REQ_CONNECTION /*| ISC_REQ_PROMPT_FOR_CREDS*/, 0, 0, InputDescriptor, // input 0, (initializing ? &SecurityContext : NULL), &BufferDescriptor, &ContextAttributes, &stamp ); if(status != SEC_I_CONTINUE_NEEDED) { (*SecurityInterface->FreeCredentialHandle)(&Credentials); (*SecurityInterface->DeleteSecurityContext)(&SecurityContext); memset(&Credentials, 0, sizeof(Credentials)); memset(&SecurityContext, 0, sizeof(SecurityContext)); gotten_credentials = FALSE; } char *result = NULL; if(BufferDescriptor.cBuffers) { int len=0; MIME_Encode_SetStr(result,len,(const char *) BufferDescriptor.pBuffers[0].pvBuffer,BufferDescriptor.pBuffers[0].cbBuffer,NULL,GEN_BASE64_ONELINE); } (*SecurityInterface->FreeContextBuffer)(BufferDescriptor.pBuffers[0].pvBuffer); delete[] ((unsigned char *)InputBuffer.pvBuffer); OP_STATUS op_err = OpStatus::OK; if(result && *result) { op_err = ret_str.SetConcat( (scheme == AUTH_SCHEME_HTTP_NTLM_NEGOTIATE || scheme == AUTH_SCHEME_HTTP_NEGOTIATE ? "Negotiate " : "NTLM "), result); } delete [] result; return op_err; } OP_STATUS NTLM_AuthElm::Update_Authenticate(ParameterList *header) { if(header) { Parameters *param = header->First(); if(param) { BOOL negotiate = (param->GetName().CompareI("Negotiate") == 0 ? TRUE : FALSE); param = param->Suc(); if((GetScheme() & AUTH_SCHEME_HTTP_MASK) != AUTH_SCHEME_HTTP_NTLM_NEGOTIATE || negotiate) RETURN_IF_ERROR(last_challenge.Set(param ? param->Name() : NULL)); else RETURN_IF_ERROR(ntlm_challenge.Set(param ? param->Name() : NULL)); } } return OpStatus::OK; } OP_STATUS NTLM_AuthElm::SetPassword(OpStringC8 a_passwd) { /* _SEC_WINNT_AUTH_IDENTITY id; id.User = UNI_L("Administrator"); id.UserLength = uni_strlen(id.User); id.Domain = UNI_L("HADES"); id.DomainLength = (id.Domain ? uni_strlen(id.Domain) : 0); id.Password = UNI_L("OperaQA"); id.PasswordLength = uni_strlen(id.Password); id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; */ // Not in use return OpStatus::OK; } BOOL NTLM_AuthElm::MustClone() const { return TRUE; } AuthElm *NTLM_AuthElm::MakeClone() { NTLM_AuthElm *elem = new NTLM_AuthElm(GetScheme(), GetUrlType(), GetPort()); if(!elem) return NULL; if(OpStatus::IsError(elem->Construct(this))) { delete elem; return NULL; } return elem; } #endif
/* * main.cpp * * Created on: 24/gen/2012 * Author: jetmir */ #include <stdio.h> #include "cv.h" #include "highgui.h" #include "FieldAnalyse.h" using namespace std; using namespace cv; int main(int argc, char * argv[]) { FieldAnalyse field; field.Launch(); sleep(50); return 0; }
#define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> //core glm functionality #include <glm/gtc/matrix_transform.hpp> //glm extension for generating common transformation matrices #include <glm/gtc/matrix_inverse.hpp> //glm extension for computing inverse matrices #include <glm/gtc/type_ptr.hpp> //glm extension for accessing the internal data structure of glm types #include "Window.h" #include "Shader.hpp" #include "Camera.hpp" #include "Model3D.hpp" #include "SkyBox.hpp" #include <iostream> // window gps::Window myWindow; // matrices glm::mat4 model; glm::mat4 view; glm::mat4 projection; glm::mat3 normalMatrix; glm::mat4 lightRotation; // light parameters glm::vec3 lightDir; glm::vec3 lightColor; glm::vec3 lightColor1; glm::vec3 lightPos; glm::vec3 lightPos1; glm::vec3 lightPos2; glm::vec3 lightPos3; glm::vec3 lightPos4; // shader uniform locations GLuint modelLoc; GLuint viewLoc; GLuint projectionLoc; GLuint normalMatrixLoc; GLuint lightDirLoc; GLuint lightColorLoc; GLuint lightColor1Loc; GLuint lightPosLoc; GLuint lightPosLoc1; GLuint lightPosLoc2; GLuint lightPosLoc3; GLuint lightPosLoc4; // camera gps::Camera myCamera( glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, -10.0f), glm::vec3(0.0f, 1.0f, 0.0f)); GLfloat cameraSpeed = 0.1f; GLboolean pressedKeys[1024]; // models gps::Model3D screenQuad; gps::Model3D ground; gps::Model3D brad; gps::Model3D christmas_tree; gps::Model3D molid; gps::Model3D cadou1; gps::Model3D cadou2; gps::Model3D cadou3; gps::Model3D cadou4; gps::Model3D cadou5; gps::Model3D snowman1; gps::Model3D home; gps::Model3D cat; gps::Model3D bustean; gps::Model3D house; gps::Model3D trunck; gps::Model3D santa; gps::Model3D felinar; gps::Model3D sanie; gps::Model3D fulg; GLfloat angle; GLfloat snowmanAngle; // shaders gps::Shader myBasicShader; gps::Shader depthMapShader; gps::Shader lightShader; gps::Shader screenQuadShader; gps::Shader skyboxShader; gps::SkyBox mySkyBox; std::vector<const GLchar*> faces; const unsigned int SHADOW_WIDTH = 2048; const unsigned int SHADOW_HEIGHT = 2048; GLuint shadowMapFBO; GLuint depthMapTexture; bool showDepthMap; int fog; int ninsoare; float snowmanX = 0.0f; float snowmanZ = 0.0f; float santaSpeed = 0.2f; int mode = 1; float delta = 0.0f; float movementSpeed = 10.0f; void updateDelta(double elapsedSeconds) { delta = delta + movementSpeed * elapsedSeconds; } double lastTimeStamp = glfwGetTime(); float xx[100]; float zz[100]; float yy[100]; float d = 0.0f; int n = 100; glm::vec3 snowflakeLength = glm::vec3(20.0, 20.0, 20.0); void generateSnowflakes() { for (int i = 0; i < n; i++) { xx[i] = -snowflakeLength.x + ((float)(std::rand() % ((int)snowflakeLength.x * 2 * 100))) / 100.0f; yy[i] = ((float)(std::rand() % ((int)snowflakeLength.y * 100))) / 100.0f; zz[i] = -snowflakeLength.z + ((float)(std::rand() % (((int)snowflakeLength.z * 2) * 100))) / 100.0f; } } GLenum glCheckError_(const char* file, int line) { GLenum errorCode; while ((errorCode = glGetError()) != GL_NO_ERROR) { std::string error; switch (errorCode) { case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: error = "STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: error = "STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; } std::cout << error << " | " << file << " (" << line << ")" << std::endl; } return errorCode; } #define glCheckError() glCheckError_(__FILE__, __LINE__) void windowResizeCallback(GLFWwindow* window, int width, int height) { fprintf(stdout, "Window resized! New width: %d , and height: %d\n", width, height); //TODO myWindow.setWindowDimensions(WindowDimensions{ width,height }); } void keyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (key == GLFW_KEY_M && action == GLFW_PRESS) showDepthMap = !showDepthMap; if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) { pressedKeys[key] = true; } else if (action == GLFW_RELEASE) { pressedKeys[key] = false; } } } bool firstMouse = true; float lastX = 400, lastY = 300; float yaw, pitch; void mouseCallback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; lastX = xpos; lastY = ypos; float sensitivity = 0.1f; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; myCamera.rotate(pitch, yaw); } void processMovement() { if (pressedKeys[GLFW_KEY_W]) { myCamera.move(gps::MOVE_FORWARD, cameraSpeed); //update view matrix view = myCamera.getViewMatrix(); myBasicShader.useShaderProgram(); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // compute normal matrix for object normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); } if (pressedKeys[GLFW_KEY_S]) { myCamera.move(gps::MOVE_BACKWARD, cameraSpeed); //update view matrix view = myCamera.getViewMatrix(); myBasicShader.useShaderProgram(); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // compute normal matrix for object normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); } if (pressedKeys[GLFW_KEY_A]) { myCamera.move(gps::MOVE_LEFT, cameraSpeed); //update view matrix view = myCamera.getViewMatrix(); myBasicShader.useShaderProgram(); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // compute normal matrix for object normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); } if (pressedKeys[GLFW_KEY_D]) { myCamera.move(gps::MOVE_RIGHT, cameraSpeed); //update view matrix view = myCamera.getViewMatrix(); myBasicShader.useShaderProgram(); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // compute normal matrix for object normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); } if (pressedKeys[GLFW_KEY_Q]) { angle += 0.3f; if (angle > 360.0f) angle -= 360.0f; glm::vec3 lightDirTr = glm::vec3(glm::rotate(glm::mat4(1.0f), glm::radians(angle), glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec4(lightDir, 1.0f)); myBasicShader.useShaderProgram(); glUniform3fv(lightDirLoc, 1, glm::value_ptr(lightDirTr)); } if (pressedKeys[GLFW_KEY_E]) { angle -= 0.3f; if (angle < 0.0f) angle += 360.0f; glm::vec3 lightDirTr = glm::vec3(glm::rotate(glm::mat4(1.0f), glm::radians(angle), glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec4(lightDir, 1.0f)); myBasicShader.useShaderProgram(); glUniform3fv(lightDirLoc, 1, glm::value_ptr(lightDirTr)); } if (pressedKeys[GLFW_KEY_O]) { fog = 0; } if (pressedKeys[GLFW_KEY_I]) { fog = 1; } if (pressedKeys[GLFW_KEY_B]) { ninsoare = 0; } if (pressedKeys[GLFW_KEY_N]) { ninsoare = 1; } if (pressedKeys[GLFW_KEY_1]) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } if (pressedKeys[GLFW_KEY_2]) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } if (pressedKeys[GLFW_KEY_3]) { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); } if (pressedKeys[GLFW_KEY_LEFT]) { snowmanAngle += 1.5f; if (snowmanAngle > 360.0f) snowmanAngle -= 360.0f; } if (pressedKeys[GLFW_KEY_RIGHT]) { snowmanAngle -= 1.5f; if (snowmanAngle < 0.0f) snowmanAngle += 360.0f; } if (pressedKeys[GLFW_KEY_UP]) { snowmanX += santaSpeed * sin(glm::radians(snowmanAngle)); snowmanZ += santaSpeed * cos(glm::radians(snowmanAngle)); } } void initOpenGLWindow() { myWindow.Create(1024, 768, "OpenGL Project Core"); } void setWindowCallbacks() { glfwSetWindowSizeCallback(myWindow.getWindow(), windowResizeCallback); glfwSetKeyCallback(myWindow.getWindow(), keyboardCallback); glfwSetCursorPosCallback(myWindow.getWindow(), mouseCallback); } void initOpenGLState() { glClearColor(0.7f, 0.7f, 0.7f, 1.0f); glViewport(0, 0, myWindow.getWindowDimensions().width, myWindow.getWindowDimensions().height); glEnable(GL_FRAMEBUFFER_SRGB); glEnable(GL_DEPTH_TEST); // enable depth-testing glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer" glEnable(GL_CULL_FACE); // cull face glCullFace(GL_BACK); // cull back face glFrontFace(GL_CCW); // GL_CCW for counter clock-wise } void initModels() { brad.LoadModel("models/brad/lowpoyltree.obj"); christmas_tree.LoadModel("models/ch/12150_Christmas_Tree_V2_L2.obj"); molid.LoadModel("models/molid/10459_White_Ash_Tree_v1_L3.obj"); cadou1.LoadModel("models/cadou/g1.obj"); cadou2.LoadModel("models/cadou/g2.obj"); cadou3.LoadModel("models/cadou/g3.obj"); cadou4.LoadModel("models/cadou/g4.obj"); cadou5.LoadModel("models/cadou/g5.obj"); sanie.LoadModel("models/sleigh/1157_Sleigh_v3_l2.obj"); snowman1.LoadModel("models/snowman/SnowmanOBJ.obj"); house.LoadModel("models/house/10783_TreeHouse_v7_LOD3.obj"); bustean.LoadModel("models/bustean/Wood.obj"); home.LoadModel("models/home/1home.obj"); santa.LoadModel("models/santa/Santa.obj"); cat.LoadModel("models/cat/12221_Cat_v1_l3.obj"); felinar.LoadModel("models/streetlamp/streetlamp.obj"); fulg.LoadModel("models/Snowflake/Snowflake.obj"); trunck.LoadModel("models/trunchi/log.obj"); ground.LoadModel("models/ground/ground.obj"); } void initShaders() { myBasicShader.loadShader("shaders/basic.vert", "shaders/basic.frag"); myBasicShader.useShaderProgram(); lightShader.loadShader("shaders/lightCube.vert", "shaders/lightCube.frag"); lightShader.useShaderProgram(); screenQuadShader.loadShader("shaders/screenQuad.vert", "shaders/screenQuad.frag"); screenQuadShader.useShaderProgram(); depthMapShader.loadShader("shaders/depthMap.vert", "shaders/depthMap.frag"); depthMapShader.useShaderProgram(); skyboxShader.loadShader("shaders/skyboxShader.vert", "shaders/skyboxShader.frag"); skyboxShader.useShaderProgram(); faces.push_back("skybox/left.jpg"); faces.push_back("skybox/right.jpg"); faces.push_back("skybox/top.jpg"); faces.push_back("skybox/bottom.jpg"); faces.push_back("skybox/back.jpg"); faces.push_back("skybox/front.jpg"); mySkyBox.Load(faces); } void initUniforms() { myBasicShader.useShaderProgram(); // create model matrix for object model = glm::mat4(1.0f); modelLoc = glGetUniformLocation(myBasicShader.shaderProgram, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); // get view matrix for current camera view = myCamera.getViewMatrix(); viewLoc = glGetUniformLocation(myBasicShader.shaderProgram, "view"); // send view matrix to shader glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // compute normal matrix for object normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); normalMatrixLoc = glGetUniformLocation(myBasicShader.shaderProgram, "normalMatrix"); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); // create projection matrix projection = glm::perspective(glm::radians(45.0f), (float)myWindow.getWindowDimensions().width / (float)myWindow.getWindowDimensions().height, 0.1f, 1000.0f); projectionLoc = glGetUniformLocation(myBasicShader.shaderProgram, "projection"); // send projection matrix to shader glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); //set the light direction (direction towards the light) lightDir = glm::vec3(30.0f, 20.0f, 0.0f); lightRotation = glm::rotate(glm::mat4(1.0f), glm::radians(angle), glm::vec3(0.0f, 1.0f, 0.0f)); lightDirLoc = glGetUniformLocation(myBasicShader.shaderProgram, "lightDir"); // send light dir to shader glUniform3fv(lightDirLoc, 1, glm::value_ptr(glm::inverseTranspose(glm::mat3(view * lightRotation)) * lightDir)); //set light color lightColor = glm::vec3(1.0f, 1.0f, 1.0f); //white light lightColorLoc = glGetUniformLocation(myBasicShader.shaderProgram, "lightColor"); // send light color to shader glUniform3fv(lightColorLoc, 1, glm::value_ptr(lightColor)); //second light source lightColor1 = glm::vec3(1.0f, 0.0f, 0.0f); //red color lightColor1Loc = glGetUniformLocation(myBasicShader.shaderProgram, "lightColor1"); glUniform3fv(lightColor1Loc, 1, glm::value_ptr(lightColor1)); //position of the second light - under the main tree lightPos = glm::vec3(-3.0f, 0.0f, -13.0f); lightPosLoc = glGetUniformLocation(myBasicShader.shaderProgram, "lightPos"); glUniform3fv(lightPosLoc, 1, glm::value_ptr(lightPos)); //position for streetlight (on fog only) lightPos1 = glm::vec3(9.0f, -1.0f, 7.0f); lightPosLoc1 = glGetUniformLocation(myBasicShader.shaderProgram, "lightPos1"); glUniform3fv(lightPosLoc1, 1, glm::value_ptr(lightPos1)); lightPos2 = glm::vec3(-20.0f, -1.0f, 20.0f); lightPosLoc2 = glGetUniformLocation(myBasicShader.shaderProgram, "lightPos2"); glUniform3fv(lightPosLoc2, 1, glm::value_ptr(lightPos2)); lightPos3 = glm::vec3(19.0f, -1.0f, -24.0f); lightPosLoc3 = glGetUniformLocation(myBasicShader.shaderProgram, "lightPos3"); glUniform3fv(lightPosLoc3, 1, glm::value_ptr(lightPos3)); lightPos4 = glm::vec3(19.0f, -1.0f, -1.0f); lightPosLoc4 = glGetUniformLocation(myBasicShader.shaderProgram, "lightPos4"); glUniform3fv(lightPosLoc4, 1, glm::value_ptr(lightPos4)); lightShader.useShaderProgram(); glUniformMatrix4fv(glGetUniformLocation(lightShader.shaderProgram, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); } void renderObjects(gps::Shader shader, bool depthPass) { // select active shader program shader.useShaderProgram(); if (ninsoare == 1) { d = 0.07; for (int i = 0; i < n; i++) { model = glm::translate(glm::mat4(1.0f), glm::vec3(xx[i], yy[i], zz[i])); yy[i] -= d; if (yy[i] <= -1.0f) { yy[i] = snowflakeLength.y; xx[i] = -snowflakeLength.x + ((float)(std::rand() % (((int)snowflakeLength.x * 2) * 10000))) / 100.0f; zz[i] = -snowflakeLength.z + ((float)(std::rand() % (((int)snowflakeLength.z * 2) * 10000))) / 100.0f; } model = glm::scale(model, glm::vec3(0.0007)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); fulg.Draw(shader); } } //draw the lame christmass tree int i1 = 4; for (float j = -25.0; j <= 27.0; j = j + 2) { if (i1 <= 20) { for (float i = -28.0; i <= 28.0; i = i + i1) { model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(i, -1.0f, j)); model = glm::scale(model, glm::vec3(0.4f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } brad.Draw(shader); i1 = i1 + 1; } } else { i1 = 3; } } //draw pathces of molid for (float j = 0.0; j <= 4.0; j= j + 3) { for (float i = 0.0; i <= 15.0; i = i + 2) { model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(7.0f + i, -1.0f, 12.0f + j)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.004f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } molid.Draw(shader); } } for (float j = 0.0; j <= 15.0; j = j + 3) { for (float i = 0.0; i <= 7.0; i = i + 2) { model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-25.0f + i, -1.0f, -8.0f - j)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.004f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } molid.Draw(shader); } } //draw the main tree model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-3.0f, -1.0f, -13.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.05f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } christmas_tree.Draw(shader); //main houses model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(19.0f, -1.0f, -12.0f)); model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } home.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(19.0f, -1.0f, -5.0f)); model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } home.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(19.0f, -1.0f, -20.0f)); model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } home.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-25.0f, -1.0f, 20.0f)); model = glm::rotate(model, glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } home.Draw(shader); //felinare model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-20.0f, -1.0f, 20.0f)); model = glm::scale(model, glm::vec3(0.8f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } felinar.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(19.0f, -1.0f, -1.0f)); model = glm::scale(model, glm::vec3(0.8f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } felinar.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(16.0f, -1.0f, -24.0f)); model = glm::scale(model, glm::vec3(0.8f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } felinar.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(14.0f, -1.0f, 7.0f)); model = glm::scale(model, glm::vec3(0.8f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } felinar.Draw(shader); //draw the cat model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(13.0f, -1.0f, -7.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cat.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(10.0f, -1.0f, -17.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cat.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-2.0f, -1.0f, 25.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cat.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-22.0f, -1.0f, 12.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cat.Draw(shader); //draw bustean pt foc de tabara model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(20.0f, -1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.1f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } bustean.Draw(shader); //draw gifts //g1 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-3.0f, -1.0f, -10.0f)); model = glm::scale(model, glm::vec3(5.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cadou1.Draw(shader); //g2 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-2.0f, -1.0f, -9.0f)); model = glm::scale(model, glm::vec3(2.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cadou2.Draw(shader); //g3 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-1.7f, -1.0f, -10.0f)); model = glm::scale(model, glm::vec3(3.5f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cadou3.Draw(shader); //g4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-2.0f, -1.0f, -9.0f)); model = glm::scale(model, glm::vec3(4.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cadou4.Draw(shader); //g5 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-2.5f, -1.0f, -9.0f)); model = glm::scale(model, glm::vec3(3.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } cadou5.Draw(shader); //draw snowmen model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-3.0f, -1.0f, -7.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-10.0f, -1.0f, 7.0f)); model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-12.0f, -1.0f, 4.0f)); //model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-9.0f, -1.0f, 4.0f)); // model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(7.5f, 1.4f, 7.5f)); // model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.007f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-22.0f, -1.0f, -3.0f)); // model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.01f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); double currentTimeStamp = glfwGetTime(); updateDelta(currentTimeStamp - lastTimeStamp); lastTimeStamp = currentTimeStamp; int var = 0; model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-15.0f, -1.0f, -9.0f)); model = glm::scale(model, glm::vec3(0.01f)); model = glm::rotate(model, glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); //model = glm::rotate(model, 3.14f, glm::vec3(0.0f, 1.0f, 0.0f)); if ( var < 60) { model = glm::translate(model, glm::vec3(delta, 0.0f, 0.0f)); var++; } else { var = 0; delta = 0; } glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); //draw animated snowman model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(8.0f, -1.0f, -5.0f)); model = glm::scale(model, glm::vec3(0.01f)); model = glm::translate(model, glm::vec3(snowmanX, 1.3f, snowmanZ)); model = glm::rotate(model, glm::radians(snowmanAngle), glm::vec3(0.0f, 1.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } snowman1.Draw(shader); //draw santa model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(6.0f, -1.0f, 12.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.005f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } santa.Draw(shader); //draw the house model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(6.0f, -1.0f, 7.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.04f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } house.Draw(shader); //sustinere casa model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(6.0f, -1.1f, 9.5f)); // model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(2.7f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } trunck.Draw(shader); //sanie mosu model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(16.0f, 0.0f, 9.0f)); model = glm::rotate(model, glm::radians(270.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } sanie.Draw(shader); // draw the ground model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, -1.0f, 0.0f)); model = glm::scale(model, glm::vec3(3.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model)); // do not send the normal matrix if we are rendering in the depth map if (!depthPass) { normalMatrix = glm::mat3(glm::inverseTranspose(view * model)); glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix)); } ground.Draw(shader); } void initFBO() { //TODO - Create the FBO, the depth texture and attach the depth texture to the FBO glGenFramebuffers(1, &shadowMapFBO); glGenTextures(1, &depthMapTexture); glBindTexture(GL_TEXTURE_2D, depthMapTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMapTexture, 0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); } glm::mat4 computeLightSpaceTrMatrix() { //TODO - Return the light-space transformation matrix glm::mat4 lightView = glm::lookAt(glm::mat3(lightRotation) * lightDir, glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); const GLfloat near_plane = 0.1f, far_plane = 80.0f; glm::mat4 lightProjection = glm::ortho(-60.0f, 60.0f, -60.0f, 60.0f, near_plane, far_plane); glm::mat4 lightSpaceTrMatrix = lightProjection * lightView; return lightSpaceTrMatrix; } void renderScene() { depthMapShader.useShaderProgram(); glUniformMatrix4fv(glGetUniformLocation(depthMapShader.shaderProgram, "lightSpaceTrMatrix"), 1, GL_FALSE, glm::value_ptr(computeLightSpaceTrMatrix())); glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT); glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFBO); glClear(GL_DEPTH_BUFFER_BIT); renderObjects(depthMapShader, true); glBindFramebuffer(GL_FRAMEBUFFER, 0); // render depth map on screen - toggled with the M key if (showDepthMap) { glViewport(0, 0, myWindow.getWindowDimensions().width, myWindow.getWindowDimensions().height); glClear(GL_COLOR_BUFFER_BIT); screenQuadShader.useShaderProgram(); //bind the depth map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthMapTexture); glUniform1i(glGetUniformLocation(screenQuadShader.shaderProgram, "depthMap"), 0); glDisable(GL_DEPTH_TEST); screenQuad.Draw(screenQuadShader); glEnable(GL_DEPTH_TEST); } else { // final scene rendering pass (with shadows) glViewport(0, 0, myWindow.getWindowDimensions().width, myWindow.getWindowDimensions().height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); myBasicShader.useShaderProgram(); view = myCamera.getViewMatrix(); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); lightRotation = glm::rotate(glm::mat4(1.0f), glm::radians(angle), glm::vec3(0.0f, 1.0f, 0.0f)); glUniform3fv(lightDirLoc, 1, glm::value_ptr(glm::inverseTranspose(glm::mat3(view * lightRotation)) * lightDir)); //bind the shadow map glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthMapTexture); glUniform1i(glGetUniformLocation(myBasicShader.shaderProgram, "shadowMap"), 3); glUniform1i(glGetUniformLocation(myBasicShader.shaderProgram, "fogSwitch"), fog); glUniformMatrix4fv(glGetUniformLocation(myBasicShader.shaderProgram, "lightSpaceTrMatrix"), 1, GL_FALSE, glm::value_ptr(computeLightSpaceTrMatrix())); renderObjects(myBasicShader, false); //draw a white cube around the light } mySkyBox.Draw(skyboxShader, view, projection); } void cleanup() { myWindow.Delete(); //cleanup code for your own data } int main(int argc, const char* argv[]) { try { initOpenGLWindow(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } initOpenGLState(); initModels(); initShaders(); initUniforms(); initFBO(); setWindowCallbacks(); glCheckError(); // application loop while (!glfwWindowShouldClose(myWindow.getWindow())) { processMovement(); renderScene(); glfwPollEvents(); glfwSwapBuffers(myWindow.getWindow()); glCheckError(); } cleanup(); return EXIT_SUCCESS; }