hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f4bd24595ae54aaad502d864082ac65a7180b5d7
739
cpp
C++
Structure_and_pointer_using_arrow_operator.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
Structure_and_pointer_using_arrow_operator.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
Structure_and_pointer_using_arrow_operator.cpp
gptakhil/Cpp-Revision
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; // Student structure struct Student { string name; int roll_number; int marks; }; // main function int main() { // Declare structure variable struct Student s1; // Declare structure pointer struct Student *ptrs1; // Store address of structure variable in structure pointer ptrs1 = &s1; // Set value of name ptrs1->name = "John"; // Set value of roll_number ptrs1->roll_number = 1; // Set value of marks ptrs1->marks = 50; // Print value of structure member cout << "s1 Information:" << endl; cout << "Name = " << ptrs1->name << endl; cout << "Roll Number = " << ptrs1->roll_number << endl; cout << "Marks = " << ptrs1->marks << endl; return 0; }
19.972973
61
0.640054
gptakhil
f4bd493befc9a42fcd2e0c51b941f91c214307bd
2,440
cpp
C++
metaforce-gui/CVarDialog.cpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
metaforce-gui/CVarDialog.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
metaforce-gui/CVarDialog.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#include "CVarDialog.hpp" #include "ui_CVarDialog.h" #include <utility> enum class CVarType { String, Boolean, }; struct CVarItem { QString m_name; CVarType m_type; QVariant m_defaultValue; CVarItem(QString name, CVarType type, QVariant defaultValue) : m_name(std::move(name)), m_type(type), m_defaultValue(std::move(defaultValue)) {} }; static std::array cvarList{ CVarItem{QStringLiteral("tweak.game.FieldOfView"), CVarType::String, 55}, CVarItem{QStringLiteral("debugOverlay.playerInfo"), CVarType::Boolean, false}, CVarItem{QStringLiteral("debugOverlay.areaInfo"), CVarType::Boolean, false}, // TODO expand }; CVarDialog::CVarDialog(QWidget* parent) : QDialog(parent), m_ui(std::make_unique<Ui::CVarDialog>()) { m_ui->setupUi(this); QStringList list; for (const auto& item : cvarList) { list << item.m_name; } m_model.setStringList(list); m_ui->cvarList->setModel(&m_model); connect(m_ui->cvarList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(handleSelectionChanged(QItemSelection))); } CVarDialog::~CVarDialog() = default; void CVarDialog::on_buttonBox_accepted() { const QModelIndexList& list = m_ui->cvarList->selectionModel()->selectedIndexes(); if (list.isEmpty()) { reject(); } else { accept(); } } void CVarDialog::on_buttonBox_rejected() { reject(); } void CVarDialog::handleSelectionChanged(const QItemSelection& selection) { const QModelIndexList& list = selection.indexes(); if (list.isEmpty()) { return; } const auto item = cvarList[(*list.begin()).row()]; m_ui->valueStack->setCurrentIndex(static_cast<int>(item.m_type)); if (item.m_type == CVarType::String) { m_ui->stringValueField->setText(item.m_defaultValue.toString()); } else if (item.m_type == CVarType::Boolean) { m_ui->booleanValueField->setChecked(item.m_defaultValue.toBool()); } } QString CVarDialog::textValue() { const QModelIndexList& list = m_ui->cvarList->selectionModel()->selectedIndexes(); if (list.isEmpty()) { return QStringLiteral(""); } const auto item = cvarList[(*list.begin()).row()]; QVariant value; if (item.m_type == CVarType::String) { value = m_ui->stringValueField->text(); } else if (item.m_type == CVarType::Boolean) { value = m_ui->booleanValueField->isChecked(); } return QStringLiteral("+") + item.m_name + QStringLiteral("=") + value.toString(); }
30.886076
107
0.703279
Jcw87
f4bddf3d7b8570b8edff54fcafb5860712621925
2,097
hpp
C++
ziomon/ziorep_framer.hpp
nikita-dubrovskii/s390-tools
074de1e14ed785c18f55ecf9762ac3f5de3465b4
[ "MIT" ]
43
2017-08-21T12:18:57.000Z
2021-01-21T09:20:59.000Z
ziomon/ziorep_framer.hpp
nikita-dubrovskii/s390-tools
074de1e14ed785c18f55ecf9762ac3f5de3465b4
[ "MIT" ]
99
2017-08-21T20:41:13.000Z
2021-01-27T16:23:07.000Z
ziomon/ziorep_framer.hpp
nikita-dubrovskii/s390-tools
074de1e14ed785c18f55ecf9762ac3f5de3465b4
[ "MIT" ]
37
2017-08-21T20:37:32.000Z
2021-02-02T10:10:45.000Z
/* * FCP report generators * * Class for reading messages into frames. * * Copyright IBM Corp. 2008, 2017 * * s390-tools is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #ifndef ZIOREP_FRAMER #define ZIOREP_FRAMER #include <list> #include "ziorep_filters.hpp" #include "ziorep_frameset.hpp" using std::list; extern "C" { #include "ziomon_dacc.h" } class Framer { public: /** * Note: Filter parameters transfer memory ownership to class. * 'filter_types' is an optional list of message types that should * be processed exclusively, anything else will be ignored. If not set, * all messages will be processed. */ Framer(__u64 begin, __u64 end, __u32 interval_length, list<MsgTypes> *filter_types, DeviceFilter *devFilter, const char *filename, int *rc); ~Framer(); /** * Retrieve the next set of messages. * Returns 0 in case of success, <0 in case of failure * and >0 in case end of data has been reached. * Set 'replace_missing' to fill in for non-present datasets. * E.g. if no utilization data was found in the interval (since there * was no traffic), a dataset with the expected number of samples * (but all 0s for the values) will be generated. */ int get_next_frameset(Frameset &frameset, bool replace_missing = false); private: void handle_msg(struct message *msg, Frameset &frameset) const; bool handle_agg_data(Frameset &frameset) const; /* timestamps of samples to consider * These are exact timestamps, we shift them a bit to make sure that * we catch any late or early messages as well */ __u64 m_begin; __u64 m_end; /// user-specified interval length __u32 m_interval_length; /* Criteria to identify the right messages */ MsgTypeFilter *m_type_filter; DeviceFilter *m_device_filter; // filename without extension const char *m_filename; FILE *m_fp; struct file_header m_fhdr; struct aggr_data *m_agg_data; /// indicates whether the .agg file was already read or not bool m_agg_read; }; #endif
25.573171
73
0.72103
nikita-dubrovskii
f4c255172c3cff4a99ca1c0952190ae2834d4131
848
hpp
C++
Object.hpp
LinarAbdrazakov/MIPT_GAME
55d96906cb60752c3907fb83ce70910879dc4ed8
[ "MIT" ]
null
null
null
Object.hpp
LinarAbdrazakov/MIPT_GAME
55d96906cb60752c3907fb83ce70910879dc4ed8
[ "MIT" ]
null
null
null
Object.hpp
LinarAbdrazakov/MIPT_GAME
55d96906cb60752c3907fb83ce70910879dc4ed8
[ "MIT" ]
null
null
null
#ifndef OBJECT_HPP #define OBJECT_HPP #include <SFML/Graphics.hpp> class Object { private: int id_; sf::Sprite* sprite_; sf::Vector2f coordinate_; sf::Vector2f speed_; sf::Vector2i size_; float* dt_; public: explicit Object(); Object(const Object&); Object(int, sf::Vector2f, sf::Vector2f, sf::Vector2i, float*); ~Object(); const int GetId() const; sf::Sprite* GetSprite() const; const sf::Vector2f GetCoordinate() const; const sf::Vector2f GetSpeed() const; const sf::Vector2i GetSize() const; float* GetDt() const; void SetId (int); void SetSprite (sf::Sprite*); void SetCoordinate(sf::Vector2f); void SetSpeed (sf::Vector2f); void SetSize (sf::Vector2i); void SetDt (float*); }; #endif
22.315789
64
0.595519
LinarAbdrazakov
f4c4917cbb9b86920862bb09496beeb71e3ec2c3
3,786
cpp
C++
src/VideoDevice.cpp
nayanavenkataramana/earlyapp
eafd8ae8507dee79d2b751f7c5d9320f5519029b
[ "MIT" ]
5
2019-01-02T18:34:52.000Z
2021-05-13T16:09:10.000Z
src/VideoDevice.cpp
nayanavenkataramana/earlyapp
eafd8ae8507dee79d2b751f7c5d9320f5519029b
[ "MIT" ]
10
2018-10-26T06:11:45.000Z
2019-06-24T06:25:43.000Z
src/VideoDevice.cpp
nayanavenkataramana/earlyapp
eafd8ae8507dee79d2b751f7c5d9320f5519029b
[ "MIT" ]
20
2018-10-26T02:16:51.000Z
2021-02-17T11:39:59.000Z
//////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018 Intel Corporation // // 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. // // SPDX-License-Identifier: MIT // //////////////////////////////////////////////////////////////////////////////// #include <string> #include <boost/format.hpp> #include "EALog.h" #include "OutputDevice.hpp" #include "VideoDevice.hpp" #include "Configuration.hpp" // A log tag for video device. #define TAG "VIDEO" namespace earlyapp { /* Define a device instance variable. */ VideoDevice* VideoDevice::m_pVDev = nullptr; /* Destructor. */ VideoDevice::~VideoDevice(void) { if(m_pVDev != nullptr) { delete m_pVDev; } } /* A static function to get an instance(singleton). */ VideoDevice* VideoDevice::getInstance(void) { if(m_pVDev == nullptr) { LINF_(TAG, "Creating a VideoDevice instance"); m_pVDev = new VideoDevice(); } return m_pVDev; } /* Intialize */ void VideoDevice::init(std::shared_ptr<Configuration> pConf) { OutputDevice::init(pConf); m_pDecPipeline = new CDecodingPipeline(m_pGPIOCtrl); if(m_pDecPipeline == nullptr) { LERR_(TAG, "Failed to create decoder instance."); return; } m_Params.bUseHWLib = true; m_Params.bUseFullColorRange = false; m_Params.videoType = MFX_CODEC_AVC; m_Params.mode = MODE_RENDERING; m_Params.memType = D3D9_MEMORY; m_Params.mode = MODE_RENDERING; // File path. strcpy(m_Params.strSrcFile, pConf->videoSplashPath().c_str()); // Width m_Params.Width = pConf->displayWidth(); // Height m_Params.Height = pConf->displayHeight(); // Default ASync depth. m_Params.nAsyncDepth = 4; // Initialize decoding pipeline. m_pDecPipeline->Init(&m_Params); LINF_(TAG, "VideoDevice initialized."); } /* Play the video device. */ void VideoDevice::play(void) { LINF_(TAG, "VideoDevice play"); // Start decoding and display. m_pDecPipeline->RunDecoding(); } /* Stop. */ void VideoDevice::stop(void) { LINF_(TAG, "VideoDevice stop"); // Stop play if(m_pDecPipeline) { delete m_pDecPipeline; m_pDecPipeline = nullptr; } } /* Terminate */ void VideoDevice::terminate(void) { LINF_(TAG, "VideoDevice terminate"); // TODO: release resources. } } // namespace
25.409396
80
0.596408
nayanavenkataramana
f4c4ea6bac0a1d4a5e6e89bd188e9b83f1d875cb
7,360
cpp
C++
src/caffe/layers/cross_correlation_layer.cpp
NicoleWang/caffe-for-rfcn
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/cross_correlation_layer.cpp
NicoleWang/caffe-for-rfcn
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/cross_correlation_layer.cpp
NicoleWang/caffe-for-rfcn
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
[ "BSD-2-Clause" ]
null
null
null
#include <algorithm> #include <cfloat> #include <vector> #include "caffe/layers/cross_correlation_layer.hpp" #include "caffe/util/math_functions.hpp" #define DEBUG_INFO #undef DEBUG_INFO namespace caffe { template <typename Dtype> void CrossCorrelationLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // std::cout << "Enter cross relation reshape function" << std::endl; //delete bottom size constraint //bottom[0]: feature map from last layer //bottom[1]: kernel const int first_spatial_axis = this->channel_axis_ + 1; CHECK_EQ(bottom[0]->num_axes(), first_spatial_axis + this->num_spatial_axes_) << "bottom num_axes may not change."; this->num_ = bottom[0]->count(0, this->channel_axis_); CHECK_EQ(bottom[0]->shape(this->channel_axis_), this->channels_) << "Input size incompatible with convolution kernel."; // TODO: generalize to handle inputs of different shapes. // for (int bottom_id = 1; bottom_id < bottom.size(); ++bottom_id) { // CHECK(bottom[0]->shape() == bottom[bottom_id]->shape()) // << "All inputs must have the same shape."; // } // Shape the tops. this->bottom_shape_ = &bottom[0]->shape(); this->compute_output_shape(); vector<int> top_shape(bottom[0]->shape().begin(), bottom[0]->shape().begin() + this->channel_axis_); top_shape.push_back(this->num_output_); for (int i = 0; i < this->num_spatial_axes_; ++i) { top_shape.push_back(this->output_shape_[i]); } for (int top_id = 0; top_id < top.size(); ++top_id) { top[top_id]->Reshape(top_shape); } if (this->reverse_dimensions()) { this->conv_out_spatial_dim_ = bottom[0]->count(first_spatial_axis); } else { this->conv_out_spatial_dim_ = top[0]->count(first_spatial_axis); } this->col_offset_ = this->kernel_dim_ * this->conv_out_spatial_dim_; this->output_offset_ = this->conv_out_channels_ * this->conv_out_spatial_dim_ / this->group_; // Setup input dimensions (conv_input_shape_). vector<int> bottom_dim_blob_shape(1, this->num_spatial_axes_ + 1); this->conv_input_shape_.Reshape(bottom_dim_blob_shape); int* conv_input_shape_data = this->conv_input_shape_.mutable_cpu_data(); for (int i = 0; i < this->num_spatial_axes_ + 1; ++i) { if (this->reverse_dimensions()) { conv_input_shape_data[i] = top[0]->shape(this->channel_axis_ + i); } else { conv_input_shape_data[i] = bottom[0]->shape(this->channel_axis_ + i); } } // The im2col result buffer will only hold one image at a time to avoid // overly large memory usage. In the special case of 1x1 convolution // it goes lazily unused to save memory. this->col_buffer_shape_.clear(); this->col_buffer_shape_.push_back(this->kernel_dim_ * this->group_); for (int i = 0; i < this->num_spatial_axes_; ++i) { if (this->reverse_dimensions()) { this->col_buffer_shape_.push_back(this->input_shape(i + 1)); } else { this->col_buffer_shape_.push_back(this->output_shape_[i]); } } this->col_buffer_.Reshape(this->col_buffer_shape_); this->bottom_dim_ = bottom[0]->count(this->channel_axis_); this->top_dim_ = top[0]->count(this->channel_axis_); this->num_kernels_im2col_ = this->conv_in_channels_ * this->conv_out_spatial_dim_; this->num_kernels_col2im_ = this->reverse_dimensions() ? this->top_dim_ : this->bottom_dim_; // Set up the all ones "bias multiplier" for adding biases by BLAS this->out_spatial_dim_ = top[0]->count(first_spatial_axis); if (this->bias_term_) { vector<int> bias_multiplier_shape(1, this->out_spatial_dim_); this->bias_multiplier_.Reshape(bias_multiplier_shape); caffe_set(this->bias_multiplier_.count(), Dtype(1), this->bias_multiplier_.mutable_cpu_data()); } } template <typename Dtype> void CrossCorrelationLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* weight = bottom[1]->cpu_data(); const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); for (int n = 0; n < this->num_; ++n) { this->forward_cpu_gemm(bottom_data + n * this->bottom_dim_, weight, top_data + n * this->top_dim_); if (this->bias_term_) { const Dtype* bias = this->blobs_[1]->cpu_data(); this->forward_cpu_bias(top_data + n * this->top_dim_, bias); } } } template <typename Dtype> void CrossCorrelationLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* weight = bottom[1]->cpu_data(); Dtype* weight_diff = bottom[1]->mutable_cpu_diff(); for (int i = 0; i < 1; ++i) { Dtype* top_diff = top[i]->mutable_cpu_diff(); /* const Dtype* tdata = top[i]->cpu_diff(); std::cout << " CROSS WEIGHT DIFF: " << std::endl; for (int j = 0; j < top[i]->count(); ++j) { std::cout << tdata[j] << " "; } std::cout << std::endl << std::endl << std::endl; */ const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); // Bias gradient, if necessary. if (this->bias_term_) { Dtype* bias_diff = this->blobs_[1]->mutable_cpu_diff(); for (int n = 0; n < this->num_; ++n) { this->backward_cpu_bias(bias_diff, top_diff + n * this->top_dim_); } } if (this->param_propagate_down_[0] || propagate_down[i]) { for (int n = 0; n < this->num_; ++n) { // gradient w.r.t. weight. Note that we will accumulate diffs. if (this->param_propagate_down_[0] || true) { this->weight_cpu_gemm(bottom_data + n * this->bottom_dim_, top_diff + n * this->top_dim_, weight_diff); } // gradient w.r.t. bottom data, if necessary. if (propagate_down[i]) { this->backward_cpu_gemm(top_diff + n * this->top_dim_, weight, bottom_diff + n * this->bottom_dim_); } } } }//end of for #ifdef DEBUG_INFO if (this->layer_param().name() == "cross" || true) { const Dtype* top_diff_0 = top[0]->cpu_diff(); const Dtype* bottom_diff_0 = bottom[0]->cpu_data(); const Dtype* bottom_diff_1 = bottom[1]->cpu_data(); Dtype sum_top_0 = 0.0, sum_bottom_0 = 0.0, sum_bottom_1 = 0.0; std::cout << "top diff: " << std::endl; for (int i = 0; i < top[0]->count(); ++i) { //std::cout << top_diff_0[i] << " "; sum_top_0 += top_diff_0[i]; } std::cout << std::endl; std::cout << "bottom 0 diff: " << std::endl; for (int i = 0; i < 50; ++i) { std::cout << bottom_diff_0[i * 50] << " "; sum_bottom_0 += bottom_diff_0[i]; } std::cout << std::endl; std::cout << "bottom 1 diff: " << std::endl; for (int i = 0; i < 50; ++i) { std::cout << bottom_diff_1[i * 50] << " "; sum_bottom_1 += bottom_diff_1[i]; } std::cout << std::endl; //std::cout << this->layer_param().name() << " cross top 0 bottom 0 1 diff: "; //std::cout << sum_top_0 << " " << sum_bottom_0 << " " << sum_bottom_1 << std::endl; } #endif } #ifdef CPU_ONLY STUB_GPU(CrossCorrelationLayer); #endif INSTANTIATE_CLASS(CrossCorrelationLayer); REGISTER_LAYER_CLASS(CrossCorrelation); } // namespace caffe
40.43956
95
0.640353
NicoleWang
f4cb58df8bc7c0e402744e2a1a91c261ba5edabc
1,797
cpp
C++
src/Display.cpp
yann-boyer/OKUR
f575dbd3d06fa8f669bfadc2918e757168e231be
[ "Zlib" ]
1
2022-03-22T15:10:44.000Z
2022-03-22T15:10:44.000Z
src/Display.cpp
yann-boyer/OKUR
f575dbd3d06fa8f669bfadc2918e757168e231be
[ "Zlib" ]
null
null
null
src/Display.cpp
yann-boyer/OKUR
f575dbd3d06fa8f669bfadc2918e757168e231be
[ "Zlib" ]
null
null
null
/* This file is a part of OKUR. This file contains code to emulate Chip8 screen. Copyright (c) 2022 - Yann BOYER. */ #include "Display.hpp" Display::Display() { chip8Window = SDL_CreateWindow( "OKUR Chip8 Emu by Yann BOYER.", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI ); if(chip8Window == nullptr) { std::cerr << "Unable to create and initialize window !" << std::endl; exit(EXIT_FAILURE); } chip8Renderer = SDL_CreateRenderer(chip8Window, -1, 0); if(chip8Renderer == nullptr) { std::cerr << "Unable to create and initialize renderer !" << std::endl; exit(EXIT_FAILURE); } chip8Texture = SDL_CreateTexture( chip8Renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT ); if(chip8Texture == nullptr) { std::cerr << "Unable to create and initialize texture !" << std::endl; exit(EXIT_FAILURE); } SDL_SetRenderDrawColor(chip8Renderer, 0, 0, 0, 0); SDL_RenderClear(chip8Renderer); SDL_RenderPresent(chip8Renderer); } void Display::bufferGraphics(MMU &mmu) { for(uint8_t y = 0; y < 32; y++) { for(uint8_t x = 0; x < 64; x++) { uint8_t pixel = mmu.gfx[y][x]; pixelBuffer[(y * SCREEN_WIDTH) + x] = (pixel * 0xFFFFFF00) | 0x000000FF; } } } void Display::drawGraphics(void) { SDL_UpdateTexture(chip8Texture, NULL, pixelBuffer, SCREEN_WIDTH * sizeof(uint32_t)); SDL_RenderClear(chip8Renderer); SDL_RenderCopy(chip8Renderer, chip8Texture, NULL, NULL); SDL_RenderPresent(chip8Renderer); } void Display::destroyDisplay(void) { SDL_DestroyWindow(chip8Window); SDL_DestroyRenderer(chip8Renderer); SDL_DestroyTexture(chip8Texture); delete[] pixelBuffer; SDL_Quit(); }
23.337662
85
0.723984
yann-boyer
f4d79e89943264d79c4041097bad11fe2e7f6c89
37,548
cpp
C++
3p/ClassLib/Windows/window.cpp
stbrenner/NiLogViewer
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
[ "MIT" ]
2
2018-11-20T15:58:08.000Z
2021-12-15T14:51:10.000Z
3p/ClassLib/Windows/window.cpp
stbrenner/NiLogViewer
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
[ "MIT" ]
1
2016-12-27T08:26:27.000Z
2016-12-27T08:26:27.000Z
3p/ClassLib/Windows/window.cpp
ymx/NiLogViewer
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
[ "MIT" ]
1
2016-08-09T10:44:48.000Z
2016-08-09T10:44:48.000Z
// // window.cpp // // (C) Copyright 2000 Jan van den Baard. // All Rights Reserved. // #include "window.h" #include "mdiwindow.h" #include "../application.h" #include "../gdi/gdiobject.h" #include "../gdi/dc.h" #include "../menus/menu.h" #include "../menus/bitmapmenu.h" #include "../tools/multimonitor.h" #include "../tools/xpcolors.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Just in case... #ifndef WM_QUERYUISTATE #define WM_CHANGEUISTATE 0x0127 #define WM_UPDATEUISTATE 0x0128 #define WM_QUERYUISTATE 0x0129 #endif // Lists of all window objects created. ClsLinkedList<ClsWindow> temporary_window_list; ClsLinkedList<ClsWindow> global_window_list; typedef BOOL ( CALLBACK *ANIMATEWINDOW )( HWND, DWORD, DWORD ); typedef BOOL ( CALLBACK *SETLAYEREDWINDOWATTRIBUTES )( HWND, COLORREF, BYTE, DWORD ); // Statics. HMENU ClsWindow::s_hMenu = NULL; HWND ClsWindow::s_hMDIClient = NULL; static ANIMATEWINDOW StaticAnimateWindow = NULL; static SETLAYEREDWINDOWATTRIBUTES StaticSetLayeredWindowAttributes = NULL; // Defined in "bitmapmenu.cpp". extern ClsLinkedList<ClsMenu> global_menu_list; // Finds a window object in the list by it's handle // value. ClsWindow *ClsFindObjectByHandle( ClsLinkedList<ClsWindow>& list, HWND hWnd ) { _ASSERT_VALID( hWnd ); // This must be valid. _ASSERT( IsWindow( hWnd )); // Only window handles. // Iterate the nodes. for ( ClsWindow *pWindow = list.GetFirst(); pWindow; pWindow = list.GetNext( pWindow )) { // Is the handle wrapped by this object // the one we are looking for? if ( pWindow->GetSafeHWND() == hWnd ) // Yes. Return a pointer to the object. return pWindow; } // Object not in the list. return NULL; } // Constructor. Setup data field(s). ClsWindow::ClsWindow() { // Setup window type. m_bIsDialog = FALSE; m_bIsMDIFrame = FALSE; m_bIsPopup = FALSE; // Clear data. m_hWnd = NULL; m_lpfnOldWndProc = NULL; m_bDestroyHandle = TRUE; s_hMenu = NULL; // Add this object to the global list. global_window_list.AddHead( this ); } // Destructor. Destroys the window // unless it is detached. ClsWindow::~ClsWindow() { // Destroy the window. Destroy(); // Remove us from the global list if we where // still linked into it. ClsWindow *pWindow; for ( pWindow = global_window_list.GetFirst(); pWindow; pWindow = global_window_list.GetNext( pWindow )) { // Is this us? if ( pWindow == this ) { // Yes. remove us from the list. global_window_list.Remove( this ); return; } } } // Destroys the wrapped window if // possible. void ClsWindow::Destroy() { // Do we wrap a valid handle? if ( GetSafeHWND()) { // Destroy the window. if ( m_bDestroyHandle ) // Destroy the handle. ::DestroyWindow( m_hWnd ); else // Detach the handle to reset // the original window procedure. Detach(); } } // Detaches the window from the // object. HWND ClsWindow::Detach() { // Handle valid? if ( GetSafeHWND()) { // Did we subclass the window? If not we can't // detach it. If we did the window would be left // without a window procedure. if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc ) { // Set back the original window procedure. ::SetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )m_lpfnOldWndProc ); // Get return code. HWND hWnd = m_hWnd; // Clear fields. m_bIsDialog = FALSE; m_hWnd = NULL; m_lpfnOldWndProc = NULL; // Return result. return hWnd; } } return NULL; } // Attach a window handle to this object. This will only // work if this object does not already have a handle // attached to it. BOOL ClsWindow::Attach( HWND hWnd, BOOL bDestroy /* = FALSE */ ) { _ASSERT_VALID( IsWindow( hWnd ) ); // Handle must be valid. _ASSERT( GetSafeHWND() == NULL ); // Already has a handle. // Is the handle already attached to // another object? If so it may not // be set to be destroyed by this object. if ( bDestroy ) { if ( ClsFindObjectByHandle( global_window_list, hWnd ) || ClsFindObjectByHandle( temporary_window_list, hWnd )) { _ASSERT( bDestroy == FALSE ); return FALSE; } } // First we see if the handle is a normal window // or a dialog. TCHAR szClassName[ 10 ]; if ( ::GetClassName( hWnd, szClassName, 10 )) { // Is it a dialog? m_bIsDialog = ( BOOL )( _tcscmp( _T( "#32770" ), szClassName ) == 0 ); // Save the handle. m_hWnd = hWnd; m_bDestroyHandle = bDestroy; // Get the window procedure. m_lpfnOldWndProc = ( WNDPROC )::GetWindowLongPtr( hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC ); // Is the window proc already our static // window procedure? if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc ) { // Call the PreSubclassWindow() override. PreSubclassWindow(); // Subclass the original window // procedure. ::SetWindowLongPtr( hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )ClsWindow::StaticWindowProc ); } // Return success. return TRUE; } // Failed. m_lpfnOldWndProc = NULL; m_hWnd = NULL; return FALSE; } // Create the window. BOOL ClsWindow::Create( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hwndParent, HMENU nIDorHMenu ) { _ASSERT( m_hWnd == NULL ); // Must be zero! // Do we already have a handle? if ( GetSafeHWND() ) return FALSE; // Setup the CREATESTRUCT. CREATESTRUCT cs; cs.dwExStyle = dwExStyle; cs.lpszClass = lpszClassName; cs.lpszName = lpszWindowName; cs.style = dwStyle; cs.x = x; cs.y = y; cs.cx = nWidth; cs.cy = nHeight; cs.hwndParent = hwndParent; cs.hMenu = nIDorHMenu; cs.lpCreateParams = 0L; // Call the PreCreateWindow() function. if ( PreCreateWindow( &cs )) { _ASSERT_VALID( cs.lpszClass ); // This must be known by now! // Create the window. m_hWnd = ::CreateWindowEx( cs.dwExStyle, cs.lpszClass, cs.lpszName, cs.style, cs.x, cs.y, cs.cx, cs.cy, cs.hwndParent, cs.hMenu, ClsGetInstanceHandle(), ( LPVOID )this ); // Subclass the window. if ( m_hWnd ) { // We destroy the handle. m_bDestroyHandle = TRUE; // Get the window procedure. m_lpfnOldWndProc = ( WNDPROC )::GetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC ); // Is the window proc already our static // window procedure? if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc ) { // Call the PreSubclassWindow() override. PreSubclassWindow(); // Subclass the original window // procedure. if ( ::SetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )ClsWindow::StaticWindowProc )) // Return success. return TRUE; } else // Return success. return TRUE; } // return success or failure. return ( BOOL )( m_hWnd ); } return FALSE; } // Create the window. BOOL ClsWindow::Create( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const ClsRect& crBounds, HWND hwndParent, HMENU nIDorHMenu ) { // Create the window. return Create( dwExStyle, lpszClassName, lpszWindowName, dwStyle, crBounds.Left(), crBounds.Top(), crBounds.Width(), crBounds.Height(), hwndParent, nIDorHMenu ); } // Modify the window style. void ClsWindow::ModifyStyle( DWORD dwRemove, DWORD dwAdd, DWORD dwFlags /* = 0 */ ) { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. // First we get the current window style. DWORD dwStyle = ( DWORD )::GetWindowLongPtr( m_hWnd, GWL_STYLE ); // Change bits. dwStyle &= ~dwRemove; dwStyle |= dwAdd; // Change the style. ::SetWindowLongPtr( m_hWnd, GWL_STYLE, ( LONG_PTR )( dwStyle | dwFlags )); } // Modify the extended window style. void ClsWindow::ModifyExStyle( DWORD dwRemove, DWORD dwAdd, DWORD dwFlags /* = 0 */ ) { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. // First we get the current window extended style. DWORD dwExStyle = ( DWORD )::GetWindowLongPtr( m_hWnd, GWL_EXSTYLE ); // Change bits. dwExStyle &= ~dwRemove; dwExStyle |= dwAdd; // Change the extended style. ::SetWindowLongPtr( m_hWnd, GWL_EXSTYLE, ( LONG_PTR )( dwExStyle | dwFlags )); } // Get the rectangle of a child window. ClsRect ClsWindow::GetChildRect( UINT nID ) const { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. ClsRect crRect; GetChildRect( crRect, nID ); return crRect; } // Get the rectangle of a child window. void ClsWindow::GetChildRect( ClsRect& crRect, UINT nID ) const { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. // Get the child window. HWND hWndChild = ::GetDlgItem( m_hWnd, nID ); // OK? if ( hWndChild ) { // Get it's rectangle. ::GetWindowRect( hWndChild, crRect ); // Map to the window. ::MapWindowPoints( NULL, m_hWnd, ( LPPOINT )( LPRECT )crRect, 2 ); } } // Set the window text. void ClsWindow::SetWindowText( LPCTSTR pszText ) { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. // If the hi-order word of "pszText" is 0 // we load the string from the resources. if ( pszText && HIWORD( pszText ) == 0 ) { // Load the string. ClsString str( pszText ); ::SetWindowText( m_hWnd, str ); return; } // Set the text. ::SetWindowText( m_hWnd, pszText ); } // Get the checked radion button. int ClsWindow::GetCheckedRadioButton( int nIDFirstButton, int nIDLastButton ) { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. // Get button checked states. for ( int i = nIDFirstButton; i <= nIDLastButton; i++ ) { // Is it checked? if ( ::IsDlgButtonChecked( m_hWnd, i )) return i; } return 0; } int ClsWindow::GetDlgItemText( int nID, LPTSTR lpStr, int nMaxCount ) const { _ASSERT_VALID( GetSafeHWND() ); ClsWindow *pWindow = GetDlgItem( nID ); if ( pWindow ) return pWindow->GetWindowText( lpStr, nMaxCount ); return 0; } int ClsWindow::GetDlgItemText( int nID, ClsString& rString ) const { _ASSERT_VALID( GetSafeHWND() ); // Must be valid. ClsWindow *pWindow = GetDlgItem( nID ); if ( pWindow ) return pWindow->GetWindowText( rString ); return 0; } void ClsWindow::DeleteTempObjects() { ClsWindow *pWindow; // Remove all objects and delete them. while (( pWindow = temporary_window_list.RemoveHead()) != NULL ) delete pWindow; } // Called just before the window is subclassed. void ClsWindow::PreSubclassWindow() { } // Called just before the window is created. BOOL ClsWindow::PreCreateWindow( LPCREATESTRUCT pCS ) { // Use default class if none is given. if ( pCS->lpszClass == NULL ) pCS->lpszClass = _T( "ClsWindowClass" ); // Continue creating the window. return TRUE; } // Handle message traffic. LRESULT ClsWindow::HandleMessageTraffic() { BOOL bTranslate = FALSE; MSG msg; // Enter the message loop. while ( GetMessage( &msg, NULL, 0, 0 ) > 0 ) { // Accelerator? if ( msg.hwnd == NULL || ( ClsGetApp()->TranslateAccelerator( &msg ))) continue; // Is there an MDI client? If so try to translate the // accelerators. if ( ClsWindow::s_hMDIClient && TranslateMDISysAccel( ClsWindow::s_hMDIClient, &msg )) continue; // Get the message window object. The message window may not // be located in the global window list since it might be a // child of the window located in the global window list. // // For example the messages from a edit control in a combobox // control. In this case, when the message window is not found, // we look up it's parent in the global window list. ClsWindow *pWindow = ClsFindObjectByHandle( global_window_list, msg.hwnd ); if ( pWindow == NULL && IsChild( msg.hwnd )) pWindow = ClsFindObjectByHandle( global_window_list, ::GetParent( msg.hwnd )); // Call the PreTranslateMessage() function to pre-process // the message. if ( pWindow ) { bTranslate = pWindow->PreTranslateMessage( &msg ); } else { // A dialog message for the active window? bTranslate = ::IsDialogMessage( GetActiveWindow(), &msg ); if ( ! bTranslate ) { // Is it a child window? If so we iterate the // parent windows until we find one that // translates the message or has no parent. if ( IsChild( msg.hwnd )) { HWND hParent = ::GetParent( msg.hwnd ); ClsWindow *pTemp; // Does the parent exist? if ( hParent ) { // Wrap the handle. pTemp = ClsWindow::FromHandle( hParent ); // Do a translation. if ( ! pTemp->PreTranslateMessage( &msg )) { // The message did not translate. Iterate until we // find a parent which does. while (( hParent = ::GetParent( hParent )) != NULL ) { // Wrap the handle. pTemp = ClsWindow::FromHandle( hParent ); // Does this one translate? if ( pTemp->PreTranslateMessage( &msg ) == TRUE ) { // Yes. Break up the loop. bTranslate = TRUE; break; } } } else // Message was translated. bTranslate = TRUE; } else { // Try it as a dialog message for the active window. bTranslate = ::IsDialogMessage( ::GetActiveWindow(), &msg ); } } else { // Try it as a dialog message for the active window. bTranslate = ::IsDialogMessage( ::GetActiveWindow(), &msg ); } } } // Can we dispatch? if ( ! bTranslate ) { // Message was not handled. Dispatch it. ::TranslateMessage( &msg ); ::DispatchMessage( &msg ); } // Delete temporary GDI, Window and (Bitmap)Menu objects. ClsGdiObject::DeleteTempObjects(); ClsMenu::DeleteTempObjects(); ClsBitmapMenu::DeleteTempObjects(); ClsWindow::DeleteTempObjects(); } // Return the result. return ( LRESULT )msg.wParam; } // Called just after the WM_NCDESTROY message // was handled. void ClsWindow::PostNcDestroy() { // Reset variables. m_bIsDialog = FALSE; m_hWnd = NULL; m_lpfnOldWndProc = NULL; } // Returns FALSE by default. BOOL ClsWindow::PreTranslateMessage( LPMSG pMsg ) { // Are we a dialog? If so see if the message can be // processed by IsDialogMessage. if ( m_bIsDialog && IsDialogMessage( pMsg )) return TRUE; // Are we a child window? If so we see if our parent // is a dialog and let it have a go at the message // first. ClsWindow *pParent = GetParent(); if ( pParent /*&& pParent->m_bIsDialog*/ && pParent->IsDialogMessage( pMsg )) return TRUE; // Message not processed. return FALSE; } // WM_COMMAND message handler. LRESULT ClsWindow::OnCommand( UINT nNotifyCode, UINT nCtrlID, HWND hWndCtrl ) { // Not handled. return -1; } // Reflected WM_COMMAND message handler. LRESULT ClsWindow::OnReflectedCommand( UINT nNotifyCode, BOOL& bNotifyParent ) { // Not handled. return -1; } // WM_NOTIFY message handler. LRESULT ClsWindow::OnNotify( LPNMHDR pNMHDR ) { // Not handled. return -1; } // Reflected WM_NOTIFY message handler. LRESULT ClsWindow::OnReflectedNotify( LPNMHDR pNMHDR, BOOL& bNotifyParent ) { // Not handled. return -1; } // WM_PAINT message handler. LRESULT ClsWindow::OnPaint( ClsDC *pDC ) { // Not handled. return -1; } // WM_ERASEBKGND message handler. LRESULT ClsWindow::OnEraseBkgnd( ClsDC *pDC ) { // Not handled. return -1; } // WM_SIZE message handler. LRESULT ClsWindow::OnSize( UINT nSizeType, int nWidth, int nHeight ) { // Not handled. return -1; } // WM_MOVE message handler. LRESULT ClsWindow::OnMove( int xPos, int yPos ) { // Not handled. return -1; } // WM_DESTROY message handler. LRESULT ClsWindow::OnDestroy() { // Not handled. return -1; } // WM_CLOSE message handler. LRESULT ClsWindow::OnClose() { // Not handled. return -1; } // WM_MEASUREITEM message handler. LRESULT ClsWindow::OnMeasureItem( UINT nID, LPMEASUREITEMSTRUCT pMis ) { // Not handled. return -1; } // WM_DRAWITEM message handler. LRESULT ClsWindow::OnDrawItem( UINT nID, LPDRAWITEMSTRUCT pDis ) { // Not handled. return -1; } // Reflected WM_MEASUREITEM message handler. LRESULT ClsWindow::OnReflectedMeasureItem( UINT nID, LPMEASUREITEMSTRUCT pMis, BOOL& bNotifyParent ) { // Not handled. return -1; } // Reflected WM_DRAWITEM message handler. LRESULT ClsWindow::OnReflectedDrawItem( UINT nID, LPDRAWITEMSTRUCT pDis, BOOL& bNotifyParent ) { // Not handled. return -1; } // WM_CREATE message handler. LRESULT ClsWindow::OnCreate( LPCREATESTRUCT pCS ) { // Not handled. Note this is a special case. -1 // means failure with WM_CREATE messages. return -2; } // Window procedure. LRESULT ClsWindow::WindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { LRESULT lResult = 0; // Do we have an original window procedure to call? if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc ) // Call the original window procedure. lResult = ::CallWindowProc( m_lpfnOldWndProc, GetSafeHWND(), uMsg, wParam, lParam ); else if ( m_bIsDialog == FALSE ) { // Are we an MDI frame? if ( m_bIsMDIFrame ) // Call the default procedure for MDI frames. // // The casting of the this pointer I do here is dangerous. If someone // decides to create a "ClsWindow" derived class and set the "m_bIsMDIFrame" // we are screwed. For now it works but I should consider another approach... lResult = ::DefFrameProc( GetSafeHWND(), reinterpret_cast< ClsMDIMainWindow * >( this )->GetMDIClient()->GetSafeHWND(), uMsg, wParam, lParam ); else // Call the default window procedure. lResult = ::DefWindowProc( GetSafeHWND(), uMsg, wParam, lParam ); } // Return the result. return lResult; } // By default we use the current window size... BOOL ClsWindow::OnGetMinSize( ClsSize& szMinSize ) { ClsRect rc; GetWindowRect( rc ); szMinSize = rc.Size(); return TRUE; } // Operator overload. ClsWindow::operator HWND() const { return m_hWnd; } LRESULT CALLBACK ClsWindow::StaticWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // We will need this. ClsWindow *pWindow = NULL; BOOL bFromTemp = FALSE; // Do we need to attach the handle to it's // object? if ( uMsg == WM_NCCREATE ) { // The object pointer of this window must be // passed using the lParam field of the // CREATESTRUCT structure. pWindow = ( ClsWindow * )(( LPCREATESTRUCT )lParam )->lpCreateParams; // Should be valid. //_ASSERT_VALID( pWindow ); // Attach us to the object. if ( pWindow ) pWindow->Attach( hWnd, TRUE ); } else if ( uMsg == WM_INITDIALOG ) { _ASSERT_VALID( lParam ); // Must be a valid pointer. // First we check to see if the lParam parameter is // an object from our global window list. for ( pWindow = global_window_list.GetFirst(); pWindow != ( ClsWindow * )lParam && pWindow; pWindow = global_window_list.GetNext( pWindow )); // If the object was not found in the list it must be // a PROPSHEETPAGE pointer. In this case the object should // be in the lParam field of this structure. if ( pWindow == NULL ) pWindow = ( ClsWindow * )(( PROPSHEETPAGE * )lParam )->lParam; // Should be valid. _ASSERT_VALID( pWindow ); // Attach us to the object. pWindow->Attach( hWnd, TRUE ); } else { // When we reach this place the handle must be attached // already. pWindow = ClsFindObjectByHandle( global_window_list, hWnd ); if ( pWindow == NULL ) { // We were not located in the globals list // so we must be in the temporary list. bFromTemp = TRUE; pWindow = ClsFindObjectByHandle( temporary_window_list, hWnd ); } } // Do we have a valid object pointer? if ( pWindow != NULL && pWindow->GetSafeHWND() ) { // Preset message result. LRESULT lResult = -1; // Get message type. switch ( uMsg ) { case WM_UPDATEUISTATE: case WM_SYSCOLORCHANGE: // Update XP colorschemes. XPColors.CreateColorTable(); // Pass on to the children. EnumChildWindows( pWindow->GetSafeHWND(), DistributeMessage, WM_SYSCOLORCHANGE ); // Fall through when the message was WM_UPDATEUISTATE... if ( uMsg == WM_SYSCOLORCHANGE ) break; case WM_CHANGEUISTATE: // Are we a child window? if ( pWindow->GetStyle() & WS_CHILD ) // Repaint... pWindow->Invalidate(); break; case WM_CREATE: // Call virtual message handler. lResult = pWindow->OnCreate(( LPCREATESTRUCT )lParam ); break; case WM_CLOSE: // Call virtual message handler. lResult = pWindow->OnClose(); break; case WM_DESTROY: { // Does this window have a menu? HMENU hMenu = pWindow->GetMenu(); if ( hMenu ) { // See if it is wrapped by an object in the global // menu list. for ( ClsMenu *pMenu = global_menu_list.GetFirst(); pMenu; pMenu = global_menu_list.GetNext( pMenu )) { // Is this it? if ( *pMenu == hMenu ) { // We detach the menu from the window before the window // destroys the menu handle. This is necessary because the // destructor of "ClsBitmapMenu" derived classes need the // handle valid to free used resources. pWindow->SetMenu( NULL ); break; } } } // Call virtual message handler. lResult = pWindow->OnDestroy(); break; } case WM_MOVE: // Call virtual message handler. lResult = pWindow->OnMove(( int )LOWORD( lParam ), ( int )HIWORD( lParam )); break; case WM_SIZE: // Call virtual message handler. lResult = pWindow->OnSize(( UINT )wParam, ( int )LOWORD( lParam ), ( int )HIWORD( lParam )); break; case WM_PAINT: { // Do we have a DC? ClsDC *pDC = wParam ? ClsDC::FromHandle(( HDC )wParam ) : NULL; // Call virtual message handler. lResult = pWindow->OnPaint( pDC ); break; } case WM_ERASEBKGND: { // Wrap handle. ClsDC *pDC = ClsDC::FromHandle(( HDC )wParam ); // Call virtual message handler. lResult = pWindow->OnEraseBkgnd( pDC ); break; } case WM_INITMENU: // Store the menu handle which just opened. ClsWindow::s_hMenu = ( HMENU )wParam; // OK? if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // Get object and call OnReflectedInitMenu() overidable. ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu ); if ( pMenu ) pMenu->OnReflectedInitMenu( pWindow ); } break; case WM_INITMENUPOPUP: // Menu handle OK? if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // Get object and call OnReflectedInitMenuPopup() overidable. ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu ); if ( pMenu ) pMenu->OnReflectedInitMenuPopup( pWindow, ( HMENU )wParam, LOWORD( lParam ), HIWORD( lParam )); } break; case WM_UNINITMENUPOPUP: // Menu handle OK? if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // Get object and call OnReflectedUnInitMenuPopup() overidable. ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu ); if ( pMenu ) pMenu->OnReflectedUnInitMenuPopup( pWindow, ( HMENU )wParam, lParam ); } break; case WM_EXITMENULOOP: // Menu handle OK? if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // Get object and call OnReflectedInitMenuPopup() overidable. ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu ); if ( pMenu ) pMenu->OnReflectedExitMenuLoop( pWindow, ( BOOL )wParam ); } // Clear the menu handle. ClsWindow::s_hMenu = NULL; break; case WM_MEASUREITEM: // Control? if ( wParam ) { // Try to get the window object of the control. ClsWindow *pChild = pWindow->FromHandle( pWindow->GetDlgItemHandle((( LPMEASUREITEMSTRUCT )lParam )->CtlID )); // Found it? if ( pChild ) { // By default we do notify the parent. BOOL bNotifyParent = TRUE; // Reflect the measure item message to the child // window. lResult = pChild->OnReflectedMeasureItem(( UINT )wParam, ( LPMEASUREITEMSTRUCT )lParam, bNotifyParent ); // Are we a dialog? if ( lResult != -1 && pWindow->IsDialog()) { // Set message result. pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult ); lResult = TRUE; } // Should we notify the parent? if ( ! bNotifyParent ) break; } } else { // Find the menu. if ( ! ClsWindow::s_hMenu ) ClsWindow::s_hMenu = pWindow->GetMenu(); if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // By default we do notify the parent. BOOL bNotifyParent = TRUE; // Wrap the handle. ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu ); if ( pMenu ) { // Call the overidable. lResult = pMenu->OnReflectedMeasureItem(( LPMEASUREITEMSTRUCT ) lParam, bNotifyParent ); // Are we a dialog? if ( lResult != -1 && pWindow->IsDialog()) { // Set message result. pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult ); lResult = TRUE; } // Should we notify the parent? if ( ! bNotifyParent ) break; } } } // Call virtual message handler. lResult = pWindow->OnMeasureItem(( UINT )wParam, ( LPMEASUREITEMSTRUCT )lParam ); break; case WM_DRAWITEM: // Control? if ( wParam ) { // Try to get the window object of the control. ClsWindow *pChild = pWindow->FromHandle( pWindow->GetDlgItemHandle((( LPDRAWITEMSTRUCT )lParam )->CtlID )); // Found it? if ( pChild ) { // By default we do notify the parent. BOOL bNotifyParent = TRUE; // Reflect the draw item message to the child // window. lResult = pChild->OnReflectedDrawItem(( UINT )wParam, ( LPDRAWITEMSTRUCT )lParam, bNotifyParent ); // Are we a dialog? if ( lResult != -1 && pWindow->IsDialog()) { // Set message result. pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult ); lResult = TRUE; } // Should we notify the parent? if ( ! bNotifyParent ) break; } } else { // Find the menu. if ( ! ClsWindow::s_hMenu ) ClsWindow::s_hMenu = pWindow->GetMenu(); if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // By default we do notify the parent. BOOL bNotifyParent = TRUE; // Wrap the handle. ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu ); if ( pMenu ) { // Call the overidable. lResult = pMenu->OnReflectedDrawItem(( LPDRAWITEMSTRUCT )lParam, bNotifyParent ); // Are we a dialog? if ( lResult != -1 && pWindow->IsDialog()) { // Set message result. pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult ); lResult = TRUE; } // Should we notify the parent? if ( ! bNotifyParent ) break; } } } // Call virtual message handler. lResult = pWindow->OnDrawItem(( UINT )wParam, ( LPDRAWITEMSTRUCT )lParam ); break; case WM_COMMAND: { // Message originates from a control? if ( lParam ) { // Try to get the window object of the control which // sent the message. ClsWindow *pChild = ClsFindObjectByHandle( global_window_list, ( HWND )lParam ); // Found it? if ( pChild ) { // By default we do notify the parent. BOOL bNotifyParent = TRUE; // Reflect the command message to the child // window. lResult = pChild->OnReflectedCommand(( UINT )HIWORD( wParam ), bNotifyParent ); // Are we a dialog? if ( lResult != -1 && pWindow->IsDialog()) { // Set message result. pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult ); lResult = TRUE; } // Should we notify the parent? if ( ! bNotifyParent ) break; } } // Call virtual message handler. lResult = pWindow->OnCommand(( UINT )HIWORD( wParam ), ( UINT )LOWORD( wParam ), ( HWND )lParam ); break; } case WM_NOTIFY: LPNMHDR pNMHDR = ( LPNMHDR )lParam; // Try to get the window object of the // notification control. ClsWindow *pChild = ClsFindObjectByHandle( global_window_list, pNMHDR->hwndFrom ); // Where we able to find the object in our // global list? if ( pChild ) { // By default we do notify the parent. BOOL bNotifyParent = TRUE; // Reflect the notification message to the // child window. lResult = pChild->OnReflectedNotify( pNMHDR, bNotifyParent ); // Are we a dialog? if ( lResult != -1 && pWindow->IsDialog()) { // Set message result. pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult ); lResult = TRUE; } // Must we notify the parent? if ( ! bNotifyParent ) break; } // Simply forward the message. pWindow->OnNotify( pNMHDR ); break; } // Are we still alive? //if ( ! bFromTemp ) // for ( ClsWindow *pTmp = global_window_list.GetFirst(); pTmp != pWindow && pTmp; pTmp = global_window_list.GetNext( pTmp )); //else // for ( ClsWindow *pTmp = temporary_window_list.GetFirst(); pTmp != pWindow && pTmp; pTmp = temporary_window_list.GetNext( pTmp )); // // We may not have been deleted by any of the virtual // message handlers! //_ASSERT( pTmp != NULL ); // If the message was not handled (lResult is -1) and the // object window handle is still valid we call the virtual // window procedure. // // Note: The WM_CREATE message is a special case which returns // -2 when the message was not handled since -1 indicates that // the window should not be created when -1 is returned. if ((( lResult == -1 && uMsg != WM_CREATE ) || ( lResult == -2 && uMsg == WM_CREATE )) && pWindow->GetSafeHWND()) // Call the procedure. lResult = pWindow->WindowProc( uMsg, wParam, lParam ); // Are we being destroyed? if ( uMsg == WM_NCDESTROY ) { // detach the handle from the object. if ( pWindow->GetSafeHWND()) { // Detach the handle. pWindow->Detach(); // Just in case these are not cleared which will // happen when the window has the ClsWindow::StaticWindowProc // as the default window procedure. pWindow->m_hWnd = NULL; pWindow->m_lpfnOldWndProc = NULL; } // Call the PostNcDestroy() routine if the class pointer // still exists in the global window list. ClsWindow *pTmp; for ( pTmp = global_window_list.GetFirst(); pTmp; pTmp = global_window_list.GetNext( pTmp )) { // Is this it? if ( pTmp == pWindow ) { // Call it. pWindow->PostNcDestroy(); return lResult; } } } // return the result of the message handling. return lResult; } // We did not find the handle in our global // window list which means that it was not (yet) // attached to a ClsWindow object. // // In this case we simply let windows handle // the messages. TCHAR szClassName[ 10 ]; // Get the class name of the window. if ( ::GetClassName( hWnd, szClassName, 10 )) { // Is it a dialog box? If so we return 0 and do not // call the default window procedure. if ( _tcscmp( _T( "#32770" ), szClassName ) == 0 ) return 0; } // Return the result of the default window // procedure. return ::DefWindowProc( hWnd, uMsg, wParam, lParam ); } // Helper which will try to locate the window object of the // given handle. If it does not find it it will create an // object for it and append it to the temporary object list. ClsWindow *ClsWindow::FindWindow( HWND hWnd ) { // Return NULL if the input is NULL. if ( hWnd == NULL ) return NULL; // First we try to locate the handle in the // global window list. ClsWindow *pWindow = ClsFindObjectByHandle( global_window_list, hWnd ); // Found it? if ( pWindow == NULL ) { // No. Try to locate it in our temporary object list. pWindow = ClsFindObjectByHandle( temporary_window_list, hWnd ); if ( pWindow == NULL ) { // Not found. Create a new object. pWindow = new ClsWindow; pWindow->Attach( hWnd ); // Remove it from the global list and // move it into the temporary object list. global_window_list.Remove( pWindow ); temporary_window_list.AddHead( pWindow ); } } // Return the object. return pWindow; } // Close all windows marked as being a popup. void ClsWindow::ClosePopups() { // Iterate the global window list. ClsWindow *pWindow; for ( pWindow = global_window_list.GetFirst(); pWindow; pWindow = global_window_list.GetNext( pWindow )) { // A popup? if ( pWindow->m_bIsPopup ) { // Get a pointer to the next in the list. Close the popup // and set the pointer to the next. ClsWindow *pNext = global_window_list.GetNext( pWindow ); pWindow->SendMessage( WM_CLOSE ); pWindow = pNext; } } // Iterate the temporary window list. for ( pWindow = temporary_window_list.GetFirst(); pWindow; pWindow = temporary_window_list.GetNext( pWindow )) { // A popup? if ( pWindow->m_bIsPopup ) { // Get a pointer to the next in the list. Close the popup // and set the pointer to the next. ClsWindow *pNext = temporary_window_list.GetNext( pWindow ); pWindow->SendMessage( WM_CLOSE ); pWindow = pNext; } } } // Center the window on another window or // on the desktop. BOOL ClsWindow::CenterWindow( ClsWindow *pOn ) { _ASSERT_VALID( GetSafeHWND() ); // Obtain the child window // screen bounds. ClsRect rc, prc, screen; GetWindowRect( rc ); // Get the rectangle of the display monitor which // the window intersects the most. ClsMultiMon mon; int nMonitor; mon.MonitorNumberFromWindow( GetSafeHWND(), MONITOR_DEFAULTTONEAREST, nMonitor ); mon.GetMonitorRect( nMonitor, prc, TRUE ); screen = prc; // Do we have a valid parent // handle? if ( pOn ) // Obtain the parent window // screen bounds. pOn->GetWindowRect( prc ); // Compute offsets... int x = prc.Left() + (( prc.Width() / 2 ) - ( rc.Width() / 2 )); int y = prc.Top() + (( prc.Height() / 2 ) - ( rc.Height() / 2 )); // Make sure the whole window remains visible on the screen. if (( x + rc.Width()) > screen.Right()) x = screen.Right() - rc.Width(); if ( x < screen.Left()) x = screen.Left(); if (( y + rc.Height()) > screen.Bottom()) y = screen.Bottom() - rc.Height(); if ( y < screen.Top()) y = screen.Top(); // Move the window so that it is // centered. return SetWindowPos( NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE ); } // AnimateWindow() API. BOOL ClsWindow::AnimateWindow( DWORD dwTime, DWORD dwFlags ) { _ASSERT_VALID( GetSafeHWND()); // Must be valid. // Just in case... #ifndef AW_HIDE #define AW_HIDE 0x00010000 #endif // Function known? if ( StaticAnimateWindow ) return ( *StaticAnimateWindow )( m_hWnd, dwTime, dwFlags ); // Get the procedure address. StaticAnimateWindow = ( ANIMATEWINDOW )GetProcAddress( GetModuleHandle( _T( "user32.dll" )), "AnimateWindow" ); if ( StaticAnimateWindow ) return ( *StaticAnimateWindow )( m_hWnd, dwTime, dwFlags ); return FALSE; } // SetLayeredWindowAttributes() API. BOOL ClsWindow::SetLayeredWindowAttributes( COLORREF crKey, BYTE bAlpha, DWORD dwFlags ) { _ASSERT_VALID( GetSafeHWND()); // Must be valid. // Function known? if ( StaticSetLayeredWindowAttributes ) return ( *StaticSetLayeredWindowAttributes )( m_hWnd, crKey, bAlpha, dwFlags ); // Get the procedure address. StaticSetLayeredWindowAttributes = ( SETLAYEREDWINDOWATTRIBUTES )GetProcAddress( GetModuleHandle( _T( "user32.dll" )), "SetLayeredWindowAttributes" ); if ( StaticSetLayeredWindowAttributes ) return ( *StaticSetLayeredWindowAttributes )( m_hWnd, crKey, bAlpha, dwFlags ); return FALSE; } // Get a pointer to the active menu object. ClsMenu *ClsWindow::GetActiveMenu() { // Is there an active menu? if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu )) { // Look it up. ClsMenu *pMenu; for ( pMenu = global_menu_list.GetFirst(); pMenu; pMenu = global_menu_list.GetNext( pMenu )) { // Is this the one? if (( HMENU )*pMenu == ClsWindow::s_hMenu ) return pMenu; } } return NULL; } // Get state of the UI. DWORD ClsWindow::GetUIState() const { _ASSERT_VALID( GetSafeHWND()); // Must be valid. // Supported? if ( ClsGetApp()->GetPlatformID() == VER_PLATFORM_WIN32_NT && ClsGetApp()->GetMajorVersion() >= 5 ) // Get the UI state. return ( DWORD )::SendMessage( m_hWnd, WM_QUERYUISTATE, 0, 0 ); // No UI state. return 0L; } // Functions which make use of the ClsDC class. ClsDC *ClsWindow::BeginPaint( LPPAINTSTRUCT pPaintStruct ) { _ASSERT_VALID( GetSafeHWND() ); _ASSERT_VALID( pPaintStruct ); return ClsDC::FromHandle( ::BeginPaint( m_hWnd, pPaintStruct )); } ClsDC *ClsWindow::GetDC() { _ASSERT_VALID( GetSafeHWND() ); return ClsDC::FromHandle( ::GetDC( m_hWnd )); } ClsDC *ClsWindow::GetDCEx( ClsRgn* prgnClip, DWORD flags ) { _ASSERT_VALID( GetSafeHWND() ); return ClsDC::FromHandle( ::GetDCEx( m_hWnd, prgnClip ? ( HRGN )*prgnClip : NULL, flags )); } ClsDC *ClsWindow::GetWindowDC() { _ASSERT_VALID( GetSafeHWND() ); return ClsDC::FromHandle( ::GetWindowDC( m_hWnd )); } int ClsWindow::ReleaseDC( ClsDC *pDC ) { _ASSERT_VALID( GetSafeHWND() ); return ::ReleaseDC( m_hWnd, *pDC ); }
26.800857
177
0.6562
stbrenner
f4d992fa6259231d30a542a191c9d94793d23fc2
3,110
cpp
C++
libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
31
2020-04-29T06:11:54.000Z
2021-11-10T19:14:09.000Z
libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
11
2020-07-27T17:12:05.000Z
2021-12-01T16:33:18.000Z
libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
null
null
null
// // KeyframeTrackHeader.cpp // ofxGuiWidgetDOMintegration // // Created by Roy Macdonald on 4/12/20. // #include "LineaDeTiempo/View/KeyframeTrackHeader.h" #include "LineaDeTiempo/View/TrackGroupView.h" #include "LineaDeTiempo/View/BaseTrackView.h" namespace ofx { namespace LineaDeTiempo { template<typename ParamType> KeyframeTrackHeader<ParamType>::KeyframeTrackHeader(ofParameter<ParamType> & param, const std::string& id, const ofRectangle& rect, BaseTrackView* track, TrackGroupView* group, bool belongsToPanel) : TrackHeader(id, rect, track, group, belongsToPanel) { _gui = addChild<ofxGuiView<ParamType>>(param, group->getTracksHeaderWidth(), this); _gui->setPosition(0, 0);//ConstVars::ViewTopHeaderHeight); _ofxGuiHeightChangeListener = _gui->shapeChanged.newListener(this, &KeyframeTrackHeader::_ofxGuiHeightChange); _colorListener = track->colorChangeEvent.newListener(this, &KeyframeTrackHeader::_colorChanged); } template<typename ParamType> float KeyframeTrackHeader<ParamType>::_getMinHeight() { return _gui->getShape().getMaxY(); } template<typename ParamType> void KeyframeTrackHeader<ParamType>::_onShapeChange(const DOM::ShapeChangeEventArgs& e) { if(e.widthChanged()) { _gui->setWidth(getWidth()); } } template<typename ParamType> void KeyframeTrackHeader<ParamType>::_ofxGuiHeightChange(DOM::ShapeChangeEventArgs& args) { if(args.changedVertically()) { if(getHeight() < args.shape.getMaxY()) { setHeight(args.shape.getMaxY()); } } } template<typename ParamType> void KeyframeTrackHeader<ParamType>::onDraw() const { // the intention of this override is to avoid the drawing of the TrackHeader class } template<typename ParamType> void KeyframeTrackHeader<ParamType>::_colorChanged(ofColor& color) { if(_gui && _gui->getOfxGui()) { _gui->getOfxGui()->setHeaderBackgroundColor(color); _gui->getOfxGui()->setBackgroundColor(color); } } template class KeyframeTrackHeader<ofRectangle>; template class KeyframeTrackHeader<ofColor>; template class KeyframeTrackHeader<ofShortColor>; template class KeyframeTrackHeader<ofFloatColor>; template class KeyframeTrackHeader<glm::vec2>; template class KeyframeTrackHeader<glm::vec3>; template class KeyframeTrackHeader<glm::vec4>; //template class KeyframeTrackHeader<glm::quat>; //template class KeyframeTrackHeader<glm::mat4>; template class KeyframeTrackHeader<bool>; template class KeyframeTrackHeader<void>; template class KeyframeTrackHeader<int8_t>; template class KeyframeTrackHeader<uint8_t>; template class KeyframeTrackHeader<int16_t>; template class KeyframeTrackHeader<uint16_t>; template class KeyframeTrackHeader<int32_t>; template class KeyframeTrackHeader<uint32_t>; template class KeyframeTrackHeader<int64_t>; template class KeyframeTrackHeader<uint64_t>; template class KeyframeTrackHeader<float>; template class KeyframeTrackHeader<double>; #ifndef TARGET_LINUX template class KeyframeTrackHeader<typename std::conditional<std::is_same<uint32_t, size_t>::value || std::is_same<uint64_t, size_t>::value, bool, size_t>::type>; #endif } } // ofx::LineaDeTiempo
26.581197
198
0.791318
roymacdonald
f4dbb4983a66a6d8cdf4192b8d85e3ba544a2928
104,662
cpp
C++
sxaccelerate/src/math/SxBlasLib.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
sxaccelerate/src/math/SxBlasLib.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
sxaccelerate/src/math/SxBlasLib.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The general purpose cross platform C/C++ framework // // S x A c c e l e r a t e // // Home: https://www.sxlib.de // License: Apache 2 // Authors: see src/AUTHORS // // --------------------------------------------------------------------------- // ref1 - Comp. Phys. Comm (128), 1-45 (2000) //#include <stdio.h> //#include <string.h> //#include <stdlib.h> //#include <iostream> #include <math.h> #include <SxBlasLib.h> #include <SxError.h> #ifdef USE_OPENMP #include <omp.h> #endif //#include <SxRandom.h> // --- BLAS, LAPACK #if defined(USE_VECLIB) //# include <veclib.h> // --- don't use HP header files! //# include <lapack.h> // more details in SxMLIB.h # include <SxMLIB.h> #elif defined (ESSE_ESSL) // --- before including ESSL we have to do a messy definition // otherwise it doesn't compile. i don't know a better way. // see also: SxFFT.h # define _ESV_COMPLEX_ # include <complex> # include <essl.h> #elif defined (USE_INTEL_MKL) // mkl uses 'long long', which is not ISO C++. Disable errors here. //#pragma GCC diagnostic push //#pragma GCC diagnostic warning "-Wlong-long" extern "C" { # include <mkl.h> } //#pragma GCC diagnostic pop #elif defined (USE_ACML) extern "C" { # include <acml.h> } #elif defined (USE_GOTO) // khr: GotoBLAS, experimental! # define blasint int extern "C" { # include <f2c.h> # include <cblas.h> # include <clapack.h> } #elif defined (USE_ATLAS) # if defined (USE_ACCELERATE_FRAMEWORK) # include <Accelerate/Accelerate.h> typedef __CLPK_integer integer; typedef __CLPK_logical logical; typedef __CLPK_real real; typedef __CLPK_doublereal doublereal; typedef __CLPK_ftnlen ftnlen; typedef __CLPK_complex complex; typedef __CLPK_doublecomplex doublecomplex; # else extern "C" { # include <f2c.h> # include <cblas.h> # include <clapack.h> } # endif /* USE_ACCELERATE_FRAMEWORK */ #else # error "No numeric library specified" // make sure that we do not drown in error messages #define SX_IGNORE_THE_REST_OF_THE_FILE #endif #ifndef SX_IGNORE_THE_REST_OF_THE_FILE //------------------------------------------------------------------------------ // BLAS/LAPACK error handling //------------------------------------------------------------------------------ #if defined (USE_VECLIB) // error handling not yet supported #elif defined (USE_ESSL) // error handling not yet supported #elif defined (USE_INTEL_MKL) // error handling not yet supported #elif defined (USE_ACML) // error handling not yet supported #elif defined (USE_GOTO) // error handling not yet supported #else # include <stdarg.h> #ifdef MACOSX # if ( DIST_VERSION_L >= 1070L ) extern "C" void cblas_xerbla (int p, char *rout, char *form, ...) # else extern "C" void cblas_xerbla (int p, const char *rout, const char *form, ...) # endif /* DIST_VERSION_L */ #else extern "C" void cblas_xerbla (int p, const char *rout, const char *form, ...) #endif /* MACOSX */ { //sxprintf ("\nA BLAS/LAPACK error has occured!\n"); std::cout << "\nA BLAS/LAPACK error has occured!\n"; // --- original code from ATLAS/interfaces/blas/C/src/cblas_xerbla.c va_list argptr; va_start(argptr, form); # ifdef GCCWIN //if (p) sxprintf("Parameter %d to routine %s was incorrect\n", p, rout); if (p) std::cout << "Parameter " << p << " to routine " << rout << " was incorrect\n"; vprintf(form, argptr); # else if (p) fprintf(stderr, "Parameter %d to routine %s was incorrect\n", p, rout); vfprintf(stderr, form, argptr); # endif /* CYGWIN */ va_end(argptr); // --- end of original ATLAS code SX_EXIT; } #endif /* USE_VECLIB */ //------------------------------------------------------------------------------ // norm of vectors //------------------------------------------------------------------------------ float norm2 (const float *vec, int n) { int incx = 1; # if defined (USE_VECLIB) return snrm2 (&n, (float *)vec, &incx); # elif defined (USE_ESSL) return snrm2 (n, vec, incx); # elif defined (USE_INTEL_MKL) return snrm2 (&n, const_cast<float *>(vec), &incx); # elif defined (USE_ACML) return snrm2 (n, const_cast<float *>(vec), incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! return cblas_snrm2 (n, const_cast<float *>(vec), incx); # else return cblas_snrm2 (n, vec, incx); # endif } double norm2 (const double *vec, int n) { int incx = 1; # if defined (USE_VECLIB) return dnrm2 (&n, (double *)vec, &incx); # elif defined (USE_ESSL) return dnrm2 (n, vec, incx); # elif defined (USE_INTEL_MKL) return dnrm2 (&n, const_cast<double *>(vec), &incx); # elif defined (USE_ACML) return dnrm2 (n, const_cast<double *>(vec), incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! return cblas_dnrm2 (n, const_cast<double*>(vec), incx); # else return cblas_dnrm2 (n, vec, incx); # endif } float norm2 (const SxComplex8 *vec, int n) { int incx = 1; # if defined (USE_VECLIB) return scnrm2 (&n, (complex8_t *)vec, &incx); # elif defined (USE_ESSL) return scnrm2 (n, (const complex<float> *)vec, incx); # elif defined (USE_INTEL_MKL) return scnrm2 (&n, (MKL_Complex8 *)const_cast<SxComplex8 *>(vec), &incx); # elif defined (USE_ACML) return scnrm2 (n, (complex *)const_cast<SxComplex8 *>(vec), incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! return cblas_scnrm2 (n, (float*)vec, incx); # else return cblas_scnrm2 (n, vec, incx); # endif } double norm2 (const SxComplex16 *vec, int n) { int incx = 1; # if defined (USE_VECLIB) return dznrm2 (&n, (complex16_t *)vec, &incx); # elif defined (USE_ESSL) return dznrm2 (n, (const complex<double> *)vec, incx); # elif defined (USE_INTEL_MKL) return dznrm2 (&n, (MKL_Complex16 *)const_cast<SxComplex16*>(vec), &incx); # elif defined (USE_ACML) return dznrm2 (n, (doublecomplex *)const_cast<SxComplex16 *>(vec), incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! return cblas_dznrm2 (n, (double*)vec, incx); # else return cblas_dznrm2 (n, vec, incx); # endif } //------------------------------------------------------------------------------ // scale vectors //------------------------------------------------------------------------------ void scale (float *vec, const float alpha, int n) { int incx = 1; # if defined (USE_VECLIB) sscal (&n, (float *)&alpha, (float *)vec, &incx); # elif defined (USE_ESSL) sscal (n, alpha, vec, incx); # elif defined (USE_INTEL_MKL) sscal (&n, const_cast<float *>(&alpha), (float *)vec, &incx); # elif defined (USE_ACML) sscal (n, alpha, vec, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_sscal (n, alpha, vec, incx); # else cblas_sscal (n, alpha, vec, incx); # endif } void scale (double *vec, const double alpha, int n) { int incx = 1; # if defined (USE_VECLIB) dscal (&n, (double *)&alpha, (double *)vec, &incx); # elif defined (USE_ESSL) dscal (n, alpha, vec, incx); # elif defined (USE_INTEL_MKL) dscal (&n, const_cast<double *>(&alpha), (double *)vec, &incx); # elif defined (USE_ACML) dscal (n, alpha, vec, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_dscal (n, alpha, vec, incx); # else cblas_dscal (n, alpha, vec, incx); # endif } void scale (SxComplex8 *vec, const SxComplex8 &alpha, int n) { int incx = 1; # if defined (USE_VECLIB) cscal (&n, (complex8_t *)&alpha, (complex8_t *)vec, &incx); # elif defined (USE_ESSL) const complex<float> alphaTmp (alpha.re, alpha.im); cscal (n, alphaTmp, (complex<float> *)vec, incx); # elif defined (USE_INTEL_MKL) cscal (&n, (MKL_Complex8 *)const_cast<SxComplex8*>(&alpha), (MKL_Complex8 *)vec, &incx); # elif defined (USE_ACML) cscal (n, (complex *)const_cast<SxComplex8 *>(&alpha), (complex *)vec, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_cscal (n, (float*)&alpha, (float*)vec, incx); # else cblas_cscal (n, &alpha, vec, incx); # endif } void scale (SxComplex16 *vec, const SxComplex16 &alpha, int n) { int incx = 1; # if defined (USE_VECLIB) zscal (&n, (complex16_t *)&alpha, (complex16_t *)vec, &incx); # elif defined (USE_ESSL) const complex<double> alphaTmp (alpha.re, alpha.im); zscal (n, alphaTmp, (complex<double> *)vec, incx); # elif defined (USE_INTEL_MKL) zscal (&n, (MKL_Complex16 *)const_cast<SxComplex16*>(&alpha), (MKL_Complex16 *)vec, &incx); # elif defined (USE_ACML) zscal (n, (doublecomplex *)const_cast<SxComplex16 *>(&alpha), (doublecomplex *)vec, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_zscal (n, (double*)&alpha, (double*)vec, incx); # else cblas_zscal (n, &alpha, vec, incx); # endif } //------------------------------------------------------------------------------ // Y += a*X //------------------------------------------------------------------------------ void axpy (float *yOut, const float &alpha, const float *xIn, int n) { int incx = 1; # if defined (USE_VECLIB) saxpy (&n, (float *)&alpha, (float *)xIn, &incx, (float *)yOut, &incx); # elif defined (USE_ESSL) saxpy (n, a, (float *)xIn, incx, (float *)yOut, incx); # elif defined (USE_INTEL_MKL) saxpy (&n, const_cast<float *>(&alpha), const_cast<float *>(xIn), &incx, yOut, &incx); # elif defined (USE_ACML) saxpy (n, alpha, (float *)const_cast<float *>(xIn), incx, (float *)yOut, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_saxpy (n, alpha, const_cast<float*>(xIn), incx, yOut, incx); # else cblas_saxpy (n, alpha, xIn, incx, yOut, incx); # endif } void axpy (double *yOut, const double &alpha, const double *xIn, int n) { int incx = 1; # if defined (USE_VECLIB) daxpy (&n, (double *)&alpha, (double *)xIn, &incx, (double *)yOut, &incx); # elif defined (USE_ESSL) daxpy (n, a, (double *)xIn, incx, (double *)yOut, incx); # elif defined (USE_INTEL_MKL) daxpy (&n, const_cast<double *>(&alpha), const_cast<double *>(xIn), &incx, (double *)yOut, &incx); # elif defined (USE_ACML) daxpy (n, alpha, (double *)const_cast<double *>(xIn), incx, (double *)yOut, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_daxpy (n, alpha, const_cast<double*>(xIn), incx, yOut, incx); # else cblas_daxpy (n, alpha, xIn, incx, yOut, incx); # endif } void axpy (SxComplex8 *yOut, const SxComplex8 &alpha, const SxComplex8 *xIn, int n) { int incx = 1; # if defined (USE_VECLIB) caxpy (&n, (complex8_t *)&alpha, (complex8_t *)xIn, &incx, (complex8_t *)yOut, &incx); # elif defined (USE_ESSL) const complex<double> alphaTmp (alpha.re, alpha.im); caxpy (n, alphaTmp, (complex<float> *)xIn, incx, (complex<float> *)yOut, incx); # elif defined (USE_INTEL_MKL) caxpy (&n, (MKL_Complex8 *)const_cast<SxComplex8 *>(&alpha), (MKL_Complex8 *)const_cast<SxComplex8 *>(xIn), &incx, (MKL_Complex8 *)yOut, &incx); # elif defined (USE_ACML) caxpy (n, (complex *)const_cast<SxComplex8 *>(&alpha), (complex *)const_cast<SxComplex8 *>(xIn), incx, (complex *)yOut, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_caxpy (n, (float*)&alpha, (float*)xIn, incx, (float*)yOut, incx); # else cblas_caxpy (n, &alpha, xIn, incx, yOut, incx); # endif } void axpy (SxComplex16 *yOut, const SxComplex16 &alpha, const SxComplex16 *xIn, int n) { int incx = 1; # if defined (USE_VECLIB) zaxpy (&n, (complex16_t *)&alpha, (complex16_t *)xIn, &incx, (complex16_t *)yOut, &incx); # elif defined (USE_ESSL) const complex<double> alphaTmp (alpha.re, alpha.im); zaxpy (n, alphaTmp, (complex<double> *)xIn, incx, (complex<double> *)yOut, incx); # elif defined (USE_INTEL_MKL) zaxpy (&n, (MKL_Complex16 *)const_cast<SxComplex16 *>(&alpha), (MKL_Complex16 *)const_cast<SxComplex16 *>(xIn), &incx, (MKL_Complex16 *)yOut, &incx); # elif defined (USE_ACML) zaxpy (n, (doublecomplex *)const_cast<SxComplex16 *>(&alpha), (doublecomplex *)const_cast<SxComplex16 *>(xIn), incx, (doublecomplex *)yOut, incx); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_zaxpy (n, (double*)&alpha, (double*)xIn, incx, (double*)yOut, incx); # else cblas_zaxpy (n, &alpha, xIn, incx, yOut, incx); # endif } //------------------------------------------------------------------------------ // scalar product //------------------------------------------------------------------------------ float scalarProduct (const float *aVec, const float *bVec, int n) { const float *aPtr = aVec; const float *bPtr = bVec; float res = 0.; for (int i=0; i < n; i++, aPtr++, bPtr++) res += *aPtr * *bPtr; return res; } double scalarProduct (const double *aVec, const double *bVec, int n) { const double *aPtr = aVec; const double *bPtr = bVec; double res = 0; for (int i=0; i < n; i++, aPtr++, bPtr++) res += *aPtr * *bPtr; return res; } SxComplex8 scalarProduct (const SxComplex8 *aVec, const SxComplex8 *bVec, int n) { const SxComplex8 *aPtr = aVec; const SxComplex8 *bPtr = bVec; SxComplex8 res = (SxComplex8)0.; for (int i=0; i < n; i++, aPtr++, bPtr++) res += aPtr->conj() * *bPtr; return res; } SxComplex16 scalarProduct (const SxComplex16 *aVec, const SxComplex16 *bVec, int n) { const SxComplex16 *aPtr = aVec; const SxComplex16 *bPtr = bVec; SxComplex16 res = (SxComplex8)0.; for (int i=0; i < n; i++, aPtr++, bPtr++) res += aPtr->conj() * *bPtr; return res; } //------------------------------------------------------------------------------ // general matrix-matrix multiplication //------------------------------------------------------------------------------ void matmult (float *resMat, const float *aMat, const float *bMat, int aMatRows, int aMatCols, int bMatCols) { float alpha = 1.0, beta = 0.0; # if defined (USE_VECLIB) char noTrans = 'N'; sgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, &alpha, (float *)aMat, &aMatRows, (float *)bMat, &aMatCols, &beta, (float *)resMat, &aMatRows, 0, 0); # elif defined (USE_ESSL) const char noTrans = 'N'; sgemm (&noTrans, &noTrans, aMatRows, bMatCols, aMatCols, alpha, aMat, aMatRows, bMat, aMatCols, beta, resMat, aMatRows); # elif defined (USE_INTEL_MKL) char noTrans = 'N'; sgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, &alpha, const_cast<float *>(aMat), &aMatRows, const_cast<float *>(bMat), &aMatCols, &beta, resMat, &aMatRows); # elif defined (USE_ACML) char noTrans = 'N'; sgemm (noTrans, noTrans, aMatRows, bMatCols, aMatCols, alpha, const_cast<float *>(aMat), aMatRows, const_cast<float *>(bMat), aMatCols, beta, resMat, aMatRows); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_sgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, alpha, const_cast<float*>(aMat), aMatRows, const_cast<float*>(bMat), aMatCols, beta, resMat, aMatRows); # else cblas_sgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, alpha, aMat, aMatRows, bMat, aMatCols, beta, resMat, aMatRows); # endif } void matmult (double *resMat, const double *aMat, const double *bMat, int aMatRows, int aMatCols, int bMatCols) { double alpha = 1.0, beta = 0.0; # if defined (USE_VECLIB) char noTrans = 'N'; dgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, &alpha, (double *)aMat, &aMatRows, (double *)bMat, &aMatCols, &beta, (double *)resMat, &aMatRows, 0, 0); # elif defined (USE_ESSL) const char noTrans = 'N'; dgemm (&noTrans, &noTrans, aMatRows, bMatCols, aMatCols, alpha, aMat, aMatRows, bMat, aMatCols, beta, resMat, aMatRows); # elif defined (USE_INTEL_MKL) char noTrans = 'N'; dgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, &alpha, const_cast<double *>(aMat), &aMatRows, const_cast<double *>(bMat), &aMatCols, &beta, resMat, &aMatRows); # elif defined (USE_ACML) char noTrans = 'N'; dgemm (noTrans, noTrans, aMatRows, bMatCols, aMatCols, alpha, const_cast<double *>(aMat), aMatRows, const_cast<double *>(bMat), aMatCols, beta, resMat, aMatRows); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, alpha, const_cast<double*>(aMat), aMatRows, const_cast<double*>(bMat), aMatCols, beta, resMat, aMatRows); # else cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, alpha, aMat, aMatRows, bMat, aMatCols, beta, resMat, aMatRows); # endif } void matmult (SxComplex8 *resMat, const SxComplex8 *aMat, const SxComplex8 *bMat, int aMatRows, int aMatCols, int bMatCols) { SxComplex8 alpha (1.0, 0.0), beta (0.0, 0.0); # if defined (USE_VECLIB) char noTrans = 'N'; cgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, (complex8_t *)&alpha, (complex8_t *)aMat, &aMatRows, (complex8_t *)bMat, &aMatCols, (complex8_t *)&beta, (complex8_t *)resMat, &aMatRows, 0, 0); # elif defined (USE_ESSL) const char noTrans = 'N'; complex<float> alphaT (alpha.re, alpha.im); complex<float> betaT (beta.re, beta.im); cgemm (&noTrans, &noTrans, aMatRows, bMatCols, aMatCols, alphaT, (complex<float> *)aMat, aMatRows, (complex<float> *)bMat, aMatCols, betaT, (complex<float> *)resMat, aMatRows); # elif defined (USE_INTEL_MKL) char noTrans = 'N'; cgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, (MKL_Complex8 *)&alpha, (MKL_Complex8 *)const_cast<SxComplex8 *>(aMat), &aMatRows, (MKL_Complex8 *)const_cast<SxComplex8 *>(bMat), &aMatCols, (MKL_Complex8 *)&beta, (MKL_Complex8 *)resMat, &aMatRows); # elif defined (USE_ACML) char noTrans = 'N'; cgemm (noTrans, noTrans, aMatRows, bMatCols, aMatCols, (complex *)const_cast<SxComplex8 *>(&alpha), (complex *)const_cast<SxComplex8 *>(aMat), aMatRows, (complex *)const_cast<SxComplex8 *>(bMat), aMatCols, (complex *)const_cast<SxComplex8 *>(&beta), (complex *)resMat, aMatRows); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! cblas_cgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, (float*)&alpha, (float*)aMat, aMatRows, (float*)bMat, aMatCols, (float*)&beta, (float*)resMat, aMatRows); # else cblas_cgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, &alpha, aMat, aMatRows, bMat, aMatCols, &beta, resMat, aMatRows); # endif } void matmult (SxComplex16 *resMat, const SxComplex16 *aMat, const SxComplex16 *bMat, int aMatRows, int aMatCols, int bMatCols) { SxComplex16 alpha (1.0, 0.0), beta (0.0, 0.0); # if defined (USE_VECLIB) char noTrans = 'N'; zgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, (complex16_t *)&alpha, (complex16_t *)aMat, &aMatRows, (complex16_t *)bMat, &aMatCols, (complex16_t *)&beta, (complex16_t *)resMat, &aMatRows, 0, 0); # elif defined (USE_ESSL) const char noTrans = 'N'; complex<double> alphaT (alpha.re, alpha.im); complex<double> betaT (beta.re, beta.im); zgemm (&noTrans, &noTrans, aMatRows, bMatCols, aMatCols, alphaT, (complex<double> *)aMat, aMatRows, (complex<double> *)bMat, aMatCols, betaT, (complex<double> *)resMat, aMatRows); # elif defined (USE_INTEL_MKL) char noTrans = 'N'; zgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols, (MKL_Complex16 *)&alpha, (MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows, (MKL_Complex16 *)const_cast<SxComplex16 *>(bMat), &aMatCols, (MKL_Complex16 *)&beta, (MKL_Complex16 *)resMat, &aMatRows); # elif defined (USE_ACML) char noTrans = 'N'; zgemm (noTrans, noTrans, aMatRows, bMatCols, aMatCols, (doublecomplex *)const_cast<SxComplex16 *>(&alpha), (doublecomplex *)const_cast<SxComplex16 *>(aMat), aMatRows, (doublecomplex *)const_cast<SxComplex16 *>(bMat), aMatCols, (doublecomplex *)const_cast<SxComplex16 *>(&beta), (doublecomplex *)resMat, aMatRows); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! if (bMatCols == 1) { cblas_zgemv (CblasColMajor, CblasNoTrans, aMatRows, aMatCols, (double*)&alpha, (double*)aMat, aMatRows, (double*)bMat, 1, (double*)&beta, (double*)resMat, 1); } else if (aMatRows == 1) { cblas_zgemv (CblasColMajor, CblasTrans, aMatCols, bMatCols, (double*)&alpha, (double*)bMat, aMatCols, (double*)aMat, 1, (double*)&beta, (double*)resMat, 1); } else { cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, (double*)&alpha, (double*)aMat, aMatRows, (double*)bMat, aMatCols, (double*)&beta, (double*)resMat, aMatRows); } # else if (bMatCols == 1) { cblas_zgemv (CblasColMajor, CblasNoTrans, aMatRows, aMatCols, &alpha, aMat, aMatRows, bMat, 1, &beta, resMat, 1); } else if (aMatRows == 1) { cblas_zgemv (CblasColMajor, CblasTrans, aMatCols, bMatCols, &alpha, bMat, aMatCols, aMat, 1, &beta, resMat, 1); } else { #if defined(USE_OPENMP) && defined(USE_ATLAS) if (aMatRows > 1024) { # pragma omp parallel { int nThreads = omp_get_num_threads (); int nb = aMatRows / nThreads; // distribute remaining elements over all threads if (nb * nThreads < aMatRows) nb++; int offset = omp_get_thread_num () * nb; // reduce nb for last thread if (offset + nb > aMatRows) nb = aMatRows - offset; cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, nb, bMatCols, aMatCols, &alpha, aMat + offset, aMatRows, bMat, aMatCols, &beta, resMat + offset, aMatRows); } } else // no openMP parallelism ... #endif cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, aMatRows, bMatCols, aMatCols, &alpha, aMat, aMatRows, bMat, aMatCols, &beta, resMat, aMatRows); } # endif } //------------------------------------------------------------------------------ // overlap matrices //------------------------------------------------------------------------------ void matovlp (float *resMat, const float *aMat, const float *bMat, int aMatRows, int aMatCols, int bMatRows, int bMatCols, int sumSize) { float alpha = 1.0, beta = 0.0; # if defined (USE_VECLIB) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; sgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, &alpha, (float *)aMat, &aMatRows, (float *)bMat, &bMatRows, &beta, (float *)resMat, &aMatCols, 0, 0); # elif defined (USE_ESSL) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; sgemm (&conjTrans, &noTrans, aMatCols, bMatCols, sumSize, alpha, aMat, aMatRows, bMat, bMatRows, beta, resMat, aMatCols); # elif defined (USE_INTEL_MKL) // SX_EXIT; // not tested // change by khr char noTrans = 'N', conjTrans = 'C'; sgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, &alpha, const_cast<float *>(aMat), &aMatRows, const_cast<float *>(bMat), &bMatRows, &beta, resMat, &aMatCols); # elif defined (USE_ACML) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; sgemm (conjTrans, noTrans, aMatCols, bMatCols, sumSize, alpha, const_cast<float *>(aMat), aMatRows, const_cast<float *>(bMat), bMatRows, beta, resMat, aMatCols); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! if (bMatCols == 1) { cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, alpha, const_cast<float*>(aMat), aMatRows, const_cast<float*>(bMat), 1, beta, resMat, 1); } else if (aMatCols == 1) { cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, alpha, const_cast<float*>(bMat), bMatRows, const_cast<float*>(aMat), 1, beta, resMat, 1); } else { cblas_sgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, alpha, const_cast<float *>(aMat), aMatRows, const_cast<float*>(bMat), bMatRows, beta, resMat, aMatCols); } # else if (bMatCols == 1) { cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, alpha, aMat, aMatRows, bMat, 1, beta, resMat, 1); } else if (aMatCols == 1) { cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, alpha, bMat, bMatRows, aMat, 1, beta, resMat, 1); } else { cblas_sgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, alpha, aMat, aMatRows, bMat, bMatRows, beta, resMat, aMatCols); } # endif } void matovlp (double *resMat, const double *aMat, const double *bMat, int aMatRows, int aMatCols, int bMatRows, int bMatCols, int sumSize) { double alpha = 1.0, beta = 0.0; # if defined (USE_VECLIB) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; dgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, &alpha, (double *)aMat, &aMatRows, (double *)bMat, &bMatRows, &beta, (double *)resMat, &aMatCols, 0, 0); # elif defined (USE_ESSL) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; dgemm (&conjTrans, &noTrans, aMatCols, bMatCols, sumSize, alpha, aMat, aMatRows, bMat, bMatRows, beta, resMat, aMatCols); # elif defined (USE_INTEL_MKL) // SX_EXIT; // not tested // change by khr char noTrans = 'N', conjTrans = 'C'; dgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, &alpha, const_cast<double *>(aMat), &aMatRows, const_cast<double *>(bMat), &bMatRows, &beta, resMat, &aMatCols); # elif defined (USE_ACML) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; dgemm (conjTrans, noTrans, aMatCols, bMatCols, sumSize, alpha, const_cast<double *>(aMat), aMatRows, const_cast<double *>(bMat), bMatRows, beta, resMat, aMatCols); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! if (bMatCols == 1) { cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, alpha, const_cast<double*>(aMat), aMatRows, const_cast<double*>(bMat), 1, beta, resMat, 1); } else if (aMatCols == 1) { cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, alpha, const_cast<double*>(bMat), bMatRows, const_cast<double*>(aMat), 1, beta, resMat, 1); } else { cblas_dgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, alpha, const_cast<double*>(aMat), aMatRows, const_cast<double*>(bMat), bMatRows, beta, resMat, aMatCols); } # else if (bMatCols == 1) { cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, alpha, aMat, aMatRows, bMat, 1, beta, resMat, 1); } else if (aMatCols == 1) { cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, alpha, bMat, bMatRows, aMat, 1, beta, resMat, 1); } else { cblas_dgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, alpha, aMat, aMatRows, bMat, bMatRows, beta, resMat, aMatCols); } # endif } void matovlp (SxComplex8 *resMat, const SxComplex8 *aMat, const SxComplex8 *bMat, int aMatRows, int aMatCols, int bMatRows, int bMatCols, int sumSize) { SxComplex8 alpha (1.0, 0.0), beta (0.0, 0.0); # if defined (USE_VECLIB) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; cgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, (complex8_t *)&alpha, (complex8_t *)aMat, &aMatRows, (complex8_t *)bMat, &bMatRows, (complex8_t *)&beta, (complex8_t *)resMat, &aMatCols, 0, 0); # elif defined (USE_ESSL) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; complex<float> alphaT (alpha.re, alpha.im); complex<float> betaT (beta.re, beta.im); cgemm (&conjTrans, &noTrans, aMatCols, bMatCols, sumSize, alphaT, (complex<float> *)aMat, aMatRows, (complex<float> *)bMat, bMatRows, betaT, (complex<float> *)resMat, aMatCols); # elif defined (USE_INTEL_MKL) char noTrans = 'N', conjTrans = 'C'; cgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, (MKL_Complex8 *)&alpha, (MKL_Complex8 *)const_cast<SxComplex8 *>(aMat), &aMatRows, (MKL_Complex8 *)const_cast<SxComplex8 *>(bMat), &bMatRows, (MKL_Complex8 *)&beta, (MKL_Complex8 *)resMat, &aMatCols); # elif defined (USE_ACML) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; cgemm (conjTrans, noTrans, aMatCols, bMatCols, sumSize, (complex *)const_cast<SxComplex8 *>(&alpha), (complex *)const_cast<SxComplex8 *>(aMat), aMatRows, (complex *)const_cast<SxComplex8 *>(bMat), bMatRows, (complex *)const_cast<SxComplex8 *>(&beta), (complex *)resMat, aMatCols); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! if (bMatCols == 1) { cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, (float*)&alpha, (float*)aMat, aMatRows, (float*)bMat, 1, (float*)&beta, (float*)resMat, 1); } else if (aMatCols == 1) { cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, (float*)&alpha, (float*)bMat, bMatRows, (float*)aMat, 1, (float*)&beta, (float*)resMat, 1); // now resMat contains (B.adjoint () ^ A) // perform conjugate (note: res is a vector) for (ssize_t i = 0; i < bMatCols; ++i) resMat[i].im = -resMat[i].im; } else { cblas_cgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, (float*)&alpha, (float*)aMat, aMatRows, (float*)bMat, bMatRows, (float*)&beta, (float*)resMat, aMatCols); } # else if (bMatCols == 1) { cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, &alpha, aMat, aMatRows, bMat, 1, &beta, resMat, 1); } else if (aMatCols == 1) { cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, &alpha, bMat, bMatRows, aMat, 1, &beta, resMat, 1); // now resMat contains (B.adjoint () ^ A) // perform conjugate (note: res is a vector) for (ssize_t i = 0; i < bMatCols; ++i) resMat[i].im = -resMat[i].im; } else { cblas_cgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, &alpha, aMat, aMatRows, bMat, bMatRows, &beta, resMat, aMatCols); } # endif } /* #include <SxTimer.h> enum BlasLibTimer { Matovlp }; REGISTER_TIMERS (BlasLibTimer) { regTimer (Matovlp, "matovlp"); } */ void matovlp (SxComplex16 *resMat, const SxComplex16 *aMat, const SxComplex16 *bMat, int aMatRows, int aMatCols, int bMatRows, int bMatCols, int sumSize) { SxComplex16 alpha (1.0, 0.0), beta (0.0, 0.0); # if defined (USE_VECLIB) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; zgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, (complex16_t *)&alpha, (complex16_t *)aMat, &aMatRows, (complex16_t *)bMat, &bMatRows, (complex16_t *)&beta, (complex16_t *)resMat, &aMatCols, 0, 0); # elif defined (USE_ESSL) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; complex<double> alphaT (alpha.re, alpha.im); complex<double> betaT (beta.re, beta.im); zgemm (&conjTrans, &noTrans, aMatCols, bMatCols, sumSize, alphaT, (complex<double> *)aMat, aMatRows, (complex<double> *)bMat, bMatRows, betaT, (complex<double> *)resMat, aMatCols); # elif defined (USE_INTEL_MKL) char noTrans = 'N', conjTrans = 'C'; if (aMat == bMat && aMatRows == bMatRows && aMatCols == bMatCols) { // special case: A.overlap (A) => use Hermitean routine ... char uplo = 'U'; zherk (&uplo, &conjTrans, &aMatCols, &sumSize, &alpha.re, (MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows, &beta.re, (MKL_Complex16 *)resMat, &aMatCols); // ... and copy upper half to lower half for (int i = 0; i < aMatCols; i++) for (int j = 0; j < i; j++) resMat[i + aMatCols * j] = resMat[j + aMatCols * i].conj (); } else { zgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize, (MKL_Complex16 *)&alpha, (MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows, (MKL_Complex16 *)const_cast<SxComplex16 *>(bMat), &bMatRows, (MKL_Complex16 *)&beta, (MKL_Complex16 *)resMat, &aMatCols); } # elif defined (USE_ACML) SX_EXIT; // not tested char noTrans = 'N', conjTrans = 'C'; zgemm (conjTrans, noTrans, aMatCols, bMatCols, sumSize, (doublecomplex *)const_cast<SxComplex16 *>(&alpha), (doublecomplex *)const_cast<SxComplex16 *>(aMat), aMatRows, (doublecomplex *)const_cast<SxComplex16 *>(bMat), bMatRows, (doublecomplex *)const_cast<SxComplex16 *>(&beta), (doublecomplex *)resMat, aMatCols); # elif defined (USE_GOTO) // khr: GotoBLAS, experimental! if (bMatCols == 1) { cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, (double*)&alpha, (double*)aMat, aMatRows, (double*)bMat, 1, (double*)&beta, (double*)resMat, 1); } else if (aMatCols == 1) { cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, (double*)&alpha, (double*)bMat, bMatRows, (double*)aMat, 1, (double*)&beta, (double*)resMat, 1); // now resMat contains (B.adjoint () ^ A) // perform conjugate (note: res is a vector) for (ssize_t i = 0; i < bMatCols; ++i) resMat[i].im = -resMat[i].im; } else { cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, (double*)&alpha, (double*)aMat, aMatRows, (double*)bMat, bMatRows, (double*)&beta, (double*)resMat, aMatCols); } # else if (bMatCols == 1) { cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols, &alpha, aMat, aMatRows, bMat, 1, &beta, resMat, 1); } else if (aMatCols == 1) { cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols, &alpha, bMat, bMatRows, aMat, 1, &beta, resMat, 1); // now resMat contains (B.adjoint () ^ A) // perform conjugate (note: res is a vector) for (ssize_t i = 0; i < bMatCols; ++i) resMat[i].im = -resMat[i].im; } else { #ifndef USE_OPENMP cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize, &alpha, aMat, aMatRows, bMat, bMatRows, &beta, resMat, aMatCols); #else //CLOCK (Matovlp); int nb = 128; int np = sumSize / nb; // --- compute contribution from rest elements if (sumSize > nb * np) { cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, sumSize - nb * np, &alpha, aMat + nb * np, aMatRows, bMat + nb * np, bMatRows, &beta, resMat, aMatCols); } else { for (int i = 0; i < aMatCols * bMatCols; ++i) resMat[i].re = resMat[i].im = 0.; } # pragma omp parallel { SxComplex16 *part = NULL; // --- compute partial results (in parallel) # pragma omp for for (int ip = 0; ip < np; ip++) { if (!part) { part = new SxComplex16[aMatCols * bMatCols]; cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, nb, &alpha, aMat + ip * nb, aMatRows, bMat + ip * nb, bMatRows, &beta, part, aMatCols); } else { cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans, aMatCols, bMatCols, nb, &alpha, aMat + ip * nb, aMatRows, bMat + ip * nb, bMatRows, &alpha, part, aMatCols); } } // --- sum partial results if (part) { # pragma omp critical cblas_zaxpy (aMatCols * bMatCols, &alpha, part, 1, resMat, 1); delete [] part; } } # endif } # endif } //------------------------------------------------------------------------------ // Matrix decompositions //------------------------------------------------------------------------------ void cholesky (float *resMat, enum UPLO uplo, float * /*inMat*/, int n) { char uploChar = (uplo == UpperRight) ? 'U' : 'L'; # if defined (USE_VECLIB) int err = 0; spotrf (&uploChar, &n, (float *)resMat, &n, &err, 0); # elif defined (USE_ESSL) int err = 0; spotrf (&uploChar, n, resMat, n, err); # elif defined (USE_INTEL_MKL) int err = 0; spotrf (&uploChar, &n, resMat, &n, &err); # elif defined (USE_ACML) int err = 0; spotrf (uploChar, n, resMat, n, &err); # else integer rank = (integer)n, err = 0; spotrf_ (&uploChar, &rank, (real *)resMat, &rank, &err); if ( err ) { // TODO: throw exception std::cout << "cholesky err=" << err << std::endl; SX_EXIT; } # endif } void cholesky (double *resMat, enum UPLO uplo, double * /*inMat*/, int n) { char uploChar = (uplo == UpperRight) ? 'U' : 'L'; # if defined (USE_VECLIB) int err = 0; dpotrf (&uploChar, &n, (double *)resMat, &n, &err, 0); # elif defined (USE_ESSL) int err = 0; dpotrf (&uploChar, n, resMat, n, err); # elif defined (USE_INTEL_MKL) int err = 0; dpotrf (&uploChar, &n, resMat, &n, &err); # elif defined (USE_ACML) int err = 0; dpotrf (uploChar, n, resMat, n, &err); # else integer rank = (integer)n, err = 0; dpotrf_ (&uploChar, &rank, (doublereal *)resMat, &rank, &err); if ( err ) { // TODO: throw exception std::cout << "cholesky err=" << err << std::endl; SX_EXIT; } # endif } void cholesky (SxComplex8 *resMat, enum UPLO uplo, SxComplex8 * /*inMat*/, int n) { char uploChar = (uplo == UpperRight) ? 'U' : 'L'; # if defined (USE_VECLIB) int err = 0; cpotrf (&uploChar, &n, (complex8_t *)resMat, &n, &err, 0); # elif defined (USE_ESSL) int err = 0; cpotrf (&uploChar, n, (complex<float> *)resMat, n, err); # elif defined (USE_INTEL_MKL) int err = 0; cpotrf (&uploChar, &n, (MKL_Complex8 *)resMat, &n, &err); # elif defined (USE_ACML) int err = 0; cpotrf (uploChar, n, (complex *)resMat, n, &err); # else integer rank = (integer)n, err = 0; cpotrf_ (&uploChar, &rank, (complex *)resMat, &rank, &err); if ( err ) { // TODO: throw exception std::cout << "cholesky err=" << err << std::endl; SX_EXIT; } # endif } void cholesky (SxComplex16 *resMat, enum UPLO uplo, SxComplex16 * /*inMat*/, int n) { char uploChar = (uplo == UpperRight) ? 'U' : 'L'; # if defined (USE_VECLIB) int err = 0; zpotrf (&uploChar, &n, (complex16_t *)resMat, &n, &err, 0); # elif defined (USE_ESSL) int err = 0; zpotrf (&uploChar, n, (complex<double> *)resMat, n, err); # elif defined (USE_INTEL_MKL) int err = 0; zpotrf(&uploChar, &n, (MKL_Complex16 *)resMat, &n, &err); # elif defined (USE_ACML) int err = 0; zpotrf(uploChar, n, (doublecomplex *)resMat, n, &err); # else integer rank = (integer)n, err = 0; zpotrf_ (&uploChar, &rank, (doublecomplex *)resMat, &rank, &err); if ( err ) { // TODO: throw exception std::cout << "cholesky err=" << err << std::endl; SX_EXIT; } # endif } void singularValueDecomp (float *mat, int nRows, int nCols, float *vals, float *left, float *right, // V^H bool zeroSpace) { char jobz = zeroSpace ? 'A' // U= M x M, V=N x N : 'S'; // U=M x s, V= s x N if (!left || !right) { jobz = 'N'; if (left || right) { // It is not possible to compute only left or only right vectors. std::cout << "Internal error in singular-value decomposition" << std::endl; SX_EXIT; } } int minMN = nRows < nCols ? nRows : nCols; int ldvt = zeroSpace ? nCols : minMN; # if defined (USE_VECLIB) SX_EXIT; // not yet implemented # elif defined (USE_ESSL) SX_EXIT; // not yet implemented # elif defined (USE_INTEL_MKL) // workspace query: int *iwork = new int[8 * minMN]; int err = 0; int lwork = -1; float optwork; sgesdd(&jobz, &nRows, &nCols, mat, &nRows, vals, left, &nRows, right, &ldvt, &optwork, &lwork, iwork, &err ); if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = (int)optwork; float* work = new float[lwork]; // --- actual compute sgesdd(&jobz, &nRows, &nCols, mat, &nRows, vals, left, &nRows, right, &ldvt, work, &lwork, iwork, &err ); delete[] work; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # elif defined (USE_ACML) SX_EXIT; # else integer *iwork = new integer[8 * minMN]; integer lwork = -1; integer err = 0; // workspace query: float optwork; integer nr = nRows, nc = nCols, ldvt_ = ldvt; sgesdd_(&jobz, &nr, &nc, mat, &nr, vals, left, &nr, right, &ldvt_, &optwork, &lwork, iwork, &err ); if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = (integer)optwork; float* work = new float[lwork]; // --- actual compute sgesdd_(&jobz, &nr, &nc, mat, &nr, vals, left, &nr, right, &ldvt_, work, &lwork, iwork, &err ); delete[] work; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # endif delete[] iwork; } void singularValueDecomp (double *mat, int nRows, int nCols, double *vals, double *left, double *right, // V^H bool zeroSpace) { char jobz = zeroSpace ? 'A' // U= M x M, V=N x N : 'S'; // U=M x s, V= s x N if (!left || !right) { jobz = 'N'; if (left || right) { // It is not possible to compute only left or only right vectors. std::cout << "Internal error in singular-value decomposition" << std::endl; SX_EXIT; } } int minMN = nRows < nCols ? nRows : nCols; int ldvt = zeroSpace ? nCols : minMN; # if defined (USE_VECLIB) SX_EXIT; // not yet implemented # elif defined (USE_ESSL) SX_EXIT; // not yet implemented # elif defined (USE_INTEL_MKL) // workspace query: int err = 0; int *iwork = new int[8 * minMN]; int lwork = -1; double optwork; dgesdd(&jobz, &nRows, &nCols, mat, &nRows, vals, left, &nRows, right, &ldvt, &optwork, &lwork, iwork, &err ); if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = int(lround(optwork)); double* work = new double[lwork]; // --- actual compute dgesdd(&jobz, &nRows, &nCols, mat, &nRows, vals, left, &nRows, right, &ldvt, work, &lwork, iwork, &err ); delete[] work; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # elif defined (USE_ACML) SX_EXIT; # else integer err = 0; integer lwork = -1; integer *iwork = new integer[8 * minMN]; // workspace query: double optwork; integer nr = nRows, nc = nCols, ldvt_ = ldvt; dgesdd_(&jobz, &nr, &nc, mat, &nr, vals, left, &nr, right, &ldvt_, &optwork, &lwork, iwork, &err ); if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = (integer)optwork; double* work = new double[lwork]; // --- actual compute dgesdd_(&jobz, &nr, &nc, mat, &nr, vals, left, &nr, right, &ldvt_, work, &lwork, iwork, &err ); delete[] work; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # endif delete[] iwork; } void singularValueDecomp (SxComplex8 *mat, int nRows, int nCols, float *vals, SxComplex8 *left, SxComplex8 *right, // V^H bool zeroSpace) { char jobz = zeroSpace ? 'A' // U= M x M, V=N x N : 'S'; // U=M x s, V= s x N if (!left || !right) { jobz = 'N'; if (left || right) { // It is not possible to compute only left or only right vectors. std::cout << "Internal error in singular-value decomposition" << std::endl; SX_EXIT; } } int minMN = nRows < nCols ? nRows : nCols; # if defined (USE_VECLIB) SX_EXIT; // not yet implemented # elif defined (USE_ESSL) SX_EXIT; // not yet implemented # elif defined (USE_INTEL_MKL) int ldvt = zeroSpace ? nCols : minMN; int lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN); int err = 0; int lwork = -1; float *rwork = new float[lrwork]; int *iwork = new int[8 * minMN]; // workspace query: MKL_Complex8 optwork; cgesdd(&jobz, &nRows, &nCols, (MKL_Complex8*)mat, &nRows, vals, (MKL_Complex8*)left, &nRows, (MKL_Complex8*)right, &ldvt, &optwork, &lwork, rwork, iwork, &err ); if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = int(lround(optwork.real)); MKL_Complex8* work = new MKL_Complex8[lwork]; // --- actual compute cgesdd(&jobz, &nRows, &nCols, (MKL_Complex8*)mat, &nRows, vals, (MKL_Complex8*)left, &nRows, (MKL_Complex8*)right, &ldvt, work, &lwork, rwork, iwork, &err ); delete[] work; delete[] iwork; delete[] rwork; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # elif defined (USE_ACML) SX_EXIT; # else integer ldvt = zeroSpace ? nCols : minMN; integer lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN); integer err = 0; integer lwork = -1; float *rwork = new float[lrwork]; integer *iwork = new integer[8 * minMN]; // workspace query: integer nr = nRows, nc = nCols; complex optwork; SX_EXIT; /* missing prototype cgesdd_(&jobz, &nr, &nc, (complex *)mat, &nr, vals, (complex*)left, &nr, (complex*)right, &ldvt, &optwork, &lwork, rwork, iwork, &err ); */ if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = (integer)optwork.r; complex* work = new complex[lwork]; // --- actual compute SX_EXIT; /* missing prototype cgesdd_(&jobz, &nr, &nc, (complex *)mat, &nr, vals, (complex*)left, &nr, (complex*)right, &ldvt, work, &lwork, rwork, iwork, &err ); */ delete[] work; delete[] iwork; delete[] rwork; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # endif } void singularValueDecomp (SxComplex16 *mat, int nRows, int nCols, double *vals, SxComplex16 *left, SxComplex16 *right, // V^H bool zeroSpace) { char jobz = zeroSpace ? 'A' // U= M x M, V=N x N : 'S'; // U=M x s, V= s x N if (!left || !right) { jobz = 'N'; if (left || right) { // It is not possible to compute only left or only right vectors. std::cout << "Internal error in singular-value decomposition" << std::endl; SX_EXIT; } } int minMN = nRows < nCols ? nRows : nCols; # if defined (USE_VECLIB) SX_EXIT; // not yet implemented # elif defined (USE_ESSL) SX_EXIT; // not yet implemented # elif defined (USE_INTEL_MKL) int ldvt = zeroSpace ? nCols : minMN; int lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN); int err = 0; int lwork = -1; double *rwork = new double[lrwork]; int *iwork = new int[8 * minMN]; // workspace query: MKL_Complex16 optwork; zgesdd(&jobz, &nRows, &nCols, (MKL_Complex16*)mat, &nRows, vals, (MKL_Complex16*)left, &nRows, (MKL_Complex16*)right, &ldvt, &optwork, &lwork, rwork, iwork, &err ); if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = int(lround(optwork.real)); MKL_Complex16* work = new MKL_Complex16[lwork]; // --- actual compute zgesdd(&jobz, &nRows, &nCols, (MKL_Complex16*)mat, &nRows, vals, (MKL_Complex16*)left, &nRows, (MKL_Complex16*)right, &ldvt, work, &lwork, rwork, iwork, &err ); delete[] work; delete[] iwork; delete[] rwork; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # elif defined (USE_ACML) SX_EXIT; # else integer ldvt = zeroSpace ? nCols : minMN; integer lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN); integer err = 0; integer lwork = -1; double *rwork = new double[lrwork]; integer *iwork = new integer[8 * minMN]; // workspace query: doublecomplex optwork; integer nr = nRows, nc = nCols; SX_EXIT; /* missing prototype: zgesdd_(&jobz, &nr, &nc, (doublecomplex *)mat, &nr, vals, (doublecomplex*)left, &nr, (doublecomplex*)right, &ldvt, &optwork, &lwork, rwork, iwork, &err ); */ if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } lwork = (integer)optwork.r; doublecomplex* work = new doublecomplex[lwork]; // --- actual compute /* missing prototype: zgesdd_(&jobz, &nr, &nc, (doublecomplex *)mat, &nr, vals, (doublecomplex*)left, &nr, (doublecomplex*)right, &ldvt, work, &lwork, rwork, iwork, &err ); */ delete[] work; delete[] iwork; delete[] rwork; if (err) { std::cout << "svd err = " << err << std::endl; SX_EXIT; } # endif } //------------------------------------------------------------------------------ // Matrix inversion //------------------------------------------------------------------------------ void matInverse (float *mat, int nRows, int nCols) { # if defined (USE_VECLIB) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; sgetrf (&nRows, &nCols, (float *)mat, &r, pivots, &err); # elif defined (USE_ESSL) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; sgetrf (nRows, nCols, mat, r, pivots, err); # elif defined (USE_INTEL_MKL) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; sgetrf (&nRows, &nCols, mat, &r, pivots, &err); # elif defined (USE_ACML) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; sgetrf (nRows, nCols, mat, r, pivots, &err); # else integer r = (integer)nRows, c = (integer)nCols, err = 0; integer *pivots = new integer[r < c ? r : c]; sgetrf_ (&r, &c, (real *)mat, &r, pivots, &err); # endif if (err) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in SGETRF: " << err <<std::endl; delete [] pivots; SX_EXIT; } // --- (2) diagonalization # if defined (USE_VECLIB) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) float *work = new float [lWork]; sgetri (&r, (float *)mat, &r, pivots, work, &lWork, &err); # elif defined (USE_ESSL) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) float *work = new float [lWork]; sgetri (r, mat, r, pivots, work, lWork, err); # elif defined (USE_INTEL_MKL) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) float *work = new float [lWork]; sgetri (&r, mat, &r, pivots, work, &lWork, &err); # elif defined (USE_ACML) float *work = NULL; // ACML doesn't use work sgetri (r, mat, r, pivots, &err); # else integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) real *work = new real [lWork]; sgetri_ (&r, (real *)mat, &r, pivots, work, &lWork, &err); # endif if ( err ) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in SGETRI: " << err <<std::endl; delete [] work; delete [] pivots; SX_EXIT; } delete [] work; delete [] pivots; } void matInverse (double *mat, int nRows, int nCols) { # if defined (USE_VECLIB) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; dgetrf (&nRows, &nCols, (double *)mat, &r, pivots, &err); # elif defined (USE_ESSL) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; dgetrf (nRows, nCols, mat, r, pivots, err); # elif defined (USE_INTEL_MKL) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; dgetrf (&nRows, &nCols, mat, &r, pivots, &err); # elif defined (USE_ACML) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; dgetrf (nRows, nCols, mat, r, pivots, &err); # else integer r = (integer)nRows, c = (integer)nCols, err = 0; integer *pivots = new integer[r < c ? r : c]; dgetrf_ (&r, &c, (doublereal *)mat, &r, pivots, &err); # endif if (err) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in DGETRF: " << err <<std::endl; delete [] pivots; SX_EXIT; } // --- (2) diagonalization # if defined (USE_VECLIB) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) double *work = new double [lWork]; dgetri (&nRows, (double *)mat, &nRows, pivots, work, &lWork, &err); # elif defined (USE_ESSL) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) double *work = new double [lWork]; dgetri (nRows, mat, nRows, pivots, work, lWork, err); # elif defined (USE_INTEL_MKL) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) double *work = new double [lWork]; dgetri (&nRows, mat, &nRows, pivots, work, &lWork, &err); # elif defined (USE_ACML) double *work = NULL; // ACML doesn't use work dgetri (nRows, mat, nRows, pivots, &err); # else integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) doublereal *work = new doublereal [lWork]; dgetri_ (&r, (doublereal *)mat, &r, pivots, work, &lWork, &err); # endif if ( err ) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in DGETRI: " << err <<std::endl; delete [] work; delete [] pivots; SX_EXIT; } delete [] work; delete [] pivots; } void matInverse (SxComplex8 *mat, int nRows, int nCols) { # if defined (USE_VECLIB) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; cgetrf (&r, &c, (complex8_t *)mat, &r, pivots, &err); # elif defined (USE_ESSL) int r, c, err=0; // map complex inversion to real inversion // +----+----+ +-----+-----+ // +----+ | Re |-Im | | re1 | im1 | // |cmlx| => +----+----+ = +-----+-----+ // +----+ | Im | Re | | im2 | re2 | // +----+----+ +-----+-----+ SxComplex8 *matPtr = mat; float *realMat = new float [ (2*nRows)*(2*nCols) ]; float *re1Ptr = realMat; float *im1Ptr = &realMat[nCols]; float *im2Ptr = &realMat[2*nRows*nCols]; float *re2Ptr = &realMat[2*nRows*nCols + nCols]; for (r=0; r<nRows; r++, re1Ptr+=nCols, re2Ptr+=nCols, im1Ptr+=nCols, im2Ptr+=nCols) { for (c=0; c<nCols; c++, matPtr++) { *re1Ptr++ = *re2Ptr++ = matPtr->re; *im1Ptr++ = -matPtr->im; *im2Ptr++ = matPtr->im; } } // --- compute inverse of real helper matrix matInverse (realMat, 2*nRows, 2*nCols); // construct complex result // +----+----+ +-----+-----+ // | Re | * | | re1 | * | +----+ // +----+----+ = +-----+-----+ => |cmlx| // | Im | * | | im2 | * | +----+ // +----+----+ +-----+-----+ matPtr = mat; re1Ptr = realMat; im2Ptr = &realMat[2*nRows*nCols]; for (r=0; r<nRows; r++, re1Ptr+=nCols, im2Ptr+=nCols) { for (c=0; c<nCols; c++, matPtr++) { matPtr->re = *re1Ptr++; matPtr->im = *im2Ptr++; } } delete [] realMat; # elif defined (USE_INTEL_MKL) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; cgetrf (&r, &c, (MKL_Complex8 *)mat, &r, pivots, &err); # elif defined (USE_ACML) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; cgetrf (r, c, (complex *)mat, r, pivots, &err); # else integer r = (integer)nRows, c = (integer)nCols, err = 0; integer *pivots = new integer[r < c ? r : c]; cgetrf_ (&r, &c, (complex *)mat, &r, pivots, &err); # endif # ifndef USE_ESSL if (err) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in CGETRF: "<<err<<std::endl; delete [] pivots; SX_EXIT; } # endif // --- (2) diagonalization # if defined (USE_VECLIB) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) complex8_t *work = new complex8_t [lWork]; cgetri (&r, (complex8_t *)mat, &r, pivots, work, &lWork, &err); # elif defined (USE_ESSL) // empty # elif defined (USE_INTEL_MKL) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) MKL_Complex8 *work = new MKL_Complex8 [lWork]; cgetri (&r, (MKL_Complex8 *)mat, &r, pivots, work, &lWork, &err); # elif defined (USE_ACML) complex *work = NULL; // ACML doesn't use work cgetri (r, (complex *)mat, r, pivots, &err); # else integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) complex *work = new complex [lWork]; cgetri_ (&r, (complex *)mat, &r, pivots, work, &lWork, &err); # endif # ifndef USE_ESSL if ( err ) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in CGETRI: "<<err<<std::endl; delete [] work; delete [] pivots; SX_EXIT; } delete [] work; delete [] pivots; # endif } void matInverse (SxComplex16 *mat, int nRows, int nCols) { # if defined (USE_VECLIB) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; zgetrf (&r, &c, (complex16_t *)mat, &r, pivots, &err); # elif defined (USE_ESSL) int r, c, err=0; // map complex inversion to real inversion // +----+----+ +-----+-----+ // +----+ | Re |-Im | | re1 | im1 | // |cmlx| => +----+----+ = +-----+-----+ // +----+ | Im | Re | | im2 | re2 | // +----+----+ +-----+-----+ SxComplex16 *matPtr = mat; double *realMat = new double [ (2*nRows)*(2*nCols) ]; double *re1Ptr = realMat; double *im1Ptr = &realMat[nCols]; double *im2Ptr = &realMat[2*nRows*nCols]; double *re2Ptr = &realMat[2*nRows*nCols + nCols]; for (r=0; r<nRows; r++, re1Ptr+=nCols, re2Ptr+=nCols, im1Ptr+=nCols, im2Ptr+=nCols) { for (c=0; c<nCols; c++, matPtr++) { *re1Ptr++ = *re2Ptr++ = matPtr->re; *im1Ptr++ = -matPtr->im; *im2Ptr++ = matPtr->im; } } // --- compute inverse of real helper matrix matInverse (realMat, 2*nRows, 2*nCols); // construct complex result // +----+----+ +-----+-----+ // | Re | * | | re1 | * | +----+ // +----+----+ = +-----+-----+ => |cmlx| // | Im | * | | im2 | * | +----+ // +----+----+ +-----+-----+ matPtr = mat; re1Ptr = realMat; im2Ptr = &realMat[2*nRows*nCols]; for (r=0; r<nRows; r++, re1Ptr+=nCols, im2Ptr+=nCols) { for (c=0; c<nCols; c++, matPtr++) { matPtr->re = *re1Ptr++; matPtr->im = *im2Ptr++; } } delete [] realMat; # elif defined (USE_INTEL_MKL) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; zgetrf (&r, &c, (MKL_Complex16 *)mat, &r, pivots, &err); # elif defined (USE_ACML) int r = nRows, c = nCols, err = 0; int *pivots = new int [r < c ? r : c]; zgetrf (r, c, (doublecomplex *)mat, r, pivots, &err); # else integer r = (integer)nRows, c = (integer)nCols, err = 0; integer *pivots = new integer[r < c ? r : c]; zgetrf_ (&r, &c, (doublecomplex *)mat, &r, pivots, &err); # endif # ifndef USE_ESSL if (err) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in ZGETRF: "<<err<<std::endl; delete [] pivots; SX_EXIT; } # endif // --- (2) diagonalization # if defined (USE_VECLIB) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) complex16_t *work = new complex16_t [lWork]; zgetri (&r, (complex16_t *)mat, &r, pivots, work, &lWork, &err); # elif defined (USE_ESSL) // empty # elif defined (USE_INTEL_MKL) int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) MKL_Complex16 *work = new MKL_Complex16 [lWork]; zgetri (&r, (MKL_Complex16 *)mat, &r, pivots, work, &lWork, &err); # elif defined (USE_ACML) doublecomplex *work = NULL; // ACML doesn't use work zgetri (r, (doublecomplex *)mat, r, pivots, &err); # else integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV) doublecomplex *work = new doublecomplex [lWork]; zgetri_ (&r, (doublecomplex *)mat, &r, pivots, work, &lWork, &err); # endif # ifndef USE_ESSL if ( err ) { // TODO: throw execption std::cout << "SxMatrix<T>::inverse: Error in ZGETRI: "<<err<<std::endl; delete [] work; delete [] pivots; SX_EXIT; } delete [] work; delete [] pivots; # endif } void matInverseTri (float * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/) { SX_EXIT; // not yet implemented } void matInverseTri (double *mat, int nRows, enum UPLO uplo) { char uploChar = (uplo == UpperRight ? 'U' : 'L'); // --- (1) Factorization: A = U*D*U^t # if defined (USE_VECLIB) SX_EXIT; // not yet implemented # elif defined ( USE_ESSL) SX_EXIT; // not yet implemented # elif defined (USE_INTEL_MKL) // int err = 0; // SX_EXIT; // not yet implemented // change by khr int r = nRows, err = 0; int *pivots = new int[r]; dsptrf (&uploChar, &r, mat, pivots, &err); # elif defined (USE_ACML) int r = nRows, err = 0; int *pivots = new int[r]; dsptrf (uploChar, r, mat, pivots, &err); # else integer r = (integer)nRows, err = 0; integer *pivots = new integer[r]; dsptrf_ (&uploChar, &r, (doublereal *)mat, pivots, &err); # endif if ( err ) { // TODO: throw execption std::cout << "SxMatrix<T>::inverseTri: Error in DSPTRF: " << err << std::endl; SX_EXIT; } // --- (2) Inverse of A # if defined (USE_VECLIB) SX_EXIT; // not yet implemented # elif defined (USE_ESSL) SX_EXIT; // not yet implemented # elif defined (USE_INTEL_MKL) // double *work = NULL, *pivots=NULL; // SX_EXIT; // not yet implemented // change by khr double *work = new double [r]; dsptri (&uploChar, &r, mat, pivots, work, &err); # elif defined (USE_ACML) double *work = NULL; // ACML doesn't use work dsptri (uploChar, r, mat, pivots, &err); # else doublereal *work = new doublereal [r]; dsptri_ (&uploChar, &r, (doublereal *)mat, pivots, work, &err); # endif # ifndef USE_ESSL if ( err ) { // TODO: throw execption std::cout << "SxMatrix<T>::inverseTri: Error in DSPTRI: " << err << std::endl; delete [] work; delete [] pivots; SX_EXIT; } delete [] work; delete [] pivots; # endif } void matInverseTri (SxComplex8 * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/) { SX_EXIT; // not yet implemented } void matInverseTri (SxComplex16 * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/) { SX_EXIT; // not yet implemented } //------------------------------------------------------------------------------ // Linear equation solver (least square based) //------------------------------------------------------------------------------ void solveLinEq (float *mat, int nRows, int nCols, float *b, int bCols) { # if defined (USE_VECLIB) //TODO SX_EXIT; # elif defined (USE_ESSL) int iopt = 2; //compute singulare Values, V and U^TB int m = nRows; int n = nCols; int nrhs = bCols; int lda = m; int ldb = m; char transa = 'N'; int naux = 0; //ESSL choose size of work array dynamically float *aux = NULL; //workarray is ignored int info; float *s = new float [n]; float *x = new float [n*nrhs]; float tau = 1e-10; // error tolerance for zero sgesvf(iopt,mat,lda,b,ldb,nrhs,s,m,n,aux,naux); sgesvs (mat,n,b,n,nrhs,s,x,n,m,n,tau); // results are now in x; copy to b for(int i = 0; i < n*nrhs; i++) { b[i] = x[i]; } delete [] s; delete [] x; //TODO TEST SX_EXIT; # elif defined (USE_INTEL_MKL) // for ilaenv MKL_INT iSpec = 9; char *name = const_cast<char*>("SGELSD"); char *opts = const_cast<char*>(" "); MKL_INT n1 = 0; MKL_INT n2 = 0; MKL_INT n3 = 0; MKL_INT n4 = 0; // for dgelsd MKL_INT m = nRows; MKL_INT n = nCols; MKL_INT minmn = n < m ? n : m; MKL_INT nrhs = bCols; MKL_INT lda = m; MKL_INT ldb = m; float *s = new float [minmn]; float rcond = -1.; MKL_INT rank; MKL_INT SMLSIZ = ilaenv(&iSpec,name,opts,&n1,&n2,&n3,&n4); MKL_INT logVal = MKL_INT(log( 1.0*n/(SMLSIZ+1))/log(2.0)) + 1; MKL_INT NLVL = 0 < logVal ? logVal : 0; MKL_INT lwork = -1; float autolwork; MKL_INT liwork = 3 * minmn * NLVL + 11 * minmn; MKL_INT *iwork = new MKL_INT [liwork]; MKL_INT info; // determine optimal lwork // dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info); sgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info); lwork = MKL_INT(autolwork+0.5); float *work = new float [lwork]; sgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info); delete [] s; delete [] work; delete [] iwork; //TODO TEST SX_EXIT; # elif defined (USE_ACML) int m = nRows; int n = nCols; int nrhs = bCols; int lda = m; int ldb = m; int minmn = n < m ? n : m; float *s = new float [minmn]; float rcond = -1.; int rank; int info; sgelsd (m,n,nrhs,mat,lda,b,ldb,s,rcond,&rank,&info); delete [] s; //TODO TEST SX_EXIT; # else // for ilaenv integer iSpec = 9; char *name = const_cast<char*>("SGELSD"); char *opts = const_cast<char*>(" "); integer n1 = 0; integer n2 = 0; integer n3 = 0; integer n4 = 0; ftnlen lname = 6; ftnlen lopts = 1; // for sgelsd integer m = nRows; integer n = nCols; integer minmn = n < m ? n : m; integer nrhs = bCols; integer lda = m; integer ldb = m; float *s = new float [minmn]; float rcond = -1.; integer rank; #ifdef MACOSX # if ( DIST_VERSION_L >= 1070L ) integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4); # else integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts); # endif /* DIST_VERSION_L */ #else integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts); #endif /* MACOSX */ integer logVal = integer(log( double(n)/double(SMLSIZ+1))/log(2.0)) + 1; integer NLVL = 0 < logVal ? logVal : 0; integer lwork = -1; float autolwork; integer liwork = 3 * minmn * NLVL + 11 * minmn; integer *iwork = new integer [liwork]; integer info; // determine optimal lwork sgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info); lwork = integer(autolwork+0.5); float *work = new float [lwork]; sgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info); delete [] s; delete [] work; delete [] iwork; # endif } void solveLinEq (double *mat, int nRows, int nCols, double *b, int bCols) { # if defined (USE_VECLIB) //TODO SX_EXIT; # elif defined (USE_ESSL) int iopt = 2; //compute singulare Values, V and U^TB int m = nRows; int n = nCols; int nrhs = bCols; int lda = m; int ldb = m; char transa = 'N'; int naux = 0; //ESSL choose size of work array dynamically double *aux = NULL; //workarray is ignored int info; double *s = new double [n]; double *x = new double [n*nrhs]; double tau = 1e-10; // error tolerance for zero dgesvf(iopt,mat,lda,b,ldb,nrhs,s,m,n,aux,naux); dgesvs (mat,n,b,n,nrhs,s,x,n,m,n,tau); // results are now in x; copy to b for(int i = 0; i < n*nrhs; i++) { b[i] = x[i]; } delete [] s; delete [] x; //TODO TEST SX_EXIT; # elif defined (USE_INTEL_MKL) // for ilaenv MKL_INT iSpec = 9; char *name = const_cast<char*>("DGELSD"); char *opts = const_cast<char*>(" "); MKL_INT n1 = 0; MKL_INT n2 = 0; MKL_INT n3 = 0; MKL_INT n4 = 0; // for dgelsd MKL_INT m = nRows; MKL_INT n = nCols; MKL_INT minmn = n < m ? n : m; MKL_INT nrhs = bCols; MKL_INT lda = m; MKL_INT ldb = m; double *s = new double [minmn]; double rcond = -1.; MKL_INT rank; MKL_INT SMLSIZ = ilaenv(&iSpec,name,opts,&n1,&n2,&n3,&n4); MKL_INT logVal = MKL_INT(log( 1.0*n/(SMLSIZ+1))/log(2.0)) + 1; MKL_INT NLVL = 0 < logVal ? logVal : 0; MKL_INT lwork = -1; double autolwork; MKL_INT liwork = 3 * minmn * NLVL + 11 * minmn; MKL_INT *iwork = new MKL_INT [liwork]; MKL_INT info; // determine optimal lwork dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info); lwork = MKL_INT(autolwork+0.5); double *work = new double [lwork]; dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info); delete [] s; delete [] work; delete [] iwork; # elif defined (USE_ACML) int m = nRows; int n = nCols; int nrhs = bCols; int lda = m; int ldb = m; int minmn = n < m ? n : m; double *s = new double [minmn]; double rcond = -1.; int rank; int info; dgelsd (m,n,nrhs,mat,lda,b,ldb,s,rcond,&rank,&info); delete [] s; //TODO TEST SX_EXIT; # else // for ilaenv integer iSpec = 9; char *name = const_cast<char*>("DGELSD"); char *opts = const_cast<char*>(" "); integer n1 = 0; integer n2 = 0; integer n3 = 0; integer n4 = 0; ftnlen lname = 6; ftnlen lopts = 1; // for dgelsd integer m = nRows; integer n = nCols; integer minmn = n < m ? n : m; integer nrhs = bCols; integer lda = m; integer ldb = m; double *s = new double [minmn]; double rcond = -1.; integer rank; #ifdef MACOSX # if ( DIST_VERSION_L >= 1070L ) integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4); # else integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts); # endif /* DIST_VERSION_L */ #else integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts); #endif /* MACOSX */ integer logVal = integer(log( double(n)/double(SMLSIZ+1))/log(2.0)) + 1; integer NLVL = 0 < logVal ? logVal : 0; integer lwork = -1; double autolwork; integer liwork = 3 * minmn * NLVL + 11 * minmn; integer *iwork = new integer [liwork]; integer info; // determine optimal lwork dgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info); lwork = integer(autolwork+0.5); double *work = new double [lwork]; dgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info); delete [] s; delete [] work; delete [] iwork; # endif } void solveLinEq (SxComplex8 * /*mat*/, int /*nRows*/, int /*nCols*/, SxComplex8 * /*b*/, int /*bCols*/) { # if defined (USE_VECLIB) //TODO SX_EXIT; # elif defined (USE_ESSL) //TODO SX_EXIT; # elif defined (USE_INTEL_MKL) //TODO SX_EXIT; # elif defined (USE_ACML) //TODO SX_EXIT; # endif } void solveLinEq (SxComplex16 * /*mat*/, int /*nRows*/, int /*nCols*/, SxComplex16 * /*b*/, int /*bCols*/) { # if defined (USE_VECLIB) //TODO SX_EXIT; # elif defined (USE_ESSL) //TODO SX_EXIT; # elif defined (USE_INTEL_MKL) //TODO SX_EXIT; # elif defined (USE_ACML) //TODO SX_EXIT; # else //TODO SX_EXIT; # endif } //------------------------------------------------------------------------------ // Eigensolver //------------------------------------------------------------------------------ int matEigensolver (SxComplex8 *eigVals, float *eigVecs, float *inMat, int n, EIGCMD cmd, int size) { # if defined (USE_VECLIB) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 4*n : size; int workDim = lWork; # elif defined (USE_ESSL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 4*n : size; int workDim = lWork; # elif defined (USE_INTEL_MKL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 4*n : size; int workDim = lWork; # elif defined (USE_ACML) int rank = n, info = 0, ldVecLeft = 1, lWork=size; # else integer rank = (integer)n, info = 0, ldVecLeft = 1; integer lWork = !size ? 4*n : size; integer workDim = lWork; # endif if ( cmd == OptSize ) lWork = -1; char jobvl = 'N', jobvr = 'V'; # if defined (USE_VECLIB) float *work = new float [workDim]; float *epsRe = new float [n], *epsIm = new float [n]; float *eigVecLeft = new float [ldVecLeft]; sgeev (&jobvl, &jobvr, &rank, (float *)inMat, &rank, epsRe, epsIm, eigVecLeft, &ldVecLeft, (float *)eigVecs, &rank, work, &lWork, &info, 0, 0); # elif defined (USE_ESSL) complex<float> *vecs = new complex<float> [rank*rank]; int iOpt = 1; // compute both vecs and vals if (cmd != OptSize) { // not supported by ESSL if (cmd == ValuesOnly) iOpt = 0; sgeev (iOpt, inMat, rank, (complex<float> *)eigVals, vecs, rank, NULL, rank, NULL, 0); complex<float> *srcPtr = vecs; float *dstPtr = eigVecs; int i, len = n*n; for (i=0; i < len; i++, srcPtr++) { *dstPtr++ = real(*srcPtr); } // --- normalize eigenvectors float c; for (i=0; i < n; i++) { c = 1. / norm2 (&eigVecs[i*n], n); scale (&eigVecs[i*n], c, n); } } delete [] vecs; return 0; # elif defined (USE_INTEL_MKL) float *work = new float [workDim]; float *epsRe = new float [n], *epsIm = new float [n]; float *eigVecLeft = new float [ldVecLeft]; sgeev (&jobvl, &jobvr, &rank, inMat, &rank, epsRe, epsIm, eigVecLeft, &ldVecLeft, eigVecs, &rank, work, &lWork, &info); # elif defined (USE_ACML) float *work = NULL; // ACML doesn't use work float *epsRe = new float [n], *epsIm = new float [n]; float *eigVecLeft = new float [ldVecLeft]; sgeev (jobvl, jobvr, rank, inMat, rank, epsRe, epsIm, eigVecLeft, ldVecLeft, eigVecs, rank, &info); # else real *work = new real [workDim]; real *epsRe = new real[n], *epsIm = new real[n]; real *eigVecLeft = new real [ldVecLeft]; sgeev_ (&jobvl, &jobvr, &rank, (real *)inMat, &rank, epsRe, epsIm, eigVecLeft, &ldVecLeft, (real *)eigVecs, &rank, work, &lWork, &info); # endif # ifndef USE_ESSL float *ptr=(float *)eigVals; float *rePtr=(float *)epsRe, *imPtr=(float *)epsIm; for (int i=0; i < n; i++) { *ptr++ = *rePtr++; // eigVals[i].re = epsRe[i]; *ptr++ = *imPtr++; // eigVals[i].im = epsIm[i]; } delete [] eigVecLeft; delete [] epsIm; delete [] epsRe; delete [] work; if ( info ) { // TODO: throw exception std::cout << "matEigensolver: Error in SGEEV: " << info << std::endl; SX_EXIT; } return (cmd == OptSize) ? (int)work[0] : 0; # endif } int matEigensolver (SxComplex16 *eigVals, double *eigVecs, double *inMat, int n, EIGCMD cmd, int size) { # if defined (USE_VECLIB) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 4*n : size; int workDim = lWork; # elif defined (USE_ESSL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 4*n : size; int workDim = lWork; # elif defined (USE_INTEL_MKL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 4*n : size; int workDim = lWork; # elif defined (USE_ACML) int rank = n, info = 0, ldVecLeft = 1, lWork=size; # else integer rank = (integer)n, info = 0, ldVecLeft = 1; integer lWork = !size ? 4*n : size; integer workDim = lWork; # endif if ( cmd == OptSize ) lWork = -1; char jobvl = 'N', jobvr = 'V'; # if defined (USE_VECLIB) double *work = new double [workDim]; double *epsRe = new double[n], *epsIm = new double[n]; double *eigVecLeft = new double [ldVecLeft]; dgeev (&jobvl, &jobvr, &rank, (double *)inMat, &rank, epsRe, epsIm, eigVecLeft, &ldVecLeft, (double *)eigVecs, &rank, work, &lWork, &info, 0, 0); # elif defined (USE_ESSL) complex<double> *vecs = new complex<double> [rank*rank]; int iOpt = 1; // compute both vecs and vals if (cmd != OptSize) { // not supported by ESSL if (cmd == ValuesOnly) iOpt = 0; dgeev (iOpt, inMat, rank, (complex<double> *)eigVals, vecs, rank, NULL, rank, NULL, 0); complex<double> *srcPtr = vecs; double *dstPtr = eigVecs; int i, len = n*n; for (i=0; i < len; i++, srcPtr++) { *dstPtr++ = real(*srcPtr); } // --- normalize eigenvectors double c; for (i=0; i < n; i++) { c = 1. / norm2 (&eigVecs[i*n], n); scale (&eigVecs[i*n], c, n); } } delete [] vecs; return 0; # elif defined (USE_INTEL_MKL) double *work = new double [workDim]; double *epsRe = new double [n], *epsIm = new double [n]; double *eigVecLeft = new double [ldVecLeft]; dgeev (&jobvl, &jobvr, &rank, inMat, &rank, epsRe, epsIm, eigVecLeft, &ldVecLeft, eigVecs, &rank, work, &lWork, &info); # elif defined (USE_ACML) double *work = NULL; // ACML doesn't use work double *epsRe = new double [n], *epsIm = new double [n]; double *eigVecLeft = new double [ldVecLeft]; dgeev (jobvl, jobvr, rank, inMat, rank, epsRe, epsIm, eigVecLeft, ldVecLeft, eigVecs, rank, &info); # else doublereal *work = new doublereal [workDim]; doublereal *epsRe = new doublereal[n], *epsIm = new doublereal[n]; doublereal *eigVecLeft = new doublereal [ldVecLeft]; dgeev_ (&jobvl, &jobvr, &rank, (doublereal *)inMat, &rank, epsRe, epsIm, eigVecLeft, &ldVecLeft, (doublereal *)eigVecs, &rank, work, &lWork, &info); # endif # ifndef USE_ESSL double *ptr=(double *)eigVals; double *rePtr=(double *)epsRe, *imPtr=(double *)epsIm; for (int i=0; i < n; i++) { *ptr++ = *rePtr++; // eigVals[i].re = epsRe[i]; *ptr++ = *imPtr++; // eigVals[i].im = epsIm[i]; } delete [] eigVecLeft; delete [] epsIm; delete [] epsRe; delete [] work; if ( info ) { // TODO: throw exception std::cout << "matEigensolver: Error in DGEEV: " << info << std::endl; SX_EXIT; } return (cmd == OptSize) ? (int)work[0] : 0; # endif } int matEigensolver (SxComplex8 *eigVals, SxComplex8 *eigVecs, SxComplex8 *inMat, int n, EIGCMD cmd, int size) { # if defined (USE_VECLIB) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 2*n : size; int workDim = lWork; # elif defined (USE_ESSL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 2*n : size; int workDim = lWork; # elif defined (USE_INTEL_MKL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 2*n : size; int workDim = lWork; # elif defined (USE_ACML) int rank = n, info = 0, ldVecLeft = 1, lWork=size; # else integer rank = (integer)n, info = 0, ldVecLeft = 1; integer lWork = !size ? 2*n : size; integer workDim = lWork; # endif if ( cmd == OptSize ) lWork = -1; char jobvl = 'N', jobvr = 'V'; # if defined (USE_VECLIB) complex8_t *eigVecLeft = new complex8_t [ldVecLeft]; complex8_t *work = new complex8_t [workDim]; float *rWork = new float [workDim]; cgeev (&jobvl, &jobvr, &rank, (complex8_t *)inMat, &rank, (complex8_t *)eigVals, eigVecLeft, &ldVecLeft, (complex8_t *)eigVecs, &rank, work, &lWork, rWork, &info, 0, 0); if (cmd == OptSize) lWork = (int)work[0].re; delete [] rWork; delete [] work; delete [] eigVecLeft; # elif defined (USE_ESSL) int iOpt = 1; // compute both vecs and vals if (cmd != OptSize) { // not supported by ESSL if (cmd == ValuesOnly) iOpt = 0; cgeev (iOpt, (complex<float> *)inMat, rank, (complex<float> *)eigVals, (complex<float> *)eigVecs, rank, NULL, rank, NULL, 0); // --- normalize eigenvectors double c; for (int i=0; i < n; i++) { c = 1. / norm2 (&eigVecs[i*n], n); scale (&eigVecs[i*n], c, n); } } # elif defined (USE_INTEL_MKL) MKL_Complex8 *eigVecLeft = new MKL_Complex8 [ldVecLeft]; MKL_Complex8 *work = new MKL_Complex8 [workDim]; float *rWork = new float [workDim]; cgeev (&jobvl, &jobvr, &rank, (MKL_Complex8 *)inMat, &rank, (MKL_Complex8 *)eigVals, eigVecLeft, &ldVecLeft, (MKL_Complex8 *)eigVecs, &rank, work, &lWork, rWork, &info); if (cmd == OptSize) lWork = (int)work[0].real; delete [] rWork; delete [] work; delete [] eigVecLeft; # elif defined (USE_ACML) complex *eigVecLeft = new complex [ldVecLeft]; cgeev (jobvl, jobvr, rank, (complex *)inMat, rank, (complex *)eigVals, eigVecLeft, ldVecLeft, (complex *)eigVecs, rank, &info); delete eigVecLeft; # else complex *eigVecLeft = new complex [ldVecLeft]; complex *work = new complex [workDim]; real *rWork = new real [workDim]; cgeev_ (&jobvl, &jobvr, &rank, (complex *)inMat, &rank, (complex *)eigVals, eigVecLeft, &ldVecLeft, (complex *)eigVecs, &rank, work, &lWork, rWork, &info); if (cmd == OptSize) lWork = (int)work[0].r; delete [] rWork; delete [] work; delete [] eigVecLeft; # endif # ifndef USE_ESSL if ( info ) { // TODO: throw exception std::cout << "matEigensolver: Error in CGEEV: " << info << std::endl; SX_EXIT; } # endif # if defined (USE_VECLIB) return (cmd == OptSize) ? lWork : 0; # elif defined (USE_ESSL) return 0; # elif defined (USE_INTEL_MKL) return (cmd == OptSize) ? lWork : 0; # elif defined (USE_ACML) return 0; # else return (cmd == OptSize) ? (int)lWork : 0; # endif } int matEigensolver (SxComplex16 *eigVals, SxComplex16 *eigVecs, SxComplex16 *inMat, int n, EIGCMD cmd, int size) { # if defined (USE_VECLIB) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 2*n : size; int workDim = lWork; # elif defined (USE_ESSL) int rank = n, ldVecLeft = 1; int lWork = !size ? 2*n : size; int workDim = lWork; # elif defined (USE_INTEL_MKL) int rank = n, info = 0, ldVecLeft = 1; int lWork = !size ? 2*n : size; int workDim = lWork; # elif defined (USE_ACML) int rank = n, info = 0, ldVecLeft = 1, lWork=size; # else integer rank = (integer)n, info = 0, ldVecLeft = 1; integer lWork = !size ? 2*n : size; integer workDim = !size ? 2*n : size; # endif if ( cmd == OptSize ) lWork = -1; char jobvl = 'N', jobvr = 'V'; # if defined (USE_VECLIB) complex16_t *eigVecLeft = new complex16_t [ldVecLeft]; complex16_t *work = new complex16_t [workDim]; double *rWork = new double [workDim]; zgeev (&jobvl, &jobvr, &rank, (complex16_t *)inMat, &rank, (complex16_t *)eigVals, eigVecLeft, &ldVecLeft, (complex16_t *)eigVecs, &rank, work, &lWork, rWork, &info, 0, 0); if (cmd == OptSize) lWork = (int)work[0].re; delete [] rWork; delete [] work; delete [] eigVecLeft; # elif defined (USE_ESSL) int iOpt = 1; // compute both vecs and vals if (cmd != OptSize) { // not supported by ESSL if (cmd == ValuesOnly) iOpt = 0; zgeev (iOpt, (complex<double> *)inMat, rank, (complex<double> *)eigVals, (complex<double> *)eigVecs, rank, NULL, rank, NULL, 0); // --- normalize eigenvectors double c; for (int i=0; i < n; i++) { c = 1. / norm2 (&eigVecs[i*n], n); scale (&eigVecs[i*n], c, n); } } # elif defined (USE_INTEL_MKL) MKL_Complex16 *eigVecLeft = new MKL_Complex16 [ldVecLeft]; MKL_Complex16 *work = new MKL_Complex16 [workDim]; double *rWork = new double [workDim]; zgeev (&jobvl, &jobvr, &rank, (MKL_Complex16 *)inMat, &rank, (MKL_Complex16 *)eigVals, eigVecLeft, &ldVecLeft, (MKL_Complex16 *)eigVecs, &rank, work, &lWork, rWork, &info); if (cmd == OptSize) lWork = (int)work[0].real; delete [] rWork; delete [] work; delete [] eigVecLeft; # elif defined (USE_ACML) doublecomplex *eigVecLeft = new doublecomplex [ldVecLeft]; zgeev (jobvl, jobvr, rank, (doublecomplex *)inMat, rank, (doublecomplex *)eigVals, eigVecLeft, ldVecLeft, (doublecomplex *)eigVecs, rank, &info); delete [] eigVecLeft; # else doublecomplex *eigVecLeft = new doublecomplex [ldVecLeft]; doublecomplex *work = new doublecomplex [workDim]; doublereal *rWork = new doublereal [workDim]; zgeev_ (&jobvl, &jobvr, &rank, (doublecomplex *)inMat, &rank, (doublecomplex *)eigVals, eigVecLeft, &ldVecLeft, (doublecomplex *)eigVecs, &rank, work, &lWork, rWork, &info); if (cmd == OptSize) lWork = (int)work[0].r; delete [] rWork; delete [] work; delete [] eigVecLeft; # endif # ifndef USE_ESSL if ( info ) { // TODO: throw exception std::cout << "matEigensolver: Error in DGEEV: " << info << std::endl; SX_EXIT; } # endif # if defined (USE_VECLIB) return (cmd == OptSize) ? lWork : 0; # elif defined (USE_ESSL) return 0; # elif defined (USE_INTEL_MKL) return (cmd == OptSize) ? lWork : 0; # elif defined (USE_ACML) return 0; # else return (cmd == OptSize) ? (int)lWork : 0; # endif } //------------------------------------------------------------------------------ // Eigensolver - tridiagonal matrices //------------------------------------------------------------------------------ void matEigensolverTri (float *eigVals, float *eigVecs, float *inMat, int n, enum UPLO uplo, EIGCMD # ifdef USE_ESSL cmd # endif ) { char jobz = 'V'; char uploChar = (uplo == UpperRight ? 'U' : 'L'); # if defined (USE_VECLIB) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 3*n; float *work = new float [workDim]; sspev (&jobz, &uploChar, &rank, (float *)inMat, (float *)eigVals, (float *)eigVecs, &ldEigVecs, work, &info, 0, 0); delete [] work; # elif defined (USE_ESSL) int info = 0, iOpt = 1; if (cmd == VectorsOnly) iOpt = 0; if (uplo == UpperRight) iOpt += 20; int rank = n; sspev (iOpt, inMat, eigVals, eigVecs, rank, n, NULL, 0); # elif defined (USE_INTEL_MKL) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 3*n; float *work = new float [workDim]; sspev (&jobz, &uploChar, &rank, (float *)inMat, (float *)eigVals, (float *)eigVecs, &ldEigVecs, work, &info); delete [] work; # elif defined (USE_ACML) int rank = n; int ldEigVecs = rank; int info = 0; sspev (jobz, uploChar, rank, inMat, eigVals, eigVecs, ldEigVecs, &info); # else integer rank = (integer)n; integer ldEigVecs = rank; integer info = 0; integer workDim = 3*n; real *work = new real [workDim]; sspev_ (&jobz, &uploChar, &rank, (real *)inMat, (real *)eigVals, (real *)eigVecs, &ldEigVecs, work, &info); delete [] work; # endif if ( info ) { // TODO: throw exception std::cout << "matEigensolverHerm: Error in SSPEV: " << info << std::endl; SX_EXIT; } } void matEigensolverTri (double *eigVals, double *eigVecs, double *inMat, int n, enum UPLO uplo, EIGCMD # ifdef USE_ESSL cmd # endif ) { char jobz = 'V'; char uploChar = (uplo == UpperRight ? 'U' : 'L'); # if defined (USE_VECLIB) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 3*n; double *work = new double [workDim]; dspev (&jobz, &uploChar, &rank, (double *)inMat, (double *)eigVals, (double *)eigVecs, &ldEigVecs, work, &info, 0, 0); delete [] work; # elif defined (USE_ESSL) int info = 0, iOpt = 1; if (cmd == VectorsOnly) iOpt = 0; if (uplo == UpperRight) iOpt += 20; int rank = n; dspev (iOpt, inMat, eigVals, eigVecs, rank, n, NULL, 0); # elif defined (USE_INTEL_MKL) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 3*n; double *work = new double [workDim]; dspev (&jobz, &uploChar, &rank, (double *)inMat, (double *)eigVals, (double *)eigVecs, &ldEigVecs, work, &info); delete [] work; # elif defined (USE_ACML) int rank = n; int ldEigVecs = rank; int info = 0; dspev (jobz, uploChar, rank, inMat, eigVals, eigVecs, ldEigVecs, &info); # else integer rank = (integer)n; integer ldEigVecs = rank; integer info = 0; integer workDim = 3*n; doublereal *work = new doublereal [workDim]; dspev_ (&jobz, &uploChar, &rank, (doublereal *)inMat, (doublereal *)eigVals, (doublereal *)eigVecs, &ldEigVecs, work, &info); delete [] work; # endif if ( info ) { // TODO: throw exception std::cout << "matEigensolverHerm: Error in DSPEV: " << info << std::endl; SX_EXIT; } } void matEigensolverTri (float *eigVals, SxComplex8 *eigVecs, SxComplex8 *inMat, int n, enum UPLO uplo, EIGCMD # ifdef USE_ESSL cmd # endif ) { char jobz = 'V'; char uploChar = (uplo == UpperRight ? 'U' : 'L'); # if defined (USE_VECLIB) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 2*n-1; int rWorkDim = 3*n-2; complex8_t *work = new complex8_t [workDim]; float *rWork = new float [rWorkDim]; chpev (&jobz, &uploChar, &rank, (complex8_t *)inMat, (float *)eigVals, (complex8_t *)eigVecs, &ldEigVecs, work, rWork, &info, 0, 0); delete [] rWork; delete [] work; # elif defined (USE_ESSL) int info = 0, iOpt = 1; if (cmd == VectorsOnly) iOpt = 0; if (uplo == UpperRight) iOpt += 20; int rank = n; chpev (iOpt, (complex<float> *)inMat, eigVals, (complex<float> *)eigVecs, rank, n, NULL, 0); # elif defined (USE_INTEL_MKL) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 2*n-1; int rWorkDim = 3*n-2; MKL_Complex8 *work = new MKL_Complex8 [workDim]; float *rWork = new float [rWorkDim]; chpev (&jobz, &uploChar, &rank, (MKL_Complex8 *)inMat, (float *)eigVals, (MKL_Complex8 *)eigVecs, &ldEigVecs, work, rWork, &info); delete [] rWork; delete [] work; # elif defined (USE_ACML) int rank = n; int ldEigVecs = rank; int info = 0; chpev (jobz, uploChar, rank, (complex *)inMat, (float *)eigVals, (complex *)eigVecs, ldEigVecs, &info); # else integer rank = (integer)n; integer ldEigVecs = rank; integer info = 0; integer workDim = 2*n-1; integer rWorkDim = 3*n-2; complex *work = new complex [workDim]; real *rWork = new real [rWorkDim]; chpev_ (&jobz, &uploChar, &rank, (complex *)inMat, (real *)eigVals, (complex *)eigVecs, &ldEigVecs, work, rWork, &info); delete [] rWork; delete [] work; # endif if ( info ) { // TODO: throw exception std::cout << "matEigensolverHerm: Error in CHPEV: " << info << std::endl; SX_EXIT; } } void matEigensolverTri (double *eigVals, SxComplex16 *eigVecs, SxComplex16 *inMat, int n, enum UPLO uplo, EIGCMD # ifdef USE_ESSL cmd # endif ) { char jobz = 'V'; char uploChar = (uplo == UpperRight ? 'U' : 'L'); # if defined (USE_VECLIB) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 2*n-1; int rWorkDim = 3*n-2; complex16_t *work = new complex16_t [workDim]; double *rWork = new double[rWorkDim]; zhpev (&jobz, &uploChar, &rank, (complex16_t *)inMat, (double *)eigVals, (complex16_t *)eigVecs, &ldEigVecs, work, rWork, &info, 0, 0); delete [] rWork; delete [] work; # elif defined (USE_ESSL) int info = 0, iOpt = 1; if (cmd == VectorsOnly) iOpt = 0; if (uplo == UpperRight) iOpt += 20; int rank = n; zhpev (iOpt, (complex<double> *)inMat, eigVals, (complex<double> *)eigVecs, rank, n, NULL, 0); # elif defined (USE_INTEL_MKL) int rank = n; int ldEigVecs = rank; int info = 0; int workDim = 2*n-1; int rWorkDim = 3*n-2; MKL_Complex16 *work = new MKL_Complex16 [workDim]; double *rWork = new double[rWorkDim]; zhpev (&jobz, &uploChar, &rank, (MKL_Complex16 *)inMat, (double *)eigVals, (MKL_Complex16 *)eigVecs, &ldEigVecs, work, rWork, &info); delete [] rWork; delete [] work; # elif defined (USE_ACML) int rank = n; int ldEigVecs = rank; int info = 0; zhpev (jobz, uploChar, rank, (doublecomplex *)inMat, (double *)eigVals, (doublecomplex *)eigVecs, ldEigVecs, &info); # else integer rank = (integer)n; integer ldEigVecs = rank; integer info = 0; integer workDim = 2*n-1; integer rWorkDim = 3*n-2; doublecomplex *work = new doublecomplex [workDim]; doublereal *rWork = new doublereal [rWorkDim]; zhpev_ (&jobz, &uploChar, &rank, (doublecomplex *)inMat, (doublereal *)eigVals, (doublecomplex *)eigVecs, &ldEigVecs, work, rWork, &info); delete [] rWork; delete [] work; # endif if ( info ) { // TODO: throw exception std::cout << "matEigensolverHerm: Error in ZHPEV: " << info << std::endl; SX_EXIT; } } // -------------------------- SX_IGNORE_THE_REST_OF_THE_FILE # endif // --------------------------
36.127718
90
0.524202
ashtonmv
f4f13b044f9221528c862b19ad1af4e8935cc5f8
77
hh
C++
build/X86/mem/protocol/VIPERCoalescer.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
5
2019-12-12T16:26:09.000Z
2022-03-17T03:23:33.000Z
build/X86/mem/protocol/VIPERCoalescer.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
build/X86/mem/protocol/VIPERCoalescer.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
#include "/home/zhoushuxin/gem5/build/X86/mem/ruby/system/VIPERCoalescer.hh"
38.5
76
0.805195
zhoushuxin
f4f1ddcc73b72ad1189d7145666bdabb400f88e4
239
cpp
C++
src/question_1/question1.cpp
juliaholland/acc-cosc-1337-midterm-juliaholland
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
[ "MIT" ]
null
null
null
src/question_1/question1.cpp
juliaholland/acc-cosc-1337-midterm-juliaholland
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
[ "MIT" ]
null
null
null
src/question_1/question1.cpp
juliaholland/acc-cosc-1337-midterm-juliaholland
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
[ "MIT" ]
null
null
null
#include "question1.h" bool test_config() { return true; } double get_kinetic_energy(double mass, double velocity) { double kineticEnergy; kineticEnergy = 0.5 * mass * velocity * velocity; return kineticEnergy; }
14.058824
55
0.682008
juliaholland
f4f2a7201d0e73ca372a5a429bfe6ca7b51eb2fd
40,892
cpp
C++
src/vedit.cpp
linails/vnote
97810731db97292f474951c3450aac150acef0bc
[ "MIT" ]
1
2019-07-27T10:46:41.000Z
2019-07-27T10:46:41.000Z
src/vedit.cpp
linails/vnote
97810731db97292f474951c3450aac150acef0bc
[ "MIT" ]
1
2022-01-22T13:10:44.000Z
2022-01-22T13:10:44.000Z
src/vedit.cpp
linails/vnote
97810731db97292f474951c3450aac150acef0bc
[ "MIT" ]
1
2021-06-17T02:43:27.000Z
2021-06-17T02:43:27.000Z
#include <QtWidgets> #include <QVector> #include <QDebug> #include "vedit.h" #include "vnote.h" #include "vconfigmanager.h" #include "vtableofcontent.h" #include "utils/vutils.h" #include "utils/veditutils.h" #include "utils/vmetawordmanager.h" #include "veditoperations.h" #include "vedittab.h" #include "dialog/vinsertlinkdialog.h" #include "utils/viconutils.h" extern VConfigManager *g_config; extern VNote *g_vnote; extern VMetaWordManager *g_mwMgr; VEdit::VEdit(VFile *p_file, QWidget *p_parent) : QTextEdit(p_parent), m_file(p_file), m_editOps(NULL), m_enableInputMethod(true) { const int labelTimerInterval = 500; const int extraSelectionHighlightTimer = 500; const int labelSize = 64; m_selectedWordColor = QColor(g_config->getEditorSelectedWordBg()); m_searchedWordColor = QColor(g_config->getEditorSearchedWordBg()); m_searchedWordCursorColor = QColor(g_config->getEditorSearchedWordCursorBg()); m_incrementalSearchedWordColor = QColor(g_config->getEditorIncrementalSearchedWordBg()); m_trailingSpaceColor = QColor(g_config->getEditorTrailingSpaceBg()); QPixmap wrapPixmap(":/resources/icons/search_wrap.svg"); m_wrapLabel = new QLabel(this); m_wrapLabel->setPixmap(wrapPixmap.scaled(labelSize, labelSize)); m_wrapLabel->hide(); m_labelTimer = new QTimer(this); m_labelTimer->setSingleShot(true); m_labelTimer->setInterval(labelTimerInterval); connect(m_labelTimer, &QTimer::timeout, this, &VEdit::labelTimerTimeout); m_highlightTimer = new QTimer(this); m_highlightTimer->setSingleShot(true); m_highlightTimer->setInterval(extraSelectionHighlightTimer); connect(m_highlightTimer, &QTimer::timeout, this, &VEdit::doHighlightExtraSelections); m_extraSelections.resize((int)SelectionId::MaxSelection); updateFontAndPalette(); m_config.init(QFontMetrics(font()), false); updateConfig(); connect(this, &VEdit::cursorPositionChanged, this, &VEdit::handleCursorPositionChanged); connect(this, &VEdit::selectionChanged, this, &VEdit::highlightSelectedWord); m_lineNumberArea = new LineNumberArea(this); connect(document(), &QTextDocument::blockCountChanged, this, &VEdit::updateLineNumberAreaMargin); connect(this, &QTextEdit::textChanged, this, &VEdit::updateLineNumberArea); connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &VEdit::updateLineNumberArea); updateLineNumberAreaMargin(); connect(document(), &QTextDocument::contentsChange, this, &VEdit::updateBlockLineDistanceHeight); } VEdit::~VEdit() { } void VEdit::updateConfig() { m_config.update(QFontMetrics(font())); if (m_config.m_tabStopWidth > 0) { setTabStopWidth(m_config.m_tabStopWidth); } emit configUpdated(); } void VEdit::beginEdit() { updateFontAndPalette(); updateConfig(); setReadOnlyAndHighlight(false); setModified(false); } void VEdit::endEdit() { setReadOnlyAndHighlight(true); } void VEdit::saveFile() { Q_ASSERT(m_file->isModifiable()); if (!document()->isModified()) { return; } m_file->setContent(toHtml()); setModified(false); } void VEdit::reloadFile() { setHtml(m_file->getContent()); setModified(false); } bool VEdit::scrollToBlock(int p_blockNumber) { QTextBlock block = document()->findBlockByNumber(p_blockNumber); if (block.isValid()) { VEditUtils::scrollBlockInPage(this, block.blockNumber(), 0); moveCursor(QTextCursor::EndOfBlock); return true; } return false; } bool VEdit::isModified() const { return document()->isModified(); } void VEdit::setModified(bool p_modified) { document()->setModified(p_modified); } void VEdit::insertImage() { if (m_editOps) { m_editOps->insertImage(); } } void VEdit::insertLink() { if (!m_editOps) { return; } QString text; QString linkText, linkUrl; QTextCursor cursor = textCursor(); if (cursor.hasSelection()) { text = VEditUtils::selectedText(cursor).trimmed(); // Only pure space is accepted. QRegExp reg("[\\S ]*"); if (reg.exactMatch(text)) { QUrl url = QUrl::fromUserInput(text, m_file->fetchBasePath()); QRegExp urlReg("[\\.\\\\/]"); if (url.isValid() && text.contains(urlReg)) { // Url. linkUrl = text; } else { // Text. linkText = text; } } } VInsertLinkDialog dialog(tr("Insert Link"), "", "", linkText, linkUrl, false, this); if (dialog.exec() == QDialog::Accepted) { linkText = dialog.getLinkText(); linkUrl = dialog.getLinkUrl(); Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty()); m_editOps->insertLink(linkText, linkUrl); } } bool VEdit::peekText(const QString &p_text, uint p_options, bool p_forward) { if (p_text.isEmpty()) { makeBlockVisible(document()->findBlock(textCursor().selectionStart())); highlightIncrementalSearchedWord(QTextCursor()); return false; } bool wrapped = false; QTextCursor retCursor; bool found = findTextHelper(p_text, p_options, p_forward, p_forward ? textCursor().position() + 1 : textCursor().position(), wrapped, retCursor); if (found) { makeBlockVisible(document()->findBlock(retCursor.selectionStart())); highlightIncrementalSearchedWord(retCursor); } return found; } // Use QTextEdit::find() instead of QTextDocument::find() because the later has // bugs in searching backward. bool VEdit::findTextHelper(const QString &p_text, uint p_options, bool p_forward, int p_start, bool &p_wrapped, QTextCursor &p_cursor) { p_wrapped = false; bool found = false; // Options QTextDocument::FindFlags findFlags; bool caseSensitive = false; if (p_options & FindOption::CaseSensitive) { findFlags |= QTextDocument::FindCaseSensitively; caseSensitive = true; } if (p_options & FindOption::WholeWordOnly) { findFlags |= QTextDocument::FindWholeWords; } if (!p_forward) { findFlags |= QTextDocument::FindBackward; } // Use regular expression bool useRegExp = false; QRegExp exp; if (p_options & FindOption::RegularExpression) { useRegExp = true; exp = QRegExp(p_text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); } // Store current state of the cursor. QTextCursor cursor = textCursor(); if (cursor.position() != p_start) { if (p_start < 0) { p_start = 0; } else if (p_start > document()->characterCount()) { p_start = document()->characterCount(); } QTextCursor startCursor = cursor; startCursor.setPosition(p_start); setTextCursor(startCursor); } while (!found) { if (useRegExp) { found = find(exp, findFlags); } else { found = find(p_text, findFlags); } if (p_wrapped) { break; } if (!found) { // Wrap to the other end of the document to search again. p_wrapped = true; QTextCursor wrapCursor = textCursor(); if (p_forward) { wrapCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); } else { wrapCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); } setTextCursor(wrapCursor); } } if (found) { p_cursor = textCursor(); } // Restore the original cursor. setTextCursor(cursor); return found; } QList<QTextCursor> VEdit::findTextAll(const QString &p_text, uint p_options) { QList<QTextCursor> results; if (p_text.isEmpty()) { return results; } // Options QTextDocument::FindFlags findFlags; bool caseSensitive = false; if (p_options & FindOption::CaseSensitive) { findFlags |= QTextDocument::FindCaseSensitively; caseSensitive = true; } if (p_options & FindOption::WholeWordOnly) { findFlags |= QTextDocument::FindWholeWords; } // Use regular expression bool useRegExp = false; QRegExp exp; if (p_options & FindOption::RegularExpression) { useRegExp = true; exp = QRegExp(p_text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); } int startPos = 0; QTextCursor cursor; QTextDocument *doc = document(); while (true) { if (useRegExp) { cursor = doc->find(exp, startPos, findFlags); } else { cursor = doc->find(p_text, startPos, findFlags); } if (cursor.isNull()) { break; } else { results.append(cursor); startPos = cursor.selectionEnd(); } } return results; } bool VEdit::findText(const QString &p_text, uint p_options, bool p_forward, QTextCursor *p_cursor, QTextCursor::MoveMode p_moveMode) { clearIncrementalSearchedWordHighlight(); if (p_text.isEmpty()) { clearSearchedWordHighlight(); return false; } QTextCursor cursor = textCursor(); bool wrapped = false; QTextCursor retCursor; int matches = 0; int start = p_forward ? cursor.position() + 1 : cursor.position(); if (p_cursor) { start = p_forward ? p_cursor->position() + 1 : p_cursor->position(); } bool found = findTextHelper(p_text, p_options, p_forward, start, wrapped, retCursor); if (found) { Q_ASSERT(!retCursor.isNull()); if (wrapped) { showWrapLabel(); } if (p_cursor) { p_cursor->setPosition(retCursor.selectionStart(), p_moveMode); } else { cursor.setPosition(retCursor.selectionStart(), p_moveMode); setTextCursor(cursor); } highlightSearchedWord(p_text, p_options); highlightSearchedWordUnderCursor(retCursor); matches = m_extraSelections[(int)SelectionId::SearchedKeyword].size(); } else { clearSearchedWordHighlight(); } if (matches == 0) { statusMessage(tr("Found no match")); } else { statusMessage(tr("Found %1 %2").arg(matches) .arg(matches > 1 ? tr("matches") : tr("match"))); } return found; } void VEdit::replaceText(const QString &p_text, uint p_options, const QString &p_replaceText, bool p_findNext) { QTextCursor cursor = textCursor(); bool wrapped = false; QTextCursor retCursor; bool found = findTextHelper(p_text, p_options, true, cursor.position(), wrapped, retCursor); if (found) { if (retCursor.selectionStart() == cursor.position()) { // Matched. retCursor.beginEditBlock(); retCursor.insertText(p_replaceText); retCursor.endEditBlock(); setTextCursor(retCursor); } if (p_findNext) { findText(p_text, p_options, true); } } } void VEdit::replaceTextAll(const QString &p_text, uint p_options, const QString &p_replaceText) { // Replace from the start to the end and restore the cursor. QTextCursor cursor = textCursor(); int nrReplaces = 0; QTextCursor tmpCursor = cursor; tmpCursor.setPosition(0); setTextCursor(tmpCursor); int start = tmpCursor.position(); while (true) { bool wrapped = false; QTextCursor retCursor; bool found = findTextHelper(p_text, p_options, true, start, wrapped, retCursor); if (!found) { break; } else { if (wrapped) { // Wrap back. break; } nrReplaces++; retCursor.beginEditBlock(); retCursor.insertText(p_replaceText); retCursor.endEditBlock(); setTextCursor(retCursor); start = retCursor.position(); } } // Restore cursor position. cursor.clearSelection(); setTextCursor(cursor); qDebug() << "replace all" << nrReplaces << "occurences"; emit statusMessage(tr("Replace %1 %2").arg(nrReplaces) .arg(nrReplaces > 1 ? tr("occurences") : tr("occurence"))); } void VEdit::showWrapLabel() { int labelW = m_wrapLabel->width(); int labelH = m_wrapLabel->height(); int x = (width() - labelW) / 2; int y = (height() - labelH) / 2; if (x < 0) { x = 0; } if (y < 0) { y = 0; } m_wrapLabel->move(x, y); m_wrapLabel->show(); m_labelTimer->stop(); m_labelTimer->start(); } void VEdit::labelTimerTimeout() { m_wrapLabel->hide(); } void VEdit::updateFontAndPalette() { setFont(g_config->getBaseEditFont()); setPalette(g_config->getBaseEditPalette()); } void VEdit::highlightExtraSelections(bool p_now) { m_highlightTimer->stop(); if (p_now) { doHighlightExtraSelections(); } else { m_highlightTimer->start(); } } void VEdit::doHighlightExtraSelections() { int nrExtra = m_extraSelections.size(); Q_ASSERT(nrExtra == (int)SelectionId::MaxSelection); QList<QTextEdit::ExtraSelection> extraSelects; for (int i = 0; i < nrExtra; ++i) { extraSelects.append(m_extraSelections[i]); } setExtraSelections(extraSelects); } void VEdit::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::CurrentLine]; if (g_config->getHighlightCursorLine() && !isReadOnly()) { // Need to highlight current line. selects.clear(); // A long block maybe splited into multiple visual lines. QTextEdit::ExtraSelection select; select.format.setBackground(m_config.m_cursorLineBg); select.format.setProperty(QTextFormat::FullWidthSelection, true); QTextCursor cursor = textCursor(); if (m_config.m_highlightWholeBlock) { cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor, 1); QTextBlock block = cursor.block(); int blockEnd = block.position() + block.length(); int pos = -1; while (cursor.position() < blockEnd && pos != cursor.position()) { QTextEdit::ExtraSelection newSelect = select; newSelect.cursor = cursor; selects.append(newSelect); pos = cursor.position(); cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, 1); } } else { cursor.clearSelection(); select.cursor = cursor; selects.append(select); } } else { // Need to clear current line highlight. if (selects.isEmpty()) { return; } selects.clear(); } highlightExtraSelections(true); } void VEdit::highlightSelectedWord() { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SelectedWord]; if (!g_config->getHighlightSelectedWord()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } QString text = textCursor().selectedText().trimmed(); if (text.isEmpty() || wordInSearchedSelection(text)) { selects.clear(); highlightExtraSelections(true); return; } QTextCharFormat format; format.setBackground(m_selectedWordColor); highlightTextAll(text, FindOption::CaseSensitive, SelectionId::SelectedWord, format); } // Do not highlight trailing spaces with current cursor right behind. static void trailingSpaceFilter(VEdit *p_editor, QList<QTextEdit::ExtraSelection> &p_result) { QTextCursor cursor = p_editor->textCursor(); if (!cursor.atBlockEnd()) { return; } int cursorPos = cursor.position(); for (auto it = p_result.begin(); it != p_result.end(); ++it) { if (it->cursor.selectionEnd() == cursorPos) { p_result.erase(it); // There will be only one. return; } } } void VEdit::highlightTrailingSpace() { if (!g_config->getEnableTrailingSpaceHighlight()) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::TrailingSpace]; if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } QTextCharFormat format; format.setBackground(m_trailingSpaceColor); QString text("\\s+$"); highlightTextAll(text, FindOption::RegularExpression, SelectionId::TrailingSpace, format, trailingSpaceFilter); } bool VEdit::wordInSearchedSelection(const QString &p_text) { QString text = p_text.trimmed(); QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword]; for (int i = 0; i < selects.size(); ++i) { QString searchedWord = selects[i].cursor.selectedText(); if (text == searchedWord.trimmed()) { return true; } } return false; } void VEdit::highlightTextAll(const QString &p_text, uint p_options, SelectionId p_id, QTextCharFormat p_format, void (*p_filter)(VEdit *, QList<QTextEdit::ExtraSelection> &)) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)p_id]; if (!p_text.isEmpty()) { selects.clear(); QList<QTextCursor> occurs = findTextAll(p_text, p_options); for (int i = 0; i < occurs.size(); ++i) { QTextEdit::ExtraSelection select; select.format = p_format; select.cursor = occurs[i]; selects.append(select); } } else { if (selects.isEmpty()) { return; } selects.clear(); } if (p_filter) { p_filter(this, selects); } highlightExtraSelections(); } void VEdit::highlightSearchedWord(const QString &p_text, uint p_options) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword]; if (!g_config->getHighlightSearchedWord() || p_text.isEmpty()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } QTextCharFormat format; format.setBackground(m_searchedWordColor); highlightTextAll(p_text, p_options, SelectionId::SearchedKeyword, format); } void VEdit::highlightSearchedWordUnderCursor(const QTextCursor &p_cursor) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor]; if (!p_cursor.hasSelection()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } selects.clear(); QTextEdit::ExtraSelection select; select.format.setBackground(m_searchedWordCursorColor); select.cursor = p_cursor; selects.append(select); highlightExtraSelections(true); } void VEdit::highlightIncrementalSearchedWord(const QTextCursor &p_cursor) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword]; if (!g_config->getHighlightSearchedWord() || !p_cursor.hasSelection()) { if (!selects.isEmpty()) { selects.clear(); highlightExtraSelections(true); } return; } selects.clear(); QTextEdit::ExtraSelection select; select.format.setBackground(m_incrementalSearchedWordColor); select.cursor = p_cursor; selects.append(select); highlightExtraSelections(true); } void VEdit::clearSearchedWordHighlight() { clearIncrementalSearchedWordHighlight(false); clearSearchedWordUnderCursorHighlight(false); QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword]; if (selects.isEmpty()) { return; } selects.clear(); highlightExtraSelections(true); } void VEdit::clearSearchedWordUnderCursorHighlight(bool p_now) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor]; if (selects.isEmpty()) { return; } selects.clear(); highlightExtraSelections(p_now); } void VEdit::clearIncrementalSearchedWordHighlight(bool p_now) { QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword]; if (selects.isEmpty()) { return; } selects.clear(); highlightExtraSelections(p_now); } void VEdit::contextMenuEvent(QContextMenuEvent *p_event) { QMenu *menu = createStandardContextMenu(); menu->setToolTipsVisible(true); const QList<QAction *> actions = menu->actions(); if (!textCursor().hasSelection()) { VEditTab *editTab = dynamic_cast<VEditTab *>(parent()); V_ASSERT(editTab); if (editTab->isEditMode()) { QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"), tr("&Save Changes And Read"), this); saveExitAct->setToolTip(tr("Save changes and exit edit mode")); connect(saveExitAct, &QAction::triggered, this, &VEdit::handleSaveExitAct); QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"), tr("&Discard Changes And Read"), this); discardExitAct->setToolTip(tr("Discard changes and exit edit mode")); connect(discardExitAct, &QAction::triggered, this, &VEdit::handleDiscardExitAct); menu->insertAction(actions.isEmpty() ? NULL : actions[0], discardExitAct); menu->insertAction(discardExitAct, saveExitAct); if (!actions.isEmpty()) { menu->insertSeparator(actions[0]); } } else if (m_file->isModifiable()) { // HTML. QAction *editAct= new QAction(VIconUtils::menuIcon(":/resources/icons/edit_note.svg"), tr("&Edit"), this); editAct->setToolTip(tr("Edit current note")); connect(editAct, &QAction::triggered, this, &VEdit::handleEditAct); menu->insertAction(actions.isEmpty() ? NULL : actions[0], editAct); // actions does not contain editAction. if (!actions.isEmpty()) { menu->insertSeparator(actions[0]); } } } alterContextMenu(menu, actions); menu->exec(p_event->globalPos()); delete menu; } void VEdit::handleSaveExitAct() { emit saveAndRead(); } void VEdit::handleDiscardExitAct() { emit discardAndRead(); } void VEdit::handleEditAct() { emit editNote(); } VFile *VEdit::getFile() const { return m_file; } void VEdit::handleCursorPositionChanged() { static QTextCursor lastCursor; QTextCursor cursor = textCursor(); if (lastCursor.isNull() || cursor.blockNumber() != lastCursor.blockNumber()) { highlightCurrentLine(); highlightTrailingSpace(); } else { // Judge whether we have trailing space at current line. QString text = cursor.block().text(); if (text.rbegin()->isSpace()) { highlightTrailingSpace(); } // Handle word-wrap in one block. // Highlight current line if in different visual line. if ((lastCursor.positionInBlock() - lastCursor.columnNumber()) != (cursor.positionInBlock() - cursor.columnNumber())) { highlightCurrentLine(); } } lastCursor = cursor; } VEditConfig &VEdit::getConfig() { return m_config; } void VEdit::mousePressEvent(QMouseEvent *p_event) { if (p_event->button() == Qt::LeftButton && p_event->modifiers() == Qt::ControlModifier && !textCursor().hasSelection()) { m_oriMouseX = p_event->x(); m_oriMouseY = p_event->y(); m_readyToScroll = true; m_mouseMoveScrolled = false; p_event->accept(); return; } m_readyToScroll = false; m_mouseMoveScrolled = false; QTextEdit::mousePressEvent(p_event); emit selectionChangedByMouse(textCursor().hasSelection()); } void VEdit::mouseReleaseEvent(QMouseEvent *p_event) { if (m_mouseMoveScrolled || m_readyToScroll) { viewport()->setCursor(Qt::IBeamCursor); m_readyToScroll = false; m_mouseMoveScrolled = false; p_event->accept(); return; } m_readyToScroll = false; m_mouseMoveScrolled = false; QTextEdit::mouseReleaseEvent(p_event); } void VEdit::mouseMoveEvent(QMouseEvent *p_event) { const int threshold = 5; if (m_readyToScroll) { int deltaX = p_event->x() - m_oriMouseX; int deltaY = p_event->y() - m_oriMouseY; if (qAbs(deltaX) >= threshold || qAbs(deltaY) >= threshold) { m_oriMouseX = p_event->x(); m_oriMouseY = p_event->y(); if (!m_mouseMoveScrolled) { m_mouseMoveScrolled = true; viewport()->setCursor(Qt::SizeAllCursor); } QScrollBar *verBar = verticalScrollBar(); QScrollBar *horBar = horizontalScrollBar(); if (verBar->isVisible()) { verBar->setValue(verBar->value() - deltaY); } if (horBar->isVisible()) { horBar->setValue(horBar->value() - deltaX); } } p_event->accept(); return; } QTextEdit::mouseMoveEvent(p_event); emit selectionChangedByMouse(textCursor().hasSelection()); } void VEdit::requestUpdateVimStatus() { if (m_editOps) { m_editOps->requestUpdateVimStatus(); } else { emit vimStatusUpdated(NULL); } } bool VEdit::jumpTitle(bool p_forward, int p_relativeLevel, int p_repeat) { Q_UNUSED(p_forward); Q_UNUSED(p_relativeLevel); Q_UNUSED(p_repeat); return false; } QVariant VEdit::inputMethodQuery(Qt::InputMethodQuery p_query) const { if (p_query == Qt::ImEnabled) { return m_enableInputMethod; } return QTextEdit::inputMethodQuery(p_query); } void VEdit::setInputMethodEnabled(bool p_enabled) { if (m_enableInputMethod != p_enabled) { m_enableInputMethod = p_enabled; QInputMethod *im = QGuiApplication::inputMethod(); im->reset(); // Ask input method to query current state, which will call inputMethodQuery(). im->update(Qt::ImEnabled); } } void VEdit::decorateText(TextDecoration p_decoration) { if (m_editOps) { m_editOps->decorateText(p_decoration); } } void VEdit::updateLineNumberAreaMargin() { int width = 0; if (g_config->getEditorLineNumber()) { width = m_lineNumberArea->calculateWidth(); } setViewportMargins(width, 0, 0, 0); } void VEdit::updateLineNumberArea() { if (g_config->getEditorLineNumber()) { if (!m_lineNumberArea->isVisible()) { updateLineNumberAreaMargin(); m_lineNumberArea->show(); } m_lineNumberArea->update(); } else if (m_lineNumberArea->isVisible()) { updateLineNumberAreaMargin(); m_lineNumberArea->hide(); } } void VEdit::resizeEvent(QResizeEvent *p_event) { QTextEdit::resizeEvent(p_event); if (g_config->getEditorLineNumber()) { QRect rect = contentsRect(); m_lineNumberArea->setGeometry(QRect(rect.left(), rect.top(), m_lineNumberArea->calculateWidth(), rect.height())); } } void VEdit::lineNumberAreaPaintEvent(QPaintEvent *p_event) { int lineNumberType = g_config->getEditorLineNumber(); if (!lineNumberType) { updateLineNumberAreaMargin(); m_lineNumberArea->hide(); return; } QPainter painter(m_lineNumberArea); painter.fillRect(p_event->rect(), g_config->getEditorLineNumberBg()); QAbstractTextDocumentLayout *layout = document()->documentLayout(); QTextBlock block = firstVisibleBlock(); if (!block.isValid()) { return; } int blockNumber = block.blockNumber(); int offsetY = contentOffsetY(); QRectF rect = layout->blockBoundingRect(block); int top = offsetY + (int)rect.y(); int bottom = top + (int)rect.height(); int eventTop = p_event->rect().top(); int eventBtm = p_event->rect().bottom(); const int digitHeight = m_lineNumberArea->getDigitHeight(); const int curBlockNumber = textCursor().block().blockNumber(); const QString &fg = g_config->getEditorLineNumberFg(); const int lineDistanceHeight = m_config.m_lineDistanceHeight; painter.setPen(fg); // Display line number only in code block. if (lineNumberType == 3) { if (m_file->getDocType() != DocType::Markdown) { return; } int number = 0; while (block.isValid() && top <= eventBtm) { int blockState = block.userState(); switch (blockState) { case HighlightBlockState::CodeBlockStart: Q_ASSERT(number == 0); number = 1; break; case HighlightBlockState::CodeBlockEnd: number = 0; break; case HighlightBlockState::CodeBlock: if (number == 0) { // Need to find current line number in code block. QTextBlock startBlock = block.previous(); while (startBlock.isValid()) { if (startBlock.userState() == HighlightBlockState::CodeBlockStart) { number = block.blockNumber() - startBlock.blockNumber(); break; } startBlock = startBlock.previous(); } } break; default: break; } if (blockState == HighlightBlockState::CodeBlock) { if (block.isVisible() && bottom >= eventTop) { QString numberStr = QString::number(number); painter.drawText(0, top + 2, m_lineNumberArea->width(), digitHeight, Qt::AlignRight, numberStr); } ++number; } block = block.next(); top = bottom; bottom = top + (int)layout->blockBoundingRect(block).height() + lineDistanceHeight; } return; } // Handle lineNumberType 1 and 2. Q_ASSERT(lineNumberType == 1 || lineNumberType == 2); while (block.isValid() && top <= eventBtm) { if (block.isVisible() && bottom >= eventTop) { bool currentLine = false; int number = blockNumber + 1; if (lineNumberType == 2) { number = blockNumber - curBlockNumber; if (number == 0) { currentLine = true; number = blockNumber + 1; } else if (number < 0) { number = -number; } } else if (blockNumber == curBlockNumber) { currentLine = true; } QString numberStr = QString::number(number); if (currentLine) { QFont font = painter.font(); font.setBold(true); painter.setFont(font); } painter.drawText(0, top + 2, m_lineNumberArea->width(), digitHeight, Qt::AlignRight, numberStr); if (currentLine) { QFont font = painter.font(); font.setBold(false); painter.setFont(font); } } block = block.next(); top = bottom; bottom = top + (int)layout->blockBoundingRect(block).height() + lineDistanceHeight; ++blockNumber; } } int VEdit::contentOffsetY() { int offsety = 0; QScrollBar *sb = verticalScrollBar(); offsety = sb->value(); return -offsety; } QTextBlock VEdit::firstVisibleBlock() { QTextDocument *doc = document(); QAbstractTextDocumentLayout *layout = doc->documentLayout(); int offsetY = contentOffsetY(); // Binary search. int idx = -1; int start = 0, end = doc->blockCount() - 1; while (start <= end) { int mid = start + (end - start) / 2; QTextBlock block = doc->findBlockByNumber(mid); if (!block.isValid()) { break; } int y = offsetY + (int)layout->blockBoundingRect(block).y(); if (y == 0) { return block; } else if (y < 0) { start = mid + 1; } else { if (idx == -1 || mid < idx) { idx = mid; } end = mid - 1; } } if (idx != -1) { return doc->findBlockByNumber(idx); } // Linear search. qDebug() << "fall back to linear search for first visible block"; QTextBlock block = doc->begin(); while (block.isValid()) { int y = offsetY + (int)layout->blockBoundingRect(block).y(); if (y >= 0) { return block; } block = block.next(); } return QTextBlock(); } int LineNumberArea::calculateWidth() const { int bc = m_document->blockCount(); if (m_blockCount == bc) { return m_width; } const_cast<LineNumberArea *>(this)->m_blockCount = bc; int digits = 1; int max = qMax(1, m_blockCount); while (max >= 10) { max /= 10; ++digits; } int width = m_digitWidth * digits; const_cast<LineNumberArea *>(this)->m_width = width; return m_width; } void VEdit::makeBlockVisible(const QTextBlock &p_block) { if (!p_block.isValid() || !p_block.isVisible()) { return; } QScrollBar *vbar = verticalScrollBar(); if (!vbar || !vbar->isVisible()) { // No vertical scrollbar. No need to scroll. return; } QAbstractTextDocumentLayout *layout = document()->documentLayout(); int height = rect().height(); QScrollBar *hbar = horizontalScrollBar(); if (hbar && hbar->isVisible()) { height -= hbar->height(); } bool moved = false; QRectF rect = layout->blockBoundingRect(p_block); int y = contentOffsetY() + (int)rect.y(); int rectHeight = (int)rect.height(); // Handle the case rectHeight >= height. if (rectHeight >= height) { if (y <= 0) { if (y + rectHeight < height) { // Need to scroll up. while (y + rectHeight < height && vbar->value() > vbar->minimum()) { moved = true; vbar->setValue(vbar->value() - vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } } } else { // Need to scroll down. while (y > 0 && vbar->value() < vbar->maximum()) { moved = true; vbar->setValue(vbar->value() + vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } } if (moved) { qDebug() << "scroll to make huge block visible"; } return; } while (y < 0 && vbar->value() > vbar->minimum()) { moved = true; vbar->setValue(vbar->value() - vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } if (moved) { qDebug() << "scroll page down to make block visible"; return; } while (y + rectHeight > height && vbar->value() < vbar->maximum()) { moved = true; vbar->setValue(vbar->value() + vbar->singleStep()); rect = layout->blockBoundingRect(p_block); rectHeight = (int)rect.height(); y = contentOffsetY() + (int)rect.y(); } if (moved) { qDebug() << "scroll page up to make block visible"; } } bool VEdit::isBlockVisible(const QTextBlock &p_block) { if (!p_block.isValid() || !p_block.isVisible()) { return false; } QScrollBar *vbar = verticalScrollBar(); if (!vbar || !vbar->isVisible()) { // No vertical scrollbar. return true; } QAbstractTextDocumentLayout *layout = document()->documentLayout(); int height = rect().height(); QScrollBar *hbar = horizontalScrollBar(); if (hbar && hbar->isVisible()) { height -= hbar->height(); } QRectF rect = layout->blockBoundingRect(p_block); int y = contentOffsetY() + (int)rect.y(); int rectHeight = (int)rect.height(); return (y >= 0 && y < height) || (y < 0 && y + rectHeight > 0); } void VEdit::alterContextMenu(QMenu *p_menu, const QList<QAction *> &p_actions) { Q_UNUSED(p_menu); Q_UNUSED(p_actions); } void VEdit::updateBlockLineDistanceHeight(int p_pos, int p_charsRemoved, int p_charsAdded) { if ((p_charsRemoved == 0 && p_charsAdded == 0) || m_config.m_lineDistanceHeight <= 0) { return; } QTextDocument *doc = document(); QTextBlock block = doc->findBlock(p_pos); QTextBlock lastBlock = doc->findBlock(p_pos + p_charsRemoved + p_charsAdded); QTextCursor cursor(block); bool changed = false; while (block.isValid()) { cursor.setPosition(block.position()); QTextBlockFormat fmt = cursor.blockFormat(); if (fmt.lineHeightType() != QTextBlockFormat::LineDistanceHeight || fmt.lineHeight() != m_config.m_lineDistanceHeight) { fmt.setLineHeight(m_config.m_lineDistanceHeight, QTextBlockFormat::LineDistanceHeight); if (!changed) { changed = true; cursor.joinPreviousEditBlock(); } cursor.mergeBlockFormat(fmt); qDebug() << "merge block format line distance" << block.blockNumber(); } if (block == lastBlock) { break; } block = block.next(); } if (changed) { cursor.endEditBlock(); } } void VEdit::evaluateMagicWords() { QString text; QTextCursor cursor = textCursor(); if (!cursor.hasSelection()) { // Get the WORD in current cursor. int start, end; VEditUtils::findCurrentWORD(cursor, start, end); if (start == end) { return; } else { cursor.setPosition(start); cursor.setPosition(end, QTextCursor::KeepAnchor); } } text = VEditUtils::selectedText(cursor); Q_ASSERT(!text.isEmpty()); QString evaText = g_mwMgr->evaluate(text); if (text != evaText) { qDebug() << "evaluateMagicWords" << text << evaText; cursor.insertText(evaText); if (m_editOps) { m_editOps->setVimMode(VimMode::Insert); } setTextCursor(cursor); } } void VEdit::setReadOnlyAndHighlight(bool p_readonly) { setReadOnly(p_readonly); highlightCurrentLine(); }
28.615815
112
0.58092
linails
f4ffdbc72af1209c3c20227409afe3684aac4f62
576
cpp
C++
libvermilion/core/src/stb_image.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/stb_image.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/stb_image.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "Texture.hpp" #include <string> unsigned char * Vermilion::Core::loadTextureData(const std::string& path, size_t * width, size_t * height, size_t * channels){ *width = 0; *height = 0; *channels = 4; Vermilion::Core::flipLoading(); return stbi_load(path.c_str(), (int*)width, (int*)height, nullptr, STBI_rgb_alpha); } void Vermilion::Core::freeTextureData(unsigned char * data){ stbi_image_free(data); } void Vermilion::Core::flipLoading(){ stbi_set_flip_vertically_on_load(true); }
28.8
126
0.713542
Jojojoppe
76028276bf7c9e6e899d16d6e47452956936c4f6
11,255
cpp
C++
src/Engine/Audio/CPianoKeyboard.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
4
2021-12-16T11:22:30.000Z
2022-01-05T11:20:32.000Z
src/Engine/Audio/CPianoKeyboard.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
1
2022-01-07T10:41:38.000Z
2022-01-09T12:04:03.000Z
src/Engine/Audio/CPianoKeyboard.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
null
null
null
/* * CPianoKeyboard (CPianoKeyboard.cpp) * MobiTracker * * Created by Marcin Skoczylas on 09-11-26. * Copyright 2009 Marcin Skoczylas. All rights reserved. * */ #include "CPianoKeyboard.h" #include "VID_Main.h" #include "CGuiMain.h" #include "CLayoutParameter.h" #define OCT_NAME_FONT_SIZE_X 8.0 #define OCT_NAME_FONT_SIZE_Y 8.0 #define OCT_NAME_GAP_X 2.0 #define OCT_NAME_GAP_Y 1.0 const char *pianoKeyboardKeyNames = "CDEFGAB"; void CPianoKeyboardCallback::PianoKeyboardNotePressed(CPianoKeyboard *pianoKeyboard, u8 note) { } void CPianoKeyboardCallback::PianoKeyboardNoteReleased(CPianoKeyboard *pianoKeyboard, u8 note) { } CPianoKeyboard::CPianoKeyboard(const char *name, float posX, float posY, float posZ, float sizeX, float sizeY, CPianoKeyboardCallback *callback) :CGuiView(name, posX, posY, posZ, sizeX, sizeY) { keyWhiteWidth = 1.0/7.0; keyBlackOffset = keyWhiteWidth * (3.0f/4.0f); keyBlackWidth = keyWhiteWidth * (2.0f/4.0f); keyBlackHeight = (3.0f/5.0f); this->numOctaves = 8; this->octaveNames = new const char *[this->numOctaves]; octaveNames[0] = "0"; octaveNames[1] = "I"; octaveNames[2] = "II"; octaveNames[3] = "III"; octaveNames[4] = "IV"; octaveNames[5] = "V"; octaveNames[6] = "VI"; octaveNames[7] = "VII"; // octaveNames[8] = "VIII"; // octaveNames[9] = "IX"; SetKeysFadeOut(true); SetKeysFadeOutSpeed(0.40f); currentOctave = 4; AddDefaultKeyCodes(); this->callback = callback; this->InitKeys(); AddLayoutParameter(new CLayoutParameterBool("Keys fade out", &doKeysFadeOut)); AddLayoutParameter(new CLayoutParameterFloat("Keys fade out speed", &keysFadeOutSpeedParameter)); } void CPianoKeyboard::SetKeysFadeOut(bool doKeysFadeOut) { this->doKeysFadeOut = doKeysFadeOut; } void CPianoKeyboard::SetKeysFadeOutSpeed(float speed) { this->keysFadeOutSpeed = speed; this->keysFadeOutSpeedOneMinus = 1.0f - this->keysFadeOutSpeed; this->keysFadeOutSpeedParameter = speed * 10.0f; } void CPianoKeyboard::LayoutParameterChanged(CLayoutParameter *layoutParameter) { this->keysFadeOutSpeed = keysFadeOutSpeedParameter / 10.0f; this->keysFadeOutSpeedOneMinus = 1.0f - this->keysFadeOutSpeed; } CPianoKey::CPianoKey(u8 keyNote, u8 keyOctave, const char *keyName, double x, double y, double sizeX, double sizeY, bool isBlackKey) { this->keyNote = keyNote; this->keyOctave = keyOctave, this->x = x; this->y = y; this->sizeX = sizeX; this->sizeY = sizeY; this->isBlackKey = isBlackKey; strcpy(this->keyName, keyName); if (!isBlackKey) { r = g = b = a = 1.0f; cr = cg = cb = ca = 1.0f; } else { r = g = b = 0; a = 1.0f; cr = cg = cb = 0; ca = 1.0f; } // LOGD("CPianoKey: %d %s: %6.3f %6.3f %6.3f %6.3f", keyNote, keyName, x, y, sizeX, sizeY); } void CPianoKeyboard::InitKeys() { char *keyName = SYS_GetCharBuf(); double fOctaveStep = 1 / (double)numOctaves; keyWhiteWidth = fOctaveStep * 1.0/7.0; keyBlackOffset = keyWhiteWidth * (3.0f/4.0f); keyBlackWidth = keyWhiteWidth * (2.0f/4.0f); keyBlackHeight = (3.0f/5.0f); CPianoKey *key = NULL; int keyNum = 0; for (int octaveNum = 0; octaveNum < numOctaves; octaveNum++) { double octaveOffset = fOctaveStep * (double)octaveNum; for (int keyNumInOctave = 0; keyNumInOctave < 7; keyNumInOctave++) { sprintf(keyName, "%c-%d", pianoKeyboardKeyNames[keyNumInOctave], octaveNum); key = new CPianoKey(keyNum, octaveNum, keyName, keyWhiteWidth * (double)keyNumInOctave + octaveOffset, 0.0f, keyWhiteWidth, 1.0f, false); keyNum++; pianoKeys.push_back(key); pianoWhiteKeys.push_back(key); if (keyNumInOctave == 0 || keyNumInOctave == 1 || keyNumInOctave == 3 || keyNumInOctave == 4 || keyNumInOctave == 5) { sprintf(keyName, "%c#%d", pianoKeyboardKeyNames[keyNumInOctave], octaveNum); key = new CPianoKey(keyNum, octaveNum, keyName, keyBlackOffset + keyWhiteWidth * (double)keyNumInOctave + octaveOffset, 0.0f, keyBlackWidth, keyBlackHeight, true); keyNum++; pianoKeys.push_back(key); pianoBlackKeys.push_back(key); } } } SYS_ReleaseCharBuf(keyName); LOGD("InitKeys done"); } void CPianoKeyboard::Render() { // LOGD("CPianoKeyboard::Render"); for (std::vector<CPianoKey *>::iterator it = pianoWhiteKeys.begin(); it != pianoWhiteKeys.end(); it++) { CPianoKey *key = *it; BlitFilledRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, key->cr, key->cg, key->cb, key->ca); // border BlitRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, 0, 0, 0, 1); } for (std::vector<CPianoKey *>::iterator it = pianoBlackKeys.begin(); it != pianoBlackKeys.end(); it++) { CPianoKey *key = *it; BlitFilledRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, key->cr, key->cg, key->cb, key->ca); BlitRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1, key->sizeX * this->sizeX, key->sizeY * this->sizeY, 0, 0, 0, 1); } } void CPianoKeyboard::DoLogic() { // LOGD("CPianoKeyboard::DoLogic"); if (doKeysFadeOut) { for (std::vector<CPianoKey *>::iterator it = pianoKeys.begin(); it != pianoKeys.end(); it++) { CPianoKey *key = *it; key->cr = key->cr * keysFadeOutSpeedOneMinus + key->r * keysFadeOutSpeed; key->cg = key->cg * keysFadeOutSpeedOneMinus + key->g * keysFadeOutSpeed; key->cb = key->cb * keysFadeOutSpeedOneMinus + key->b * keysFadeOutSpeed; key->ca = key->ca * keysFadeOutSpeedOneMinus + key->a * keysFadeOutSpeed; } } } bool CPianoKeyboard::DoTap(float x, float y) { LOGG("CPianoKeyboard::DoTap: x=%f y=%f posX=%f posY=%f sizeX=%f sizeY=%f", x, y, posX, posY, sizeX, sizeY); // this->pressedNote = GetPressedNote(x, y); // // if (pressedNote != NOTE_NONE) // { // if (callback != NULL) // callback->PianoKeyboardNotePressed(pressedNote + editNoteOctave*12); //this->selectedInstrument, // } // LOGG("pressed note=%d", pressedNote); // if (pressedNote != NOTE_NONE) // return true; return false; } u8 CPianoKeyboard::GetPressedNote(float x, float y) { return -1; } bool CPianoKeyboard::DoDoubleTap(float x, float y) { return this->DoTap(x, y); } bool CPianoKeyboard::DoFinishTap(float x, float y) { if (IsInsideNonVisible(x, y)) return true; return false; } bool CPianoKeyboard::DoFinishDoubleTap(float x, float y) { return this->DoFinishTap(x, y); } bool CPianoKeyboard::DoMove(float x, float y, float distX, float distY, float diffX, float diffY) { LOGG("CPianoKeyboard::DoMove"); // if (x < SCREEN_WIDTH-menuButtonSizeX) // { // u8 bPressedNote = this->GetPressedNote(x, y); // LOGG("bPressedNote=%d", bPressedNote); // // if (bPressedNote != this->pressedNote) // { // this->pressedNote = bPressedNote; // // if (bPressedNote != NOTE_NONE) // { // if (callback != NULL) // callback->PianoKeyboardNotePressed(bPressedNote + editNoteOctave*12); //this->selectedInstrument, // } // LOGG("pressed note=%d", pressedNote); // } // // if (pressedNote != NOTE_NONE) // { // return true; // } // } return false; //this->DoTap(x, y); } bool CPianoKeyboard::FinishMove(float x, float y, float distX, float distY, float accelerationX, float accelerationY) { // if (x < SCREEN_WIDTH-menuButtonSizeX) // return this->DoFinishTap(x, y); return false; } bool CPianoKeyboard::KeyDown(u32 keyCode, bool isShift, bool isAlt, bool isControl, bool isSuper) { LOGD("CPianoKeyboard::KeyDown: keyCode=%x", keyCode); // TODO: make via callback if (keyCode == '[') { if (currentOctave > 0) currentOctave--; return true; } else if (keyCode == ']') { if (currentOctave < numOctaves-2) currentOctave++; return true; } else if (this->callback != NULL) { // scan for note key code for (std::list<CPianoNoteKeyCode *>::iterator it = notesKeyCodes.begin(); it != notesKeyCodes.end(); it++) { CPianoNoteKeyCode *noteKeyCode = *it; if (keyCode == noteKeyCode->keyCode) { this->callback->PianoKeyboardNotePressed(this, noteKeyCode->keyNote + currentOctave*12); return true; } } } return false; } bool CPianoKeyboard::KeyUp(u32 keyCode, bool isShift, bool isAlt, bool isControl, bool isSuper) { LOGD("CPianoKeyboard::KeyUp: keyCode=%x", keyCode); if (this->callback != NULL) { // scan for note key code for (std::list<CPianoNoteKeyCode *>::iterator it = notesKeyCodes.begin(); it != notesKeyCodes.end(); it++) { CPianoNoteKeyCode *noteKeyCode = *it; if (keyCode == noteKeyCode->keyCode) { this->callback->PianoKeyboardNoteReleased(this, noteKeyCode->keyNote + currentOctave*12); return true; } } } return false; } void CPianoKeyboard::AddDefaultKeyCodes() { // 0 = C-0 notesKeyCodes.push_back(new CPianoNoteKeyCode('z', 0)); // C-0 notesKeyCodes.push_back(new CPianoNoteKeyCode('s', 1)); notesKeyCodes.push_back(new CPianoNoteKeyCode('x', 2)); notesKeyCodes.push_back(new CPianoNoteKeyCode('d', 3)); notesKeyCodes.push_back(new CPianoNoteKeyCode('c', 4)); notesKeyCodes.push_back(new CPianoNoteKeyCode('v', 5)); notesKeyCodes.push_back(new CPianoNoteKeyCode('g', 6)); notesKeyCodes.push_back(new CPianoNoteKeyCode('b', 7)); notesKeyCodes.push_back(new CPianoNoteKeyCode('h', 8)); notesKeyCodes.push_back(new CPianoNoteKeyCode('n', 9)); notesKeyCodes.push_back(new CPianoNoteKeyCode('j', 10)); notesKeyCodes.push_back(new CPianoNoteKeyCode('m', 11)); notesKeyCodes.push_back(new CPianoNoteKeyCode(',', 12)); // C-1 notesKeyCodes.push_back(new CPianoNoteKeyCode('l', 13)); notesKeyCodes.push_back(new CPianoNoteKeyCode('.', 14)); notesKeyCodes.push_back(new CPianoNoteKeyCode(';', 15)); notesKeyCodes.push_back(new CPianoNoteKeyCode('/', 16)); notesKeyCodes.push_back(new CPianoNoteKeyCode('q', 12)); // C-1 notesKeyCodes.push_back(new CPianoNoteKeyCode('2', 13)); notesKeyCodes.push_back(new CPianoNoteKeyCode('w', 14)); notesKeyCodes.push_back(new CPianoNoteKeyCode('3', 15)); notesKeyCodes.push_back(new CPianoNoteKeyCode('e', 16)); notesKeyCodes.push_back(new CPianoNoteKeyCode('r', 17)); notesKeyCodes.push_back(new CPianoNoteKeyCode('5', 18)); notesKeyCodes.push_back(new CPianoNoteKeyCode('t', 19)); notesKeyCodes.push_back(new CPianoNoteKeyCode('6', 20)); notesKeyCodes.push_back(new CPianoNoteKeyCode('y', 21)); notesKeyCodes.push_back(new CPianoNoteKeyCode('7', 22)); notesKeyCodes.push_back(new CPianoNoteKeyCode('u', 23)); notesKeyCodes.push_back(new CPianoNoteKeyCode('i', 24)); notesKeyCodes.push_back(new CPianoNoteKeyCode('9', 25)); notesKeyCodes.push_back(new CPianoNoteKeyCode('o', 26)); notesKeyCodes.push_back(new CPianoNoteKeyCode('0', 27)); notesKeyCodes.push_back(new CPianoNoteKeyCode('p', 28)); } CPianoKeyboard::~CPianoKeyboard() { while(!pianoKeys.empty()) { CPianoKey *key = pianoKeys.back(); pianoKeys.pop_back(); delete key; } while(!notesKeyCodes.empty()) { CPianoNoteKeyCode *keyCode = notesKeyCodes.back(); notesKeyCodes.pop_back(); delete keyCode; } }
28.278894
153
0.687517
slajerek
760412626f88fb941d8e6b4255045abda9a3697f
1,340
hpp
C++
src/entity/sprite/Sprite.hpp
JulienTD/pacman
71e92b367b4c57bba065c18faa67570842bdd67f
[ "MIT" ]
null
null
null
src/entity/sprite/Sprite.hpp
JulienTD/pacman
71e92b367b4c57bba065c18faa67570842bdd67f
[ "MIT" ]
null
null
null
src/entity/sprite/Sprite.hpp
JulienTD/pacman
71e92b367b4c57bba065c18faa67570842bdd67f
[ "MIT" ]
null
null
null
#ifndef SPRITE_HPP_ #define SPRITE_HPP_ #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_pixels.h> #include <SDL2/SDL_image.h> #include "window/Window.hpp" #include "entity/Entity.hpp" class Sprite : public Entity { public: Sprite(std::string id, std::string spritePath, Window *window, int x, int y, int width, int height); ~Sprite(); void setMaxStateNbr(int stateNbr); void setXStateGap(int xGap); void setYStateGap(int yGap); void setSpriteX(int spriteX); void setSpriteY(int spriteY); void setSpriteHeight(int spriteHeight); void setSpriteWidth(int spriteWidth); void setXAnimation(bool xAnimation); void setYAnimation(bool yAnimation); void setTickRate(int tickRate); void setTickStep(int tickStep); void render(Window *window); protected: private: SDL_Surface *_image; SDL_Texture *_texture; int _width; int _height; int _stateNbr; int _maxStateNbr; int _xStateGap; int _yStateGap; int _spriteX; int _spriteY; int _spriteWidth; int _spriteHeight; bool _xAnimation; bool _yAnimation; int _currentTick; int _tickRate; int _tickStep; }; #endif /* !SPRITE_HPP_ */
26.8
108
0.629851
JulienTD
760a33560dd67baa90060d7973adde8257a61375
837
hpp
C++
PolyEngine/Editor/Src/Controls/IControlBase.hpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
65
2017-04-04T20:33:44.000Z
2019-12-02T23:06:58.000Z
PolyEngine/Editor/Src/Controls/IControlBase.hpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
46
2017-04-21T12:26:38.000Z
2019-12-15T05:31:47.000Z
PolyEngine/Editor/Src/Controls/IControlBase.hpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
51
2017-04-12T10:53:32.000Z
2019-11-20T13:05:54.000Z
#pragma once #include <QtWidgets/qwidget.h> #include <QtCore/qtimer.h> #include <RTTI/RTTI.hpp> #include <Utils/Logger.hpp> using namespace Poly; // This is base class for all controls for core types such as int, string or vector. // @see Poly::RTTI::eCorePropertyType class IControlBase { public: // Assigns given object to control and updates this control. virtual void SetObject(void* ptr) = 0; // Name of assigned property. virtual void SetName(String name) = 0; // Tool tip for this control. virtual void SetToolTip(String type) = 0; // If set to true then control will not permit changing its content. virtual void SetDisableEdit(bool disable) = 0; // Resets this control to initial state; virtual void Reset() = 0; // Call this to update control state from assigned object. virtual void UpdateControl() = 0; };
26.15625
84
0.734767
PiotrMoscicki
76169e6048a4751df05e23b45ca86658151d7cd1
755
cpp
C++
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
cnm06/Competitive-Programming
94242ae458570d503b8218f37624b88cc5020d23
[ "MIT" ]
994
2017-02-28T06:13:47.000Z
2022-03-31T10:49:00.000Z
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
16
2018-01-01T02:59:55.000Z
2021-11-22T12:49:16.000Z
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
325
2017-06-15T03:32:43.000Z
2022-03-28T22:43:42.000Z
#include <iostream> #include <bits/stdc++.h> using namespace std; long long int n, temp; int main() { cin>>n; if(n<10 && n>0) { cout<<n<<endl; } else if(n>9 && n<190) { n=n-9; temp=n%2; n=9+n/2; if(temp==0) { cout<<n%10<<endl; } else { n++; cout<<n/10<<endl; } } else { n=n-189; temp=n%3; n=99+n/3; if(temp==0) { cout<<n%10<<endl; } else if(temp==1) { n++; cout<<n/100<<endl; } else { n++; n=n/10; cout<<n%10<<endl; } } return 0; }
14.803922
30
0.316556
cnm06
7626c7483fb2ea7749e070c7818a48b71e7fa0c9
46
cpp
C++
tests/src/experimental/tests_Optional.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2021-07-16T14:19:50.000Z
2021-07-16T14:19:50.000Z
tests/src/experimental/tests_Optional.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2018-06-05T11:03:30.000Z
2018-06-05T11:03:30.000Z
tests/src/experimental/tests_Optional.cpp
tum-ei-rcs/mart-common
6f8f18ac23401eb294d96db490fbdf78bf9b316c
[ "MIT" ]
null
null
null
#include <mart-common/experimental/Optional.h>
46
46
0.826087
Mike-Bal
762a0dc66e72d07d2707b64b32450fe35bb7e0c6
2,276
cpp
C++
tc 160+/OptimalList.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/OptimalList.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/OptimalList.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; const int di[] = { -1, 0, 1, 0 }; const int dj[] = { 0, 1, 0, -1 }; string dir = "NESW"; int getDir(char c) { return dir.find(c); } class OptimalList { public: string optimize(string inst) { int i = 0; int j = 0; for (int k=0; k<(int)inst.size(); ++k) { int d = getDir(inst[k]); i += di[d]; j += dj[d]; } int d1; if (i >= 0) d1 = 2; else d1 = 0; int d2; if (j >= 0) d2 = 1; else d2 = 3; if (dir[d1] > dir[d2]) return string(abs(j), dir[d2]) + string(abs(i), dir[d1]); else return string(abs(i), dir[d1]) + string(abs(j), dir[d2]); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "NENENNWWWWWS"; string Arg1 = "NNNWWW"; verify_case(0, Arg1, optimize(Arg0)); } void test_case_1() { string Arg0 = "NNEESSWW"; string Arg1 = ""; verify_case(1, Arg1, optimize(Arg0)); } void test_case_2() { string Arg0 = "NEWSNWESWESSEWSENSEWSEWESEWWEWEEWESSSWWWWWW"; string Arg1 = "SSSSSSSSWWW"; verify_case(2, Arg1, optimize(Arg0)); } void test_case_3() { string Arg0 = "NENENE"; string Arg1 = "EEENNN"; verify_case(3, Arg1, optimize(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { OptimalList ___test; ___test.run_test(-1); } // END CUT HERE
29.558442
315
0.566784
ibudiselic
762ae0e3ad471639a76e787ed602828358d9d040
5,668
cpp
C++
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
// // chorusmodel.cpp // MDStudio // // Created by Daniel Cliche on 2017-05-08. // Copyright © 2017-2020 Daniel Cliche. All rights reserved. // #include "chorusmodel.h" #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string.h> #define GRAPH_SAMPLE_RATE 44100 #define ROUND(n) ((int)((float)(n) + 0.5)) #define BSZ 8192 // must be about 1/5 of a second at given sample rate #define MODF(n, i, f) ((i) = (int)(n), (f) = (n) - (float)(i)) using namespace MDStudio; #define NUM_MIX_MODES 7 // --------------------------------------------------------------------------------------------------------------------- ChorusModel::ChorusModel() { _paramWidth = 0.8f; _paramDelay = 0.2f; _paramMixMode = 0; _sweepSamples = 0; _delaySamples = 22; _lfoPhase = 0.0f; setRate(0.2f); setWidth(0.5f); _fp = 0; _sweep = 0.0; setMixMode(kMixStereoWetOnly); _wet = 0.0f; // allocate the buffer _buf = new GraphSampleType[BSZ]; memset(_buf, 0, sizeof(GraphSampleType) * BSZ); } // --------------------------------------------------------------------------------------------------------------------- ChorusModel::~ChorusModel() { if (_buf) delete[] _buf; } // --------------------------------------------------------------------------------------------------------------------- void ChorusModel::setRate(float rate) { _paramSweepRate = rate; _lfoDeltaPhase = 2 * M_PI * rate / GRAPH_SAMPLE_RATE; // map into param onto desired sweep range with log curve _sweepRate = pow(10.0, (double)_paramSweepRate); _sweepRate -= 1.0; _sweepRate *= 1.1f; _sweepRate += 0.1f; // finish setup setSweep(); } // --------------------------------------------------------------------------------------------------------------------- // Maps 0.0-1.0 input to calculated width in samples from 0ms to 50ms void ChorusModel::setWidth(float v) { _paramWidth = v; // map so that we can spec between 0ms and 50ms _sweepSamples = ROUND(v * 0.05 * GRAPH_SAMPLE_RATE); // finish setup setSweep(); } // --------------------------------------------------------------------------------------------------------------------- // Expects input from 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 void ChorusModel::setDelay(float v) { _paramDelay = v; // make onto desired values applying log curve double delay = pow(10.0, (double)v * 2.0) / 1000.0; // map logarithmically and convert to seconds _delaySamples = ROUND(delay * GRAPH_SAMPLE_RATE); // finish setup setSweep(); } // --------------------------------------------------------------------------------------------------------------------- // Sets up sweep based on rate, depth, and delay as they're all interrelated // Assumes _sweepRate, _sweepSamples, and _delaySamples have all been set by // setRate, setWidth, and setDelay void ChorusModel::setSweep() { // calc min and max sweep now _minSweepSamples = _delaySamples; _maxSweepSamples = _delaySamples + _sweepSamples; // set intial sweep pointer to midrange _sweep = (_minSweepSamples + _maxSweepSamples) / 2; } // --------------------------------------------------------------------------------------------------------------------- void ChorusModel::setMixMode(int mixMode) { _paramMixMode = mixMode; switch (mixMode) { case kMixMono: default: _mixLeftWet = _mixRightWet = 1.0; _mixLeftDry = _mixRightDry = 1.0f; break; case kMixWetOnly: _mixLeftWet = _mixRightWet = 1.0f; _mixLeftDry = _mixRightDry = 0.0; break; case kMixWetLeft: _mixLeftWet = 1.0f; _mixLeftDry = 0.0f; _mixRightWet = 0.0f; _mixRightDry = 1.0f; break; case kMixWetRight: _mixLeftWet = 0.0f; _mixLeftDry = 1.0f; _mixRightWet = 1.0f; _mixRightDry = 0.0f; break; case kMixStereoWetOnly: _mixLeftWet = 1.0f; _mixLeftDry = 0.0f; _mixRightWet = -1.0f; _mixRightDry = 0.0f; break; } } // --------------------------------------------------------------------------------------------------------------------- void ChorusModel::setWet(float v) { _wet = v; } // --------------------------------------------------------------------------------------------------------------------- int ChorusModel::renderInput(UInt32 inNumberFrames, GraphSampleType* ioData[2], UInt32 stride) { float* io1 = ioData[0]; float* io2 = ioData[1]; for (int i = 0; i < inNumberFrames; ++i) { // assemble mono input value and store it in circle queue float inval = (*io1 + *io2) / 2.0f; _buf[_fp] = inval; _fp = (_fp + 1) & (BSZ - 1); // build the two emptying pointers and do linear interpolation int ep1, ep2; float w1, w2; float ep = _fp - _sweep; MODF(ep, ep1, w2); ep1 &= (BSZ - 1); ep2 = ep1 + 1; ep2 &= (BSZ - 1); w1 = 1.0 - w2; GraphSampleType outval = _buf[ep1] * w1 + _buf[ep2] * w2; // develop output mix *io1 = (float)(_mixLeftDry * *io1 + _mixLeftWet * _wet * outval); *io2 = (float)(_mixRightDry * *io2 + _mixRightWet * _wet * outval); _sweep = _minSweepSamples + _sweepSamples * (sinf(_lfoPhase) + 1.0f) / 2.0f; _lfoPhase += _lfoDeltaPhase; _lfoPhase = fmod(_lfoPhase, 2 * M_PI); io1 += stride; io2 += stride; } return 0; }
31.314917
120
0.481475
dcliche
762b2d51877e601a10f55acb64f4fd2c81f7dd2d
14,190
cc
C++
src/HR2Scheduler.cc
harsha-simhadri/sbsched
8d12a010727ea415d5e4a23d389740d57c68278c
[ "MIT" ]
1
2020-09-30T14:47:02.000Z
2020-09-30T14:47:02.000Z
src/HR2Scheduler.cc
harsha-simhadri/sbsched
8d12a010727ea415d5e4a23d389740d57c68278c
[ "MIT" ]
null
null
null
src/HR2Scheduler.cc
harsha-simhadri/sbsched
8d12a010727ea415d5e4a23d389740d57c68278c
[ "MIT" ]
null
null
null
// This code is part of the project "Experimental Analysis of Space-Bounded // Schedulers", presented at Symposium on Parallelism in Algorithms and // Architectures, 2014. // Copyright (c) 2014 Harsha Vardhan Simhadri, Guy Blelloch, Phillip Gibbons, // Jeremy Fineman, Aapo Kyrola. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights (to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "HR2Scheduler.hh" #include <assert.h> HR2Scheduler::Cluster::Cluster (const lluint size, const int block_size, int num_children, int sibling_id, Cluster * parent, Cluster ** children) : _size (size), _block_size (block_size), _occupied(0), _num_children(num_children), _sibling_id(sibling_id), _parent(parent), _locked_thread_id (-1) { _children = new Cluster* [_num_children]; if (children!=NULL) for (int i=0; i<_num_children; ++i) _children[i]=children[i]; } HR2Scheduler::Cluster* HR2Scheduler::Cluster::create_tree( Cluster * root, Cluster ** leaf_array, int num_levels, uint * fan_outs, lluint * sizes, uint * block_sizes, int bucket_version) { static int leaf_counter=0; Cluster * ret; if (root == NULL) { // Create the root (RAM) node ret = new Cluster (1<<((sizeof(lluint)*4)-1) -1, block_sizes[0], fan_outs[0], 0); if (bucket_version==0) ret->_buckets = new Buckets<HR2Job*> (num_levels,0,*block_sizes,sizes,*fan_outs,SIGMA); else if (bucket_version==1) ret->_buckets = new TopDistrBuckets<HR2Job*> (num_levels,0,*block_sizes,sizes,*fan_outs,SIGMA); else exit(-1); leaf_counter = 0; for (int i=0; i<fan_outs[0]; ++i) { ret->_children[i] = create_tree (ret, leaf_array, num_levels-1, fan_outs+1, sizes+1, block_sizes+1,bucket_version); ret->_children[i]->_sibling_id = i; } } else if (num_levels>0) { ret = new Cluster (sizes[0], block_sizes[0], fan_outs[0], -1, root); if (bucket_version==0) ret->_buckets = new Buckets<HR2Job*> (num_levels,*sizes,*block_sizes,sizes,*fan_outs,SIGMA); else if (bucket_version==1) ret->_buckets = new TopDistrBuckets<HR2Job*> (num_levels,*sizes,*block_sizes,sizes,*fan_outs,SIGMA); else exit(-1); for (int i=0; i<fan_outs[0]; ++i) { ret->_children[i] = create_tree (ret, leaf_array, num_levels-1, fan_outs+1, sizes+1, block_sizes+1,bucket_version); ret->_children[i]->_sibling_id = i; } } else { ret = new Cluster (0, 1, 1, -1, root); // L0 cache/register leaf_array[leaf_counter++] = ret; } return ret; } void HR2Scheduler::print_tree( Cluster * root, int num_levels, int total_levels) { if (total_levels == -1) total_levels=num_levels; if (num_levels > 0) { for (int i=0; i<total_levels-num_levels; ++i) std::cout<<"\t\t"; std::cout<<"Occ:"<<root->_occupied<<" | "; if (root->is_locked()) std::cout<<"L | "; else std::cout<<"U | "; for (int i=0; i<root->_buckets->_num_levels; ++i) std::cout<<root->_buckets->_queues[i]->size()<<","; std::cout<<std::endl; for (int i=0; i<root->_num_children; ++i) print_tree (root->_children[i], num_levels-1, total_levels); } } void HR2Scheduler::print_job (HR2Job* sized_job) { std::cout<<" Job: "<<sized_job->get_id() <<", Str: "<<sized_job->strand_id() <<", Pin: "<<sized_job->get_pin_cluster() <<", Pin_Cl_Sz: "<<((HR2Scheduler::Cluster*)sized_job->get_pin_cluster())->_size <<", Pin_Cl_Occ: "<<((HR2Scheduler::Cluster*)sized_job->get_pin_cluster())->_occupied <<std::endl <<", Task_Size: "<<sized_job->size(1) <<", Strand_Size: "<<sized_job->strand_size(1) <<", cont_job? "<<sized_job->is_cont_job() <<", maximal_job: "<<sized_job->is_maximal() <<std::endl; } HR2Scheduler::HR2Scheduler (int num_threads, int num_levels, int * fan_outs, lluint * sizes, int * block_sizes, int bucket_version) : Scheduler (num_threads) { _type = 0; std::cout<<_type<<std::endl; _tree = new TreeOfCaches; _tree->_num_levels=num_levels; _tree->_fan_outs=new uint[_tree->_num_levels]; _tree->_sizes=new lluint[_tree->_num_levels]; _tree->_block_sizes=new uint[_tree->_num_levels]; _tree->_num_leaves=1; for (int i=0; i<_tree->_num_levels; ++i) { _tree->_fan_outs[i] = fan_outs[i]; _tree->_sizes[i] = sizes[i]; _tree->_block_sizes[i] = block_sizes[i]; _tree->_num_leaves*=fan_outs[i]; } _tree->_leaf_array = new Cluster* [_tree->_num_leaves]; _tree->_root = _tree->_root->create_tree (NULL, _tree->_leaf_array, _tree->_num_levels, _tree->_fan_outs, _tree->_sizes, _tree->_block_sizes,bucket_version); _tree->_num_locks_held = new int [_tree->_num_leaves]; _tree->_locked_clusters = new Cluster** [_tree->_num_leaves]; for (int i=0; i<_tree->_num_leaves; ++i) { _tree->_num_locks_held[i] = 0; _tree->_locked_clusters[i] = new Cluster*[_tree->_num_levels+1+8]; // +8 is to pad each list for (int j=0; j<_tree->_num_levels+1; ++j) _tree->_locked_clusters[i][j] = NULL; } } HR2Scheduler::~HR2Scheduler() { for (int i=0; i<_tree->_num_leaves; ++i) delete _tree->_locked_clusters[i]; delete _tree->_fan_outs; delete _tree->_sizes; delete _tree->_block_sizes; delete _tree->_num_locks_held; delete _tree->_locked_clusters; // Delete the cluster tree too } // Basic sanity check on locks held by a thread void HR2Scheduler::check_lock_consistency (int thread_id) { for (int i=0; i<_tree->_num_levels+1; ++i) { if (i<_tree->_num_locks_held[thread_id]) assert (_tree->_locked_clusters[thread_id][i] != NULL); else assert (_tree->_locked_clusters[thread_id][i] == NULL); if (i != _tree->_num_levels+1) if (_tree->_locked_clusters[thread_id][i] != NULL) assert (_tree->_locked_clusters[thread_id][i] != _tree->_locked_clusters[thread_id][i+1]); } } // Lock up 'node', and add that lock to the locked up node list void HR2Scheduler::lock (Cluster* node, int thread_id) { // std::cout<<"Lock, thr: "<<thread_id<<" "<<node<<std::endl; if (node->_num_children > 1) { node->lock(); assert(node->_locked_thread_id == -1); node->_locked_thread_id = thread_id; _tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]] = node; ++_tree->_num_locks_held[thread_id]; } } bool HR2Scheduler::has_lock (Cluster* node, int thread_id) { // std::cerr<<__func__<<": Not currently operational"<<std::endl; return (node->_num_children==1 || node->_locked_thread_id == thread_id); } void HR2Scheduler::print_locks (int thread_id) { std::cout<<"Thread "<<thread_id<<" has "<<_tree->_num_locks_held[thread_id] <<" locks: "; for (int i=0; i<_tree->_num_locks_held[thread_id]; ++i) { std::cout<<" '"<<_tree->_locked_clusters[thread_id][i]; } std::cout<<std::endl; } // Check if the node is the last in the list of locked nodes, void HR2Scheduler::unlock (Cluster* node, int thread_id) { //std::cout<<"Unlock, thr: "<<thread_id<<" "<<node<<std::endl; if (node->_num_children > 1) { --_tree->_num_locks_held[thread_id]; _tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]] = NULL; assert(node->_locked_thread_id == thread_id); node->_locked_thread_id = -1; node->unlock(); } } // Release all locks held by thread in the inverse order they were obtained void HR2Scheduler::release_locks (int thread_id) { while (_tree->_num_locks_held[thread_id] > 0) unlock (_tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]-1], thread_id); } /* Should be called only by a thread holding a lock on the current cluster */ void HR2Scheduler::pin (HR2Job *job, Cluster *cluster) { assert (cluster->_occupied <= cluster->_size); job->pin_to_cluster (cluster, job->size(cluster->_block_size)); } void HR2Scheduler::add (Job* uncast_job, int thread_id) { HR2Job* job = (HR2Job*)uncast_job; Cluster *root = _tree->_root; /* Job added by an agent other than the threads */ if (thread_id == _num_threads) { root->lock (); pin (job, root); root->_occupied+=job->size(root->_block_size); root->_buckets->add_job_to_bucket (job, 0); root->unlock (); return; } /* If root has no active job, set it here */ if (job->get_pin_cluster() == NULL) { for (Cluster *cur = _tree->_leaf_array[thread_id];cur->_parent!=NULL;cur = cur->_parent) lock (cur, thread_id); pin (job, root); root->_occupied+=job->size(root->_block_size); release_locks (thread_id); } /* Add job to the approporiate queue */ int child_id=0; for (Cluster * cur = _tree->_leaf_array[thread_id];;cur = cur->_parent ) { if (job->get_pin_cluster() == cur) { cur->_buckets->add_job_to_bucket (job, child_id); return; } child_id = cur->_sibling_id; } assert (false);exit(-1); } void HR2Scheduler::add_multiple (int num_jobs, Job** uncast_jobs, int thread_id) { HR2Job* job = (HR2Job*)uncast_jobs[0]; Cluster *root = _tree->_root; /* Job added by an agent other than the threads */ if (thread_id == _num_threads) { root->lock (); for (int i=0; i<num_jobs; ++i) { job = (HR2Job*)uncast_jobs[i]; pin (job, root); root->_occupied+=job->size(root->_block_size); root->_buckets->add_job_to_bucket (job, 0); } root->unlock (); return; } /* If root has no active job, set it here */ if (job->get_pin_cluster() == NULL) { for (Cluster *cur = _tree->_leaf_array[thread_id];cur->_parent!=NULL;cur = cur->_parent) lock (cur, thread_id); for (int i=0; i<num_jobs; ++i) { job = (HR2Job*)uncast_jobs[i]; pin (job, root); root->_occupied+=job->size(root->_block_size); } release_locks (thread_id); } /* Add job to the approporiate queue */ int child_id=0; for (Cluster * cur = _tree->_leaf_array[thread_id];;cur = cur->_parent ) { if (job->get_pin_cluster() == cur) { for (int i=0; i<num_jobs; ++i) { job = (HR2Job*)uncast_jobs[i]; cur->_buckets->add_job_to_bucket (job, child_id); } return; } child_id = cur->_sibling_id; } assert (false);exit(-1); } void HR2Scheduler::done (Job *uncast_job, int thread_id, bool deactivate) { HR2Job * job = (HR2Job*)uncast_job; Cluster * cur = _tree->_leaf_array[thread_id]; Cluster * pin = (Cluster*) job->get_pin_cluster(); /* Update occupied size */ for ( ; cur!=pin; cur=cur->_parent) { lluint strand_size = job->strand_size(cur->_block_size); lock (cur,thread_id); cur->_occupied -= (strand_size>(int)(MU*(cur->_size)) ? (int)(MU*(cur->_size)) : strand_size); } /* If the done task started a pin, clean up the allocation */ if (deactivate) { // Strand joins and end its task if (job->is_maximal()) { lock (cur, thread_id); cur->_occupied -= job->size(cur->_block_size); } } release_locks (thread_id); /* Last job done in the system */ if (job->parent_fork()==NULL && deactivate) { //print_tree (_tree->_root, _tree->_num_levels, _tree->_num_levels); //std::cout<<"Finished root task at thread: "<<thread_id<<std::endl; } } bool HR2Scheduler::fit_job (HR2Job *job, int thread_id, int height, int bucket_level) { Cluster *leaf=_tree->_leaf_array[thread_id]; Cluster *cur=leaf; for (int i=0; i<height-bucket_level; ++i) { lock (cur, thread_id); if (cur->_occupied > (1-MU)*(double)cur->_size) { release_locks (thread_id); return false; } cur=cur->_parent; } lluint task_size = job->size (cur->_block_size); assert (task_size <= SIGMA*(cur->_size) || cur->_parent == NULL); if (bucket_level > 0) { assert (!job->is_cont_job()); lock (cur, thread_id); if (task_size > cur->_size-cur->_occupied) { release_locks (thread_id); return false; } else { pin (job, cur); assert (job->is_maximal()); cur->_occupied += task_size; } } else { assert (job->get_pin_cluster() == cur); } for (Cluster *iter=leaf; iter!=cur ; iter=iter->_parent) { lluint strand_size = ((HR2Job*)job)->strand_size (iter->_block_size); assert (has_lock (iter, thread_id)); assert (iter->_occupied <= (1-MU)*iter->_size); iter->_occupied += (strand_size<(int)(MU*iter->_size) ? strand_size : (int)(MU*iter->_size)); } release_locks(thread_id); return true; } Job* HR2Scheduler::get (int thread_id) { HR2Job * job = NULL; int height=1; int child_id=_tree->_leaf_array[thread_id]->_sibling_id; for ( Cluster *cur=_tree->_leaf_array[thread_id]->_parent; cur!=NULL; cur=cur->_parent,++height) { int level = cur->_buckets->get_job_from_bucket(&job, 0, child_id); while (level !=-1) { if (fit_job (job, thread_id, height, level)==true) { release_locks(thread_id); return job; } else { cur->_buckets->return_to_queue (job, level, child_id); } level = cur->_buckets->get_job_from_bucket(&job, 1+level, child_id); } if ( cur->_occupied > (int)((1-MU)* cur->_size) ) return NULL; child_id = cur->_sibling_id; } return NULL; } bool HR2Scheduler::more (int thread_id) { std::cerr<<__func__<<" has been deprecated"<<std::endl; exit (-1); }
31.744966
106
0.657717
harsha-simhadri
762d09dad5ba121135195bebd503ada89e9d4a39
144
hpp
C++
star.rg/include/tileDB.hpp
masscry/badbaby
f0b2e793081491ed7598d3170725fe4b48ae1fff
[ "MIT" ]
null
null
null
star.rg/include/tileDB.hpp
masscry/badbaby
f0b2e793081491ed7598d3170725fe4b48ae1fff
[ "MIT" ]
null
null
null
star.rg/include/tileDB.hpp
masscry/badbaby
f0b2e793081491ed7598d3170725fe4b48ae1fff
[ "MIT" ]
null
null
null
#pragma once #ifndef TILE_DATABASE_HEADER #define TILE_DATABASE_HEADER extern const tileInfo_t tileID[]; #endif // TILE_DATABASE_HEADER
10.285714
33
0.791667
masscry
7631c1aa955429bb64b7372f54adb09b33ab2d4e
3,619
cpp
C++
core123/ut/ut_simd_threefry.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
22
2019-04-10T18:05:35.000Z
2021-12-30T12:26:39.000Z
core123/ut/ut_simd_threefry.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
13
2019-04-09T00:19:29.000Z
2021-11-04T15:57:13.000Z
core123/ut/ut_simd_threefry.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
4
2019-04-07T16:33:44.000Z
2020-07-02T02:58:51.000Z
#if defined(__ICC) #include <stdio.h> int main(int, char **){ printf(__FILE__ " Icc (through version 18) doesn't fully support gcc's 'vector' extensions."); return 0; } #else #pragma GCC diagnostic ignored "-Wunknown-warning-option" #pragma GCC diagnostic ignored "-Wpsabi" // see comments in simd_threefry.hpp #include <core123/simd_threefry.hpp> #include <core123/streamutils.hpp> #include <core123/timeit.hpp> #include <numeric> #include <iostream> #include <chrono> using core123::threefry; using core123::insbe; using core123::timeit; using namespace std::chrono; static constexpr unsigned ROUNDS = 12; int main(int, char **){ using vcbrng = threefry<4, uint64_tx8, ROUNDS>; vcbrng::domain_type ctr; using eltype = vcbrng::domain_type::value_type; ctr[0] = eltype{00,01,02,03,04,05,06,07}; ctr[1] = eltype{10,11,12,13,14,15,16,17}; if(ctr.size()>2){ ctr[2] = eltype{20,21,22,23,24,25,26,27}; ctr[3] = eltype{30,31,32,33,34,35,36,37}; } { vcbrng tf; auto r = tf(ctr); std::cout << "Vector threefry: sizeof(range_type): " << sizeof(vcbrng::range_type) << "\n"; std::cout << std::hex; switch(r.size()){ case 4: std::cout << r[0][0] << " " << r[1][0] << " " << r[2][0] << " " << r[3][0] << "\n"; std::cout << r[0][1] << " " << r[1][1] << " " << r[2][1] << " " << r[3][1] << "\n"; std::cout << r[0][2] << " " << r[1][2] << " " << r[2][2] << " " << r[3][2] << "\n"; std::cout << r[0][3] << " " << r[1][3] << " " << r[2][3] << " " << r[3][3] << "\n"; break; case 2: throw "Nope. Not done yet"; std::cout << r[0][0] << " " << r[1][0] << "\n"; std::cout << r[0][1] << " " << r[1][1] << "\n"; std::cout << r[0][2] << " " << r[1][2] << "\n"; std::cout << r[0][3] << " " << r[1][3] << "\n"; break; } tf.setkey(r); // Don't allow the optimizer to exploit zero-valued keys. ctr = r; // set the key and counter to "random" values static const int LOOP = 2; static const int millis = 2000; eltype sum = {}; auto result = timeit(milliseconds(millis), [&ctr, &sum, tf](){ eltype incr = {1, 1, 1, 1, 1, 1, 1, 1}; for(int i=0; i<LOOP; ++i){ ctr[0] += incr; auto rv = tf(ctr); sum = std::accumulate(rv.begin(), rv.end(), sum); // i.e., sum += r[0] + r[1] + .. + r[N-1]; } }); // Print the sum, so the optimizer can't elide the whole thing! std::cout << "sum = " << sum[0] << " " << sum[1] << " " << sum[2] << " " << sum[3] << " " << sum[4] << " " << sum[5] << " " << sum[6] << " " << sum[7] << "\n"; float ns_per_byte = 1.e9*result.sec_per_iter()/LOOP/sizeof(vcbrng::range_type); printf("8-way simd threefry: %lld calls in about %d ms. %.2f ns per call. %.3f ns per byte.\n", LOOP*result.count, millis, 1.e9*result.sec_per_iter()/LOOP, ns_per_byte); static const float GHz = 3.7; printf("at %.1fGHz that's %.2f cpb or %.1f bytes per cycle\n", GHz, ns_per_byte * GHz, 1./(ns_per_byte * GHz)); } std::cout << "Scalar threefry:\n"; { using cbrng = threefry<4, uint64_t, ROUNDS>; cbrng::range_type r; cbrng tf; r = tf({00, 10, 20, 30}); std::cout << insbe(r) << "\n"; r = tf({01, 11, 21, 31}); std::cout << insbe(r) << "\n"; r = tf({02, 12, 22, 32}); std::cout << insbe(r) << "\n"; r = tf({03, 13, 23, 33}); std::cout << insbe(r) << "\n"; } return 0; } #endif // not __ICC
36.555556
163
0.498757
fennm
763e5b8db9c5b5d782ba03570f8a664a402f751e
4,163
hpp
C++
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
TakahiroNISHIOKA/scenario_simulator_v2
949a46a64a26d17413c2586577e1f3a5ba41161e
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
TakahiroNISHIOKA/scenario_simulator_v2
949a46a64a26d17413c2586577e1f3a5ba41161e
[ "Apache-2.0" ]
null
null
null
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
TakahiroNISHIOKA/scenario_simulator_v2
949a46a64a26d17413c2586577e1f3a5ba41161e
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2020 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_ #define OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_ #include <chrono> #include <cmath> #include <functional> #include <unordered_map> namespace openscenario_interpreter { inline namespace utility { template <typename Clock = std::chrono::system_clock> class ExecutionTimer { class Statistics { std::int64_t ns_max = 0; std::int64_t ns_min = std::numeric_limits<std::int64_t>::max(); std::int64_t ns_sum = 0; std::int64_t ns_square_sum = 0; int count = 0; public: template <typename Duration> auto add(Duration diff) -> void { std::int64_t diff_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count(); count++; ns_max = std::max(ns_max, diff_ns); ns_min = std::min(ns_max, diff_ns); ns_sum += diff_ns; ns_square_sum += std::pow(diff_ns, 2); } template <typename T> auto max() const { return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_max)); } template <typename T> auto min() const { return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_min)); } template <typename T> auto mean() const { return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_sum / count)); } template <typename T> auto standardDeviation() const { std::int64_t mean_of_square = ns_square_sum / count; std::int64_t square_of_mean = std::pow(ns_sum / count, 2); std::int64_t var = mean_of_square - square_of_mean; double standard_deviation = std::sqrt(var); return std::chrono::duration_cast<T>( std::chrono::nanoseconds(static_cast<std::int64_t>(standard_deviation))); } friend auto operator<<(std::ostream & os, const Statistics & statistics) -> std::ostream & { using namespace std::chrono; return os << "mean = " << statistics.template mean<milliseconds>().count() << " ms, " << "max = " << statistics.template max<milliseconds>().count() << " ms, " << "standard deviation = " << statistics.template standardDeviation<milliseconds>().count() / 1000.0 << " ms"; } }; std::unordered_map<std::string, Statistics> statistics_map; public: template <typename Thunk, typename... Ts> auto invoke(const std::string & tag, Thunk && thunk) -> typename std::enable_if< std::is_same<typename std::result_of<Thunk()>::type, void>::value, typename Clock::duration>::type { const auto begin = Clock::now(); thunk(); const auto end = Clock::now(); statistics_map[tag].add(end - begin); return end - begin; } template <typename Thunk, typename... Ts> auto invoke(const std::string & tag, Thunk && thunk) -> typename std::enable_if< std::is_same<typename std::result_of<Thunk()>::type, bool>::value, typename Clock::duration>::type { const auto begin = Clock::now(); const auto result = thunk(); const auto end = Clock::now(); if (result) { statistics_map[tag].add(end - begin); } return end - begin; } auto clear() { statistics_map.clear(); } auto getStatistics(const std::string & tag) -> const auto & { return statistics_map[tag]; } auto begin() const { return statistics_map.begin(); } auto end() const { return statistics_map.end(); } }; } // namespace utility } // namespace openscenario_interpreter #endif // OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_
29.111888
99
0.664425
TakahiroNISHIOKA
76427c417c94cb5460cf6ef17f43fbcd44277d62
293
hpp
C++
src/resources/resource.hpp
ifamakes/sidhe-cpp
ce660872fa0c9eba7d41357ab330410a397f59eb
[ "CC0-1.0" ]
null
null
null
src/resources/resource.hpp
ifamakes/sidhe-cpp
ce660872fa0c9eba7d41357ab330410a397f59eb
[ "CC0-1.0" ]
null
null
null
src/resources/resource.hpp
ifamakes/sidhe-cpp
ce660872fa0c9eba7d41357ab330410a397f59eb
[ "CC0-1.0" ]
null
null
null
#pragma once #include <iostream> #include <string> struct Resource { virtual ~Resource() = default; virtual void print() const = 0; }; struct File : Resource { std::string_view filename; virtual void print() const override { std::cout << __PRETTY_FUNCTION__ << std::endl; }; };
19.533333
50
0.675768
ifamakes
76442cf857d809354d445c7ecfb216a91d327ab3
15,115
cpp
C++
src/server.cpp
Subsentient/nexus
719cca618afe8729522607ed35e9415d76582347
[ "Unlicense" ]
2
2016-03-17T21:25:51.000Z
2021-09-02T13:20:23.000Z
src/server.cpp
Subsentient/nexus
719cca618afe8729522607ed35e9415d76582347
[ "Unlicense" ]
1
2018-03-04T18:55:48.000Z
2018-03-07T00:19:37.000Z
src/server.cpp
Subsentient/nexus
719cca618afe8729522607ed35e9415d76582347
[ "Unlicense" ]
2
2016-03-19T00:31:27.000Z
2017-01-09T23:41:32.000Z
/*NEXUS IRC session BNC, by Subsentient. This software is public domain.*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <ctype.h> #ifdef WIN #include <winsock2.h> #else #include <fcntl.h> #endif #include <list> #include <string> #include "server.h" #include "netcore.h" #include "config.h" #include "nexus.h" #include "state.h" #include "scrollback.h" #include "irc.h" #include "substrings/substrings.h" /**This file has our IRC pseudo-server that we run ourselves and its interaction with clients.**/ //Globals std::list<struct ClientListStruct> ClientListCore; struct ClientListStruct *CurrentClient, *PreviousClient; //Prototypes namespace Server { static void SendChannelNamesList(const class ChannelList *const Channel, struct ClientListStruct *Client); static void SendChannelRejoin(const class ChannelList *const Channel, const int ClientDescriptor); static void SendIRCWelcome(const int ClientDescriptor); } //Functions struct ClientListStruct *Server::ClientList::Lookup(const int Descriptor) { std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); for (; Iter != ClientListCore.end(); ++Iter) { if (Iter->Descriptor == Descriptor) { return &*Iter; //Not used to doing this kind of weird shit. That'd seem really stupid and redundant in C, where Iter would be a pointer. } } return NULL; } struct ClientListStruct *Server::ClientList::Add(const struct ClientListStruct *const InStruct) { ClientListCore.push_front(*InStruct); return &*ClientListCore.begin(); } void Server::ClientList::Shutdown(void) { ClientListCore.clear(); PreviousClient = NULL; CurrentClient = NULL; } bool Server::ClientList::Del(const int Descriptor) { std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); for (; Iter != ClientListCore.end(); ++Iter) { if (Iter->Descriptor == Descriptor) { if (&*Iter == CurrentClient) CurrentClient = reinterpret_cast<struct ClientListStruct*>(-1); if (&*Iter == PreviousClient) PreviousClient = reinterpret_cast<struct ClientListStruct*>(-1); ClientListCore.erase(Iter); return true; } } return false; } bool Server::ForwardToAll(const char *const InStream) { //This function sends the provided text stream to all clients. Very simple. std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); for (; Iter != ClientListCore.end(); ++Iter) { Iter->SendLine(InStream); } return true; } bool Server::NukeClient(const int Descriptor) { //Close the descriptor, remove from select() tracking, and purge him from our minds. struct ClientListStruct *Client = Server::ClientList::Lookup(Descriptor); if (!Client) return false; Net::Close(Client->Descriptor); NEXUS::DescriptorSet_Del(Client->Descriptor); Server::ClientList::Del(Client->Descriptor); return true; } void Server::SendQuit(const int Descriptor, const char *const Reason) { //Tells all clients or just one client to quit std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin(); char OutBuf[2048]; for (; Iter != ClientListCore.end(); ++Iter) { //If not on "everyone" mode we check if the descriptor matches. if (Descriptor != -1 && Descriptor != Iter->Descriptor) continue; if (Reason) { snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s QUIT :%s\r\n", IRCConfig.Nick, Iter->Ident, Iter->IP, Reason); } else { snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s QUIT :Disconnected from NEXUS.\r\n", IRCConfig.Nick, Iter->Ident, Iter->IP); } try { Net::Write(Iter->Descriptor, OutBuf, strlen(OutBuf)); } catch (...) {} } } static void Server::SendIRCWelcome(const int ClientDescriptor) { char OutBuf[2048]; struct ClientListStruct *Client = Server::ClientList::Lookup(ClientDescriptor); std::map<std::string, ChannelList>::iterator Iter = ChannelListCore.begin(); const int ClientCount = ClientListCore.size(); if (!Client) return; //First thing we send is our greeting, telling them they're connected OK. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 001 %s :NEXUS is forwarding you to server %s:%hu\r\n", IRCConfig.Nick, IRCConfig.Server, IRCConfig.PortNum); //Putting IRCConfig.Nick here is the same as sending a NICK command. Client->SendLine(OutBuf); //Tell them to join all channels we are already in. for (; Iter != ChannelListCore.end(); ++Iter) { Server::SendChannelRejoin(&Iter->second, Client->Descriptor); } //Count clients for our next cool little trick. /**Send a MOTD.**/ //Send the beginning. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 375 %s :Welcome to NEXUS " NEXUS_VERSION ". You are being forwarded to \"%s:%hu\".\r\n", IRCConfig.Nick, IRCConfig.Server, IRCConfig.PortNum); Client->SendLine(OutBuf); //For dumb bots that connect, make it abundantly clear what their nick should be. snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s NICK :%s\r\n", Client->OriginalNick, Client->Ident, Client->IP, IRCConfig.Nick); Client->SendLine(OutBuf); //Send the middle. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 372 %s :There are currently %d other instances connected to this NEXUS server.\r\n", IRCConfig.Nick, ClientCount - 1); Client->SendLine(OutBuf); //Send the end. snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 376 %s :End of MOTD.\r\n", IRCConfig.Nick); Client->SendLine(OutBuf); //Send all scrollback. Scrollback::SendAllToClient(Client); } static void Server::SendChannelNamesList(const class ChannelList *const Channel, struct ClientListStruct *Client) { char OutBuf[2048]; unsigned Ticker = 1; std::map<std::string, struct UserStruct> &UserListRef = Channel->GetUserList(); std::map<std::string, struct UserStruct>::iterator Iter = UserListRef.begin(); SendBegin: std::string OutString = std::string(":" NEXUS_FAKEHOST " 353 ") + IRCConfig.Nick + " = " + Channel->GetChannelName() + " :"; for (Ticker = 1; Iter != UserListRef.end(); ++Iter, ++Ticker) { const struct UserStruct *Worker = &Iter->second; //Reconstitute the mode flag for this user. const char Sym = State::UserModes_Get_Mode2Symbol(Worker->Modes); if (Sym) { OutString += Sym; } OutString += Worker->Nick; std::map<std::string, struct UserStruct>::iterator TempIter = Iter; ++TempIter; if (Ticker == 20 || TempIter == UserListRef.end()) { OutString += "\r\n"; Client->SendLine(OutString.c_str()); if (TempIter != UserListRef.end()) { goto SendBegin; } } else { OutString += " "; } } snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 366 %s %s :End of /NAMES list.\r\n", IRCConfig.Nick, Channel->GetChannelName()); Client->SendLine(OutBuf); } static void Server::SendChannelRejoin(const class ChannelList *const Channel, const int ClientDescriptor) { //Sends the list of channels we are in to the client specified. char OutBuf[2048]; struct ClientListStruct *Client = Server::ClientList::Lookup(ClientDescriptor); if (!Client) return; //Send the join command. snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s JOIN %s\r\n", IRCConfig.Nick, Client->Ident, Client->IP, Channel->GetChannelName()); Client->SendLine(OutBuf); //Send the topic and the setter of the topic. if (*Channel->GetTopic() && *Channel->GetWhoSetTopic() && Channel->GetWhenSetTopic() != 0) { snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 332 %s %s :%s\r\n", IRCConfig.Nick, Channel->GetChannelName(), Channel->GetTopic()); Client->SendLine(OutBuf); snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 333 %s %s %s %u\r\n", IRCConfig.Nick, Channel->GetChannelName(), Channel->GetWhoSetTopic(), Channel->GetWhenSetTopic()); Client->SendLine(OutBuf); } //Send list of users. Server::SendChannelNamesList(Channel, Client); } struct ClientListStruct *Server::AcceptLoop(void) { struct ClientListStruct TempClient; char InBuf[2048]; struct ClientListStruct *Client = NULL; bool UserProvided = false, NickProvided = false; bool PasswordProvided = false; if (!Net::AcceptClient(&TempClient.Descriptor, TempClient.IP, sizeof TempClient.IP)) { //No client. return NULL; } ///Apparently there is a client. Client = Server::ClientList::Add(&TempClient); //Store their information. /**Continuously try to read their replies until we get them.**/ while (!UserProvided || !NickProvided) { //Wait for their greeting. const bool NetReadReturn = Net::Read(Client->Descriptor, InBuf, sizeof InBuf, true); if (!NetReadReturn) { Server::NukeClient(Client->Descriptor); return NULL; } //Does it start with USER? if (!strncmp(InBuf, "USER", sizeof "USER" - 1) || !strncmp(InBuf, "user", sizeof "user" - 1)) { //This information is needed to fool the IRC clients. const char *TWorker = InBuf + sizeof "USER"; unsigned Inc = 0; //If we want a password, WE WANT A PASSWORD. You're supposed to send PASS first, dunce! if (*NEXUSConfig.ServerPassword && !PasswordProvided) { Server::NukeClient(Client->Descriptor); return NULL; } while (*TWorker == ' ' || *TWorker == ':') ++TWorker; for (; TWorker[Inc] != ' ' && TWorker[Inc] != '\0' && Inc < sizeof Client->Ident - 1; ++Inc) { //Copy in the ident they sent us. Client->Ident[Inc] = TWorker[Inc]; } Client->Ident[Inc] = '\0'; UserProvided = true; } else if (!strncmp(InBuf, "NICK", sizeof "NICK" - 1) || !strncmp(InBuf, "nick", sizeof "nick" - 1)) { const char *TWorker = InBuf + sizeof "nick"; //If we want a password, WE WANT A PASSWORD. if (*NEXUSConfig.ServerPassword && !PasswordProvided) { Net::Close(Client->Descriptor); return NULL; } while (*TWorker == ' ' || *TWorker == ':') ++TWorker; strncpy(Client->OriginalNick, TWorker, sizeof Client->OriginalNick - 1); //Copy in their chosen nick. Client->OriginalNick[sizeof Client->OriginalNick - 1] = '\0'; NickProvided = true; } else if (!strncmp(InBuf, "PASS", sizeof "PASS" - 1)) { const char *TW = InBuf + sizeof "PASS"; if (!*NEXUSConfig.ServerPassword) { //We don't NEED a password. Just ignore this. continue; } while (*TW == ' ') ++TW; if (!strcmp(TW, NEXUSConfig.ServerPassword)) PasswordProvided = true; else { //Wrong password. Net::Close(Client->Descriptor); return NULL; } } continue; } //Time to welcome them. Server::SendIRCWelcome(Client->Descriptor); //Return the client we found. return Client; } enum ServerMessageType Server::GetMessageType(const char *InStream_) { //Another function torn out of aqu4bot. const char *InStream = InStream_; char Command[32]; unsigned Inc = 0; for (; InStream[Inc] != ' ' && InStream[Inc] != '\0' && Inc < sizeof Command - 1; ++Inc) { /*Copy in the command.*/ Command[Inc] = toupper(InStream[Inc]); } Command[Inc] = '\0'; /*Time for the comparison.*/ if (!strcmp(Command, "PRIVMSG")) return SERVERMSG_PRIVMSG; else if (!strcmp(Command, "NOTICE")) return SERVERMSG_NOTICE; else if (!strcmp(Command, "MODE")) return SERVERMSG_MODE; else if (!strcmp(Command, "JOIN")) return SERVERMSG_JOIN; else if (!strcmp(Command, "PART")) return SERVERMSG_PART; else if (!strcmp(Command, "PING")) return SERVERMSG_PING; else if (!strcmp(Command, "PONG")) return SERVERMSG_PONG; else if (!strcmp(Command, "NICK")) return SERVERMSG_NICK; else if (!strcmp(Command, "QUIT")) return SERVERMSG_QUIT; else if (!strcmp(Command, "KICK")) return SERVERMSG_KICK; else if (!strcmp(Command, "KILL")) return SERVERMSG_KILL; else if (!strcmp(Command, "INVITE")) return SERVERMSG_INVITE; else if (!strcmp(Command, "TOPIC")) return SERVERMSG_TOPIC; else if (!strcmp(Command, "NAMES")) return SERVERMSG_NAMES; else if (!strcmp(Command, "WHO")) return SERVERMSG_WHO; else return SERVERMSG_UNKNOWN; } bool ClientListStruct::Ping() { std::string Out = "PING :" NEXUS_FAKEHOST "\r\n"; bool RetVal = false; #ifdef WIN u_long Value = 1; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, O_NONBLOCK); //Set nonblocking. Necessary for our single-threaded model. #endif //WIN try { Net::Write(this->Descriptor, Out.c_str(), Out.length()); } catch (Net::Errors::Any) { goto End; } RetVal = true; this->PingSentTime = time(NULL); this->WaitingForPing = true; End: #ifdef WIN Value = 0; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, 0); #endif //WIN return RetVal; } bool ClientListStruct::CompletePing(void) { if (!this->WaitingForPing) return false; this->WaitingForPing = false; this->PingRecvTime = time(NULL); return true; } ClientListStruct::ClientListStruct(const int InDescriptor, const char *IP, const char *OriginalNick, const char *Ident) : WaitingForPing(false), PingSentTime(0), PingRecvTime(time(NULL)), Descriptor(InDescriptor) { //PingRecvTime is initialized with a real time so that the server doesn't send pings instantly. SubStrings.Copy(this->IP, IP, sizeof this->IP); SubStrings.Copy(this->OriginalNick, OriginalNick, sizeof this->OriginalNick); SubStrings.Copy(this->Ident, Ident, sizeof this->Ident); } ClientListStruct::ClientListStruct(void) : WaitingForPing(false), PingSentTime(0), PingRecvTime(time(NULL)), Descriptor(0) { } void ClientListStruct::SendNxCtlPrivmsg(const char *const String) { std::string Out = std::string(":" CONTROL_NICKNAME "!NEXUS@NEXUS PRIVMSG ") + IRCConfig.Nick + " :" + String; if (!SubStrings.EndsWith("\r\n", Out.c_str())) { //SendLine() does the same thing, but we're aiming for consistency and safety. Out += "\r\n"; } this->SendLine(Out.c_str()); } void ClientListStruct::SendLine(const char *const String) { std::string Out = String; if (!SubStrings.EndsWith("\r\n", Out.c_str())) { Out += "\r\n"; } this->WriteQueue.push(Out); } bool ClientListStruct::FlushSendBuffer(void) { if (this->WriteQueue.empty()) return false; while (!this->WriteQueue.empty()) { if (!this->WriteQueue_Pop()) return false; } return true; } bool ClientListStruct::WriteQueue_Pop(void) { if (this->WriteQueue.empty()) return false; bool RetVal = false; std::string Out = this->WriteQueue.front(); #ifdef WIN u_long Value = 1; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, O_NONBLOCK); //Set nonblocking. Necessary for our single-threaded model. #endif //WIN try { Net::Write(this->Descriptor, Out.c_str(), Out.length()); } catch (Net::Errors::BlockingError Err) { if (Err.BytesSentBeforeBlocking > 0) { std::string &Str = this->WriteQueue.front(); std::string New = Str; Str = New.c_str() + Err.BytesSentBeforeBlocking; } goto End; } catch (Net::Errors::Any) { //We will probably get Net::Errors::BlockingError. goto End; } RetVal = true; this->WriteQueue.pop(); End: #ifdef WIN Value = 0; ioctlsocket(this->Descriptor, FIONBIO, &Value); #else fcntl(this->Descriptor, F_SETFL, 0); #endif //WIN return RetVal; }
27.836096
139
0.691631
Subsentient
764d3fec3b50869b29975839adf3de55ea856e79
3,491
cpp
C++
dp0.cpp
lordblendi/cpp-deklarativ-programozas-hf
85d875d9eb35f1dcc0275439f8284993b556143f
[ "MIT" ]
null
null
null
dp0.cpp
lordblendi/cpp-deklarativ-programozas-hf
85d875d9eb35f1dcc0275439f8284993b556143f
[ "MIT" ]
null
null
null
dp0.cpp
lordblendi/cpp-deklarativ-programozas-hf
85d875d9eb35f1dcc0275439f8284993b556143f
[ "MIT" ]
null
null
null
//segédfgv length_help(L,N) = N+L hossza, N-ben tárolom az addigi elemek számát int length_help(list l, int n){ if(nil == l) return n; return length_help(tl(l), n+1); } //length(L) = L lista hossza int list_length(list l){ return length_help(l, 0); } //insert_nth(L,N,E) L lista olyan másolata, amelyben az L lista n-edik és N+1-edik eleme közé be van szúrva az E elem (a lista számozása 0-tól kezdõdik) list insert_nth(list l, int n, int e){ if(n==0) return cons(e, l); return cons(hd(l), insert_nth(tl(l), n-1, e)); } //number_to_base(n, b, l) az n számot visszaadja az l listában b számrendszerben list number_to_base(int n, int b, list l){ if(n<b) return cons(n, l); return number_to_base((n-n%b)/b, b, cons(n%b, l)); } //number_to_base_ten(l,alap,szorzo,szam, i) az l listát visszadja számként 10-es számrendszerben. b a számrender, amiben a szám van, i hanyadik elemnél tartok, szorzo az aktuális szorzó (=hatványai az alapnak), szam pedig hogy mennyi az aktuális összeg int number_to_base_ten(list l, int alap, int szorzo, int szam, int i){ if(i < 0) return szam; return szam + number_to_base_ten(l, alap, szorzo*alap, nth(l, i)* szorzo, i-1); } //nth(l,n) visszadja az l lista n-edik elemét. a számozás 0-tól kezdõdik int nth(list l, int n){ if(n==0) return hd(l); return nth(tl(l), n-1); } //split(l,r,n) r-ben visszaad minden második számot az l listából. n értékétõl függõen ez lehetnek páros vagy páratlan sorszámú elem list split(list l, list r, int n){ if(n > 1) return split(l, cons(nth(l,n),r),n-2); return cons(nth(l,n), r); } //paratlan(l) visszaadja az L lista páratlan helyiértéken álló elemeit -> megfelelõ n értékkel meghívja a splitet list paratlan(list l){ if((list_length(l) % 2) == 0) return split(l, nil, list_length(l)-2); return split(l, nil, list_length(l)-1); } //paros(l) visszaadja az L lista páros helyiértéken álló elemeit -> megfelelõ n értékkel meghívja a splitet list paros(list l){ if((list_length(l) % 2) == 0) return split(l, nil, list_length(l)-1); return split(l, nil, list_length(l)-2); } //páratlan listába a páros lista elemeit megfordítva beleszúrjuk list beszur(list paratlan, list paros){ return beszur_help(paratlan, paros, list_length(paros)-1, 1); } //beszur_help(paratlan, paros, n, i) segédfgv a beszúrhoz, beszúrja a paratlan lista minden 2. elemének a paros listát visszafelé. n és i tartják számon, hogy melyik listában hanyadik elemnél tartok list beszur_help(list paratlan, list paros, int n, int i){ if(n < 0) return paratlan; return beszur_help(insert_nth(paratlan, i, nth(paros,n)), paros, n-1, i+2); } /* osszekevert(S, A) == SK, ha SK az S szám A alapú összekevert változata (S>0, A>1 egész számok). Egy S szám A alapú összekevertjét úgy kapjuk meg, hogy az S számot felírjuk az A alapú számrendszerben, a számjegyeit egy listával ábrázoljuk, a listát a fentiek szerint átrendezzük, majd a kapott lista elemeit egy A alapú szám jegyeinek tekintve elõállítjuk a keresett értéket. ha a lista hossza <4, akkor felesleges cserélgetnünk, mert csak 1 párosodik szám van, és felesleges cserélgetni */ int osszekevert(const int S, const int A) { if(list_length(number_to_base(S,A,nil))<4) return S; return number_to_base_ten(beszur(paratlan(number_to_base(S,A,nil)), paros(number_to_base(S,A,nil))) , A,1,0,list_length(beszur(paratlan(number_to_base(S,A,nil)), paros(number_to_base(S,A,nil))))-1); }
43.6375
254
0.708393
lordblendi
764f988d3b8a1339b595365a3abbb9929fee84b1
1,955
inl
C++
RTCLI.AOT/Internal/Managed.inl
Team-RTCLI/RTCLI.Runtime
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
[ "MIT" ]
19
2020-10-21T02:54:39.000Z
2022-03-31T02:55:48.000Z
RTCLI.AOT/Internal/Managed.inl
Team-RTCLI/RTCLI.Runtime
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
[ "MIT" ]
null
null
null
RTCLI.AOT/Internal/Managed.inl
Team-RTCLI/RTCLI.Runtime
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
[ "MIT" ]
null
null
null
namespace RTCLI { namespace System { // ******************* Managed<T> *************************// template<typename T> RTCLI_FORCEINLINE Managed<T>::operator const T&() const RTCLI_NOEXCEPT { if(!object) { return null; } return *static_cast<const T*>(object); } template<typename T> RTCLI_FORCEINLINE Managed<T>::operator T&() RTCLI_NOEXCEPT { if(!object) { return null; } return *static_cast<T*>(object); } template<typename T> RTCLI_FORCEINLINE Managed<T>::Managed() RTCLI_NOEXCEPT :object(const_cast<System::Object*>(&RTCLI::nullObject)) { } template<typename T> RTCLI_FORCEINLINE Managed<T>::Managed(nullref_t null) RTCLI_NOEXCEPT :object(const_cast<System::Object*>(&RTCLI::nullObject)) { } template<typename T> RTCLI_FORCEINLINE Managed<T>::Managed(const System::Object& object_) RTCLI_NOEXCEPT { if (object_.isNull()) { object = const_cast<System::Object*>(&RTCLI::nullObject); } else { object = const_cast<System::Object*>(&object_); } } template<typename T> RTCLI_FORCEINLINE T& Managed<T>::Get() RTCLI_NOEXCEPT { return *static_cast<T*>(object); } template<typename T> RTCLI_FORCEINLINE const T& Managed<T>::Get() const RTCLI_NOEXCEPT { return *static_cast<const T*>(object); } template<typename T> RTCLI_FORCEINLINE Managed<T>& Managed<T>::operator=(const System::Object& object_) RTCLI_NOEXCEPT { if(this->object == &object_) { return *this; } if (object_.isNull()) { object = const_cast<System::Object*>(&RTCLI::nullObject); } else { object = const_cast<System::Object*>(&object_); } return *this; } } }
24.4375
101
0.557545
Team-RTCLI
7653a2d7c669c259f2df23c413a6d5a80fe46dde
862
cpp
C++
src/core/resumable.cpp
Anomander/xi
0340675310c41d659762fc3eea48c84ff13b95db
[ "MIT" ]
null
null
null
src/core/resumable.cpp
Anomander/xi
0340675310c41d659762fc3eea48c84ff13b95db
[ "MIT" ]
null
null
null
src/core/resumable.cpp
Anomander/xi
0340675310c41d659762fc3eea48c84ff13b95db
[ "MIT" ]
null
null
null
#include "xi/core/resumable.h" #include "xi/core/abstract_worker.h" namespace xi { namespace core { namespace v2 { thread_local resumable_stat RESUMABLE_STAT; } void resumable::attach_executor(abstract_worker* e) { _worker = e; } void resumable::detach_executor(abstract_worker* e) { assert(_worker == e); _worker = nullptr; } void resumable::unblock() { sleep_hook.unlink(); ready_hook.unlink(); _worker->schedule(this); } void resumable::block() { yield(blocked); } steady_clock::time_point resumable::wakeup_time() { return _wakeup_time; } void resumable::wakeup_time(steady_clock::time_point when) { _wakeup_time = when; } void resumable::sleep_for(nanoseconds ns) { assert(_worker != nullptr); ready_hook.unlink(); _worker->sleep_for(this, ns); block(); } } }
18.73913
62
0.668213
Anomander
76578b47ce79e8d46b82ba4c2a9ca7a80b451c9b
555
cpp
C++
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
2
2016-08-31T19:13:24.000Z
2017-02-18T18:48:31.000Z
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
1
2018-12-10T16:32:26.000Z
2018-12-27T19:50:48.000Z
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
null
null
null
// Xiaoyan Wang 9/8/2016 #include <iostream> // #include <vector> using namespace std; // arry stores 0, 9^1, 9^2 ... 9^8 int arry[] = {1, 9, 81, 729, 6561, 59049, 531441, 4782969, 43046721/*, 387420489*/}; // input range: 1 to 10^10 int main() { ios::sync_with_stdio(false); int n; while(cin >> n && n) { int result = 0; int digit; for(int i = 0, div = 1; i < 10; ++i, div *= 10) { if((digit = (n % (div * 10)) / div) > 4) --digit; result += digit * arry[i]; } cout << n << ": " << result << "\n"; } cout << flush; return 0; }
22.2
84
0.536937
Horizon-Blue
765928c98b462e252e72220293d6e1eb924600d4
54
hpp
C++
src/boost_geometry_formulas_thomas_inverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_geometry_formulas_thomas_inverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_geometry_formulas_thomas_inverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/geometry/formulas/thomas_inverse.hpp>
27
53
0.833333
miathedev
766150558a10806e22a6e4d1dc3931ce9f259468
7,410
cpp
C++
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
cibercitizen1/zmqHelper
8fbfe33ddb2642657ed565ffbb157e174035a52d
[ "MIT" ]
5
2015-01-02T15:54:39.000Z
2021-01-12T18:00:29.000Z
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
cibercitizen1/zmqHelper
8fbfe33ddb2642657ed565ffbb157e174035a52d
[ "MIT" ]
null
null
null
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
cibercitizen1/zmqHelper
8fbfe33ddb2642657ed565ffbb157e174035a52d
[ "MIT" ]
2
2017-09-01T19:54:50.000Z
2017-11-09T14:34:11.000Z
// --------------------------------------------------------------- // server.cpp // // multi-threaded router server done right ! // // // -> ROUTER socket -> main-thread -> in-proc socket -> delegate to worker // /* * ON MULTITHREADING WITH ZeroMQ * * Remember: * * Do not use or close sockets except in the thread that created them. * * Don't share ZeroMQ sockets between threads. * ZeroMQ sockets are not threadsafe. * * Isolate data privately within its thread and never share data * in multiple threads. The only exception to this are ZeroMQ contexts, * which are threadsafe. * * Stay away from the classic concurrency mechanisms like as mutexes, * critical sections, semaphores, etc. These are an anti-pattern * in ZeroMQ applications. * * Create one ZeroMQ context at the start of your process, * and pass that to all threads that you want to connect via inproc sockets. * * * * If you need to start more than one proxy in an application, * for example, you will want to run each in their own thread. * It is easy to make the error of creating the proxy frontend * and backend sockets in one thread, and then passing the sockets * to the proxy in another thread. This may appear to work at first * but will fail randomly in real use. * * Some widely used models, despite being the basis for entire * industries, are fundamentally broken, and shared state concurrency * is one of them. Code that wants to scale without limit does it * like the Internet does, by sending messages and sharing nothing * */ /* * * ON CONTEXTS * * ZeroMQ applications always start by creating a context, * and then using that for creating sockets. * In C, it's the zmq_ctx_new() call. * You should create and use exactly one context in your process. * Technically, the context is the container for all sockets * in a single process, and acts as the transport for inproc sockets, * which are the fastest way to connect threads in one process. * If at runtime a process has two contexts, * these are like separate ZeroMQ instances. * If that's explicitly what you want, OK, but otherwise remember: * * Do one zmq_ctx_new() at the start of your main line code, * and one zmq_ctx_destroy() at the end. */ // --------------------------------------------------------------- #include <iostream> #include <future> #include <thread> #include <string> #include <vector> #include <stdlib.h> #include "../../zmqHelper.hpp" // --------------------------------------------------------------- // --------------------------------------------------------------- const std::string PORT_NUMBER = "5580"; // --------------------------------------------------------------- // --------------------------------------------------------------- template <typename ITERABLE> void showLines (const std::string & msg, ITERABLE & it) { std::cout << msg << ": message: |"; for (auto item : it) { std::cout << item << "|"; } std::cout << "\n"; } // --------------------------------------------------------------- // --------------------------------------------------------------- // --------------------------------------------------------------- // --------------------------------------------------------------- class Worker { private: // // // zmq::context_t & sharedContext; // // previous version: the thread in constructor creates // the socket but it is used by the thread in main // // zmqHelper::SocketAdaptor< ZMQ_REP > internalRepSocket; // // // std::thread * theThread = nullptr; // ------------------------------------------------------------- // ------------------------------------------------------------- void main (){ // // a new thread executes this // // // the socket is created and use here // // remember RAII (resourse adquisition is initialization) // zmqHelper::SocketAdaptor< ZMQ_REP > internalRepSocket {sharedContext}; // // // internalRepSocket.connect ("inproc://innerChannel"); // // // std::cout << " ***** worker main " << this << " starts **** \n"; // // // std::vector<std::string> lines; while ( internalRepSocket.receiveText (lines) ) { std::cout << " ** worker: " << this; showLines (" got ", lines); // // do some work ! // sleep (1); // // reply // internalRepSocket.sendText ({"echo of: " + lines[0] + " " + lines[1]}); } // while } // () public: // ------------------------------------------------------------- // ------------------------------------------------------------- Worker ( zmq::context_t & sharedContext_) : sharedContext {sharedContext_} { // // // theThread = new std::thread (&Worker::main, this); } // ------------------------------------------------------------- // ------------------------------------------------------------- ~Worker ( ) { std::cerr << " worker destructor \n"; if (theThread == nullptr) { return; } theThread->join (); delete (theThread); theThread = nullptr; } }; // --------------------------------------------------------------- // --------------------------------------------------------------- int main () { std::cout << " main stars \n"; // // create internal socket to talk to workers // zmqHelper::SocketAdaptor< ZMQ_DEALER > innerDealerSocket; innerDealerSocket.bind ("inproc://innerChannel"); // // 4 workers, you can experience with the // number of workers, timing run.client // Worker wk1 {innerDealerSocket.getContext()}; Worker wk2 {innerDealerSocket.getContext()}; Worker wk3 {innerDealerSocket.getContext()}; Worker wk4 {innerDealerSocket.getContext()}; std::cerr << "main(): workers created\n"; // // create external socket to talk with clients // zmqHelper::SocketAdaptor< ZMQ_ROUTER > outerRouterSocket; outerRouterSocket.bind ("tcp://*:" + PORT_NUMBER); // // for ever ... // while (true) { std::cout << "\n\n while(true): waiting for clients/worker ... \n"; std::vector<std::string> lines; // // wait (blocking poll) for data in either of the sockets // std::vector< zmqHelper::ZmqSocketType * > list = { outerRouterSocket.getZmqSocket(), innerDealerSocket.getZmqSocket() }; zmqHelper::ZmqSocketType * who = zmqHelper::waitForDataInSockets ( list ); // // there is data // if ( who == outerRouterSocket.getZmqSocket() ) { // // from client // if ( outerRouterSocket.receiveText (lines) ) { std::cout << " server: client -> data -> worker \n"; // // delegate to worker // innerDealerSocket.sendText( lines ); } else { std::cout << " outer socket: awoken for nothing ?????????????????\n"; } } else if ( who == innerDealerSocket.getZmqSocket() ) { // // reply from worker // if ( innerDealerSocket.receiveText (lines) ) { std::cout << " server: client <- data <- worker \n"; // // answer the client // outerRouterSocket.sendText( lines ); } else { std::cout << " inner socket: awoken for nothing ?????????????????\n"; } } else { std::cout << " ****** server: error in polling? \n"; } } // while } // main ()
26.183746
82
0.518758
cibercitizen1
7673c1cf27f096c1ee32b3c97b316fb1166fc777
109
hpp
C++
PlanetaMatchMakerServer/source/server/server_constants.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
6
2019-08-15T09:48:55.000Z
2021-07-25T14:40:59.000Z
PlanetaMatchMakerServer/source/server/server_constants.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
43
2019-12-25T14:54:52.000Z
2022-02-24T17:22:48.000Z
PlanetaMatchMakerServer/source/server/server_constants.hpp
InstytutXR/PlanetaMatchMaker
4bf7503c031aea467c191c3a0d14c6dd58354f99
[ "MIT" ]
2
2020-05-06T20:14:44.000Z
2020-06-02T21:21:10.000Z
#pragma once #include "data/data_constants.hpp" namespace pgl { constexpr version_type api_version = 0; }
13.625
40
0.761468
InstytutXR
76821c60e0b5e0d0b79e905cf309fa43dd9dda05
2,072
cpp
C++
src/core/CL/CLHelpers.cpp
longbowlee/ARMComputeLibrary
c772c0b2ecfe76cac5867915fdc296d14bb829a2
[ "MIT" ]
3
2017-04-02T08:41:24.000Z
2017-10-20T07:56:01.000Z
src/core/CL/CLHelpers.cpp
loliod/ComputeLibrary
871448ee8eff790c4ccc3250008dd71170cc78b2
[ "MIT" ]
null
null
null
src/core/CL/CLHelpers.cpp
loliod/ComputeLibrary
871448ee8eff790c4ccc3250008dd71170cc78b2
[ "MIT" ]
1
2017-12-21T04:13:45.000Z
2017-12-21T04:13:45.000Z
/* * Copyright (c) 2016, 2017 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/core/CL/CLHelpers.h" #include "arm_compute/core/Error.h" #include "arm_compute/core/Types.h" namespace arm_compute { std::string get_cl_type_from_data_type(const DataType &dt) { switch(dt) { case DataType::U8: return "uchar"; case DataType::S8: return "char"; case DataType::U16: return "ushort"; case DataType::S16: return "short"; case DataType::U32: return "uint"; case DataType::S32: return "int"; case DataType::U64: return "ulong"; case DataType::S64: return "long"; case DataType::F16: return "half"; case DataType::F32: return "float"; default: ARM_COMPUTE_ERROR("Unsupported input data type."); return ""; } } } // namespace arm_compute
33.967213
81
0.662645
longbowlee
76860c006f96ab42e021eb975a9e686c1500b924
719
cpp
C++
src/pass/analyze-usage/conditional.cpp
arrow-lang/arrow-legacy
5857697b88201c9a6abdd63c1b132741f3451b01
[ "MIT" ]
1
2017-05-02T14:13:51.000Z
2017-05-02T14:13:51.000Z
src/pass/analyze-usage/conditional.cpp
arrow-lang/arrow-legacy
5857697b88201c9a6abdd63c1b132741f3451b01
[ "MIT" ]
null
null
null
src/pass/analyze-usage/conditional.cpp
arrow-lang/arrow-legacy
5857697b88201c9a6abdd63c1b132741f3451b01
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2015 Ryan Leckey, All Rights Reserved. // Distributed under the MIT License // See accompanying file LICENSE #include <algorithm> #include "arrow/pass/analyze-usage.hpp" #include "arrow/match.hpp" namespace arrow { namespace pass { void AnalyzeUsage::visit_conditional(ast::Conditional& x) { // Accept the conditiona (always entered) x.condition->accept(*this); // Accept the lhs-hand-side (but apply its result as not-definite) _enter_block(*x.lhs); x.lhs->accept(*this); _exit_block(false); // Accept the rhs-hand-side (but apply its result as not-definite) _enter_block(*x.rhs); x.rhs->accept(*this); _exit_block(false); } } // namespace pass } // namespace arrow
23.193548
68
0.713491
arrow-lang
768629ebd1783b922f786e0b5e0b29393a08a2a2
639
cpp
C++
src/E12.cpp
microentropie/IEC60063
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
[ "MIT" ]
null
null
null
src/E12.cpp
microentropie/IEC60063
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
[ "MIT" ]
null
null
null
src/E12.cpp
microentropie/IEC60063
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
[ "MIT" ]
null
null
null
/* Author: Stefano Di Paolo License: MIT, https://en.wikipedia.org/wiki/MIT_License Date: 2017-12-31 Library: IEC60063 series resistors. Sources repository: https://github.com/microentropie/ */ #include "E-series.h" const char E12Tolerance[] = "10%"; #define E12size 12 static const unsigned short E12[E12size + 1] = { 100, 120, 150, 180, 220, 270, 330, 390, 470, 560, 680, 820, 1000 }; float E12Value(float r) { return EserieValue(E12, E12size, r); } char *E12FormattedValue(char *buf, int len, float r, char unitTypeChar) { return EserieFormattedValue(buf, len, E12, E12size, r, unitTypeChar); }
22.821429
117
0.682316
microentropie
768e2018aa71800fb684786b766ce0df824b538e
604
cpp
C++
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<algorithm> #include<cstring> #include<string.h> #include<math.h> #include<cmath> using namespace std; typedef long long int ll; class Point{ private : double x,y; public: Point(double a,double b) { x=a;y=b; } double Distance( Point const & b ) { double ans=0; ans = sqrt( pow(x- b.x,2)+ pow(y- b.y,2 ) ); return ans; } }; int main() { double a,b,c,d; cin>>a>>b>>c>>d; Point A(a,b),B(c,d); cout<<A.Distance(B)<<endl; return 0; double x=2.5; //cout<<pow(x,3)<<endl; return 0; }
15.1
48
0.56457
BachWV
7692b4bc129f3cee9fead0e4559e38bac59cce54
6,004
cpp
C++
src/LinearColorCalibrator.cpp
alarrosa14/Sendero
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
[ "MIT" ]
1
2016-07-06T23:22:16.000Z
2016-07-06T23:22:16.000Z
src/LinearColorCalibrator.cpp
alarrosa14/Sendero
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
[ "MIT" ]
null
null
null
src/LinearColorCalibrator.cpp
alarrosa14/Sendero
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
[ "MIT" ]
null
null
null
// // LinearColorCalibrator.cpp // LEDColorCalibrator // // Created by Tomas Laurenzo on 4/20/13. // // #include "LinearColorCalibrator.h" LinearColorCalibrator::LinearColorCalibrator(){ gammaCorrecting = false; isCalculated = true; } void LinearColorCalibrator::useGamma() { gammaCorrecting = true; } void LinearColorCalibrator::dontUseGamma() { gammaCorrecting = false; } void LinearColorCalibrator::setGamma (float gamma) { this->gamma = gamma; } bool LinearColorCalibrator::calculateCalibration() { if (pairs.size() < 3) { isCalculated = false; return false; } ofColor v0 = pairs[pairs.size() - 1].first; ofColor v1 = pairs[pairs.size() - 2].first; ofColor v2 = pairs[pairs.size() - 3].first; ofColor w0 = pairs[pairs.size() - 1].second; ofColor w1 = pairs[pairs.size() - 2].second; ofColor w2 = pairs[pairs.size() - 3].second; double *A; A = new double[81]; // matrix in COLUMN MAJOR ORDER // columns 1..3 int i = 0; A[i++] = v0.r; A[i++] = v1.r; A[i++] = v2.r; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.g; A[i++] = v1.g; A[i++] = v2.g; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.b; A[i++] = v1.b; A[i++] = v2.b; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; //columns 4..6 A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.r; A[i++] = v1.r; A[i++] = v2.r; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.g; A[i++] = v1.g; A[i++] = v2.g; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.b; A[i++] = v1.b; A[i++] = v2.b; A[i++] = 0; A[i++] = 0; A[i++] = 0; //columns 7..9 A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.r; A[i++] = v1.r; A[i++] = v2.r; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.g; A[i++] = v1.g; A[i++] = v2.g; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = 0; A[i++] = v0.b; A[i++] = v1.b; A[i++] = v2.b; double *b; b = new double[9]; // w1, w2, w3 i = 0; b[i++] = w0[0]; b[i++] = w0[1]; b[i++] = w0[2]; b[i++] = w1[0]; b[i++] = w1[1]; b[i++] = w1[2]; b[i++] = w2[0]; b[i++] = w2[1]; b[i++] = w2[2]; // solving the linear system AX = b int N = 9; // number of columns of A int NRHS = 1; // number of columns of b int LDA = 9; // number of rows of A int IPIV[9]; // pivot indices int LDB = 9; // number of rows of b int INFO = 0; //INFO = clapack_dgesv((CBLAS_ORDER) 101, N, NRHS, A, LDA, IPIV, b, LDB); dgesv_(&N, &NRHS, A, &LDA, IPIV, b, &LDB, &INFO); if (INFO == 0) cout << endl << "dgesv_: OK"; if (INFO < 0) cout << "dgesv_: the element " << INFO << " is invalid"; if (INFO > 0) cout << "dgesv_: the LU decomposition returned 0 "; cout << endl << endl; /* __CLPK_integer is long * __CLPK_doublereal is double * dgesv_(__CLPK_integer *n, __CLPK_integer *nrhs, __CLPK_doublereal *a, __CLPK_integer *lda, __CLPK_integer *ipiv, __CLPK_doublereal *b, __CLPK_integer *ldb, __CLPK_integer *info) void dgesv_(const int *N, const int *nrhs, double *A, const int *lda, int *ipiv, double *b, const int *ldb, int *info); Notice that all parameters are passed by reference. That's the good old Fortran way. The meanings of the parameters are: N number of columns of A nrhs number of columns of b, usually 1 lda number of rows (Leading Dimension of A) of A ipiv pivot indices ldb number of rows of b */ i = 0; T[0][0] = b[i++]; T[1][0] = b[i++]; T[2][0] = b[i++]; T[0][1] = b[i++]; T[1][1] = b[i++]; T[2][1] = b[i++]; T[0][2] = b[i++]; T[1][2] = b[i++]; T[2][2] = b[i++]; cout << "Transformation matrix: " << endl; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j ++) { cout << "\t" << T[i][j]; } cout << endl; } cout << endl; isCalculated = true; delete[]A; delete[]b; } ofColor LinearColorCalibrator::getCalibratedColor(ofColor color) { if (!isCalculated) calculateCalibration(); if (!isCalculated) return color; // calibrated color = T * color ofColor res; res = res.black; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { res[i] += color[i] * T[j][i]; } } if (gammaCorrecting) { for (int i = 0; i < 3; i++) { float f = (int)res[i] / 255.0f; float r = pow(f, gamma); int g = r * 255.0f; int o = f * 255.0f; res[i] = g; } } return res; } float LinearColorCalibrator::getGamma() { return gamma; } void LinearColorCalibrator::addEquivalentPair(ofColor first, ofColor second) { // we assume lineal, because we are in a hurry and non linear is complicated // todo: change it to non linear transformation using little CMS // the idea is, we create a profile for the LEDs and a profile for the monitor and use little CMS to make the // transformation between them // pair <first, second> p; pairs.push_back(pair<ofColor, ofColor>(first, second)); isCalculated = false; } void LinearColorCalibrator::reset() { pairs.clear(); isCalculated = false; }
21.519713
124
0.463025
alarrosa14
7693b2d81fb6d9bef245f2341f00fb948e664470
5,756
cpp
C++
Source/PraticeActor/CBattlePC.cpp
CitrusNyamNyam/Unreal-Portfolio
f5a63fbe796e0531604470767207831b5c523b54
[ "MIT" ]
1
2018-11-25T10:40:10.000Z
2018-11-25T10:40:10.000Z
Source/PraticeActor/CBattlePC.cpp
CitrusNyamNyam/Unreal-Portfolio
f5a63fbe796e0531604470767207831b5c523b54
[ "MIT" ]
null
null
null
Source/PraticeActor/CBattlePC.cpp
CitrusNyamNyam/Unreal-Portfolio
f5a63fbe796e0531604470767207831b5c523b54
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "CBattlePC.h" #include "CBattleGM.h" #include "CPlayer.h" #include "CAirplane_C130.h" #include "CFlyingViewer.h" #include "CResult_Widget.h" #include "CClientMain_Widget.h" #include "CWorldMap_Widget.h" #include "Animation/WidgetAnimation.h" #include "UserWidget.h" #include "UnrealNetwork.h" #include "Engine.h" ACBattlePC::ACBattlePC() :bDived(false), bWorldMap(false) , MapSize(816000.0f,816000.0f,0.0f) { static ConstructorHelpers::FObjectFinder<UClass> clientWidget(TEXT("/Game/GameMode/Battle/UMG/WidgetBP_ClientMain.WidgetBP_ClientMain_C")); if (clientWidget.Object) TSubClientMainWidget = clientWidget.Object; static ConstructorHelpers::FObjectFinder<UClass> resultWidget(TEXT("/Game/GameMode/Battle/UMG/WidgetBP_Result.WidgetBP_Result_C")); if (resultWidget.Object) TSubResultWidget = resultWidget.Object; static ConstructorHelpers::FObjectFinder<UClass> worldMapWidget(TEXT("/Game/WorldMap/WidgetBP_WorldMap.WidgetBP_WorldMap_C")); if (worldMapWidget.Object) TSubWorldMapWidget = worldMapWidget.Object; } void ACBattlePC::BeginPlay() { Super::BeginPlay(); TArray<AActor*> outActors; UGameplayStatics::GetAllActorsWithTag(GetWorld(), FName("C130"), outActors); if (outActors.Num() > 0) { Airplane_C130 = Cast<ACAirplane_C130>(outActors[0]); } SetInputMode(FInputModeGameOnly()); bShowMouseCursor = false; if (!HasAuthority()) { ClientMainWidget = CreateWidget<UCClientMain_Widget>(GetWorld(), TSubClientMainWidget); ResultWidget = CreateWidget<UCResult_Widget>(GetWorld(), TSubResultWidget); if (ClientMainWidget) { ClientMainWidget->AddToViewport(); } } } void ACBattlePC::SetupInputComponent() { Super::SetupInputComponent(); InputComponent->BindAction("WorldMap", EInputEvent::IE_Pressed, this, &ACBattlePC::OnOpenWorldMap); } bool ACBattlePC::GetAirplane() { ACFlyingViewer* viewer = Cast<ACFlyingViewer>(GetPawn()); if (viewer) { return true; } else return false; } FVector ACBattlePC::GetPawnDirection() { ACFlyingViewer* viewer = Cast<ACFlyingViewer>(GetPawn()); if (viewer) { return Airplane_C130->GetActorForwardVector(); } else { return GetPawn()->GetActorForwardVector(); } return FVector::ZeroVector; } void ACBattlePC::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ACBattlePC, NotificationFromServer); } void ACBattlePC::OnCharacterDeath() { ACBattleGM* gameMode = Cast<ACBattleGM>(UGameplayStatics::GetGameMode(GetWorld())); if (gameMode) { gameMode->OnCharacterDeath(this); } } void ACBattlePC::OnOpenWorldMap() { if (WorldMapWidget == NULL) { WorldMapWidget = CreateWidget<UCWorldMap_Widget>(GetWorld(), TSubWorldMapWidget); } if (WorldMapWidget != NULL) { if (!bWorldMap) { bWorldMap = true; WorldMapWidget->AddToViewport(); } else { bWorldMap = false; WorldMapWidget->RemoveFromParent(); } } } FVector ACBattlePC::GetPawnPosition() { if (GetPawn()) { return GetPawn()->GetActorLocation(); } return FVector(9999999999,9999999999,0); } bool ACBattlePC::ServerRPC_RideInAirplaneC130_Validate(ACAirplane_C130 * airplane) { return true; } void ACBattlePC::ServerRPC_RideInAirplaneC130_Implementation(ACAirplane_C130 * airplane) { if (airplane) { GetPawn()->Destroy(); FActorSpawnParameters parameters; parameters.Owner = this; parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; FVector location = airplane->GetActorLocation(); ACFlyingViewer* viewer = GetWorld()->SpawnActor<ACFlyingViewer>(ACFlyingViewer::StaticClass(), location, FRotator::ZeroRotator, parameters); Possess(viewer); FAttachmentTransformRules rules(EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, true); viewer->AttachToActor(airplane, rules); } } bool ACBattlePC::ServerRPC_WantToDive_Validate() { return true; } void ACBattlePC::ServerRPC_WantToDive_Implementation() { if (bDived) return; bDived = true; FVector location = GetPawn()->GetActorLocation(); location.Z -= 1000.0f; FActorSpawnParameters parameters; parameters.Owner = this; parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; ACPlayer* player = GetWorld()->SpawnActor<ACPlayer>(ACPlayer::StaticClass(), location, FRotator::ZeroRotator, parameters); GetPawn()->Destroy(); if (player) { player->SetDive(true); Possess(player); } } void ACBattlePC::ClientRPC_BackToLobby_Implementation() { UGameplayStatics::OpenLevel(GetWorld(), FName("Lobby")); } void ACBattlePC::ClientRPC_ShowDeathResult_Implementation(int rank) { if (ResultWidget) { ResultWidget->ResultString = FString(TEXT("that's fine, that can happen..")); ResultWidget->RankString = FString("#") + FString::FromInt(rank); ResultWidget->AddToViewport(); FInputModeUIOnly Mode; Mode.SetWidgetToFocus(ResultWidget->GetCachedWidget()); SetInputMode(Mode); bShowMouseCursor = true; } } void ACBattlePC::ClientRPC_ShowWinnerResult_Implementation() { if (ResultWidget) { ResultWidget->ResultString = FString(TEXT("WINNER WINNER CHICKEN DINNER")); ResultWidget->RankString = FString("#") + FString::FromInt(1); ResultWidget->AddToViewport(); FInputModeUIOnly Mode; Mode.SetWidgetToFocus(ResultWidget->GetCachedWidget()); SetInputMode(Mode); bShowMouseCursor = true; } } void ACBattlePC::ClientRPC_ShowBloodScreenEffect_Implementation() { if (ClientMainWidget) { if (ClientMainWidget->BloodEffectAnimation) { ClientMainWidget->PlayAnimation(ClientMainWidget->BloodEffectAnimation); } } }
23.590164
142
0.761119
CitrusNyamNyam
7696137c106984a49fa532b5274a6d9255224b6d
112
hpp
C++
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
mycloudmyworld2019/DA-DAPPS
534ace858fb5d852d69a578151929e64e2932f8b
[ "MIT" ]
null
null
null
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
mycloudmyworld2019/DA-DAPPS
534ace858fb5d852d69a578151929e64e2932f8b
[ "MIT" ]
null
null
null
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
mycloudmyworld2019/DA-DAPPS
534ace858fb5d852d69a578151929e64e2932f8b
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in DA-DAPPS/LICENSE */ #pragma once #include <DA-DAPPSio/chain/block.hpp>
16
42
0.669643
mycloudmyworld2019
769ab67ecf0ee03b324e9690cea3ba77cadf5b8a
912
cpp
C++
graph-source-code/463-D/8599017.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/463-D/8599017.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/463-D/8599017.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <map> #include <vector> #include <stack> #include <queue> #include <set> #include <cassert> #include <cstdlib> #include <cmath> #include <algorithm> using namespace std; typedef long long ll; typedef pair<int,int> PII; typedef vector<int> VI; const int mod=1000000007; const int MAXN=1002; int n,K; int a[6][MAXN],pos[6][MAXN],dp[MAXN]; void solve(){ scanf("%d%d",&n,&K); for(int i=1;i<=K;i++) for(int j=1;j<=n;j++){ scanf("%d",&a[i][j]); pos[i][a[i][j]]=j; } int k,res=0; for(int j=1;j<=n;j++){ int mx=0; for(int i=1;i<j;i++){ for(k=2;k<=K && pos[k][a[1][i]]<pos[k][a[1][j]];k++); if(k==K+1 && mx<dp[i]) mx=dp[i]; } dp[j]=mx+1; res=max(res,dp[j]); } printf("%d\n",res); } int main() { solve(); return 0; }
15.724138
57
0.541667
AmrARaouf
769bdd7f174ebb9828896a352014acc70c9af3c4
14,894
cpp
C++
app/uart/main.cpp
wrmlab/wrmos
37067b659aa25e2d85f040ab0d2be85b6f4de485
[ "MIT" ]
16
2018-06-05T15:23:08.000Z
2022-01-06T13:41:44.000Z
app/uart/main.cpp
sergey-worm/wrmos
37067b659aa25e2d85f040ab0d2be85b6f4de485
[ "MIT" ]
null
null
null
app/uart/main.cpp
sergey-worm/wrmos
37067b659aa25e2d85f040ab0d2be85b6f4de485
[ "MIT" ]
3
2018-03-15T16:40:59.000Z
2021-04-01T22:55:15.000Z
//################################################################################################## // // uart - userspace UART driver. // //################################################################################################## #include <stdio.h> #include <string.h> #include <assert.h> #include "sys_utils.h" #include "l4_api.h" #include "wrmos.h" #include "cbuf.h" #define UART_WITH_VIDEO #include "uart.h" // one-directional stream struct Stream_t { Cbuf_t cbuf; // circular buffer Wrm_sem_t sem; // 'irq received' semaphore }; // driver data struct Driver_t { Stream_t tx; // Stream_t rx; // Wrm_mtx_t write_to_uart_mtx; // addr_t ioaddr; // }; static Driver_t driver; int wait_attach_msg(const char* thread_name, L4_thrid_t* client) { // register thread by name word_t key0 = 0; word_t key1 = 0; int rc = wrm_nthread_register(thread_name, &key0, &key1); if (rc) { wrm_loge("attach: wrm_nthread_register(%s) - rc=%u.\n", thread_name, rc); assert(false); } wrm_logi("attach: thread '%s' is registered, key: %lx/%lx.\n", thread_name, key0, key1); L4_utcb_t* utcb = l4_utcb(); // wait attach msg loop L4_thrid_t from = L4_thrid_t::Nil; while (1) { wrm_logi("attach: wait attach msg.\n"); int rc = l4_receive(L4_thrid_t::Any, L4_time_t::Never, &from); if (rc) { wrm_loge("attach: l4_receive() - rc=%u.\n", rc); continue; } word_t ecode = 0; L4_msgtag_t tag = utcb->msgtag(); word_t k0 = utcb->mr[1]; word_t k1 = utcb->mr[2]; if (tag.untyped() != 2 || tag.typed() != 0) { wrm_loge("attach: wrong msg format.\n"); ecode = 1; } if (!ecode && (k0 != key0 || k1 != key1)) { wrm_loge("attach: wrong key.\n"); ecode = 2; } // send reply tag.untyped(1); tag.typed(0); utcb->mr[0] = tag.raw(); utcb->mr[1] = ecode; rc = l4_send(from, L4_time_t::Zero); if (rc) wrm_loge("attach: l4_send(rep) - rc=%d.\n", rc); if (!ecode && !rc) break; // attached } *client = from; wrm_logi("attach: attached to %u.\n", from.number()); return 0; } // read from tx.cbuf and write to uart device // this func may be called from hw-thread and tx-thread void write_to_uart() { //wrm_logd("--: %s().\n", __func__); uart_tx_irq(driver.ioaddr, 0); // disable tx irq unsigned written = 0; // NOTE: The best way is write to UART FIFO char-by-char through uart_putc() // while fifo-is-not-full. But TopUART doesn't allow detect state // fifo-is-not-full. Therefore, we use uart_put_buf() and write FIFO_SZ // bytes. For most UARTs driver return FIFO_SZ=1 --> we will work // as uart_putc() while fifo-is-not-full. For TopUART FIFO_SZ=64, every // writing we put to UART FIFO_SZ bytes. #if 0 // char-by-char // write to uart char-by-char wrm_mtx_lock(&driver.write_to_uart_mtx); while (1) { static char txchar = 0; static int is_there_unsent = 0; // read charecter from tx-buffer if need if (!is_there_unsent) { unsigned read = driver.tx.cbuf.read(&txchar, 1); if (!read) break; is_there_unsent = 1; } // write charecter to uart int rc = uart_putc(driver.ioaddr, txchar); if (rc < 0) { wrm_loge("--: uart_put_buf() - rc=%d.\n", rc); break; // uart tx empty } if (!rc) { wrm_logd("--: uart_tx_full, enable tx irq.\n"); uart_tx_irq(driver.ioaddr, 1); break; } is_there_unsent = 0; written++; } wrm_mtx_unlock(&driver.write_to_uart_mtx); #else // put buf unsigned fifo_sz = 0; char buf[128]; fifo_sz = uart_fifo_size(driver.ioaddr); assert(fifo_sz); if (fifo_sz > sizeof(buf)) { wrm_logw("--: fifo_sz/%u > bufsz/%zu, use %zu.\n", fifo_sz, sizeof(buf), sizeof(buf)); fifo_sz = sizeof(buf); } // write to uart fifo-by-fifo wrm_mtx_lock(&driver.write_to_uart_mtx); while (1) { if (!(uart_status(driver.ioaddr) & Uart_status_tx_ready) && !driver.tx.cbuf.empty()) { //wrm_logd("--: uart_tx_not_ready, data exist -> enable tx irq.\n"); uart_tx_irq(driver.ioaddr, 1); break; } // read charecters from tx-buffer if need unsigned read = driver.tx.cbuf.read(buf, fifo_sz); //wrm_logd("--: read from cbuf %d bytes.\n", read); if (!read) break; // no data anymore // write charecter to uart int rc = uart_put_buf(driver.ioaddr, buf, read); if (rc < 0) { wrm_loge("--: uart_put_buf() - rc=%d.\n", rc); break; } written += rc; if (read != (unsigned) rc) { wrm_loge("--: uart_put_buf() - wr=%u, lost %u bytes.\n", read, read - rc); break; } } wrm_mtx_unlock(&driver.write_to_uart_mtx); #endif //wrm_logd("--: written=%u.\n", written); } size_t put_to_txbuf(const char* buf, unsigned sz) { // put line by line and add '\r' unsigned written = 0; while (written < sz) { const char* pos = buf + written; const char* end = strchr(pos, '\n'); unsigned l = end ? (end + 1 - pos) : (sz - written); // length for line or tail // write all line unsigned wr = driver.tx.cbuf.write(pos, l); written += wr; if (wr != l) { wrm_loge("tx: buffer full, write=%u, written=%u, lost=%u.\n", l, wr, l - wr); break; // buf full } if (end) { wr = driver.tx.cbuf.write("\r", 1); if (wr != 1) { wrm_loge("tx: buffer full, write=1, written=%u.\n", wr); break; // buf full } } } return written; } long tx_thread(long unused) { wrm_logi("tx: hello: %s.\n", __func__); wrm_logi("tx: myid=%u.\n", l4_utcb()->global_id().number()); // wait for attach message L4_thrid_t client = L4_thrid_t::Nil; int rc = wait_attach_msg("uart-tx-stream", &client); if (rc) { wrm_loge("tx: wait_attach_msg() - rc=%d.\n", rc); assert(false); } wrm_logi("tx: attached to client=%u\n", client.number()); // prepare for requests L4_utcb_t* utcb = l4_utcb(); static char tx_buf[0x1000]; L4_acceptor_t acceptor = L4_acceptor_t::create(L4_fpage_t::create_nil(), true); // allow strings L4_string_item_t bitem = L4_string_item_t::create_simple((word_t)tx_buf, sizeof(tx_buf)-1); utcb->br[0] = acceptor.raw(); utcb->br[1] = bitem.word0(); utcb->br[2] = bitem.word1(); // wait request loop while (1) { //wrm_logi("tx: wait request.\n"); L4_thrid_t from = L4_thrid_t::Nil; int rc = l4_receive(client, L4_time_t::Never, &from); if (rc) { wrm_loge("tx: l4_receive() - rc=%u.\n", rc); assert(false); } L4_msgtag_t tag = utcb->msgtag(); word_t mr[L4_utcb_t::Mr_words]; memcpy(mr, utcb->mr, (1 + tag.untyped() + tag.typed()) * sizeof(word_t)); from = tag.propagated() ? utcb->sender() : from; //wrm_logi("tx: received: from=%u, tag=0x%x, u=%u, t=%u, mr[1]=0x%x, mr[2]=0x%x.\n", // from.number(), tag.raw(), tag.untyped(), tag.typed(), mr[1], mr[2]); L4_typed_item_t item = L4_typed_item_t::create(mr[1], mr[2]); L4_string_item_t sitem = L4_string_item_t::create(mr[1], mr[2]); assert(tag.untyped() == 0); assert(tag.typed() == 2); assert(item.is_string_item()); //wrm_logi("tx: request is got: sz=%u.\n", sitem.length()); //wrm_logi("tx: request is got: buf=0x%x, sz=%u, txbf=0x%p: %.*s.\n", // sitem.pointer(), sitem.length(), tx_buf, sitem.length(), (char*)sitem.pointer()); ((char*)sitem.pointer())[sitem.length()] = '\0'; // add terminator unsigned written = put_to_txbuf((char*)sitem.pointer(), sitem.length()); if (written != sitem.length()) { wrm_loge("tx: buffer full, write=%u, written=%u, lost=%u.\n", sitem.length(), written, sitem.length() - written); } //wrm_logd("tx: written=%u to cbuf.\n", written); if (written) { write_to_uart(); } // send reply to client tag.propagated(false); tag.ipc_label(0); tag.untyped(2); tag.typed(0); utcb->mr[0] = tag.raw(); utcb->mr[1] = rc; // ecode utcb->mr[2] = written; // bytes written rc = l4_send(from, L4_time_t::Zero); if (rc) { wrm_loge("l4_send(rep) - rc=%u.\n", rc); l4_kdb("tx: l4_send(cli) is failed"); } } return 0; } long rx_thread(long unused) { wrm_logi("rx: hello: %s.\n", __func__); wrm_logi("rx: myid=%u.\n", l4_utcb()->global_id().number()); // wait for attach message L4_thrid_t client = L4_thrid_t::Nil; int rc = wait_attach_msg("uart-rx-stream", &client); if (rc) { wrm_loge("rx: wait_attach_msg() - rc=%u.\n", rc); assert(false); } wrm_logi("rx: attached to client=%u\n", client.number()); // prepare for requests L4_utcb_t* utcb = l4_utcb(); static char rx_buf[0x1000]; L4_acceptor_t acceptor = L4_acceptor_t::create(L4_fpage_t::create_nil(), false); utcb->br[0] = acceptor.raw(); // wait request loop while (1) { //wrm_logi("rx: wait request.\n"); L4_thrid_t from = L4_thrid_t::Nil; int rc = l4_receive(client, L4_time_t::Never, &from); L4_msgtag_t tag = utcb->msgtag(); if (rc) { wrm_loge("rx: l4_receive() - rc=%u.\n", rc); assert(false); } word_t mr[256]; memcpy(mr, utcb->mr, (1 + tag.untyped() + tag.typed()) * sizeof(word_t)); from = tag.propagated() ? utcb->sender() : from; //wrm_logi("rx: received ipc: from=%u, tag=0x%lx, u=%u, t=%u, mr[1]=0x%lx, mr[2]=0x%lx.\n", // from.number(), tag.raw(), tag.untyped(), tag.typed(), mr[1], mr[2]); assert(tag.untyped() == 1); assert(tag.typed() == 0); size_t cli_bfsz = mr[1]; size_t read = 0; while (1) { read = driver.rx.cbuf.read(rx_buf, min(sizeof(rx_buf), cli_bfsz)); if (read) break; rc = wrm_sem_wait(&driver.rx.sem); // wait rx operation if (rc) { wrm_loge("wrm_sem_wait(rx) - rc=%d.\n", rc); rc = -1; break; } } //wrm_logi("rx: read=%u.\n", read); // send reply to client L4_string_item_t sitem = L4_string_item_t::create_simple((word_t)rx_buf, read); tag.propagated(false); tag.ipc_label(0); // ? tag.untyped(1); tag.typed(2); utcb->mr[0] = tag.raw(); utcb->mr[1] = rc; // ecode utcb->mr[2] = sitem.word0(); // utcb->mr[3] = sitem.word1(); // rc = l4_send(from, L4_time_t::Zero); if (rc) { wrm_loge("l4_send(rep) - rc=%u.\n", rc); l4_kdb("rx: l4_send(cli) is failed"); } } return 0; } void read_from_uart() { char buf[64]; unsigned read = 0; while (1) { // read data from uart unsigned rd = 0; char ch = 0; while (rd < sizeof(buf) && (ch = uart_getc(driver.ioaddr))) buf[rd++] = ch; //wrm_logd("hw: read from uart %d bytes.\n", rc); //wrm_logd("hw: rx(%u): '%.*s' (rx=%u, tx=%u all=%u)\n", // rc, rc, buf, cnt_rx, cnt_tx, cnt_all); read += rd; if (!rd) break; // write data to rx-buffer unsigned written = driver.rx.cbuf.write(buf, rd); if (written != rd) { wrm_loge("hw: rx_buf full, lost %u bytes.\n", rd - written); break; } //wrm_logi("post rx sem.\n"); int rc = wrm_sem_post(&driver.rx.sem); if (rc) wrm_loge("hw: wrm_sem_post(rx.sem) - rc=%d.\n", rc); } if (!read) wrm_loge("hw: no data for read in uart.\n"); } void irq_thread(const char* uart_dev_name) { // rename main thread memcpy(&l4_utcb()->tls[0], "u-hw", 4); // attach to IRQ unsigned intno = -1; int rc = wrm_dev_attach_int(uart_dev_name, &intno); wrm_logi("attach_int: dev=%s, irq=%u.\n", uart_dev_name, intno); if (rc) { wrm_loge("wrm_dev_attach_int() - rc=%d.\n", rc); return; } uart_rx_irq(driver.ioaddr, 1); unsigned icnt_rx = 0; unsigned icnt_tx = 0; unsigned icnt_all = 0; unsigned icnt_nil = 0; // wait interrupt loop while (1) { // wait interrupt //wrm_logd("hw: wait interrupt ... (irq: rx/tx/all/nil=%u/%u/%u/%u).\n", // icnt_rx, icnt_tx, icnt_all, icnt_nil); rc = wrm_dev_wait_int(intno, Uart_need_ack_irq_before_reenable); assert(!rc); icnt_all++; unsigned loop_cnt = 0; while (1) { int status = uart_status(driver.ioaddr); int tx_ready = !!(status & Uart_status_tx_ready); int rx_ready = !!(status & Uart_status_rx_ready); int tx_irq = !!(status & Uart_status_tx_irq); int rx_irq = !!(status & Uart_status_rx_irq); //wrm_logd("hw: status: loop=%u: ready_rx/tx=%d/%d, irq_rx/tx=%d/%d.\n", // loop_cnt, rx_ready, tx_ready, rx_irq, tx_irq); if (!rx_irq && !tx_irq) { // we got real irq but UART hasn't interrupt inside int_status register //wrm_loge("hw: no irq: loop=%u: ready_rx/tx=%d/%d, irq_rx/tx=%d/%d.\n", // loop_cnt, rx_ready, tx_ready, rx_irq, tx_irq); icnt_nil++; break; } if (rx_irq) icnt_rx++; if (tx_irq) icnt_tx++; if (rx_ready) read_from_uart(); if (tx_ready) write_to_uart(); loop_cnt++; int need_check_status = uart_clear_irq(driver.ioaddr); if (!need_check_status) break; } } } int main(int argc, const char* argv[]) { wrm_logi("hello.\n"); wrm_logi("argc=%d, argv=0x%p.\n", argc, argv); for (int i=0; i<argc; i++) wrm_logi("arg[%d] = %s.\n", i, argv[i]); wrm_logi("myid=%u.\n", l4_utcb()->global_id().number()); // map IO const char* uart_dev_name = argc>=2 ? argv[1] : ""; addr_t ioaddr = -1; size_t iosize = -1; int rc = wrm_dev_map_io(uart_dev_name, &ioaddr, &iosize); if (rc) { wrm_loge("wrm_dev_map_io() - rc=%d.\n", rc); return -1; } wrm_logi("map_io: addr=0x%lx, sz=0x%zx.\n", ioaddr, iosize); driver.ioaddr = ioaddr; static char rx_buf[0x1000]; static char tx_buf[0x2000]; driver.rx.cbuf.init(rx_buf, sizeof(rx_buf)); driver.tx.cbuf.init(tx_buf, sizeof(tx_buf)); rc = wrm_sem_init(&driver.rx.sem, Wrm_sem_binary, 0); if (rc) { wrm_loge("wrm_sem_init(rx.sem) - rc=%d.", rc); return -2; } rc = wrm_mtx_init(&driver.write_to_uart_mtx); if (rc) { wrm_loge("wrm_mtx_init(write_to_uart_mtx) - rc=%d.", rc); return -3; } // I do not known sys_freq. // Do not init, I hope uart was initialized by kernel. // uart_init(ioaddr, 115200, 40*1000*1000/*?*/); // create tx thread L4_fpage_t stack_fp = wrm_pgpool_alloc(Cfg_page_sz); L4_fpage_t utcb_fp = wrm_pgpool_alloc(Cfg_page_sz); assert(!stack_fp.is_nil()); assert(!utcb_fp.is_nil()); L4_thrid_t txid = L4_thrid_t::Nil; rc = wrm_thr_create(utcb_fp, tx_thread, 0, stack_fp.addr(), stack_fp.size(), 255, "u-tx", Wrm_thr_flag_no, &txid); wrm_logi("create_thread: rc=%d, id=%u.\n", rc, txid.number()); if (rc) { wrm_loge("wrm_thr_create(tx) - rc=%d.", rc); return -4; } // create rx thread stack_fp = wrm_pgpool_alloc(Cfg_page_sz); utcb_fp = wrm_pgpool_alloc(Cfg_page_sz); assert(!stack_fp.is_nil()); assert(!utcb_fp.is_nil()); L4_thrid_t rxid = L4_thrid_t::Nil; rc = wrm_thr_create(utcb_fp, rx_thread, 0, stack_fp.addr(), stack_fp.size(), 255, "u-rx", Wrm_thr_flag_no, &rxid); wrm_logi("create_thread: rc=%d, id=%u.\n", rc, rxid.number()); if (rc) { wrm_loge("wrm_thr_create(rx) - rc=%d.\n", rc); return -5; } irq_thread(uart_dev_name); wrm_loge("return from app uart - something going wrong.\n"); return 0; }
24.864775
100
0.606889
wrmlab
769cf243a888d3bcc6809d48babe1b071ff489e7
319
cpp
C++
WumbukDraw/staticimage.cpp
YangPeihao1203/WumbukDraw
e0854e62cc050c99deda04a849d46824f458cbbc
[ "MIT" ]
null
null
null
WumbukDraw/staticimage.cpp
YangPeihao1203/WumbukDraw
e0854e62cc050c99deda04a849d46824f458cbbc
[ "MIT" ]
null
null
null
WumbukDraw/staticimage.cpp
YangPeihao1203/WumbukDraw
e0854e62cc050c99deda04a849d46824f458cbbc
[ "MIT" ]
null
null
null
#include "staticimage.h" StaticImage::StaticImage() { } void StaticImage::inSertPicture(QString filePath,QGraphicsScene *parent) { QPixmap pixmap =QPixmap::fromImage(QImage(filePath)); this->setPixmap(pixmap); setFlag(QGraphicsItem::ItemIsMovable); }
19.9375
73
0.623824
YangPeihao1203
372164b0b94deb130806f24ae1c6cf3f7bc02514
2,280
cpp
C++
src/stmt.cpp
magicmoremagic/bengine-sqlite
4e777cbbca9e64be5c49a24778847bf8e23fd99d
[ "MIT" ]
null
null
null
src/stmt.cpp
magicmoremagic/bengine-sqlite
4e777cbbca9e64be5c49a24778847bf8e23fd99d
[ "MIT" ]
null
null
null
src/stmt.cpp
magicmoremagic/bengine-sqlite
4e777cbbca9e64be5c49a24778847bf8e23fd99d
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "stmt.hpp" #include "db.hpp" #include "result_code.hpp" #include "sqlite.hpp" #include <cassert> #include <limits> namespace be::sqlite { /////////////////////////////////////////////////////////////////////////////// /// \brief Compiles the provided SQL query against the provided database and /// constructs a Stmt object to represent it. /// /// \details A statement Id will be generated automatically by hashing the /// SQL text provided. /// /// \note The lifetime of the provided Db object must extend beyond the end /// of the newly created Stmt object. /// /// \param db The database on which the statement is to be executed. /// \param sql The SQL text of the statement to compile. Stmt::Stmt(Db& db, const S& sql) : Stmt(db, Id(sql), sql) { } /////////////////////////////////////////////////////////////////////////////// /// \brief Compiles the provided SQL query against the provided database and /// constructs a Stmt object to represent it using the provided ID. /// /// \note The lifetime of the provided Db object must extend beyond the end /// of the newly created Stmt object. /// /// \param db The database on which the statement is to be executed. /// \param id The Id of the statement. /// \param sql The SQL text of the statement to compile. Stmt::Stmt(Db& db, Id id, const S& sql) { sqlite3_stmt* stmt = nullptr; const char* tail = nullptr; const char* start = sql.c_str(); const char* end = start + sql.length(); assert(sql.length() + 1 < static_cast<std::size_t>(std::numeric_limits<int>::max())); int result = sqlite3_prepare_v2(db.raw(), start, static_cast<int>(sql.length() + 1), &stmt, &tail); if (result != SQLITE_OK || !stmt) { throw SqlTrace(db.raw(), ext_result_code(result), sql); } else if (tail && tail < end) { throw SqlTrace(ExtendedResultCode::api_misuse, "Multiple SQL statements provided to Stmt constructor!", sql); } else { stmt_ptr_ = sqlite3_stmt_ptr(stmt); stmt_ = stmt; con_ = db.raw(); id_ = id; } } /////////////////////////////////////////////////////////////////////////////// void Stmt::deleter::operator()(sqlite3_stmt* stmt) { sqlite3_finalize(stmt); } } // be::sqlite
37.377049
115
0.59386
magicmoremagic
3722de4415fda998571a8d968689831478fc0bf1
43
hpp
C++
src/boost_mpl_aux__type_wrapper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__type_wrapper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__type_wrapper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/type_wrapper.hpp>
21.5
42
0.790698
miathedev
372398f052543364536b3337a1043e781c804f22
7,932
cpp
C++
src/Modules/UI/Macro Elements/Options_Graphics.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
5
2018-10-12T17:40:17.000Z
2020-11-20T10:49:34.000Z
src/Modules/UI/Macro Elements/Options_Graphics.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
71
2018-07-19T01:59:38.000Z
2020-03-29T18:03:13.000Z
src/Modules/UI/Macro Elements/Options_Graphics.cpp
Yattabyte/reVision
014cb450d1c30b8f64abbacf00425b4f814b05a0
[ "MIT" ]
1
2022-03-24T13:21:25.000Z
2022-03-24T13:21:25.000Z
#include "Modules/UI/Macro Elements/Options_Graphics.h" #include "Modules/UI/Basic Elements/Slider.h" #include "Modules/UI/Basic Elements/SideList.h" #include "Modules/UI/Basic Elements/Toggle.h" #include "Engine.h" Options_Graphics::Options_Graphics(Engine& engine) : Options_Pane(engine) { // Title m_title->setText("Graphics Options"); // Material Size Option float materialSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_MATERIAL_SIZE, materialSize); auto element_material_list = std::make_shared<SideList>(engine); element_material_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" }); m_materialSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F }; int counter = 0; int index = 0; for (const auto& size : m_materialSizes) { if (materialSize == size) index = counter; counter++; } element_material_list->setIndex(index); addOption(engine, element_material_list, 1.0F, "Texture Quality:", "Adjusts the resolution of in-game geometry textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_material_list]() { setTextureResolution(element_material_list->getIndex()); }); // Shadow Size Option float shadowSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_SHADOW_SIZE, shadowSize); auto element_shadow_list = std::make_shared<SideList>(engine); element_shadow_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" }); m_shadowSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F }; counter = 0; index = 0; for (const auto& size : m_shadowSizes) { if (shadowSize == size) index = counter; counter++; } element_shadow_list->setIndex(index); addOption(engine, element_shadow_list, 1.0F, "Shadow Quality:", "Adjusts the resolution of all dynamic light shadows textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_shadow_list]() { setShadowSize(element_shadow_list->getIndex()); }); // Reflection Size Option float envSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_ENVMAP_SIZE, envSize); auto element_env_list = std::make_shared<SideList>(engine); element_env_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" }); m_reflectionSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F }; counter = 0; index = 0; for (const auto& size : m_reflectionSizes) { if (envSize == size) index = counter; counter++; } element_env_list->setIndex(index); addOption(engine, element_env_list, 1.0F, "Reflection Quality:", "Adjusts the resolution of all environment map textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_env_list]() { setReflectionSize(element_env_list->getIndex()); }); // Light Bounce Option float bounceSize = 1024; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, bounceSize); auto element_bounce_list = std::make_shared<SideList>(engine); element_bounce_list->setStrings({ "Very Low", "Low", "Medium", "High", "Very High", "Ultra" }); m_bounceQuality = { 8, 12, 16, 24, 32, 64 }; counter = 0; index = 0; for (const auto& size : m_bounceQuality) { if (bounceSize == size) index = counter; counter++; } element_bounce_list->setIndex(index); addOption(engine, element_bounce_list, 1.0F, "Light Bounce Quality:", "Adjusts the resolution of the real-time GI simulation.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_bounce_list]() { setBounceQuality(element_bounce_list->getIndex()); }); // Shadow Count Option float maxShadowCasters = 6.0F; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_SHADOW_MAX_PER_FRAME, maxShadowCasters); auto maxShadow_slider = std::make_shared<Slider>(engine, maxShadowCasters, glm::vec2(1.0F, 100.0F)); addOption(engine, maxShadow_slider, 0.75F, "Max Concurrent Shadows:", "Set the maximum number of shadows updated per frame.", static_cast<int>(Slider::Interact::on_value_change), [&, maxShadow_slider]() { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SHADOW_MAX_PER_FRAME, maxShadow_slider->getValue()); }); // Envmap Count Option float maxReflectionCasters = 6.0F; engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_ENVMAP_MAX_PER_FRAME, maxReflectionCasters); auto maxReflection_slider = std::make_shared<Slider>(engine, maxReflectionCasters, glm::vec2(1.0F, 100.0F)); addOption(engine, maxReflection_slider, 0.75F, "Max Concurrent Reflections:", "Set the maximum number of reflections updated per frame.", static_cast<int>(Slider::Interact::on_value_change), [&, maxReflection_slider]() { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_ENVMAP_MAX_PER_FRAME, maxReflection_slider->getValue()); }); // Bloom Option bool element_bloom_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_BLOOM, element_bloom_state); auto element_bloom = std::make_shared<Toggle>(engine, element_bloom_state); addOption(engine, element_bloom, 0.5F, "Bloom:", "Turns the bloom effect on or off.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_bloom]() { setBloom(element_bloom->isToggled()); }); // SSAO Option bool element_ssao_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_SSAO, element_ssao_state); auto element_ssao = std::make_shared<Toggle>(engine, element_ssao_state); addOption(engine, element_ssao, 0.5F, "SSAO:", "Turns screen-space ambient occlusion effect on or off. Works with baked AO.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_ssao]() { setSSAO(element_ssao->isToggled()); }); // SSR Option bool element_ssr_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_SSR, element_ssr_state); auto element_ssr = std::make_shared<Toggle>(engine, element_ssr_state); addOption(engine, element_ssr, 0.5F, "SSR:", "Turns screen-space reflections on or off. Works with baked reflections.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_ssr]() { setSSR(element_ssr->isToggled()); }); // FXAA Option bool element_fxaa_state = true; engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_FXAA, element_fxaa_state); auto element_fxaa = std::make_shared<Toggle>(engine, element_fxaa_state); addOption(engine, element_fxaa, 0.5F, "FXAA:", "Turns fast approximate anti-aliasing on or off.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_fxaa]() { setFXAA(element_fxaa->isToggled()); }); } void Options_Graphics::setTextureResolution(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_MATERIAL_SIZE, m_materialSizes[index]); } void Options_Graphics::setShadowSize(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SHADOW_SIZE, m_shadowSizes[index]); } void Options_Graphics::setReflectionSize(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_ENVMAP_SIZE, m_reflectionSizes[index]); } void Options_Graphics::setBounceQuality(const size_t& index) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, m_bounceQuality[index]); } void Options_Graphics::setBloom(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_BLOOM, b ? 1.0F : 0.0F); } void Options_Graphics::setSSAO(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SSAO, b ? 1.0F : 0.0F); } void Options_Graphics::setSSR(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SSR, b ? 1.0F : 0.0F); } void Options_Graphics::setFXAA(const bool& b) { m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_FXAA, b ? 1.0F : 0.0F); }
50.522293
271
0.757186
Yattabyte
37309bee6eb272dc1b99f9659ca749ea8ee4cf80
9,450
cpp
C++
utils.cpp
Litvinovis/webserver
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
[ "Apache-2.0" ]
2
2021-04-22T11:07:04.000Z
2022-01-04T13:57:57.000Z
utils.cpp
Litvinovis/webserver
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
[ "Apache-2.0" ]
18
2021-05-10T15:33:00.000Z
2021-05-30T16:32:16.000Z
utils.cpp
Litvinovis/webserver
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
[ "Apache-2.0" ]
2
2021-04-15T13:06:08.000Z
2021-05-26T18:08:41.000Z
#include <iostream> #include <unistd.h> #include <sys/stat.h> #include "utils.hpp" #include "Setting.hpp" #include <cstring> // for linux namespace utils { std::vector<char> read_file(std::string filename) { std::vector<char> buf; int fd; char* line; if ((fd = open(filename.c_str(), O_RDONLY)) < 0) utils::e_throw("open", __FILE__, __LINE__); while (get_next_line(fd, &line) > 0) buf.insert(buf.end(), line, line + std::strlen(line)); buf.insert(buf.end(), line, line + std::strlen(line)); close(fd); return buf; } std::vector<char> read_file_raw(std::string filename) { std::vector<char> buf; int fd; char line[5]; int m; if ((fd = open(filename.c_str(), O_RDONLY)) < 0) utils::e_throw("open", __FILE__, __LINE__); while ((m = read(fd, line, 5)) > 0) { if (m == -1) utils::e_throw("read", __FILE__, __LINE__); buf.insert(buf.end(), line, line + m); } close(fd); return buf; } void write_file_raw(std::string filename, std::vector<char> buf) { int fd; int m; int offset; offset = 0; m = 0; if ((fd = open(filename.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644)) < 0) utils::e_throw("open", __FILE__, __LINE__); std::vector<char>::iterator it = buf.begin(); while (it != buf.end()) { if(lseek(fd, 0, SEEK_CUR) == -1) utils::e_throw("lseek", __FILE__, __LINE__); if ((m = write(fd, &buf[offset], buf.size())) < 0) utils::e_throw("write_file_raw", __FILE__, __LINE__); offset = offset + m; it = it + m; } close(fd); } bool file_exists (std::string filename) { struct stat buffer; return (stat (filename.c_str(), &buffer) == 0); } int file_dir_exists (std::string filename) { struct stat info; if( stat(filename.c_str(), &info ) != 0 ) return 0; else if( info.st_mode & S_IFDIR ) return 2; else return 1; } bool in_array(const std::string &value, const std::vector<std::string> &array) { for ( std::vector<std::string>::const_iterator it = array.begin(); it != array.end(); ++it) { if (value == *it) return true; } return false; } size_t get_current_time_in_ms(void) { struct timeval tv; size_t time_in_mill; gettimeofday(&tv, NULL); time_in_mill = tv.tv_sec * 1000 + tv.tv_usec / 1000; return (time_in_mill); } void ft_usleep(int ms) { size_t start_time; size_t end_time; int elapsed_time; start_time = get_current_time_in_ms(); end_time = get_current_time_in_ms(); elapsed_time = end_time - start_time; while (elapsed_time < ms) { usleep(10); end_time = get_current_time_in_ms(); elapsed_time = end_time - start_time; } } std::string ft_strtrim(const std::string &s1, const std::string& set) { size_t start = 0; size_t end = 0; size_t index = 0; while (s1.c_str()[index] && utils::ft_strchr(set, s1.c_str()[index]) != -1) { index++; } start = index; end = s1.length(); return s1.substr(start, end); } std::string ft_strtrim2(const std::string &s1, const std::string& set) { size_t start; size_t end; size_t index = 0; while (s1[index] && utils::ft_strchr(set, s1[index]) != -1) { index++; } start = index; end = s1.length(); while (end && utils::ft_strchr(set, s1[end]) != -1) { --end; } return s1.substr(start, end); } int ft_strchr(const std::string& str, int ch) { char *src; int index; src = (char *)str.c_str(); index = 0; while (src[index] != 0) if (src[index++] == ch) return (index); if (src[index] == ch) return (index); return (-1); } std::map<std::string, std::string> parseBufToHeaderMap(const std::map<std::string, std::string> & header, const std::vector<char> & buf) { // All headers in map (key - value) std::vector<char>::const_iterator head = buf.begin(); std::vector<char>::const_iterator tail = head; std::map<std::string, std::string> header_new = header; while (head != buf.end() && *head != '\r') { while (tail != buf.end() && *tail != '\r') ++tail; std::vector<char>::const_iterator separator = head; while (separator != buf.end() && separator != tail && *separator != ':') ++separator; if (separator == tail) break; std::string key(head, separator); std::vector<char>::const_iterator value = ++separator; while (value != tail && (*value == ' ' || *value == ':')) ++value; header_new[key] = std::string(value, tail); while (tail != buf.end() && (*tail == '\r' || *tail == '\n')) ++tail; head = tail; } return header_new; } std::string base64encode(std::vector<char> buf) { const char base64Keys[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; std::string output; char chr1, chr2, chr3; int enc1, enc2, enc3, enc4; size_t i = 0; size_t buf_len = buf.size(); output.reserve(4 * buf_len / 3); while (i < buf_len) { chr1 = (i < buf_len) ? buf[i++] : 0; chr2 = (i < buf_len) ? buf[i++] : 0; chr3 = (i < buf_len) ? buf[i++] : 0; enc1 = chr1 >> 2; enc2 = ((chr1 & 0x3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 0xF) << 2) | (chr3 >> 6); enc4 = chr3 & 0x3F; if (chr2 == 0) { enc3 = 64; enc4 = 64; } else if (chr3 == 0) { enc4 = 64; } output += base64Keys[enc1]; output += base64Keys[enc2]; output += base64Keys[enc3]; output += base64Keys[enc4]; } return output; } std::string base64decode(const std::string & s) { const char base64Keys[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string output; output.clear(); output.reserve(3 * s.length() / 4); std::vector<int> T(256, -1); for (int i = 0; i < 64; ++i) { T[base64Keys[i]] = i; } int val = 0; int valb = -8; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; if (T[c] == -1) break; val = (val << 6) + T[c]; valb += 6; if (valb >= 0) { output += char((val >> valb) & 0xFF); valb -= 8; } } return output; } std::string to_string(int n) { char * loc_num = ft_itoa(n); std::string msg = std::string(loc_num); free(loc_num); return msg; } std::string get_current_time_fmt() { struct timeval tv; time_t nowtime; struct tm *nowtm; char tmbuf[64]; gettimeofday(&tv, NULL); nowtime = tv.tv_sec; nowtm = localtime(&nowtime); strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm); std::string str(tmbuf); return str; } void log_print_template(const char *color, const std::string & filename, const std::string & msg, int n) { std::cout << color; std::cout << get_current_time_fmt() << " "; std::cout << filename << ":" << RES << " " << msg; if (n != -1) std::cout << n; std::cout << std::endl; } void log(Setting & config, const std::string & filename, const std::string & msg, int n) { if (filename == "EventLoop.cpp" && config.getDebugLevel() == -9) log_print_template(GRA, filename, msg, n); if (filename == "Response.cpp" && config.getDebugLevel() > 1) log_print_template(CYN, filename, msg, n); if (filename == "ProcessMethod.cpp" && config.getDebugLevel() > 1) log_print_template(MAG, filename, msg, n); if (filename == "Client.cpp" && config.getDebugLevel() > 2) log_print_template(BLU, filename, msg, n); if (filename == "HTTP HEADER" && config.getDebugLevel() == -1) log_print_template(GRN, filename, msg, n); } void e_throw(const std::string & msg, const std::string & filename, int line) { throw std::runtime_error(msg + ": " + strerror(errno) + " at "+ filename + ":" + to_string(line)); } }
30.882353
108
0.480635
Litvinovis
37332b84069848d85aeb8f925be6fd3454cd7939
604
hpp
C++
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
Aschratt/Texturize
bba688d1afd60363f03e02d28e642a63845591d6
[ "MIT" ]
11
2019-05-17T12:23:12.000Z
2020-11-12T14:03:23.000Z
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
crud89/Texturize
bba688d1afd60363f03e02d28e642a63845591d6
[ "MIT" ]
2
2019-04-01T08:37:36.000Z
2019-04-01T08:49:15.000Z
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
crud89/Texturize
bba688d1afd60363f03e02d28e642a63845591d6
[ "MIT" ]
1
2019-06-25T01:04:35.000Z
2019-06-25T01:04:35.000Z
#pragma once #include <texturize.hpp> #include <analysis.hpp> #include <codecs.hpp> #include <string> #include <iostream> namespace Texturize { /// \brief class TEXTURIZE_API EXRCodec : public ISampleCodec { public: virtual void load(const std::string& fileName, Sample& sample) const override; virtual void load(std::istream& stream, Sample& sample) const override; virtual void save(const std::string& fileName, const Sample& sample, const int depth = CV_8U) const override; virtual void save(std::ostream& stream, const Sample& sample, const int depth = CV_8U) const override; }; }
27.454545
111
0.738411
Aschratt
3733399ac2e2ccfedf640afe18d3d4056fa00c11
1,757
cpp
C++
queue/queue_LL.cpp
vivekrajx/dsa
23351634652aaabfa40f8679ccff9f6fa9f844e9
[ "MIT" ]
null
null
null
queue/queue_LL.cpp
vivekrajx/dsa
23351634652aaabfa40f8679ccff9f6fa9f844e9
[ "MIT" ]
null
null
null
queue/queue_LL.cpp
vivekrajx/dsa
23351634652aaabfa40f8679ccff9f6fa9f844e9
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; struct Node { int data; Node* link; }; //declated glboally struct Node * front = NULL; struct Node * rear = NULL; //Enqueue from front & Dequeue from rear both take O(1) time here. //Enqueue from rear void Enqueue(int x) { Node* temp = new Node(); temp->data = x; temp->link = NULL; //if queue is empty if(front == NULL and rear == NULL) { front = rear = temp; //set both front and rear as to temp return; } rear->link = temp; //build new link while enqueuing rear = temp; //update rear } //Dequeue from front void Dequeue() { Node * temp = front; // we created this temp ptr to node in which we store //the addr of current head or current front //CASE 1: if queue is empty if(front == NULL) return; //CASE 2: only element in queue if(front == rear) { front = rear = NULL; //removed the only element in the queue } //CASE 3: all other cases else { front = front->link; } free(temp); //since front was incr, leaving a prev front in mem we free it } void Print(){ cout<<"Queue: "; Node* current = front; // Initialize current while (current != NULL) { cout<<current->data<<" "; current = current->link; } cout<<endl; } int Front(){ return front->data; //return front element of queue } int Rear(){ return rear->data; //return rear element of queue } bool isEmpty(){ if(front==NULL) return true; else return false; } int main(){ Enqueue(2); Print(); Enqueue(4); Print(); Enqueue(6); Print(); Dequeue(); Print(); Dequeue(); Print(); Dequeue(); Print(); }
19.307692
78
0.575982
vivekrajx
3735ac75271b959791cd33dbbaa242366ebba1cd
1,004
cpp
C++
Paperworks/src/Paperworks/Graphics/Renderer.cpp
codenobacon4u/paperworks
0e96cd2fb6070a2387ddd36aaa327b04733234fa
[ "MIT" ]
1
2019-08-15T18:58:54.000Z
2019-08-15T18:58:54.000Z
Paperworks/src/Paperworks/Graphics/Renderer.cpp
codenobacon4u/paperworks
0e96cd2fb6070a2387ddd36aaa327b04733234fa
[ "MIT" ]
null
null
null
Paperworks/src/Paperworks/Graphics/Renderer.cpp
codenobacon4u/paperworks
0e96cd2fb6070a2387ddd36aaa327b04733234fa
[ "MIT" ]
null
null
null
#include "pwpch.h" #include "Renderer.h" #include "Renderer2D.h" namespace Paperworks { Unique<Renderer::SceneData> Renderer::s_SceneData = CreateUnique<Renderer::SceneData>(); void Renderer::Init() { RenderCmd::Init(); Renderer2D::Init(); } void Renderer::Shutdown() { Renderer2D::Shutdown(); } void Renderer::Begin() { } void Renderer::Begin(Camera& camera) { s_SceneData->Projection = camera.GetProjectionMatrix(); s_SceneData->View = camera.GetViewMatrix(); } void Renderer::End() { } void Renderer::WindowResized(uint32_t width, uint32_t height) { RenderCmd::SetViewport(0, 0, width, height); } void Renderer::Submit(const Shared<VertexArray>& vertexArray, const Shared<Shader>& shader, const glm::mat4& transform) { shader->Bind(); shader->SetMat4("u_MVP.proj", s_SceneData->Projection); shader->SetMat4("u_MVP.view", s_SceneData->View); shader->SetMat4("u_MVP.modl", transform); vertexArray->Bind(); RenderCmd::DrawIndexed(vertexArray); } }
20.08
120
0.703187
codenobacon4u
3741ebbac3567d9bd1d0fb3eee75a5c2a9b3a458
2,817
cpp
C++
src/input/SDLJoystickInput.cpp
benlamonica/tetra-table
521082f2a848d04608ef6368004e90e780ef62ea
[ "Apache-2.0" ]
null
null
null
src/input/SDLJoystickInput.cpp
benlamonica/tetra-table
521082f2a848d04608ef6368004e90e780ef62ea
[ "Apache-2.0" ]
null
null
null
src/input/SDLJoystickInput.cpp
benlamonica/tetra-table
521082f2a848d04608ef6368004e90e780ef62ea
[ "Apache-2.0" ]
null
null
null
// // SDLJoystickInput.cpp // TetraTable // // Created by Ben La Monica on 3/23/15. // Copyright (c) 2015 Benjamin Alan La Monica. All rights reserved. // #include "SDLJoystickInput.hpp" #include "../util/SDLUtil.hpp" #include <syslog.h> #include <SDL2/SDL.h> #include "../util/TimeUtil.hpp" SDLJoystickInput::SDLJoystickInput(TetraTable *game, TetraTableInput::Ptr delegate) : TetraTableInput(game, delegate), m_direction(pieces::NONE){ } SDLJoystickInput::~SDLJoystickInput() { } void SDLJoystickInput::getNextMove(std::vector<pieces::Move>& moves) { SDLUtil& sdl = SDLUtil::instance(); using namespace pieces; using namespace util; SDLEvent::Ptr event = sdl.getNextEvent(); if (event && event->m_event.type >= 0x600 && event->m_event.type < 0x700) { switch(event->m_event.type) { case SDL_JOYAXISMOTION: { Sint16 x = SDL_JoystickGetAxis(event->joy,0); Sint16 y = SDL_JoystickGetAxis(event->joy,1); syslog(LOG_WARNING, "axis event: x,y (%d,%d)", x, y); if (x < 128) { m_direction.store(LEFT); m_repeatingStarts.store(now() + 200000000); syslog(LOG_WARNING, "LEFT %lld (%lld)", m_repeatingStarts.load(), now()); } else if (x > 128) { m_direction.store(RIGHT); m_repeatingStarts.store(now() + 200000000); syslog(LOG_WARNING, "RIGHT"); } else if (y > 128) { syslog(LOG_WARNING, "DOWN"); m_repeatingStarts.store(now() + 200000000); m_direction.store(DOWN); } else { m_repeatingStarts.store(INT64_MAX); m_direction.store(NONE); } break; } case SDL_JOYBUTTONDOWN: { Uint8 button = event->m_event.jbutton.button; syslog(LOG_WARNING, "button %d %s", button, event->m_event.jbutton.state == SDL_PRESSED ? "pressed" : "released"); if (button == 0) { moves.push_back(ROTATE_LEFT); } else if (button == 1) { moves.push_back(DROP); } else if (button == 2) { moves.push_back(HOLD_PIECE); } else if (button == 3) { moves.push_back(ROTATE_RIGHT); } else if (button == 4) { //moves.push_back(QUIT); } break; } } moves.push_back(m_direction.load()); } else { if (m_repeatingStarts.load() <= util::now()) { moves.push_back(m_direction.load()); } util::millisleep(30); } }
36.584416
145
0.520412
benlamonica
374816a086693c8e9be578dd2257e444b6fe5ab8
506
cpp
C++
Snipets/01_Decisiones/IfeIfAnidado.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/01_Decisiones/IfeIfAnidado.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
Snipets/01_Decisiones/IfeIfAnidado.cpp
Gabroide/Learning-C
63a89b9b6b84e410756e70e346173d475a1802a6
[ "Apache-2.0" ]
null
null
null
// IfeIfAnidado.cpp // Programa para saber si el numero introducido es par o impar utilizando un bucle if #include <iostream> #include <stdlib.h> int main() { int n; std::cout << "Introduce un numero: "; std::cin >> n; if(n%2 == 0) // Calculamos el residuo del numero al dividirlo entre 2. Si el residuo es 0 el numero es par std::cout << "El numero introducido es par" << std::endl; else std::cout << "El numero introducido es impar" << std::endl; system("pause"); return 0; }
22
114
0.65415
Gabroide
374ebc05844425a2785be3d7ac1b445de32c8207
12,027
cpp
C++
src/mesh/mechanical/plane/fem_submesh.cpp
annierhea/neon
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
[ "MIT" ]
null
null
null
src/mesh/mechanical/plane/fem_submesh.cpp
annierhea/neon
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
[ "MIT" ]
null
null
null
src/mesh/mechanical/plane/fem_submesh.cpp
annierhea/neon
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
[ "MIT" ]
null
null
null
#include "fem_submesh.hpp" #include "exceptions.hpp" #include "constitutive/constitutive_model_factory.hpp" #include "geometry/projection.hpp" #include "interpolations/interpolation_factory.hpp" #include "material/material_property.hpp" #include "mesh/material_coordinates.hpp" #include "mesh/dof_allocator.hpp" #include "numeric/mechanics" #include "traits/mechanics.hpp" #include <cfenv> #include <chrono> #include <termcolor/termcolor.hpp> namespace neon::mechanical::plane { fem_submesh::fem_submesh(json const& material_data, json const& simulation_data, std::shared_ptr<material_coordinates>& coordinates, basic_submesh const& submesh) : detail::fem_submesh<plane::fem_submesh, plane::internal_variables_t>(submesh), coordinates{coordinates}, sf(make_surface_interpolation(topology(), simulation_data)), view(sf->quadrature().points()), variables(std::make_shared<internal_variables_t>(elements() * sf->quadrature().points())), cm(make_constitutive_model(variables, material_data, simulation_data)) { // Allocate storage for the displacement gradient variables->add(variable::second::displacement_gradient, variable::second::deformation_gradient, variable::second::cauchy_stress, variable::scalar::DetF); // Get the old data to the undeformed configuration for (auto& F : variables->get(variable::second::deformation_gradient)) { F = matrix2::Identity(); } variables->commit(); dof_allocator(node_indices, dof_list, traits::dof_order); } void fem_submesh::save_internal_variables(bool const have_converged) { if (have_converged) { variables->commit(); } else { variables->revert(); } } std::pair<index_view, matrix> fem_submesh::tangent_stiffness(std::int64_t const element) const { auto const x = geometry::project_to_plane( coordinates->current_configuration(local_node_view(element))); matrix ke = material_tangent_stiffness(x, element); if (!cm->is_finite_deformation()) return {local_dof_view(element), ke}; ke.noalias() += geometric_tangent_stiffness(x, element); return {local_dof_view(element), ke}; } std::pair<index_view, vector> fem_submesh::internal_force(std::int64_t const element) const { auto const x = geometry::project_to_plane( coordinates->current_configuration(local_node_view(element))); return {local_dof_view(element), internal_nodal_force(x, element)}; } matrix fem_submesh::geometric_tangent_stiffness(matrix2x const& x, std::int64_t const element) const { auto const& cauchy_stresses = variables->get(variable::second::cauchy_stress); auto const n = nodes_per_element(); matrix const kgeo = sf->quadrature() .integrate(matrix::Zero(n, n).eval(), [&](auto const& femval, auto const& l) -> matrix { auto const& [N, rhea] = femval; matrix2 const Jacobian = local_deformation_gradient(rhea, x); auto const cauchy = cauchy_stresses[view(element, l)]; // Compute the symmetric gradient operator auto const L = (rhea * Jacobian.inverse()).transpose(); return L.transpose() * cauchy * L * Jacobian.determinant(); }); return identity_expansion(kgeo, dofs_per_node()); } matrix fem_submesh::material_tangent_stiffness(matrix2x const& x, std::int64_t const element) const { auto const local_dofs = nodes_per_element() * dofs_per_node(); auto const& tangent_operators = variables->get(variable::fourth::tangent_operator); return sf->quadrature().integrate(matrix::Zero(local_dofs, local_dofs).eval(), [&](auto const& femval, auto const& l) -> matrix { auto const& [N, rhea] = femval; auto const& D = tangent_operators[view(element, l)]; matrix2 const Jacobian{local_deformation_gradient(rhea, x)}; auto const B = fem::sym_gradient<2>( (rhea * Jacobian.inverse()).transpose()); return B.transpose() * D * B * Jacobian.determinant(); }); } vector fem_submesh::internal_nodal_force(matrix2x const& x, std::int64_t const element) const { auto const& cauchy_stresses = variables->get(variable::second::cauchy_stress); auto const [m, n] = std::make_tuple(nodes_per_element(), dofs_per_node()); vector fint = vector::Zero(m * n); sf->quadrature().integrate(Eigen::Map<row_matrix>(fint.data(), m, n), [&](auto const& femval, auto const& l) -> row_matrix { auto const& [N, dN] = femval; matrix2 const Jacobian = local_deformation_gradient(dN, x); auto const& cauchy_stress = cauchy_stresses[view(element, l)]; // Compute the symmetric gradient operator auto const Bt = dN * Jacobian.inverse(); return Bt * cauchy_stress * Jacobian.determinant(); }); return fint; } std::pair<index_view, matrix> fem_submesh::consistent_mass(std::int64_t const element) const { auto const X = coordinates->initial_configuration(local_node_view(element)); return {local_dof_view(element), X}; // auto const density_0 = cm->intrinsic_material().initial_density(); // // auto m = sf->quadrature().integrate(matrix::Zero(nodes_per_element(), nodes_per_element()).eval(), // [&](auto const& femval, auto const& l) -> matrix { // auto const & [N, dN] = femval; // // auto const Jacobian = local_deformation_gradient(dN, X); // // return N * density_0 * N.transpose() // * Jacobian.determinant(); // }); // return {local_dof_view(element), identity_expansion(m, dofs_per_node())}; } std::pair<index_view, vector> fem_submesh::diagonal_mass(std::int64_t const element) const { auto const& [dofs, consistent_m] = this->consistent_mass(element); vector diagonal_m(consistent_m.rows()); for (auto i = 0; i < consistent_m.rows(); ++i) { diagonal_m(i) = consistent_m.row(i).sum(); } return {local_dof_view(element), diagonal_m}; } void fem_submesh::update_internal_variables(double const time_step_size) { std::feclearexcept(FE_ALL_EXCEPT); update_deformation_measures(); update_Jacobian_determinants(); cm->update_internal_variables(time_step_size); if (std::fetestexcept(FE_INVALID)) { throw computational_error("Floating point error reported\n"); } } void fem_submesh::update_deformation_measures() { auto& H_list = variables->get(variable::second::displacement_gradient); auto& F_list = variables->get(variable::second::deformation_gradient); for (std::int64_t element{0}; element < elements(); ++element) { // Gather the material coordinates auto const X = geometry::project_to_plane( coordinates->initial_configuration(local_node_view(element))); auto const x = geometry::project_to_plane( coordinates->current_configuration(local_node_view(element))); sf->quadrature().for_each([&](auto const& femval, const auto& l) { auto const& [N, rhea] = femval; // Local deformation gradient for the initial configuration matrix2 const F_0 = local_deformation_gradient(rhea, X); matrix2 const F = local_deformation_gradient(rhea, x); // Gradient operator in index notation auto const& B_0t = rhea * F_0.inverse(); // Displacement gradient matrix2 const H = (x - X) * B_0t; H_list[view(element, l)] = H; F_list[view(element, l)] = F * F_0.inverse(); }); } } void fem_submesh::update_Jacobian_determinants() { auto const& F = variables->get(variable::second::deformation_gradient); auto& F_det = variables->get(variable::scalar::DetF); std::transform(begin(F), end(F), begin(F_det), [](auto const& F) { return F.determinant(); }); auto const found = std::find_if(begin(F_det), end(F_det), [](auto const value) { return value <= 0.0; }); if (found != F_det.end()) { auto const i = std::distance(begin(F_det), found); auto const [element, quadrature_point] = std::div(i, sf->quadrature().points()); throw computational_error("Positive Jacobian assumption violated at element " + std::to_string(element) + " and local quadrature point " + std::to_string(quadrature_point) + " (" + std::to_string(*found) + ")"); } } std::pair<vector, vector> fem_submesh::nodal_averaged_variable(variable::scalar const scalar_name) const { vector count = vector::Zero(coordinates->size()); vector value = count; auto const& scalar_list = variables->get(scalar_name); auto const& E = sf->local_quadrature_extrapolation(); // vector format of values vector component = vector::Zero(sf->quadrature().points()); for (std::int64_t element{0}; element < elements(); ++element) { for (std::size_t l{0}; l < sf->quadrature().points(); ++l) { component(l) = scalar_list[view(element, l)]; } // Local extrapolation to the nodes vector const nodal_component = E * component; // Assemble these into the global value vector auto const& node_list = local_node_view(element); for (auto n = 0; n < nodal_component.rows(); n++) { value(node_list[n]) += nodal_component(n); count(node_list[n]) += 1.0; } } return {value, count}; } std::pair<vector, vector> fem_submesh::nodal_averaged_variable(variable::second const tensor_name) const { vector count = vector::Zero(coordinates->size() * 4); vector value = count; auto const& tensor_list = variables->get(tensor_name); matrix const E = sf->local_quadrature_extrapolation(); // vector format of values vector component(sf->quadrature().points()); for (std::int64_t element{0}; element < elements(); ++element) { // Assemble these into the global value vector auto const& node_list = local_node_view(element); for (auto ci = 0; ci < 2; ++ci) { for (auto cj = 0; cj < 2; ++cj) { for (std::size_t l{0}; l < sf->quadrature().points(); ++l) { component(l) = tensor_list[view(element, l)](ci, cj); } // Local extrapolation to the nodes vector const nodal_component = E * component; for (auto n = 0; n < nodal_component.rows(); n++) { value(node_list[n] * 4 + ci * 2 + cj) += nodal_component(n); count(node_list[n] * 4 + ci * 2 + cj) += 1.0; } } } } return {value, count}; } }
36.445455
105
0.579529
annierhea
3753e8029f41cd6f3f89d6a217e100fa572871af
20,003
cpp
C++
src/zutil/conn.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
1
2021-03-04T02:35:47.000Z
2021-03-04T02:35:47.000Z
src/zutil/conn.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
null
null
null
src/zutil/conn.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, Nefelus Inc // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "conn.h" #include "wire.h" #include "zui.h" Ath__connWord::Ath__connWord(uint r1, uint c1) { _conn._fromRow= r1; _conn._fromCol= c1; _conn._toRow= 0; _conn._toCol= 0; _conn._ordered= 0; _conn._placed= 0; _conn._posFlow= 0; _conn._corner= 0; _conn._straight= 0; _conn._dir= 0; } Ath__connWord::Ath__connWord(uint r1, uint c1, uint type) { _conn._fromRow= r1; _conn._fromCol= c1; _conn._toRow= type; _conn._toCol= type; _conn._ordered= 0; _conn._placed= 0; _conn._posFlow= 0; _conn._corner= 0; _conn._straight= 0; _conn._dir= 0; } bool Ath__connWord::ordered() { return (_conn._ordered>0) ? true : false; } void Ath__connWord::orderByRow(uint r1, uint c1, uint r2, uint c2, uint colCnt) { if (r1>r2) { set(r2, c2, r1, c1, colCnt); _conn._ordered= 1; } else { set(r1, c1, r2, c2, colCnt); } } Ath__connWord::Ath__connWord(uint r1, uint c1, uint r2, uint c2, uint colCnt) { set(r1, c1, r2, c2, colCnt); _conn._ordered= 0; _conn._placed= 0; _conn._posFlow= 0; _conn._corner= 0; _conn._straight= 0; _conn._dir= 0; if (getRowDist()==0) { _conn._straight= 1; if (c1>c2) { set(r1, c1, r2, c2, colCnt); _conn._fromCol= c2; _conn._toCol= c1; _conn._ordered= 1; } } else if (getColDist()==0) { _conn._straight= 1; _conn._dir= 1; if (r1>r2) { _conn._fromRow= r2; _conn._toRow= r1; _conn._ordered= 1; } } else { orderByRow(r1, c1, r2, c2, colCnt); _conn._corner= 1; } } int Ath__connWord::getStraight() { if (_conn._straight>0) return _conn._dir; else return -1; } int Ath__connWord::getRowDist() { return _conn._toRow - _conn._fromRow; } int Ath__connWord::getColDist() { return _conn._toCol - _conn._fromCol; } uint Ath__connWord::getDist() { return ath__max(getRowDistAbs(), getColDistAbs()) ; } uint Ath__connWord::getMinDist() { return ath__min(getRowDistAbs(), getColDistAbs()) ; } uint Ath__connWord::getMaxDist() { return ath__max(getRowDistAbs(), getColDistAbs()) ; } uint Ath__connWord::getRowDistAbs() { int dist= getRowDist(); if (dist<0) return -dist; else return dist; } uint Ath__connWord::getSeg(uint *c1, uint *c2) { if (_conn._straight==0) return 0; if (_conn._dir==0) { *c2= _conn._toCol; *c1= _conn._fromCol; return _conn._fromRow; } else { *c2= _conn._toRow; *c1= _conn._fromRow; return _conn._fromCol; } } uint Ath__connWord::getColDistAbs() { int dist= getColDist(); if (dist<0) return -dist; else return dist; } Ath__connWord::Ath__connWord(uint v) { setAll(v); } uint Ath__connWord::getAll() { return _all; } void Ath__connWord::setAll(uint v) { _all= v; } uint Ath__connWord::getFromRowCol(uint *col) { *col= _conn._fromCol; return _conn._fromRow; } uint Ath__connWord::getToRowCol(uint *col) { *col= _conn._toCol; return _conn._toRow; } uint Ath__connWord::getFrom() { return _conn._colCnt * _conn._fromRow + _conn._fromCol; } uint Ath__connWord::getTo() { return _conn._colCnt * _conn._toRow + _conn._toCol; } uint Ath__connWord::set(uint x1, uint y1, uint x2, uint y2, uint colCnt) { _conn._fromRow= x1; _conn._fromCol= y1; _conn._toRow= x2; _conn._toCol= y2; _conn._colCnt= colCnt; return _all; } void Ath__p2pConn::setNext(Ath__p2pConn *v) { _next= v; } void Ath__p2pConn::setPin(Ath__qPin *q) { _srcPin= q; } Ath__qPin *Ath__p2pConn::getSrcPin() { return _srcPin; } Ath__connTable::Ath__connTable(AthPool<Ath__p2pConn> *pool, uint n, uint pinLength, uint tileSize) { if (n==0) n=32; _nextSegCnt= 2; _tileSize= 0; _pinLength= 0; if (tileSize>0) { _nextSegCnt= tileSize/pinLength+1; _tileSize= tileSize; _pinLength= pinLength; } _maxBankCnt= n; _straightTable[0]= new Ath__array2d<Ath__p2pConn*>(n, true); _straightTable[1]= new Ath__array2d<Ath__p2pConn*>(n, true); _nextTable[0]= new Ath__array2d<Ath__p2pConn*>(_nextSegCnt); _nextTable[1]= new Ath__array2d<Ath__p2pConn*>(_nextSegCnt); _cornerTable= new Ath__array2d<Ath__p2pConn*>(2*n, true); _tmpTablePtr= NULL; _tmpArrayPtr= NULL; _poolPtr= pool; //_poolPtr= new AthPool<Ath__p2pConn>(1024); } uint Ath__connTable::getSegmentIndex(uint dir, uint dx, uint dy) { if (_pinLength==0) return 0; if (dir>0) { // vertical return dy/_pinLength; } else { return dx/_pinLength; } } Ath__p2pConn* Ath__connTable::addConn(uint netId, Ath__connWord w, uint dx, uint dy) { Ath__p2pConn* conn= _poolPtr->alloc(); conn->_netId= netId; conn->_conn= w; uint dist= w.getDist(); int dir= w.getStraight(); if (dir<0) { _cornerTable->add(dist, conn); } else { if (dist>1) { _straightTable[dir]->add(dist, conn); } else { if (dy==0) { // default _nextTable[dir]->add(0, conn); } else { uint kk= getSegmentIndex(dir, dx, dy); _nextTable[dir]->add(kk, conn); } } } return conn; } uint Ath__connTable::addStraightConn(uint dir, uint dist, Ath__p2pConn* p2p) { return _straightTable[dir]->add(dist, p2p); } uint Ath__connTable::addCornerConn2(uint type, Ath__p2pConn* p2p, uint ii, uint jj) { Ath__connWord w(ii, jj, type); p2p->_conn= w; return _cornerTable->add(type, p2p); } void Ath__connTable::printConnStats(FILE *fp) { fprintf(fp, "\n\nNet length distribution per tile unit length\n"); fprintf(fp, "--------------------------------------------\n"); char buff[128]; for (uint ii= 0; ii<_nextSegCnt; ii++) { sprintf(buff, " next tile HORIZONTAL conns - Length= %7d", (ii+1)*_pinLength); _nextTable[0]->printCnt(fp, ii, buff); } fprintf(fp, "\n"); for (uint jj= 0; jj<_nextSegCnt; jj++) { sprintf(buff, " next tile VERTICAL conns - Length= %7d", (jj+1)*_pinLength); _nextTable[1]->printCnt(fp, jj, buff); } fprintf(fp, "\n\n--------- straight tile-feedthru's\n"); _straightTable[0]->printAllCnts(fp, "tile-dist", " HORIZONTAL"); _straightTable[1]->printAllCnts(fp, "tile-dist", " VERTICAL"); fprintf(fp, "\n\n--------- corner tile-feedthru's\n"); _cornerTable->printAllCnts(fp, "tile-dist", "CORNER"); } uint Ath__connTable::startNextIterator(uint dir, uint seg) { _tmpTablePtr= _nextTable[dir]; return _tmpTablePtr->startIterator(seg); } uint Ath__connTable::startCornerIterator(uint dist) { _tmpTablePtr= _cornerTable; return _tmpTablePtr->startIterator(dist); } uint Ath__connTable::startStraightIterator(uint dir, uint dist) { _tmpTablePtr= _straightTable[dir]; return _tmpTablePtr->startIterator(dist); } int Ath__connTable::getNextConn(Ath__connWord *conn, uint *netId) { Ath__p2pConn* p2p= NULL; uint next= _tmpTablePtr->getNext(&p2p); if (next==0) return 0; *netId= p2p->_netId; *conn= p2p->_conn; return next; } Ath__p2pConn* Ath__connTable::getNextConn() { Ath__p2pConn* p2p= NULL; if (_tmpTablePtr->getNext(&p2p)==0) return NULL; return p2p; } Ath__array2d<Ath__p2pConn*>* Ath__connTable::startStraightArrayIterator(uint dir) { _tmpArrayPtr= _straightTable[dir]; for (uint ii= 0; ii<_maxBankCnt; ii++) { _tmpCurrentIndex[ii]= 0; _tmpCnt[ii]= _tmpArrayPtr->getCnt(ii); } return _tmpArrayPtr; } bool Ath__connTable::getNextArrayConn(uint ii, Ath__connWord *conn, uint *netId) { if (_tmpCurrentIndex[ii]>=_tmpCnt[ii]) return false; Ath__p2pConn* p2p= _tmpArrayPtr->get(ii, _tmpCurrentIndex[ii]); _tmpCurrentIndex[ii] ++; *netId= p2p->_netId; *conn= p2p->_conn; return true; } uint Ath__qPin::getToRowCol(uint *col) { return _conn.getToRowCol(col); } uint Ath__qPin::getTurnRowCol(uint *row, uint *col) { Ath__qPin* src= getSrcPin(); *row= src->_head->_conn.getFromRowCol(col); uint tmp1; //TODO return src->_head->_conn.getToRowCol(&tmp1); } int Ath__qPin::getTurnDist(uint *row, uint *col, int *dir) { uint turnRow, turnCol; getTurnRowCol(&turnRow, &turnCol); int rowDist= turnRow - *row; int colDist= turnCol - *col; if (rowDist==0) // horizontal { *dir= 1; if (colDist<0) { *col= turnCol; return -colDist; } return colDist; } if (colDist==0) // vertical { *dir= 0; if (rowDist<0) { *row= turnRow; return -rowDist; } return rowDist; } *dir= -1; return -1; } bool Ath__qPin::isTargeted() { return (_targeted>0) ? true : false; } bool Ath__qPin::isAssigned() { return (_assigned>0) ? true : false; } void Ath__qPin::setTargeted() { _targeted= 1; } void Ath__qPin::setPlaced() { _placed= 1; } bool Ath__qPin::isPlaced() { return (_placed>0) ? true : false; } bool Ath__qPin::isSrc() { return (_src>0) ? true : false; } Ath__qPin* Ath__qPin::getSrcPin() { if (_src>0) return this; else return _head->getSrcPin(); } Ath__qPin* Ath__qPin::getDstPin() { if (_src>0) return _next; else return this; } Ath__box *Ath__qPin::getInstBox() { return _instBB; } uint Ath__qPin::getLayer() { if (_portBB!=NULL) return _portBB->_layer; if (_targetBB!=NULL) return _targetBB->_layer; if (_instBB!=NULL) return _instBB->_layer; return 0; } void Ath__qPin::addBusBox(Ath__box *bb) { bb->_next= _busList; _busList= bb; } void Ath__qPin::setInstBox(Ath__box *bb) { _instBB= bb; } void Ath__qPin::getNextObsBox(Ath__searchBox *sbb) { Ath__box *bb= _obsList; if (_obsList->_next!=NULL) bb= _obsList->_next; sbb->set(bb->_xlo, bb->_ylo, bb->_xhi, bb->_yhi, bb->_layer, 0); } void Ath__qPin::getObsBox(Ath__searchBox *sbb) { Ath__box *bb= _obsList; sbb->set(bb->_xlo, bb->_ylo, bb->_xhi, bb->_yhi, bb->_layer, 0); } void Ath__qPin::getTargetBox(Ath__searchBox *bb) { bb->set(_targetBB->_xlo, _targetBB->_ylo, _targetBB->_xhi, _targetBB->_yhi, _targetBB->_layer, 0); } uint Ath__qPin::makeZuiObject(Ath__zui *zui, uint width, bool actual, bool instFlag) { if (width<=0) width= 1000; if (instFlag) { uint w2= width/2; zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _instBB->_layer, _instBB->getMidX()-w2, _instBB->getMidY()-w2, _instBB->getMidX()+w2, _instBB->getMidY()+w2); return _instBB->_layer; } if (actual && (_portBB!=NULL)) { int x1= _portBB->_xlo; int y1= _portBB->_ylo; int x2= _portBB->_xhi; int y2= _portBB->_yhi; zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _portBB->_layer, x1, y1, x2, y2); return _portBB->_layer; } if (_targetBB!=NULL) { uint w2= width/2; int x1= _targetBB->_xlo; int y1= _targetBB->_ylo; int x2= _targetBB->_xhi; int y2= _targetBB->_yhi; if (x1==x2) { x1 -= w2; x2 += w2; } else if (y1==y2) { y1 -= w2; y2 += w2; } zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _targetBB->_layer, x1, y1, x2, y2); return _targetBB->_layer; } } Ath__box* Ath__qPin::getPortCoords(int *x1, int *y1, int *x2, int *y2, uint *layer) { if (_portBB==NULL) return NULL; *x1= _portBB->_xlo; *y1= _portBB->_ylo; *x2= _portBB->_xhi; *y2= _portBB->_yhi; *layer= _portBB->_layer; return _portBB; } Ath__box* Ath__qPin::getBusList() { return _busList; } uint Ath__qPin::makePinObsZui(Ath__zui *zui, int width, int x1, int y1, int x2, int y2, int layer) { uint w2= width/2; if (x1==x2) { x1 -= w2; x2 += w2; } else if (y1==y2) { y1 -= w2; y2 += w2; } return zui->addBox(_nameId, Ath_box__bus, Ath_hier__tile, layer, x1, y1, x2, y2); } uint Ath__qPin::makeBusZuiObject(Ath__zui *zui, uint width) { uint cnt= 0; // if (obs==NULL) // nextTile shapes don't have shapes for (Ath__box *obs= _obsList; obs!=NULL; obs= obs->_next) { cnt += makePinObsZui(zui, width, obs->_xlo, obs->_ylo, obs->_xhi, obs->_yhi, obs->_layer); } return cnt; } void Ath__qPin::reset() { _src= 0; _tjunction= 0; _placed= 0; _fixed= 0; _assigned= 0; _targeted= 0; _nameId= 0; _instBB= NULL; _targetBB= NULL; _portBB= NULL; _portWireId= 0; _obsList= NULL; _busList= NULL; } void Ath__qPin::setPortWireId(uint id) { _portWireId= id; } void Ath__qPin::pinBoxDef(FILE *fp, char *layerName, char *orient, int defUnits) { fprintf(stdout, "TODO: pinBoxDef\n"); return; /* fprintf(fp, " ( %d %d ) %s ", _bb->_xlo/defUnits, _bb->_ylo/defUnits, orient); fprintf(fp, " + LAYER %s ( %d %d ) ( %d %d ) ", layerName, 0, 0, _bb->getDX()/defUnits, _bb->getDY()/defUnits); */ } Ath__qPinTable::Ath__qPinTable(AthPool<Ath__qPin> *qPinPool, AthPool<Ath__box> *boxPool, uint n) { _table= new Ath__array1D<Ath__qPin*>(n); for (uint jj= 0; jj<2; jj++) { _nextPinShape[jj]= NULL; _straightPinShape[jj]= NULL; _thruObsShape[jj]= NULL; } for (uint ii= 0; ii<4; ii++) { _cornerPinShape[ii]= NULL; _cornerObsShape[ii]= NULL; } _pool= qPinPool; //_pool->setDbg(1); _pinBoxPool= boxPool; } Ath__box* Ath__qPinTable::getHeadStraightPinShape(uint dir) { return _straightPinShape[dir]; } Ath__box* Ath__qPinTable::getHeadNextPinShape(uint dir) { return _nextPinShape[dir]; } Ath__box* Ath__qPinTable::getHeadCornerPinShape(uint type) { return _cornerPinShape[type]; } Ath__box* Ath__qPinTable::getHeadCornerObsShape(uint type) { return _cornerObsShape[type]; } Ath__box* Ath__qPinTable::getHeadObsShape(uint dir) { return _thruObsShape[dir]; } void Ath__qPinTable::freeBoxes(Ath__box *head) { Ath__box *e= head; while (e!=NULL) { Ath__box *f= e->_next; _pinBoxPool->free(e); e= f; } } void Ath__qPinTable::freeNextPinShapes() { freeBoxes(_nextPinShape[0]); freeBoxes(_nextPinShape[1]); _nextPinShape[0]= NULL; _nextPinShape[1]= NULL; } Ath__box* Ath__qPinTable::newPinBox(uint layer, int x1, int y1, int x2, int y2) { uint n; Ath__box *a= _pinBoxPool->alloc(NULL, &n); a->set(x1, y1, x2, y2); a->_id= n; a->_layer= layer; return a; } Ath__box* Ath__qPinTable::addPinBox(Ath__box *e, Ath__box *head) { e->_next= head; return e; } Ath__box* Ath__qPinTable::addNextPinBox(uint pinId, uint dir, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile); _nextPinShape[dir]= addPinBox(bbPin, _nextPinShape[dir]); return bbPin; } Ath__box* Ath__qPinTable::addThruObsBox(uint netId, uint dir, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__bus, netId, Ath_hier__tile); _thruObsShape[dir]= addPinBox(bbPin, _thruObsShape[dir]); return _thruObsShape[dir]; } Ath__box* Ath__qPinTable::addCornerPinBox(uint pinId, uint type, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile); _cornerPinShape[type]= addPinBox(bbPin, _cornerPinShape[type]); return _cornerPinShape[type]; } Ath__box* Ath__qPinTable::addCornerObsBox(uint netId, uint type, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__bus, netId, Ath_hier__tile); _cornerObsShape[type]= addPinBox(bbPin, _cornerObsShape[type]); return bbPin; } Ath__box* Ath__qPinTable::addStraightPinBox(uint pinId, uint dir, uint layer, int x1, int y1, int x2, int y2) { Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2); bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile); _straightPinShape[dir]= addPinBox(bbPin, _straightPinShape[dir]); return bbPin; } Ath__qPinTable::~Ath__qPinTable() { for (uint jj= 0; jj<2; jj++) { freeBoxes(_nextPinShape[jj]); freeBoxes(_straightPinShape[jj]); freeBoxes(_thruObsShape[jj]); freeBoxes(_cornerPinShape[jj]); } freeBoxes(_cornerPinShape[2]); freeBoxes(_cornerPinShape[3]); } Ath__qPin* Ath__qPinTable::addPin(Ath__qPin* next, uint netId, uint ioNetId, Ath__connWord w, AthPool<Ath__qPin> *pool) { uint id; Ath__qPin* pin= _pool->alloc(NULL, &id); pin->_conn= w; pin->reset(); pin->_netId= netId; pin->_ioNetId= ioNetId; pin->_nameId= id; pin->_next= NULL; if (next!=NULL) { next->_next= pin; pin->_src= 0; } else { _table->add(pin); pin->_src= 1; } return pin; } Ath__qPin *Ath__qPinTable::getNextSrcPin_next() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; int cornerFlag= srcPin->_conn.getStraight(); if (cornerFlag<0) continue; if (srcPin->_conn.getDist()>1) continue; return srcPin; } return NULL; } Ath__qPin *Ath__qPinTable::getNextSrcPin_thru() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; if (srcPin->_conn.getStraight()<0) continue; if (srcPin->_conn.getDist()<2) continue; return srcPin; } return NULL; } Ath__qPin *Ath__qPinTable::getNextSrcPin_corner() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; int cornerFlag= srcPin->_conn.getStraight(); if (cornerFlag>=0) continue; // if (srcPin->_conn.getDist()>1) // continue; if (srcPin->_assigned==0) continue; return srcPin; } return NULL; } Ath__qPin *Ath__qPinTable::getNextSrcPin_all() { Ath__qPin *srcPin; while (_table->getNext(srcPin)) { if (srcPin->_src==0) continue; return srcPin; } return NULL; } bool Ath__qPinTable::startIterator() { if (_table->getCnt()<=0) return false; _table->resetIterator(); return true; } uint Ath__qPinTable::getCnt() { return _table->getCnt(); } Ath__qPin *Ath__qPinTable::get(uint ii) { return _table->get(ii); } Ath__qBus::Ath__qBus(uint n) { _table= new Ath__array1D<Ath__p2pConn*>(n); } void Ath__qBus::addConn(Ath__p2pConn *conn) { _table->add(conn); } uint Ath__qBus::getCnt() { return _table->getCnt(); } Ath__p2pConn *Ath__qBus::get(uint ii) { return _table->get(ii); }
22.399776
120
0.653602
mgwoo
375eaa78b581f84c658ae81f2e900ae9266ba765
212
hpp
C++
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_LANG_AST_NODE_OMNI_IDX_DEF_HPP #define STAN_LANG_AST_NODE_OMNI_IDX_DEF_HPP #include <stan/lang/ast.hpp> namespace stan { namespace lang { omni_idx::omni_idx() { } } } #endif
15.142857
44
0.707547
alashworth
3764cc4b84406d41e5a8ca372a2e8f204b4dfab6
1,144
cpp
C++
src/input/InputHandler.cpp
Estebanan/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
3
2019-07-31T06:13:41.000Z
2021-04-04T15:32:40.000Z
src/input/InputHandler.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
src/input/InputHandler.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
#include "InputHandler.h" static constexpr unsigned int MAX_KEYS = 1024; static constexpr unsigned int MAX_MOUSEBUTTONS = 32; static bool keys[MAX_KEYS] = {false}; static bool mousebuttons[MAX_MOUSEBUTTONS] = {false}; static int mouse_x; static int mouse_y; bool InputHandler::isKeyPressed(unsigned int key) { if(key >= 0 && key < MAX_KEYS) return keys[key]; else return false; } bool InputHandler::isMouseButtonPressed(unsigned int mousebutton) { if(mousebutton >= 0 && mousebutton < MAX_MOUSEBUTTONS) return mousebuttons[mousebutton]; else return false; } void InputHandler::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { keys[key] = action != GLFW_RELEASE; } void InputHandler::mouseButtonCallback(GLFWwindow *window, int button, int action, int mods) { mousebuttons[button] = action != GLFW_RELEASE; } void InputHandler::cursorPositionCallback(GLFWwindow *window, double xpos, double ypos) { mouse_x = xpos; mouse_y = ypos; } int InputHandler::getMouseX() { return mouse_x; } int InputHandler::getMouseY() { return mouse_y; }
24.869565
97
0.714161
Estebanan
3766f6f9125d4549e0161570c5f138a8acec49e9
1,991
cpp
C++
fluffy/core/src/api/modules.cpp
Lo-X/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2015-12-27T14:42:53.000Z
2018-04-18T07:28:05.000Z
fluffy/core/src/api/modules.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2018-04-27T14:26:29.000Z
2021-01-29T16:28:18.000Z
fluffy/core/src/api/modules.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
null
null
null
#include <fluffy/api/context.hpp> #include <fluffy/api/modules.hpp> #include <fluffy/graphics/shader.hpp> #include <fluffy/graphics/texture.hpp> #include <fluffy/input/input.hpp> #include <fluffy/resources/resource_library.hpp> using namespace Fluffy; void ModuleRegistry::registerModule(BaseModule* module) { ModuleType type = module->getType(); auto it = mRegistry.find(type); if (it != mRegistry.end()) { FLUFFY_LOG_WARN("Module '{}' of type '{}' has already been registered. Removing it.", it->second->getName(), EnumNames::ModuleType[(int)type]); delete it->second; } mRegistry[type] = module; } std::map<ModuleType, BaseModule*> ModuleRegistry::getModules() const { return mRegistry; } BaseModule* ModuleRegistry::getModule(ModuleType type) const { auto it = mRegistry.find(type); if (it != mRegistry.end()) { return it->second; } return nullptr; } /**********************************************************************************************************************/ void SystemModule::initialize(const Context& context) { mResources = CreateUnique<ResourceLibrary>(context); mResources->init<Texture2D>(); // mResources->init<Shader>(); } void SystemModule::terminate() { } ResourceLibrary& SystemModule::getResources() const { return *mResources; } /**********************************************************************************************************************/ VideoModule::VideoModule(Window::Definition&& windowDefinition) : mWindowDefinition(windowDefinition) { } void VideoModule::initialize(const Context& context) { mWindow = createWindow(mWindowDefinition); } void VideoModule::terminate() { } /**********************************************************************************************************************/ void InputModule::initialize(const Context& context) { Input::create(context.video->getWindow()); } void InputModule::terminate() { }
24.580247
151
0.575088
Lo-X
376853218b7f464eea1549c8f70589ea89b5519c
634
cpp
C++
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
#include "testall.h" #include "cworkplace.h" #include <iostream> #include "cworkerbuilder.h" #include "cluaworker.h" namespace KOT { void TestWorker() { std::cout << "===========TestWorker==========" << std::endl; CLuaWorkerBuilder builder; builder.SetWorkerPath("../script/test/"); // builder.AddEnvPath("../script/test/?.lua"); // TestWorkerBuilder builder; CWorkPlace::GetInstance().AddWorker(builder.SetWorkerID("worker1")); CWorkPlace::GetInstance().AddWorker(builder.SetWorkerID("worker2")); CWorkPlace::GetInstance().Exec(); std::cout << "=============================" << std::endl; } }
26.416667
72
0.623028
43437
3769d204cf627abd6b7049c46d29850bf6eade8b
3,454
cpp
C++
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
6
2016-06-08T05:29:49.000Z
2020-05-26T14:07:01.000Z
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
null
null
null
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
null
null
null
#include "precomp.h" #include "Game.h" using namespace std; CL_GraphicContext *Game::gc; string Game::winner; Game::Game(CL_DisplayWindow &window) { gc = &window.get_gc(); board = &Board::GetInstance(); startMessage = new string("Press [1] to start first, or\n\n\nPress [2] to start with computer"); whichPlayer[0] = "Player White (You)"; whichPlayer[1] = "Player Black (Computer)"; } Game::~Game(){ delete player; delete computer; } void Game::Run(CL_DisplayWindow &window){ game_display_window = window; *gc = window.get_gc(); quit = false; CL_Slot slot_key_down = window.get_ic().get_keyboard().sig_key_down().connect(this, &Game::OnKeyDown); function<void(string)> callbackFunction; callbackFunction = &(Game::PlayerHasWonNotification); player = new Player(*gc, callbackFunction); player->AttachKeyboard(game_display_window); computer = new PlayerNPC(*gc,callbackFunction); sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); //Set up font CL_FontDescription system_font_desc; system_font_desc.set_typeface_name("courier new"); CL_Font_System system_font(*gc, system_font_desc); system_font.set_font_metrics(CL_FontMetrics(7.0f)); string spacing = " "; string columnIdentifiers = "Use keys: [1] [2] [3] [4] [5] [6] [7]"; system_font.draw_text(*gc, 10, 20, *startMessage); window.flip(0); while (startMessage != nullptr) { CL_KeepAlive::process(); } char numberOfMinMaxCalls[32]; numberOfMinMaxCalls[0] = '\0'; while (!quit) { gc->clear(CL_Colorf(20, 56, 108)); int currentPlayer = board->Turn % 2; if (currentPlayer == 0) system_font.draw_text(*gc, 10, 20, "Current Turn: " + whichPlayer[0]); else system_font.draw_text(*gc, 10, 20, "Current Turn: " + whichPlayer[1]); //Draw column numbers system_font.draw_text(*gc, 10, 120, columnIdentifiers); board->Draw(*gc); system_font.draw_text(*gc, 350, 50, numberOfMinMaxCalls); system_font.draw_text(*gc, 410, 80, horizonMessage); if(!winner.empty()) { system_font.draw_text(*gc, 10, 60, winner); } window.flip(0); CL_KeepAlive::process(); if (currentPlayer == 0) player->WaitForTurn(); else { int minMaxCalls = computer->WaitForTurn(); sprintf_s(numberOfMinMaxCalls, "#MinMaxCalls: %d", minMaxCalls); } } } string Game::GetActivePlayerName(Player *playerKI) { if(playerKI->PlayerIdentifier() == 'o') { return "Black Player"; } else return "White Player"; } void Game::PlayerHasWonNotification(string whosTheWinner) { if (winner.empty()) //only assign winner the first time a winner is determined winner = whosTheWinner; } void Game::OnKeyDown(const CL_InputEvent &key, const CL_InputState &state) { if (key.id == CL_KEY_ESCAPE) quit = true; else if (startMessage != nullptr && key.id == CL_KEY_1) { board->Turn = 0; //player 1 makes all even turns, computer all odd delete startMessage; startMessage = nullptr; } else if (startMessage != nullptr && key.id == CL_KEY_2) { board->Turn = 1; //cheap trick to start with computer instead of player delete startMessage; startMessage = nullptr; } else if (key.id == CL_KEY_UP) { if (PlayerNPC::Horizon < 42) { PlayerNPC::Horizon += 1; sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); } } else if (key.id == CL_KEY_DOWN) { if (PlayerNPC::Horizon > 0) { PlayerNPC::Horizon -= 1; sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); } } }
24.671429
103
0.690214
Mobiletainment
3769fa67cbbf10f4f4b80414b2bc8a4a39fb5aed
6,302
cpp
C++
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
5
2016-06-14T17:56:47.000Z
2022-02-10T19:54:25.000Z
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
42
2016-06-21T20:48:22.000Z
2021-03-23T15:20:51.000Z
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
1
2016-10-02T02:58:49.000Z
2016-10-02T02:58:49.000Z
/** * Copyright (c) 2016 Xavier R. Guerin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <ace/filesystem/Path.h> #include <ace/common/String.h> #include <sstream> #include <string> #include <vector> namespace ace { namespace fs { Path::Path(std::string const& v, bool enforceDir) : Path() { std::vector<std::string> elems; common::String::split(v, '/', elems); for (size_t i = 0; i < elems.size(); i += 1) { if (not elems[i].empty() || (elems[i].empty() && (i == 0 or i == elems.size() - 1))) { m_elements.push_back(elems[i]); } } if (not isDirectory() and enforceDir) { m_elements.push_back(std::string()); } } Path::Path(std::vector<std::string> const& c) : m_elements(c) {} Path Path::operator-(Path const& o) const { if (m_elements.empty()) { return Path(); } if (o.empty()) { return Path(*this); } std::vector<std::string> vals; auto ita = m_elements.begin(); auto itb = o.m_elements.begin(); while (ita != m_elements.end() and itb != o.m_elements.end()) { if (*ita != *itb) { break; } ita++, itb++; } if (ita == m_elements.end() || (itb != o.m_elements.end() && not itb->empty())) { return Path(); } while (ita != m_elements.end()) { vals.push_back(*ita++); } return Path(vals); } Path Path::operator/(Path const& o) const { if (o.isAbsolute()) { return Path(); } if (m_elements.empty() or not isDirectory()) { return Path(); } std::vector<std::string> elems(m_elements); elems.erase(--elems.end()); for (auto& e : o.m_elements) { elems.push_back(e); } return Path(elems); } std::string Path::toString() const { std::ostringstream oss; oss << *this; return oss.str(); } Path Path::prune() const { std::vector<std::string> elems(m_elements); if (not elems.empty()) { if ((--elems.end())->empty()) { elems.erase(--elems.end()); } elems.erase(--elems.end()); if (not elems.empty()) { elems.push_back(""); } } return Path(elems); } Path Path::compress() const { std::vector<std::string> elems; for (auto& e : m_elements) { if (e == ".") { continue; } elems.push_back(e); } return Path(elems); } bool Path::isAbsolute() const { if (m_elements.empty()) { return false; } return (*m_elements.begin()).empty(); } bool Path::isDirectory() const { if (m_elements.empty()) { return false; } return (*m_elements.rbegin()).empty(); } std::string Path::prefix(std::string const& a, std::string const& b) { Path pa(a), pb(b); return prefix(pa, pb).toString(); } Path Path::prefix(Path const& a, Path const& b) { std::vector<std::string> vals; if (a.empty() or b.empty()) { return Path(); } auto ita = a.begin(); auto itb = b.begin(); while (ita != a.end() and itb != b.end()) { if (*ita != *itb) { break; } vals.push_back(*ita); ita++, itb++; } if (ita == a.end() and itb == b.end()) { return Path(vals); } else if (ita != a.end() and itb != b.end()) { vals.push_back(std::string()); return Path(vals); } else if ((ita != a.end() and itb == b.end()) || (ita == a.end() and itb != b.end())) { if (not vals.empty()) { vals.erase(--vals.end()); vals.push_back(std::string()); return Path(vals); } } return Path(); } std::ostream& operator<<(std::ostream& o, Path const& p) { for (size_t i = 0; i < p.m_elements.size(); i += 1) { o << p.m_elements[i]; if (i < p.m_elements.size() - 1) { o << "/"; } } return o; } bool Path::operator==(Path const& o) const { return m_elements == o.m_elements; } bool Path::operator!=(Path const& o) const { return m_elements != o.m_elements; } bool Path::empty() const { return m_elements.empty(); } Path::iterator Path::begin() { return m_elements.begin(); } Path::const_iterator Path::begin() const { return m_elements.begin(); } Path::iterator Path::end() { return m_elements.end(); } Path::const_iterator Path::end() const { return m_elements.end(); } Path::reverse_iterator Path::rbegin() { return m_elements.rbegin(); } Path::const_reverse_iterator Path::rbegin() const { return m_elements.rbegin(); } Path::reverse_iterator Path::rend() { return m_elements.rend(); } Path::const_reverse_iterator Path::rend() const { return m_elements.rend(); } Path::iterator Path::up(iterator const& i) { Path::iterator n(i); return --n; } Path::const_iterator Path::up(const_iterator const& i) const { Path::const_iterator n(i); return --n; } Path::iterator Path::down(iterator const& i) { Path::iterator n(i); return ++n; } Path::const_iterator Path::down(const_iterator const& i) const { Path::const_iterator n(i); return ++n; } Path::reverse_iterator Path::up(reverse_iterator const& i) { Path::reverse_iterator n(i); return ++n; } Path::const_reverse_iterator Path::up(const_reverse_iterator const& i) const { Path::const_reverse_iterator n(i); return ++n; } Path::reverse_iterator Path::down(reverse_iterator const& i) { Path::reverse_iterator n(i); return --n; } Path::const_reverse_iterator Path::down(const_reverse_iterator const& i) const { Path::const_reverse_iterator n(i); return --n; } }}
19.571429
80
0.631387
xguerin
376a7ab1b23739b7e20d45adf6fb0641e9c95b0f
2,616
hpp
C++
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "foundation/axis.SystemBase.hpp" #include "domain/fwd/numerical_model.hpp" #include "foundation/memory/RelativePointer.hpp" #include "Foundation/Axis.CommonLibrary.hpp" namespace axis { namespace domain { namespace analyses { class ModelOperatorFacade; /** * Implements a version of the numerical model with reduced functionality, * so that it can be used with external processing devices. **/ class AXISCOMMONLIBRARY_API ReducedNumericalModel { public: ReducedNumericalModel(NumericalModel& sourceModel, ModelOperatorFacade& op); ~ReducedNumericalModel(void); const ModelDynamics& Dynamics(void) const; ModelDynamics& Dynamics(void); const ModelKinematics& Kinematics(void) const; ModelKinematics& Kinematics(void); size_type GetElementCount(void) const; size_type GetNodeCount(void) const; const axis::domain::elements::FiniteElement& GetElement(size_type index) const; axis::domain::elements::FiniteElement& GetElement(size_type index); const axis::foundation::memory::RelativePointer GetElementPointer(size_type index) const; axis::foundation::memory::RelativePointer GetElementPointer(size_type index); const axis::domain::elements::Node& GetNode(size_type index) const; axis::domain::elements::Node& GetNode(size_type index); const axis::foundation::memory::RelativePointer GetNodePointer(size_type index) const; axis::foundation::memory::RelativePointer GetNodePointer(size_type index); ModelOperatorFacade& GetOperator(void); /** * Creates a facade with reduced functionality that operates on components of an existing * numerical model. * * @param [in,out] sourceModel Source numerical model. * @param [in,out] op The object which provides an interface to external processing * using this model. * * @return A pointer to the reduced numerical model, located in model memory. **/ static axis::foundation::memory::RelativePointer Create(NumericalModel& sourceModel, ModelOperatorFacade& op); private: void *operator new (size_t, void *ptr); void operator delete(void *, void *); ModelOperatorFacade *operator_; axis::foundation::memory::RelativePointer nodeArrayPtr_; axis::foundation::memory::RelativePointer elementArrayPtr_; axis::foundation::memory::RelativePointer outputBucketArrayPtr_; size_type elementCount_; size_type nodeCount_; axis::foundation::memory::RelativePointer kinematics_; axis::foundation::memory::RelativePointer dynamics_; }; } } } // namespace axis::domain::analyses
40.875
96
0.748853
renato-yuzup
3770ca1dd46873dd38256f23ab25bafeb9f6febb
37,357
cpp
C++
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include "..\SafeMacros.h" #include "..\Logging\MessageLogger.h" //--------------------------------------------------------------------------- #include <shfolder.h> //--------------------------------------------------------------------------- #include "FrameWorkInterface.h" #include "ZXLogFile.h" #include "ZXPluginManager.h" #include "ZXProjectManager.h" #include "ZXGuiManager.h" #include "fMain.h" #include "fAbout.h" #include "fRenameProject.h" #include "fCopyProject.h" //-- PRAGMA'S --------------------------------------------------------------- #pragma package(smart_init) #pragma link "KRegistry" #pragma link "pngimage" #pragma resource "*.dfm" //--------------------------------------------------------------------------- using namespace Scorpio; using namespace GUI; using namespace Logging; using namespace Interface; using namespace Plugin; using namespace Project; //--------------------------------------------------------------------------- TMRUProjectsVector g_mruList; const TColor g_Colors[] = { clRed, clYellow, clLime, clAqua }; //--------------------------------------------------------------------------- // Constructor /** * Initializes the main form * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- __fastcall TfrmMain::TfrmMain(TComponent* Owner) : TForm(Owner), m_bClosing(false), m_iTopOfButtons(8) { RL_METHOD } //--------------------------------------------------------------------------- // Denstructor /** * Checks all allocate memory is freed * @author Tony Thompson * @date Created 23 April 2005 */ //--------------------------------------------------------------------------- __fastcall TfrmMain::~TfrmMain() { if (NULL != frmAbout) { ZX_LOG_ERROR(lfGeneral, "frmAbout is not freed"); } if (0 != m_SwitcherButtons.size()) { ZX_LOG_ERROR(lfGeneral, "Not all the Switcher Buttons have been freed"); } } //--------------------------------------------------------------------------- // FormCreate /** * Event handler for the when the form is created * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormCreate(TObject *Sender) { RL_METHOD PROTECT_BEGIN RestoreStates(); panTitle->DoubleBuffered = true; // panMRUList->DoubleBuffered = true; panPluginButtons->DoubleBuffered = true; GetLocation(); GetMachines(); UpdateGUI(); edtNewProjectLocation->Text = GetMyDocumentsFolder() + "\\TommyGun\\"; //pgcPlugins->DoubleBuffered = true; Registration(); PROTECT_END } //--------------------------------------------------------------------------- // FormActivate /** * Repositions the form when it is activate (only once though) * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormActivate(TObject *Sender) { RL_METHOD PROTECT_BEGIN static bool bRepositioned = false; if (false == bRepositioned) { bRepositioned = true; int iValue = 0; bool bState = false; if (regScorpio->Read("States", "Top" , iValue)) Top = iValue; if (regScorpio->Read("States", "Left" , iValue)) Left = iValue; if (regScorpio->Read("States", "Maximized" , bState) && bState) WindowState = wsMaximized; } FormResize(NULL); PROTECT_END } //--------------------------------------------------------------------------- // FormCloseQuery /** * Queries the form to see if its OK to close * @param Sender the VCL object that called the method * @param CanClose true if canclose, false if not * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormCloseQuery(TObject *Sender, bool &CanClose) { RL_METHOD PROTECT_BEGIN CanClose = false; if (S_OK == g_PluginManager.Notify(g_PluginManager.Handle, TZX_VERB_NEW, NULL, 0, 0)) { // notify of closing g_PluginManager.Notify(g_PluginManager.Handle, TZX_VERB_EXIT, NULL, 0, 0); m_bClosing = true; // can close application CanClose = true; } PROTECT_END } //--------------------------------------------------------------------------- // FormClose /** * Event handler for the when the form is created * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormClose(TObject *Sender, TCloseAction &Action) { RL_METHOD PROTECT_BEGIN if (WindowState != wsMaximized) { regScorpio->Write("States", "Top" , Top ); regScorpio->Write("States", "Left" , Left ); regScorpio->Write("States", "Width" , Width ); regScorpio->Write("States", "Height" , Height ); } regScorpio->Write("States", "Maximized" , WindowState == wsMaximized); PROTECT_END } //--------------------------------------------------------------------------- // FormResize /** * Event handler for the when the form is resized * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormResize(TObject *Sender) { stsStatus->Panels->Items[0]->Width = stsStatus->ClientWidth - 260 - stsStatus->Panels->Items[1]->Width; stsStatus->Update(); if (pgcPlugins->Width != panPageContainer->Width + 8) { pgcPlugins->Width = panPageContainer->Width + 8; pgcPlugins->Left = -4; } if (pgcPlugins->Height!= panPageContainer->Height + 9) { pgcPlugins->Height = panPageContainer->Height + 9; pgcPlugins->Top = -8; } pgcPlugins->Update(); } //--------------------------------------------------------------------------- // appEventsException /** * Event handler for when an exception occurs * @param Sender the vcl object that caused the event * @param E the exception object * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::appEventsException(TObject *Sender, Exception *E) { RL_METHOD ZXPlugin* Plugin = g_PluginManager.CheckException(); if (true == SAFE_PTR(Plugin)) { m_MessageBox.ShowExceptionMessage(Plugin->Description, Plugin->Vendor, (DWORD)Plugin->ModuleAddress, (DWORD)ExceptAddr(), E->Message, true); Plugin->Unload(); } else { if (0 < g_Exceptions.size()) { for (unsigned int i = 0; i < g_Exceptions.size(); ++i) { m_MessageBox.ShowExceptionMessage(g_Exceptions[i].sMessage, g_Exceptions[i].sFile, g_Exceptions[i].sFunc, g_Exceptions[i].iLine); } g_Exceptions.clear(); } else { m_MessageBox.ShowExceptionMessage(E->Message, __FILE__, __FUNC__, __LINE__); } } } //--------------------------------------------------------------------------- // appEventsHint /** * Event handler for when a hint occurs * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::appEventsHint(TObject *Sender) { stsStatus->Panels->Items[0]->Text = Application->Hint; } //--------------------------------------------------------------------------- // mnuHelpAboutClick /** * Event handler for the about menu * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuHelpAboutClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN frmAbout = new TfrmAbout(Application); frmAbout->Execute(); SAFE_DELETE(frmAbout); PROTECT_END } //--------------------------------------------------------------------------- // mnuViewPluginSwitcherClick /** * Toggles the visibility of the plugin switcher * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewPluginSwitcherClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN mnuViewPluginSwitcher->Checked = !mnuViewPluginSwitcher->Checked; panPluginSwitcher->Visible = mnuViewPluginSwitcher->Checked; regScorpio->Write("States", "Switcher", mnuViewPluginSwitcher->Checked); PROTECT_END } //--------------------------------------------------------------------------- // mnuViewStandardClick /** * Toggles the visibility of the standard toolbar * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewStandardClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN mnuViewStandard->Checked = !mnuViewStandard->Checked; //tbrStandard->Visible = mnuViewStandard->Checked; panToolbars->Visible = mnuViewStandard->Checked; regScorpio->Write("States", "Standard", mnuViewStandard->Checked); PROTECT_END } //--------------------------------------------------------------------------- // spdPluginsUpClick /** * Scrolls the plugin buttons down into view within the browser * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::spdPluginsUpClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Top = std::min(0, panPluginButtons->Top + 76); PROTECT_END } //--------------------------------------------------------------------------- // spdPluginsDownClick /** * Scrolls the plugin buttons up into view within the browser * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::spdPluginsDownClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); panPluginButtons->Top = std::min(0, std::max(panPluginButtonsContainer->Height - m_iTopOfButtons + 64, panPluginButtons->Top - 76)); PROTECT_END } //--------------------------------------------------------------------------- // panPluginButtonsContainerResize /** * Resizes the plugin browser panels * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::panPluginButtonsContainerResize(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); panPluginButtons->Top = 0; PROTECT_END } //--------------------------------------------------------------------------- // actSwitch01Execute /** * Switches to plugin using the Ctrl+Fn keys * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::actSwitch01Execute(TObject *Sender) { RL_METHOD PROTECT_BEGIN int iPluginIndex = ((TAction*)Sender)->Tag; if (0 <= iPluginIndex && iPluginIndex < (int)m_SwitcherButtons.size()) { PostNotifyEvent(m_SwitcherButtons[iPluginIndex].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); } PROTECT_END } //--------------------------------------------------------------------------- // OnPluginButtonClick /** * Event handler for when a plugin buttons is pressed * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::OnPluginButtonClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN //ClearStatusSlots(); //pgcPlugins->ActivePageIndex = ((TComponent*)Sender)->Tag; PostNotifyEvent(m_SwitcherButtons[((TComponent*)Sender)->Tag].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); PROTECT_END } //--------------------------------------------------------------------------- // RestoreStates /** * Restores the states of some form objects * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::RestoreStates(void) { RL_METHOD PROTECT_BEGIN bool bState = true; int iValue = 0; regScorpio->Read("States", "Switcher" , bState); if (bState) mnuViewPluginSwitcherClick(NULL); if (regScorpio->Read("States", "Standard" , bState) && false == bState) mnuViewStandardClick(NULL); if (regScorpio->Read("States", "Width" , iValue) && false == bState) Width = iValue; if (regScorpio->Read("States", "Height" , iValue) && false == bState) Height = iValue; PROTECT_END } //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewOptionsClick(TObject *Sender) { PROTECT_BEGIN g_GuiManager.OptionsShow(); tbrStandard->AutoSize = false; tbrStandard->AutoSize = true; String sFolder; if (regScorpio->Read("ProjectFolder", sFolder)) { edtNewProjectLocation->Text = sFolder; } PROTECT_END } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateOptions(void) { bool bValue = true; regScorpio->Read("ShowPluginIcons", bValue); stsStatus->Panels->Items[1]->Width = bValue ? 200 : 0; FormResize(NULL); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::AddSwitcherButton(TZX_HPLUGIN PluginHandle, const String& sCaption) { TSwitcherButton Button; Button.PluginHandle = PluginHandle; Button.IconButton = new KIconButton(NULL); Button.IconButton->Name = "Button" + IntToStr(PluginHandle); Button.IconButton->Caption = sCaption; Button.IconButton->Parent = panPluginButtons; Button.IconButton->Left = 4; Button.IconButton->Top = 8 + (m_SwitcherButtons.size() * 76); Button.IconButton->Height = 68; Button.IconButton->Width = 68; Button.IconButton->Tag = m_SwitcherButtons.size(); Button.IconButton->IconsCold = imgLarge; Button.IconButton->IconsHot = imgLarge; Button.IconButton->IconIndex = -1; Button.IconButton->Grouped = true; Button.IconButton->ColorHighlight = (TColor)0x00F6E8E0;//clInfoBk; Button.IconButton->ColorSelected = (TColor)0x00EED2C1;//clWhite; Button.IconButton->Color = (TColor)0x00846142;//panPluginButtons->Color; //clBtnFace; Button.IconButton->ColorBorder = (TColor)0x00846142; Button.IconButton->ColorBackground = panPluginButtons->Color; //Button.IconButton->Color = clBtnShadow; //Button.IconButton->ColorBorderSelected = clWhite; //Button.IconButton->ColorHighlight = 0x00F6E8E0; //Button.IconButton->ColorSelected = 0x00EED2C1; Button.IconButton->Font->Name = "Octin Stencil Rg"; Button.IconButton->Font->Size = 8; Button.IconButton->CornerWidth = 10; Button.IconButton->CornerHeight = 10; Button.IconButton->OnClick = OnPluginButtonClick; m_SwitcherButtons.push_back(Button); m_SwitcherButtons[0].IconButton->Selected = true; m_iTopOfButtons = 4 + ((m_SwitcherButtons.size()) * 84); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::RemoveSwitcherButton(TZX_HPLUGIN PluginHandle) { // remove the button TSwitcherButtonIterator it = m_SwitcherButtons.begin(); for (it = m_SwitcherButtons.begin(); it != m_SwitcherButtons.end(); it++) { if ((*it).PluginHandle == PluginHandle) { SAFE_DELETE((*it).IconButton); //SAFE_DELETE((*it).Panel); m_SwitcherButtons.erase(it); break; } } // reposition the remaining buttons for (unsigned int i = 0; i < m_SwitcherButtons.size(); ++i) { m_SwitcherButtons[i].IconButton->Top = 4 + (i * 84); m_SwitcherButtons[i].IconButton->Tag = i; } // resize the panel m_iTopOfButtons = 4 + (m_SwitcherButtons.size() * 84); panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::SetSwitcherBitmap(TZX_HPLUGIN PluginHandle, TImage* Image) { TSwitcherButtonIterator it = m_SwitcherButtons.begin(); for (it = m_SwitcherButtons.begin(); it != m_SwitcherButtons.end(); it++) { if ((*it).PluginHandle == PluginHandle) { int iIndex = imgLarge->AddMasked(Image->Picture->Bitmap, Image->Picture->Bitmap->Canvas->Pixels[0][0]); (*it).IconButton->IconIndex = iIndex; } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::ClearStatusSlots(void) { // clear the status bar slots for the next plugin stsStatus->Panels->Items[2]->Text = ""; stsStatus->Panels->Items[3]->Text = ""; stsStatus->Panels->Items[4]->Text = ""; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileNewProjectExecute(TObject *Sender) { if (g_ProjectManager.Close()) { ActiveControl = edtNewProjectName; } FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileOpenProjectAccept(TObject *Sender) { g_ProjectManager.Load(actFileOpenProject->Dialog->FileName); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileSaveProjectExecute(TObject *Sender) { g_ProjectManager.Save(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileCloseProjectExecute(TObject *Sender) { g_ProjectManager.Close(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::SwitchToPlugin(TZX_HPLUGIN PluginHandle) { int iPluginIndex = -1; for (int i = 0; i < (int)m_SwitcherButtons.size(); i++) { if (m_SwitcherButtons[i].PluginHandle == PluginHandle) { iPluginIndex = i; break; } } if (0 <= iPluginIndex && iPluginIndex < pgcPlugins->PageCount) { ClearStatusSlots(); m_SwitcherButtons[iPluginIndex].IconButton->Selected = true; pgcPlugins->ActivePageIndex = iPluginIndex; UpdateGUI(); } } //--------------------------------------------------------------------------- AnsiString __fastcall TfrmMain::GetMyDocumentsFolder() { CHAR my_documents[MAX_PATH]; HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, my_documents); if (SUCCEEDED(result)) { AnsiString folder = AnsiString(my_documents); AnsiString myDocFolder = StringReplace(folder, "Documents", "My Documents", TReplaceFlags() << rfReplaceAll); if (DirectoryExists(folder)) { return folder; } if (DirectoryExists(myDocFolder)) { return myDocFolder; } } return ""; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdOpenProjectClick(TObject *Sender) { if (DirectoryExists(edtNewProjectLocation->Text)) { actFileOpenProject->Dialog->InitialDir = edtNewProjectLocation->Text; } else { actFileOpenProject->Dialog->InitialDir = GetMyDocumentsFolder() + "\\TommyGun\\"; } actFileOpenProject->Execute(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::edtNewProjectNameChange(TObject *Sender) { lblMessage->Visible = false; UpdateOk(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdCreateProjectClick(TObject *Sender) { String sBaseFolder = edtNewProjectLocation->Text; if (sBaseFolder[sBaseFolder.Length()] != '\\') { sBaseFolder += "\\"; } String sProjectFolder = sBaseFolder + edtNewProjectName->Text + "\\"; if (ForceDirectories(sBaseFolder)) { regScorpio->Write("Plugins", "MachineFolder", cmbNewProjectMachine->Text); regScorpio->Write("ProjectFolder", sBaseFolder); String sProjectFile = sProjectFolder + "project.xml" ; //sProjectFile = ChangeFileExt(sProjectFile, ".xml"); if (false == DirectoryExists(sProjectFolder)) { if (ForceDirectories(sProjectFolder)) { // add the file name to the projects list g_ProjectManager.New(sProjectFile, cmbNewProjectMachine->Text); } else { lblMessage->Caption = "Location is not valid please select a new Location"; lblMessage->Visible = true; } } else { lblMessage->Caption = "A Project file with that Name already exists at the Location"; lblMessage->Visible = true; } } else { lblMessage->Caption = "Location is not valid please select a new Location"; lblMessage->Visible = true; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateOk(void) { cmdCreateProject->Enabled = !edtNewProjectName->Text.Trim().IsEmpty() && !edtNewProjectLocation->Text.Trim().IsEmpty() && -1 != cmbNewProjectMachine->ItemIndex; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::GetMachines(void) { cmbNewProjectMachine->Items->Clear(); // read the registry setting and set it to the appropreiate folder String sRegFolder; regScorpio->Read("Plugins", "MachineFolder", sRegFolder); cmbNewProjectMachine->Clear(); cmbNewProjectMachine->ItemIndex = -1; String sPluginsFolder = ExtractFilePath(Application->ExeName) + "Plugins\\_*"; // find the machine specific plugin folders TSearchRec sr; if (0 == FindFirst(sPluginsFolder, faAnyFile, sr)) { do { if ((sr.Attr & faDirectory) == faDirectory) { String sFolder = sr.Name.SubString(2, sr.Name.Length()); cmbNewProjectMachine->Items->Add(sFolder); if (sFolder.LowerCase() == sRegFolder.LowerCase()) { cmbNewProjectMachine->ItemIndex = cmbNewProjectMachine->Items->Count - 1; } } } while(0 == FindNext(sr)); FindClose(sr); } if (cmbNewProjectMachine->ItemIndex == -1 && cmbNewProjectMachine->Items->Count > 0) { cmbNewProjectMachine->ItemIndex = 0; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::GetLocation(void) { String sProjectFolder; if (regScorpio->Read("ProjectFolder", sProjectFolder)) { edtNewProjectLocation->Text = sProjectFolder; } else { edtNewProjectLocation->Text = ExtractFilePath(Application->ExeName) + "Projects\\"; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::FillProjectList(void) { lstProjects->Items->Clear(); g_ProjectManager.GetMRUList(g_mruList, true); if (g_mruList.size()) { // fill the projects list view with the time stamp sorted items for (int i = 0; i < (int)g_mruList.size(); ++i) { TListItem *item = lstProjects->Items->Add(); String sProjectFolder = ExtractFilePath(g_mruList[i].File); sProjectFolder.SetLength(sProjectFolder.Length() - 1); String sFolder = ExtractFileName(sProjectFolder); if (g_mruList[i].Exists) { item->Caption = sFolder; // set the machine name //item->SubItems->Add(g_mruList[i].Machine); item->SubItems->Add(sProjectFolder); item->ImageIndex = -1; int iDate = Now(); if ((int)g_mruList[i].TimeStamp == iDate) { item->SubItems->Add("Today"); } else if ((int)g_mruList[i].TimeStamp == iDate - 1) { item->SubItems->Add("Yesterday"); } else { item->SubItems->Add(g_mruList[i].TimeStamp.FormatString("dddddd")); } } else { item->Caption = sFolder + " (missing)"; // set the machine name item->SubItems->Add("Unknown"); item->SubItems->Add("Unknown"); } } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsChange(TObject *Sender, TListItem *Item, TItemChange Change) { cmdProjectRemove->Visible = lstProjects->ItemIndex != -1; cmdProjectRestore->Visible = lstProjects->ItemIndex != -1; cmdProjectCopy->Visible = lstProjects->ItemIndex != -1; // load the selected file if (lstProjects->ItemIndex != -1 && lstProjects->ItemIndex < (int)g_mruList.size()) { cmdProjectRemove->Top = 47 + ((lstProjects->Selected->Index - lstProjects->TopItem->Index) * 17/*cmdProjectRemove->Height*/); cmdProjectRestore->Top = cmdProjectRemove->Top; cmdProjectCopy->Top = cmdProjectRemove->Top; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsClick(TObject *Sender) { lstProjectsChange(NULL, NULL, TItemChange()); // load the selected file if (lstProjects->ItemIndex != -1 && lstProjects->ItemIndex < (int)g_mruList.size()) { g_ProjectManager.Load(g_mruList[lstProjects->ItemIndex].File); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdBrowseClick(TObject *Sender) { dlgBrowse->DefaultFolder = edtNewProjectLocation->Text; dlgBrowse->Title = "Select Project Folder"; if (dlgBrowse->Execute()) { edtNewProjectLocation->Text = dlgBrowse->FileName; } UpdateOk(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdCleanMissingProjectsClick(TObject *Sender) { g_ProjectManager.GetMRUList(g_mruList, true); if (g_mruList.size()) { // fill the projects list view with the time stamp sorted items for (int i = 0; i < (int)g_mruList.size(); ++i) { String sFile = ExtractFileName(g_mruList[i].File); sFile = ChangeFileExt(sFile, ""); if (false == g_mruList[i].Exists || g_mruList[i].Machine.LowerCase() == "unknown") { regScorpio->ClearValue("MRU", IntToStr(i)); } } } FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFindExecute(TObject *Sender) { TAction* action = dynamic_cast<TAction*>(Sender); if (true == SAFE_PTR(action)) { // send the find message to the active plugin g_PluginManager.NotifyPlugin(TZXN_EDIT_FIND + action->Tag, NULL, 0, 0); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateGUI(void) { // query the active plugin to see what it supports and update the gui bool bEnableFind = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_FIND, NULL, 0, 0); actFind->Enabled = bEnableFind; actFindReplace->Enabled = bEnableFind; actFindNext->Enabled = bEnableFind; actFindPrev->Enabled = bEnableFind; mnuEditFindReplace->Enabled = bEnableFind; bool bEnableCopyCutPaste = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_COPYPASTE, NULL, 0, 0); actEditCopy2->Enabled = bEnableCopyCutPaste; actEditCut2->Enabled = bEnableCopyCutPaste; actEditPaste2->Enabled = bEnableCopyCutPaste; //actEditUndo->Enabled = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_UNDO, NULL, 0, 0); //actEditRedo->Enabled = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_REDO, NULL, 0, 0); //actEditUndoList->Enabled = actEditUndo->Enabled && actEditRedo->Enabled; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::pgcPluginsChange(TObject *Sender) { PostNotifyEvent(m_SwitcherButtons[pgcPlugins->ActivePageIndex].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditDeleteExecute(TObject *Sender) { bool bSendDelToControl = false; String sClass = ActiveControl->ClassName(); TCustomEdit* pEdit = dynamic_cast<TCustomEdit*>(ActiveControl); bSendDelToControl = (true == SAFE_PTR(pEdit) && true == pEdit->Enabled); if (bSendDelToControl) { SendMessage(ActiveControl->Handle, WM_KEYDOWN, VK_DELETE, 0); } else { g_PluginManager.NotifyPlugin(TZX_VERB_DELETE, NULL, 0, 0); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRemoveProjectClick(TObject *Sender) { int iAnswer = 0; Message ( mbtError, "Remove or Delete the project?", "You can choose to Remove or Delete the project from the list", "You can choose to either just Remove the project from the list, " "Delete the project folder entirely or " "Cancel this operation and leave the list unchanged.\n\n" "Click,\n\tDelete\tto Delete the project permanently.\n" "\tRemove\tto just Remove the entry from the list.\n" "\tCancel\tto Cancel this operation and leave the entry in the list.", "Cancel", "Remove", "Delete", iAnswer ); if (iAnswer != 0) { g_ProjectManager.Remove(lstProjects->Items->Item[lstProjects->ItemIndex]->Caption, iAnswer == 2); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRenameProjectClick(TObject *Sender) { if (false == SAFE_PTR(frmRenameProject)) { frmRenameProject = new TfrmRenameProject(NULL); } if (true == SAFE_PTR(frmRenameProject) && lstProjects->ItemIndex != -1) { String sOldName = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (frmRenameProject->Execute(sOldName)) { // rename the project g_ProjectManager.Rename(sOldName, frmRenameProject->edtNewName->Text.Trim()); } SAFE_DELETE(frmRenameProject); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popMRUListPopup(TObject *Sender) { popRemoveProject->Enabled = lstProjects->ItemIndex != -1; popRenameProject->Enabled = lstProjects->ItemIndex != -1; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsColumnClick(TObject *Sender, TListColumn *Column) { static TListColumn *LastColumn = NULL; if (lstProjects->Items->Count) { if (LastColumn) { //LastColumn->ImageIndex = 0; } bool bAscending = g_ProjectManager.SortProjects(Column->Index); //Column->ImageIndex = bAscending ? 2 : 1; LastColumn = Column; FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if (ActiveControl != Sender) { ActiveControl = dynamic_cast<TWinControl*>(Sender); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditCopyExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_COPY, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditCutExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_CUT, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditPasteExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_PASTE, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRestoreProjectClick(TObject *Sender) { String sProject = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (sProject.SubString(sProject.Length() - 9, 10) == " (missing)") { sProject = sProject.SubString(1, sProject.Length() - 10); } g_ProjectManager.Restore(sProject); FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popCopyProjectClick(TObject *Sender) { if (false == SAFE_PTR(frmCopyProject)) { frmCopyProject = new TfrmCopyProject(NULL); } if (true == SAFE_PTR(frmCopyProject) && lstProjects->ItemIndex != -1) { String sOldName = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (frmCopyProject->Execute(sOldName)) { // rename the project g_ProjectManager.Copy(sOldName, frmCopyProject->edtNewName->Text.Trim()); } SAFE_DELETE(frmCopyProject); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsKeyPress(TObject *Sender, char &Key) { if (Key == VK_RETURN && lstProjects->ItemIndex != -1) { lstProjectsClick(NULL); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actRunExecute(TObject *Sender) { // send play message g_PluginManager.Notify(NULL, TZXN_GAME_PLAY, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::Registration(void) { /*const int cVersion = 0x1350; int iVersion = cVersion; bool bState = false; regScorpio->Read("States", "Registered" , bState); regScorpio->Read("States", "RegisteredVersion" , iVersion); if (!bState || iVersion != cVersion) { regScorpio->Write("States", "Registered", true); regScorpio->Write("States", "RegisteredVersion", cVersion); new TRegistrationThread(IdSMTP1, IdMessage1); }*/ } //---------------------------------------------------------------------------
37.171144
164
0.530048
tonyt73
3779477a90842c9ea994f741358951e2e030df74
105
hpp
C++
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
935
2018-05-23T14:56:18.000Z
2022-03-29T07:27:20.000Z
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
314
2018-05-04T15:58:06.000Z
2022-03-30T16:24:17.000Z
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
65
2019-04-21T14:26:51.000Z
2022-03-12T03:16:41.000Z
#pragma once namespace thor { void initializeTimers(); void initTimerOnThisCpu(); } // namespace thor
11.666667
26
0.742857
kITerE
377c25f611fb8ce80317421179313c9ea52cc430
1,956
cpp
C++
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include <sys/utsname.h> #include <string> #include <vector> #include <any> using namespace std; typedef unsigned short int ushort; void run(vector<string>); utsname getUname() { utsname uts; if (uname(&uts) < 0) throw "uname() failed"; return uts; } int main(int argc, char** argv){ vector<string> args; for(int i = 0; i < argc; ++i) args.push_back(string(argv[i])); try { run(args); } catch (string errorMessage){ perror(errorMessage.c_str()); return 1; } catch (any error) { return 1; } return 0; } void run(vector<string> args) { utsname uts = getUname(); bool flag_s = args.size() == 1; bool flag_n = false; bool flag_r = false; bool flag_m = false; if (args.size() > 1) { for (ushort i = 1u; i < args.size(); ++i) { if (args[i][0] == '-') { for (ushort j = 1u; j < args[i].length(); ++j) { switch (args[i][j]) { case 's': flag_s = true; break; case 'n': flag_n = true; break; case 'r': flag_r = true; break; case 'm': flag_m = true; break; case 'a': flag_s = flag_n = flag_r = flag_m = true; break; } } } } } if (!flag_s && !flag_n && !flag_r && !flag_m) flag_s = true; if (flag_s) printf("%s ", uts.sysname); if (flag_n) printf("%s ", uts.nodename); if (flag_r) printf("%s ", uts.release); if (flag_m) printf("%s ", uts.machine); printf("\n"); return void(); }
26.794521
69
0.416155
Marc-JB
3780ccd6e1370bf0a3ac7d3677c50f0c0d0e0db2
2,000
cpp
C++
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
#include "gkpch.h" #include "Input.h" #include "Window.h" namespace Gecko { void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods); void cursor_position_callback(GLFWwindow *window, double xpos, double ypos); void mouse_button_callback(GLFWwindow *window, int button, int action, int mods); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); Window::Window(const std::string t, int w, int h) : m_Title(t), m_Width(w), m_Height(h) { if (!glfwInit()) { glfwTerminate(); GK_LOG(GK_ERROR) << "Failed to initialize GLFW!\n"; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif m_GLFWWindow = glfwCreateWindow(m_Width, m_Height, m_Title.c_str(), NULL, NULL); if (m_GLFWWindow == nullptr) { glfwTerminate(); GK_LOG(GK_ERROR) << "Failed to create GLFWWindow!\n"; } glfwMakeContextCurrent(m_GLFWWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { GK_LOG(GK_ERROR) << "Failed to initialize GLAD!\n"; } glfwSwapInterval(1); glfwSetKeyCallback(m_GLFWWindow, key_callback); glfwSetCursorPosCallback(m_GLFWWindow, cursor_position_callback); glfwSetMouseButtonCallback(m_GLFWWindow, mouse_button_callback); glfwSetScrollCallback(m_GLFWWindow, scroll_callback); } void Window::Update() { glfwPollEvents(); glfwGetWindowSize(m_GLFWWindow, &m_Width, &m_Height); glfwSwapBuffers(m_GLFWWindow); } void Window::Clean() { glfwDestroyWindow(m_GLFWWindow); glfwTerminate(); } Window::~Window() { Clean(); } } // namespace Gecko
32.258065
88
0.6525
Liamcreed
3786ccf7530bb04fb445a71d1f144c15e5628757
11,406
cpp
C++
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "stdafx.h" #include "NetworkSystem.h" #include "Peer.h" #include "Stream.h" #include "Memory/Allocators.h" #include "Util/Environment.h" #include "Util/Logger.h" #include "Util/_String.h" #include "Network/Messages/ConnectionRequestAccepted.h" #include "Network/Messages/PingResponse.h" #include "Network/Messages/ConnectionLost.h" using namespace Teardrop; using namespace Integration; Raknet::System::System(int maxIncomingConnections, short listenPort) : mMe(0) , mGuid(0) { mMaxIncomingConnections = maxIncomingConnections; mListenPort = listenPort; } Raknet::System::~System() { } Allocator* Raknet::System::s_pAllocator = TD_GET_ALLOCATOR(DEFAULT); void* Raknet::System::malloc(size_t sz) { return s_pAllocator->Allocate(sz TD_ALLOC_SITE); } void* Raknet::System::realloc(void* pMem, size_t sz) { return s_pAllocator->Reallocate(pMem, sz TD_ALLOC_SITE); } void Raknet::System::free(void* pMem) { return s_pAllocator->Deallocate(pMem); } void Raknet::System::setAllocator(Allocator* pAlloc) { assert(pAlloc); s_pAllocator = pAlloc; } Allocator* Raknet::System::getAllocator() { return s_pAllocator; } void Raknet::System::getTypes(Type* typeArray, int& typeCount) { if (typeCount < 1) { typeCount = 0; return; // TODO: throw? } typeArray[0] = System::SYSTEM_NETWORK; typeCount = 1; } Net::Message* Raknet::System::createMessage(unsigned char msgId) { // for now, the TD msg ID is still an unsigned char (tho this // is likely to change once we get lots of messages) if (s_factory[msgId]) return s_factory[msgId](); return 0; } unsigned long long Raknet::System::getTime() { return RakNet::GetTime(); } bool Raknet::System::connect(const String& address, unsigned short port) { return mMe->Connect(address, port, 0, 0); } Teardrop::Net::Peer* Raknet::System::createPeer(Net::Message& msg) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(msg.m_pPeer); return new Raknet::Peer(pPeer->mGuid); } void Raknet::System::destroyPeer(Teardrop::Net::Peer* pPeer) { delete pPeer; } Net::MessagePtr Raknet::System::getNextMessage() { Net::MessagePtr pMsg; Packet* pPacket = mMe->Receive(); // we only want to deal with TD messages here -- system/API messages // should be dealt with in a different path if (pPacket) { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Incoming packet: id=%d, len=%d", pPacket->data[0], pPacket->length); Environment::get().pLogger->logMessage(buf); #endif Raknet::Stream bs(pPacket->data, pPacket->length, false); // connected messages need to have their remote endpoint information set up bool bIsConnected = false; switch (pPacket->data[0]) { // disconnected connection request, no guid or systemaddr available case ID_NEW_INCOMING_CONNECTION: Environment::get().pLogger->logMessage("\nNEW INCOMING CONNECTION\n"); break; // Non-system/control messages have their message ID in the second byte case ID_USER_PACKET_ENUM+1: pMsg = createMessage(pPacket->data[1]); if (pMsg) { pMsg->deserialize(bs); bIsConnected = true; } break; // disconnected ping response, no guid or systemaddr available case ID_PONG: pMsg = TD_NEW Net::PingResponse; pMsg->deserialize(bs); break; // we sent out a connect request, and the other end replied in the affirmative; // this is where we set up the ID info for "the other guy", which should be extracted // by whoever processes this message and stored for later use in sending messages // to this remote endpoint case ID_CONNECTION_REQUEST_ACCEPTED: pMsg = TD_NEW Net::ConnectionRequestAccepted; pMsg->deserialize(bs); bIsConnected = true; break; // connected disconnect notice, we need to case ID_CONNECTION_LOST: case ID_DISCONNECTION_NOTIFICATION: pMsg = TD_NEW Net::ConnectionLost; pMsg->deserialize(bs); bIsConnected = true; break; } if (bIsConnected) { pMsg->m_pPeer = TD_NEW Raknet::Peer(pPacket->guid, pPacket->systemAddress); } } return pMsg; } // broadcast to all peers void Raknet::System::send(Net::Message& msg) { SystemAddress dest; Raknet::Stream bs; msg.serialize(bs); #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet (broadcast): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, true); } // send to single peer void Raknet::System::send(Net::Message& msg, Teardrop::Net::Peer* pRecipient) { Raknet::Stream bs; msg.serialize(bs); Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pRecipient); SystemAddress dest; if (pPeer) dest = mMe->GetSystemAddressFromGuid(pPeer->mGuid); else { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Failed to send outgoing packet (null recipient): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif return; } #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet: id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, false); } // send to multiple peers void Raknet::System::send(Net::Message& msg, Teardrop::Net::Peer** pRecipients, int nRecipients) { Raknet::Stream bs; msg.serialize(bs); for (int i=0; i<nRecipients; ++i) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pRecipients[i]); SystemAddress dest; if (pPeer) dest = mMe->GetSystemAddressFromGuid(pPeer->mGuid); else { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Failed to send outgoing packet (null recipient): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif return; } #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet: id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, false); } } void Raknet::System::disconnect(Net::Peer* pPeer) { // sending a zero to this method means disconnect ourselves if (pPeer) { Raknet::Peer* pP = static_cast<Raknet::Peer*>(pPeer); mMe->CloseConnection(pP->mAddr, true, 0, HIGH_PRIORITY); } //else // m_pPeer->CloseConnection(UNASSIGNED_SYSTEM_ADDRESS, true, 0, HIGH_PRIORITY); Sleep(500); } void Raknet::System::disconnect(unsigned int addr, unsigned short port) { mMe->CloseConnection( SystemAddress(addr, port), true, 0, HIGH_PRIORITY); Sleep(500); } // for unconnected systems (i.e servers in a server list) void Raknet::System::ping(const char* addr, unsigned short port) { mMe->Ping(addr, port, false); } void Raknet::System::setDisconnectedPingResponse(const char *data, unsigned int dataSize) { mMe->SetOfflinePingResponse(data, dataSize); } // for unconnected systems (i.e available servers on the LAN) void Raknet::System::requestServerInfo(const char* addr) { //InterrogateServer msg; //send(&msg, addr, PORT_GAME_SERVER_CLIENT_LISTENER); } bool Raknet::System::isLocalOrigination(Net::Message* pMsg) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pMsg->m_pPeer); return (mMe->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) == pPeer->mGuid); } unsigned int Raknet::System::getLocalIpV4() { const char * localIp = mMe->GetLocalIP(0); unsigned char ip[4]; unsigned int a, b, c, d; sscanf_s(localIp, "%d.%d.%d.%d", &a, &b, &c, &d); ip[0] = d; ip[1] = c; ip[2] = b; ip[3] = a; return *((unsigned int*)ip); } #include "Network/Messages/Advertise.h" #include "Network/Messages/Unadvertise.h" #include "Network/Messages/PlayerJoinServer.h" #include "Network/Messages/PlayerLeaveServer.h" #include "Network/Messages/PlayerJoinGame.h" #include "Network/Messages/PlayerLeaveGame.h" #include "Network/Messages/UpdateServerState.h" #include "Network/Messages/UpdatePlayerState.h" #include "Network/Messages/GameStarted.h" #include "Network/Messages/GameEnded.h" #include "Network/Messages/PlayerPositionSync.h" #include "Network/Messages/PlayerCommand.h" #include "Network/Messages/InterrogateServer.h" #include "Network/Messages/QueryIFF.h" #include "Network/Messages/ResponseIFF.h" #include "Network/Messages/PlayerEntityVariantChanged.h" #include "RakMemoryOverride.h" #include "PacketLogger.h" class MyLogger : public PacketLogger { public: void WriteLog(const char* msg) { #if defined(_DEBUG) Teardrop::Environment::get().pLogger->logMessage(msg); #endif } }; MyLogger s_logger; using namespace Teardrop::Net; using namespace Raknet; void Raknet::System::initialize() { rakMalloc = Raknet::System::malloc; rakRealloc = Raknet::System::realloc; rakFree = Raknet::System::free; Advertise _a; Unadvertise _u; PlayerJoinServer _pjs; PlayerLeaveServer _pls; PlayerJoinGame _pjg; PlayerLeaveGame _plg; UpdatePlayerState _ups; UpdateServerState _uss; GameStarted _gs; GameEnded _ge; PlayerPositionSync _pps; PlayerCommand _pc; InterrogateServer _ic; QueryIFF _qi; ResponseIFF _ri; PlayerVariantChanged _pvc; // initialize Raknet mMe = RakNetworkFactory::GetRakPeerInterface(); mMe->AttachPlugin(&s_logger); // for now, prevent ping responses entirely (server can reset this later) mMe->SetOfflinePingResponse(0, 0); // startup our peer -- we talk to the master server as well as // game clients through this peer, so make enough to go around SocketDescriptor desc(mListenPort, 0); bool rtn = mMe->Startup(mMaxIncomingConnections, 30, &desc, 1); if (rtn && mMaxIncomingConnections > 2) { mMe->SetMaximumIncomingConnections(mMaxIncomingConnections); } // set our guid and address members mGuid = new RakNetGUID; *mGuid = mMe->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); } void Raknet::System::shutdown() { delete mGuid; mGuid = 0; mMe->Shutdown(300); RakNetworkFactory::DestroyRakPeerInterface(mMe); mMe = 0; }
26.711944
131
0.722865
nbtdev
3787b2e14e8aec29261c5661003b1b503ecae611
5,587
cpp
C++
basic_calculator_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
basic_calculator_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
basic_calculator_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/basic-calculator-ii/ #include <string> #include <vector> #include <limits> #include "utils.h" namespace basic_calculator_2 { class Solution { public: // Note: The expression must be valid and contain only the following // characters: '0'-'9', '+', '-', '*', '/', ' '. For an empty expression, // returns 0. // // Time: O(n), Space: O(n), n - number of characters // int run(const std::string& s) { if (!s.size()) return 0; struct Operation { int left_operand; char type; }; std::vector<Operation> operations; auto i = s.cbegin(); const auto end = s.cend(); while (i != end) { Operation op; op.left_operand = readOperand(i, end); op.type = readOperator(i, end); while (operations.size()) { const Operation& op_last = operations.back(); if (getOperationPriority(op_last.type) >= getOperationPriority(op.type)) { op.left_operand = doOperation(op_last.type, op_last.left_operand, op.left_operand); operations.pop_back(); } else { break; } } operations.push_back(op); } assert(operations.size() == 1); const Operation& result = operations.front(); return result.left_operand; } private: int readOperand(std::string::const_iterator& begin, const std::string::const_iterator& end) const { std::string s; for (; begin != end; begin++) { const char c = *begin; if (std::isspace(c)) { if (!s.size()) continue; break; } if (!std::isdigit(c)) break; s += c; } return std::atoi(s.c_str()); } char readOperator(std::string::const_iterator& begin, const std::string::const_iterator& end) const { while (begin != end) { const char c = *(begin++); if (std::isspace(c)) continue; return c; } return 0; } int doOperation(char operation, int operand1, int operand2) const { switch (operation) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': return operand1 / operand2; } return operand1; } int getOperationPriority(char operation) const { switch (operation) { case '+': case '-': return 1; case '*': case '/': return 2; } return 0; } }; int main() { ASSERT( Solution().run("") == 0 ); ASSERT( Solution().run("0") == 0 ); ASSERT( Solution().run("1") == 1 ); ASSERT( Solution().run("123") == 123 ); ASSERT( Solution().run("0+1") == 1 ); ASSERT( Solution().run("1+0") == 1 ); ASSERT( Solution().run("1+1") == 2 ); ASSERT( Solution().run("1+2") == 3 ); ASSERT( Solution().run("1+10") == 11 ); ASSERT( Solution().run("10+1") == 11 ); ASSERT( Solution().run("0-1") == -1 ); ASSERT( Solution().run("1-0") == 1 ); ASSERT( Solution().run("1-1") == 0 ); ASSERT( Solution().run("1-2") == -1 ); ASSERT( Solution().run("10-1") == 9 ); ASSERT( Solution().run("1-10") == -9 ); ASSERT( Solution().run("0*1") == 0 ); ASSERT( Solution().run("1*0") == 0 ); ASSERT( Solution().run("1*1") == 1 ); ASSERT( Solution().run("1*2") == 2 ); ASSERT( Solution().run("2*1") == 2 ); ASSERT( Solution().run("10*1") == 10 ); ASSERT( Solution().run("0/1") == 0 ); ASSERT( Solution().run("1/1") == 1 ); ASSERT( Solution().run("1/2") == 0 ); ASSERT( Solution().run("2/1") == 2 ); ASSERT( Solution().run("10/1") == 10 ); ASSERT( Solution().run("1+2-3") == 0 ); ASSERT( Solution().run("2-3+1") == 0 ); ASSERT( Solution().run("1+2*3") == 7 ); ASSERT( Solution().run("2*3+1") == 7 ); ASSERT( Solution().run("4+4/2") == 6 ); ASSERT( Solution().run("4/2+4") == 6 ); ASSERT( Solution().run("1-2*3") == -5 ); ASSERT( Solution().run("2*3-1") == 5 ); ASSERT( Solution().run("4-4/2") == 2 ); ASSERT( Solution().run("4/2-4") == -2 ); ASSERT( Solution().run("2*8/4") == 4 ); ASSERT( Solution().run("8/4*2") == 4 ); ASSERT( Solution().run("1+2*8/4-2") == 3 ); ASSERT( Solution().run(" ") == 0 ); ASSERT( Solution().run(" ") == 0 ); ASSERT( Solution().run("1 ") == 1 ); ASSERT( Solution().run(" 1") == 1 ); ASSERT( Solution().run(" 1 ") == 1 ); ASSERT( Solution().run(" 1 + 2 ") == 3 ); ASSERT( Solution().run(" 1 + 2 ") == 3 ); const int MAX = std::numeric_limits<int>::max(); const std::string MAX_STR = std::to_string(MAX); ASSERT( Solution().run(MAX_STR) == MAX ); ASSERT( Solution().run(MAX_STR + "+0") == MAX ); ASSERT( Solution().run(MAX_STR + "-0") == MAX ); ASSERT( Solution().run(MAX_STR + "*0") == 0 ); ASSERT( Solution().run(MAX_STR + "*1") == MAX ); ASSERT( Solution().run(MAX_STR + "/1") == MAX ); ASSERT( Solution().run(MAX_STR + "-1") == MAX-1 ); ASSERT( Solution().run(MAX_STR + "/2") == MAX/2 ); ASSERT( Solution().run(MAX_STR + "-" + MAX_STR) == 0 ); ASSERT( Solution().run(MAX_STR + "/" + MAX_STR) == 1 ); return 0; } }
29.098958
103
0.488992
artureganyan
3788fe0530bfedf4b2e6bad1f465723806fc3ce3
479
cpp
C++
HASInheritance/HASInheritance.cpp
100dlswjd/Cpp_study
0165bd0421ec8e4f86e72aa5bda847fb5c3f5cfb
[ "MIT" ]
1
2022-01-25T10:43:25.000Z
2022-01-25T10:43:25.000Z
HASInheritance/HASInheritance.cpp
100dlswjd/Cpp_study
0165bd0421ec8e4f86e72aa5bda847fb5c3f5cfb
[ "MIT" ]
null
null
null
HASInheritance/HASInheritance.cpp
100dlswjd/Cpp_study
0165bd0421ec8e4f86e72aa5bda847fb5c3f5cfb
[ "MIT" ]
1
2021-07-18T18:05:45.000Z
2021-07-18T18:05:45.000Z
#include<iostream> #include<cstring> class Gun { private: int bullet; public: Gun(int bnum) : bullet(bnum) { } void Shot() { std::cout << "BBANG!" << std::endl; bullet--; } }; class Police : public Gun { private: int handcuffs; public: Police(int bnum, int bcuff) : Gun(bnum), handcuffs(bcuff) { } void PutHandcuff() { std::cout << "SNAP!" << std::endl; handcuffs--; } }; int main(void) { Police pman(5, 3); pman.Shot(); pman.PutHandcuff(); return 0; }
12.605263
58
0.613779
100dlswjd
378971e99a6f2f5ed67bb9bedf76c75a656ef0f4
21,041
cc
C++
aeh/src/imgui_sdl_binding.cc
asielorz/aeh
6dbcce0970a558fb7f164b8880a3e834f9f6c8c9
[ "MIT" ]
null
null
null
aeh/src/imgui_sdl_binding.cc
asielorz/aeh
6dbcce0970a558fb7f164b8880a3e834f9f6c8c9
[ "MIT" ]
null
null
null
aeh/src/imgui_sdl_binding.cc
asielorz/aeh
6dbcce0970a558fb7f164b8880a3e834f9f6c8c9
[ "MIT" ]
null
null
null
#if defined AEH_WITH_SDL2 && defined AEH_WITH_IMGUI #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #ifdef _MSC_VER #pragma warning(disable : 4121) // alignment of a member was sensitive to packing #endif #include "imgui_sdl_binding.hh" #include <imgui.h> // SDL,GL3W #include <SDL.h> #include <SDL_syswm.h> #include <gl/gl_core_4_5.hh> // This example is using gl3w to access OpenGL functions (because it is small). You may use glew/glad/glLoadGen/etc. whatever already works for you. namespace aeh::ImGui_SDL { // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. // If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void RenderDrawData(Renderer const & renderer, ImDrawData * draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) ImGuiIO & io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Backup GL state GLenum last_active_texture; gl::GetIntegerv(gl::ACTIVE_TEXTURE, (GLint *)&last_active_texture); gl::ActiveTexture(gl::TEXTURE0); GLint last_program; gl::GetIntegerv(gl::CURRENT_PROGRAM, &last_program); GLint last_texture; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture); GLint last_sampler; gl::GetIntegerv(gl::SAMPLER_BINDING, &last_sampler); GLint last_array_buffer; gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_polygon_mode[2]; gl::GetIntegerv(gl::POLYGON_MODE, last_polygon_mode); GLint last_viewport[4]; gl::GetIntegerv(gl::VIEWPORT, last_viewport); GLint last_scissor_box[4]; gl::GetIntegerv(gl::SCISSOR_BOX, last_scissor_box); GLenum last_blend_src_rgb; gl::GetIntegerv(gl::BLEND_SRC_RGB, (GLint *)&last_blend_src_rgb); GLenum last_blend_dst_rgb; gl::GetIntegerv(gl::BLEND_DST_RGB, (GLint *)&last_blend_dst_rgb); GLenum last_blend_src_alpha; gl::GetIntegerv(gl::BLEND_SRC_ALPHA, (GLint *)&last_blend_src_alpha); GLenum last_blend_dst_alpha; gl::GetIntegerv(gl::BLEND_DST_ALPHA, (GLint *)&last_blend_dst_alpha); GLenum last_blend_equation_rgb; gl::GetIntegerv(gl::BLEND_EQUATION_RGB, (GLint *)&last_blend_equation_rgb); GLenum last_blend_equation_alpha; gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, (GLint *)&last_blend_equation_alpha); GLboolean last_enable_blend = gl::IsEnabled(gl::BLEND); GLboolean last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE); GLboolean last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST); GLboolean last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill gl::Enable(gl::BLEND); gl::BlendEquation(gl::FUNC_ADD); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); gl::Disable(gl::CULL_FACE); gl::Disable(gl::DEPTH_TEST); gl::Enable(gl::SCISSOR_TEST); gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL); // Setup viewport, orthographic projection matrix gl::Viewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const float ortho_projection[4][4] = { { 2.0f / io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / -io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, {-1.0f, 1.0f, 0.0f, 1.0f }, }; gl::UseProgram(renderer.ShaderHandle); gl::Uniform1i(renderer.AttribLocationTex, 0); gl::UniformMatrix4fv(renderer.AttribLocationProjMtx, 1, gl::FALSE_, &ortho_projection[0][0]); gl::BindSampler(0, 0); // Rely on combined texture/sampler state. // Recreate the VAO every time // (This is to easily allow multiple GL contexts. VAO are not shared among GL contexts, and we don't track creation/deletion of windows so we don't have an obvious key to use to cache them.) GLuint vao_handle = 0; gl::GenVertexArrays(1, &vao_handle); gl::BindVertexArray(vao_handle); gl::BindBuffer(gl::ARRAY_BUFFER, renderer.VboHandle); gl::EnableVertexAttribArray(renderer.AttribLocationPosition); gl::EnableVertexAttribArray(renderer.AttribLocationUV); gl::EnableVertexAttribArray(renderer.AttribLocationColor); gl::VertexAttribPointer(renderer.AttribLocationPosition, 2, gl::FLOAT, gl::FALSE_, sizeof(ImDrawVert), (GLvoid *)IM_OFFSETOF(ImDrawVert, pos)); gl::VertexAttribPointer(renderer.AttribLocationUV, 2, gl::FLOAT, gl::FALSE_, sizeof(ImDrawVert), (GLvoid *)IM_OFFSETOF(ImDrawVert, uv)); gl::VertexAttribPointer(renderer.AttribLocationColor, 4, gl::UNSIGNED_BYTE, gl::TRUE_, sizeof(ImDrawVert), (GLvoid *)IM_OFFSETOF(ImDrawVert, col)); // Draw for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList * cmd_list = draw_data->CmdLists[n]; const ImDrawIdx * idx_buffer_offset = 0; gl::BindBuffer(gl::ARRAY_BUFFER, renderer.VboHandle); gl::BufferData(gl::ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid *)cmd_list->VtxBuffer.Data, gl::STREAM_DRAW); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, renderer.ElementsHandle); gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid *)cmd_list->IdxBuffer.Data, gl::STREAM_DRAW); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd * pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { gl::BindTexture(gl::TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); gl::Scissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); gl::DrawElements(gl::TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? gl::UNSIGNED_SHORT : gl::UNSIGNED_INT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } gl::DeleteVertexArrays(1, &vao_handle); // Restore modified GL state gl::UseProgram(last_program); gl::BindTexture(gl::TEXTURE_2D, last_texture); gl::BindSampler(0, last_sampler); gl::ActiveTexture(last_active_texture); gl::BindVertexArray(last_vertex_array); gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer); gl::BlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); gl::BlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); if (last_enable_blend) gl::Enable(gl::BLEND); else gl::Disable(gl::BLEND); if (last_enable_cull_face) gl::Enable(gl::CULL_FACE); else gl::Disable(gl::CULL_FACE); if (last_enable_depth_test) gl::Enable(gl::DEPTH_TEST); else gl::Disable(gl::DEPTH_TEST); if (last_enable_scissor_test) gl::Enable(gl::SCISSOR_TEST); else gl::Disable(gl::SCISSOR_TEST); gl::PolygonMode(gl::FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); gl::Viewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); gl::Scissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); } static const char * GetClipboardText(void *) { return SDL_GetClipboardText(); } static void SetClipboardText(void *, const char * text) { SDL_SetClipboardText(text); } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. bool ProcessEvent(Renderer & renderer, SDL_Event const * event) { ImGuiIO & io = ImGui::GetIO(); switch (event->type) { case SDL_MOUSEWHEEL: { if (event->wheel.x > 0) io.MouseWheelH += 1; if (event->wheel.x < 0) io.MouseWheelH -= 1; if (event->wheel.y > 0) io.MouseWheel += 1; if (event->wheel.y < 0) io.MouseWheel -= 1; return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) renderer.MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) renderer.MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) renderer.MousePressed[2] = true; return true; } case SDL_TEXTINPUT: { io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { int key = event->key.keysym.scancode; IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown)); io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); return true; } } return false; } void CreateFontsTexture(Renderer & renderer) { // Build texture atlas ImGuiIO & io = ImGui::GetIO(); unsigned char * pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // Upload texture to graphics system GLint last_texture; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture); gl::GenTextures(1, &renderer.FontTexture); gl::BindTexture(gl::TEXTURE_2D, renderer.FontTexture); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR); gl::PixelStorei(gl::UNPACK_ROW_LENGTH, 0); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA, width, height, 0, gl::RGBA, gl::UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)renderer.FontTexture; // Restore state gl::BindTexture(gl::TEXTURE_2D, last_texture); } void RefreshFontsTexture(Renderer & renderer) { if (!HasDeviceObjects(renderer)) { // No device objects them. Create them. CreateDeviceObjects(renderer); } else { // Already has device objecs. Just reset the font texture. InvalidateFontsTexture(renderer); CreateFontsTexture(renderer); } } bool CreateDeviceObjects(Renderer & renderer) { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture); gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer); gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar * vertex_shader = "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 FraUV;\n" "out vec4 FraColor;\n" "void main()\n" "{\n" " FraUV = UV;\n" " FraColor = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar * fragment_shader = "uniform sampler2D Texture;\n" "in vec2 FraUV;\n" "in vec4 FraColor;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = FraColor * texture( Texture, FraUV.st);\n" "}\n"; GLchar const * vertex_shader_with_version[2] = { renderer.GlslVersion, vertex_shader }; GLchar const * fragment_shader_with_version[2] = { renderer.GlslVersion, fragment_shader }; renderer.ShaderHandle = gl::CreateProgram(); renderer.VertHandle = gl::CreateShader(gl::VERTEX_SHADER); renderer.FragHandle = gl::CreateShader(gl::FRAGMENT_SHADER); gl::ShaderSource(renderer.VertHandle, 2, vertex_shader_with_version, NULL); gl::ShaderSource(renderer.FragHandle, 2, fragment_shader_with_version, NULL); gl::CompileShader(renderer.VertHandle); gl::CompileShader(renderer.FragHandle); gl::AttachShader(renderer.ShaderHandle, renderer.VertHandle); gl::AttachShader(renderer.ShaderHandle, renderer.FragHandle); gl::LinkProgram(renderer.ShaderHandle); renderer.AttribLocationTex = gl::GetUniformLocation(renderer.ShaderHandle, "Texture"); renderer.AttribLocationProjMtx = gl::GetUniformLocation(renderer.ShaderHandle, "ProjMtx"); renderer.AttribLocationPosition = gl::GetAttribLocation(renderer.ShaderHandle, "Position"); renderer.AttribLocationUV = gl::GetAttribLocation(renderer.ShaderHandle, "UV"); renderer.AttribLocationColor = gl::GetAttribLocation(renderer.ShaderHandle, "Color"); gl::GenBuffers(1, &renderer.VboHandle); gl::GenBuffers(1, &renderer.ElementsHandle); ImGui_SDL::CreateFontsTexture(renderer); // Restore modified GL state gl::BindTexture(gl::TEXTURE_2D, last_texture); gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer); gl::BindVertexArray(last_vertex_array); return true; } void InvalidateFontsTexture(Renderer & renderer) { if (renderer.FontTexture) { gl::DeleteTextures(1, &renderer.FontTexture); ImGui::GetIO().Fonts->TexID = 0; renderer.FontTexture = 0; } } void InvalidateDeviceObjects(Renderer & renderer) { if (renderer.VboHandle) gl::DeleteBuffers(1, &renderer.VboHandle); if (renderer.ElementsHandle) gl::DeleteBuffers(1, &renderer.ElementsHandle); renderer.VboHandle = renderer.ElementsHandle = 0; if (renderer.ShaderHandle && renderer.VertHandle) gl::DetachShader(renderer.ShaderHandle, renderer.VertHandle); if (renderer.VertHandle) gl::DeleteShader(renderer.VertHandle); renderer.VertHandle = 0; if (renderer.ShaderHandle && renderer.FragHandle) gl::DetachShader(renderer.ShaderHandle, renderer.FragHandle); if (renderer.FragHandle) gl::DeleteShader(renderer.FragHandle); renderer.FragHandle = 0; if (renderer.ShaderHandle) gl::DeleteProgram(renderer.ShaderHandle); renderer.ShaderHandle = 0; InvalidateFontsTexture(renderer); } bool HasDeviceObjects(Renderer const & renderer) { return renderer.ShaderHandle != 0; } bool Init(Renderer & renderer, SDL_Window * window, const char * glsl_version) { // Store GL version string so we can refer to it later in case we recreate shaders. if (glsl_version == NULL) glsl_version = "#version 150"; IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(renderer.GlslVersion)); strcpy(renderer.GlslVersion, glsl_version); strcat(renderer.GlslVersion, "\n"); // Setup back-end capabilities flags ImGuiIO & io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT; io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE; io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V; io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X; io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y; io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z; io.SetClipboardTextFn = ImGui_SDL::SetClipboardText; io.GetClipboardTextFn = ImGui_SDL::GetClipboardText; io.ClipboardUserData = NULL; renderer.MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); renderer.MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); renderer.MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); renderer.MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); renderer.MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); renderer.MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); renderer.MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); #ifdef _WIN32 SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); io.ImeWindowHandle = wmInfo.info.win.window; #else (void)window; #endif return true; } void Shutdown(Renderer & renderer) { // Destroy SDL mouse cursors for (SDL_Cursor * const cursor : renderer.MouseCursors) SDL_FreeCursor(cursor); memset(renderer.MouseCursors, 0, sizeof(renderer.MouseCursors)); // Destroy OpenGL objects ImGui_SDL::InvalidateDeviceObjects(renderer); } void NewFrame(Renderer & renderer, SDL_Window * window) { if (!HasDeviceObjects(renderer)) ImGui_SDL::CreateDeviceObjects(renderer); ImGuiIO & io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = renderer.Time > 0 ? (float)((double)(current_time - renderer.Time) / frequency) : (float)(1.0f / 60.0f); renderer.Time = current_time; // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler) int mx, my; Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my); io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); io.MouseDown[0] = renderer.MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = renderer.MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = renderer.MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; renderer.MousePressed[0] = renderer.MousePressed[1] = renderer.MousePressed[2] = false; // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016) #if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4) if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0) io.MousePos = ImVec2((float)mx, (float)my); bool any_mouse_button_down = false; for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++) any_mouse_button_down |= io.MouseDown[n]; if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0) SDL_CaptureMouse(SDL_TRUE); if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0) SDL_CaptureMouse(SDL_FALSE); #else if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0) io.MousePos = ImVec2((float)mx, (float)my); #endif // Update OS/hardware mouse cursor if imgui isn't drawing a software cursor if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0) { ImGuiMouseCursor cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None) { SDL_ShowCursor(0); } else { SDL_SetCursor(renderer.MouseCursors[cursor] ? renderer.MouseCursors[cursor] : renderer.MouseCursors[ImGuiMouseCursor_Arrow]); SDL_ShowCursor(1); } } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); } } // namespace aeh::ImGui_SDL #endif // AEH_WITH_SDL2 && AEH_WITH_IMGUI
44.111111
244
0.740126
asielorz
378a8d3d6ef3cd2a57365c051682f558de2d86b3
943
cpp
C++
Cpp/68_text_justification/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/68_text_justification/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/68_text_justification/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> res; // num reprents the number of words in every row // cur is the current sum of lengths of added words int num, cur; for (int i = 0; i < words.size(); i += num) { for (num = cur = 0; i + num < words.size() && cur + words[i+num].size() <= maxWidth - num; num ++) cur += words[i+num].size(); string tmp = words[i]; for (int j = 0; j < num - 1; j ++) { if (i + num >= words.size()) tmp += " "; else tmp += string((maxWidth-cur) / (num-1) + (j < (maxWidth-cur) % (num-1)), ' '); tmp += words[i+j+1]; } tmp += string(maxWidth - tmp.size(), ' '); res.push_back(tmp); } return res; } };
34.925926
111
0.435843
zszyellow
378b5453822e8722875760675501fe3bfa67f4fd
463
cpp
C++
chapter-3/Program 3.4.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-3/Program 3.4.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-3/Program 3.4.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
/* write a program that performs LL COMPOUND assignment operations on an integer*/ #include"iostream" #include"conio.h" using namespace std; main() { int a=10; cout<<" Values of a "<<a<<endl; a+=5; cout<<"Values of a+=5 : "<<a<<endl; a-=5; cout<<"Values of a-=5 : "<<a<<endl; a*=2; cout<<"Values of a*=2 : "<<a<<endl; a/=2; cout<<"values of a/=2 : "<<a<<endl; a%=2; cout<<"values of a%=2 : "<<a<<endl; getch(); }
19.291667
69
0.537797
JahanzebNawaz
3795da8821bd6ffe8c5ee2562e4a6098e40ec5dd
2,657
cpp
C++
src/tuning/kernels/invert.cpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/tuning/kernels/invert.cpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/tuning/kernels/invert.cpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file uses the auto-tuner to tune the invert OpenCL kernels. // // ================================================================================================= #include "tuning/kernels/invert.hpp" // Shortcuts to the clblast namespace using half = clblast::half; using float2 = clblast::float2; using double2 = clblast::double2; // Main function (not within the clblast namespace) int main(int argc, char *argv[]) { const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv); switch(clblast::GetPrecision(command_line_args)) { case clblast::Precision::kHalf: clblast::Tuner<half>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<half>, clblast::InvertTestValidArguments<half>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<half>, clblast::InvertSetArguments<half>); break; case clblast::Precision::kSingle: clblast::Tuner<float>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<float>, clblast::InvertTestValidArguments<float>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<float>, clblast::InvertSetArguments<float>); break; case clblast::Precision::kDouble: clblast::Tuner<double>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<double>, clblast::InvertTestValidArguments<double>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<double>, clblast::InvertSetArguments<double>); break; case clblast::Precision::kComplexSingle: clblast::Tuner<float2>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<float2>, clblast::InvertTestValidArguments<float2>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<float2>, clblast::InvertSetArguments<float2>); break; case clblast::Precision::kComplexDouble: clblast::Tuner<double2>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<double2>, clblast::InvertTestValidArguments<double2>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<double2>, clblast::InvertSetArguments<double2>); break; } return 0; } // =================================================================================================
75.914286
324
0.700414
vbkaisetsu
379660dcd5087fcecb1536dbfcc7bc3261befd38
129
hpp
C++
dependencies/glm/gtx/vector_angle.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/glm/gtx/vector_angle.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/glm/gtx/vector_angle.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:03e7fef2ca71e571577cdf63f979796b3db5d2d1dc938db5c767359822f146d4 size 1652
32.25
75
0.883721
realtehcman
379691a259e1f33731f12d3e463e148b22cb7abc
14,463
cpp
C++
sources/DisplayIa.cpp
usernameHed/Worms
35ee28362b936b46d24e7c911a46a2cfd615128b
[ "MIT" ]
null
null
null
sources/DisplayIa.cpp
usernameHed/Worms
35ee28362b936b46d24e7c911a46a2cfd615128b
[ "MIT" ]
null
null
null
sources/DisplayIa.cpp
usernameHed/Worms
35ee28362b936b46d24e7c911a46a2cfd615128b
[ "MIT" ]
null
null
null
#include "Display.hh" #include "AICore.hh" bool Display::iaIsPlaying() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return (false); int idTeam = this->listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->listPlayers[this->gameloop.getWormsPlayer()][1]; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getType() == IA) { //std::cout << "IA PLAY !" << std::endl; return (true); } //std::cout << "player PLAY !" << std::endl; return (false); } void Display::iaExportInfo() { std::cout << "send info to LUA..." << std::endl; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; //int idTeam = this->listPlayers[this->gameloop.getWormsPlayer()][0]; //int idWorms = this->listPlayers[this->gameloop.getWormsPlayer()][1]; AICore ac(*this); //LUARes res; ac.fillArray(); this->iaPlay.setIaMove(ac.executeBrain()); if (this->iaPlay.getIaMove().idWorms == -1) //TODO: IA TIR DIRECT { LUARes tmplua; tmplua.idWorms = 0; tmplua.weaponType = 0; if (!this->gameloop.menuSet) this->affWeaponsHUD(); this->iaPlay.setIaMove(tmplua); } this->iaPlay.setAttack(false); this->iaPlay.reset(); } int Display::sign(int x) const { if (x < 0) return (-1); return 1; } bool Display::testLine(int x1, int y1, int x2, int y2) { int x = x2; int y = y2; int dy = y2 - y1; int dx = x2 - x1; if (std::abs(dy) > std::abs(dx)) { for(y = y1; y != y2; y += this->sign(dy)) { x = x1 + ( y - y1 ) * dx / dy; //this->island.change(x, y, SAND); if (this->island.isDestructible(this->island.getMapping(x, y))) return (false); } } else { for( x = x1; x != x2; x += this->sign(dx)) { y = y1 + ( x - x1 ) * dy / dx; //this->island.change(x, y, SAND); if (this->island.isDestructible(this->island.getMapping(x, y))) return (false); } } if (this->island.isDestructible(this->island.getMapping(x2, y2))) return (false); return (true); } bool Display::testIfToMuchFalling(int x, int y) { /////////////////// don't turn if is falling ! int z = y; while (z + 1 < this->island.getSizeY() - 1 && (!(this->island.isDestructible(this->island.getMapping(x, z))))) { ++z; if (z > this->island.getSizeY() - 5) return (false); } if (z - y >= (this->gameloop.getHeightWorms() * 5) || z > this->island.getSizeY() - 5) { std::cout << "FUCK FUCK FUCK !" << std::endl; return (false); } return (true); } void Display::hideWorms() { std::cout << "hide !" << std::endl; if (!this->checkNbPlayer(this->iaPlay.getIaMove().idWorms)) return; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeamTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][0]; int idWormsTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][1]; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; if ((this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() == DYNAMIT && this->iaPlay.hideHoriz > this->iaPlay.maxHideDynamit) || (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() != DYNAMIT && this->iaPlay.hideHoriz > this->iaPlay.maxHide)) return; this->iaPlay.hideHoriz++; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; int xEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().x; int yEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().y; int right = (x > xEnemy) ? -1 : 1; if (this->testIfToMuchFalling(x, y - right)) this->changeHoriz(x, y, idTeam, idWorms, -right); else this->changeHoriz(x, y, idTeam, idWorms, right); if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() != DYNAMIT) return; if (this->iaPlay.jumpHide < this->iaPlay.jumpHideMax) { std::cout << "jump hide" << std::endl; if (this->jump(x, y, idTeam, idWorms, JUMP_WORMS)) { ++this->iaPlay.jumpHide; } return; } } bool Display::testIsGroundDown(int x, int y) { int z = y; while (z + 1 < this->island.getSizeY() - 2) { if (this->island.isDestructible(this->island.getMapping(x, z))) { std::cout << "ok down" << std::endl; return (true); } ++z; } std::cout << "not ok" << std::endl; return (false); } void Display::iaMoveAfterJump() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; if (this->iaPlay.paraTime >= this->iaPlay.paraTimeMax) return; ++this->iaPlay.paraTime; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) { std::cout << "right" << std::endl; if (this->testIsGroundDown(x + 1, y) && this->testIsGroundDown(x + 2, y) && this->testIsGroundDown(x + 3, y) && this->testIsGroundDown(x + 4, y) && this->testIsGroundDown(x + 5, y) ) this->changeHoriz(x, y, idTeam, idWorms, 1); else this->changeHoriz(x, y, idTeam, idWorms, -1); } else { std::cout << "left" << std::endl; if (this->testIsGroundDown(x - 1, y) && this->testIsGroundDown(x - 2, y) && this->testIsGroundDown(x - 3, y) && this->testIsGroundDown(x - 4, y) && this->testIsGroundDown(x - 5, y) ) this->changeHoriz(x, y, idTeam, idWorms, -1); else this->changeHoriz(x, y, idTeam, idWorms, 1); } } void Display::iaPlaying() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; if (!this->weapons->getCanUsWeapon() && this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() == JUMPTHOUGHTWALL) { this->iaMoveAfterJump(); return; } if (this->iaPlay.getAttack()) { this->hideWorms(); return; } if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getLife().getPv() < 5) { LUARes tmplua; tmplua.idWorms = this->iaPlay.getIaMove().idWorms; tmplua.weaponType = -1; this->iaPlay.setIaMove(tmplua); this->iaNoLoSe(); return; } if (this->iaPlay.getIaMove().weaponType == 0) this->iaCac(); else if (this->iaPlay.getIaMove().weaponType == 1) this->iaDirect(); else if (this->iaPlay.getIaMove().weaponType == 2) this->iaIndirect(); else this->iaNoLoSe(); } void Display::iaJump() { if (!this->weapons->getCanUsWeapon()) return; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(JUMPTHOUGHTWALL); if (!this->gameloop.menuSet) this->affWeaponsHUD(); this->weapons->attack(); } void Display::iaCac() { std::cout << "cac !" << std::endl; std::cout << "attack the worms: " << this->iaPlay.getIaMove().idWorms << std::endl; if (!this->checkNbPlayer(this->iaPlay.getIaMove().idWorms)) return; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeamTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][0]; int idWormsTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][1]; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; int xEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().x; int yEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().y; int right = (x > xEnemy) ? -1 : 1; /*if (std::abs(y - yEnemy) > this->gameloop.getHeightWorms() * 10) { LUARes tmplua; tmplua.idWorms = this->iaPlay.getIaMove().idWorms; tmplua.weaponType = 1; this->iaPlay.setIaMove(tmplua); return; }*/ std::vector<int> wormsHit = this->weapons->getIaHit(x, y, this->gameloop.getWormsPlayer(), right); int i = 0; while (i < wormsHit.size()) { if (!this->checkNbPlayer(wormsHit[i])) { ++i; continue; } int tmpIdTeam = this->gameloop.listPlayers[wormsHit[i]][0]; //if (wormsHit[i] == this->iaPlay.getIaMove().idWorms) if (tmpIdTeam != idTeam) { std::cout << "CAC ATTACK !!" << std::endl; //random CAC ! WeaponsType tmpWeaponType = DYNAMIT; if (this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getLife().getPv() <= 3) tmpWeaponType = FINGER; else if (this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getLife().getPv() <= 25) tmpWeaponType = POUNCH; else if (this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getLife().getPv() <= 30) tmpWeaponType = BASEBALL; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(tmpWeaponType); if (!this->gameloop.menuSet) this->affWeaponsHUD(); if (tmpWeaponType == DYNAMIT) { int tmpRand = std::rand() % 100; if (tmpRand < 5) tmpWeaponType = FINGER; else if (tmpRand < 20) tmpWeaponType = BASEBALL; else if (tmpRand < 70 - ((this->gameloop.difficulty == HARD_GAME) ? ((this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getType() == HUMAN) ? 25 : 0) : 0) ) tmpWeaponType = POUNCH; else { if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) this->dynamity(x + this->gameloop.getWidthWorm(), y); else this->dynamity(x - this->gameloop.getWidthWorm(), y); } } std::cout << "WEAPOIN TYPE: " << tmpWeaponType << std::endl; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(tmpWeaponType); if (!this->gameloop.menuSet) this->affWeaponsHUD(); this->weapons->attack(); ////////////////// this->displayWeaponType(); this->gameloop.setPhase(4); this->gameloop.setWaitTimeAfterAttack(); this->gameloop._debugTimerGame = 0.0; ////////////////// this->iaPlay.setAttack(true); return; } ++i; } int tmpXDebug = x; int tmpYDebug = y; if (!this->testIfToMuchFalling(x, y + right)) { std::cout << "MEGAJUMP ?" << std::endl; if (right > 0 && x > (this->island.getSizeX() / 100) * 70) this->changeHoriz(x, y, idTeam, idWorms, -right); else if (right < 0 && x < (this->island.getSizeX() / 100) * 30) this->changeHoriz(x, y, idTeam, idWorms, -right); this->iaJump(); return; } if (!this->changeHoriz(x, y, idTeam, idWorms, right)) { if (this->iaPlay.jumpFocus < this->iaPlay.jumpFocusMax) { std::cout << "JUMPPPPPPPPPPPPp" << std::endl; if (this->jump(x, y, idTeam, idWorms, JUMP_WORMS)) { ++this->iaPlay.jumpFocus; } return; } this->iaPlay.jumpDebugFocus++; std::cout << "err: " << this->iaPlay.jumpDebugFocus << std::endl; if (this->iaPlay.jumpDebugFocus > this->iaPlay.jumpDebugFocusMax) { LUARes tmplua; tmplua.idWorms = this->iaPlay.getIaMove().idWorms; tmplua.weaponType = -1; this->iaPlay.setIaMove(tmplua); } } /*if (!(tmpXDebug == x && tmpYDebug == y)) { x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; }*/ } void Display::iaDirect() { std::cout << "direct !" << std::endl; } void Display::iaIndirect() { std::cout << "indirect !" << std::endl; } void Display::iaNoLoSe() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; if (this->gameloop.menuSet) return; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(DRILL); if (!this->gameloop.menuSet) this->affWeaponsHUD(); int right = -1; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) right = 1; if (!this->testIfToMuchFalling(x, y + right)) right *= -1; if (this->changeHoriz(x, y, idTeam, idWorms, right)) return; int angleToFind = 140; if (this->iaPlay.angleTmpDrill == -420042) { if (y > this->island.getSizeY() - this->gameloop.getHeightWorms() * 2) angleToFind = 65 - 55 + (rand() % 70); else angleToFind = 140 - 55 + (rand() % 70); this->iaPlay.angleTmpDrill = angleToFind; } else { if (y > this->island.getSizeY() - this->gameloop.getHeightWorms() * 2) this->iaPlay.angleTmpDrill = 65 - 55 + (rand() % 70); //this->iaPlay.angleTmpDrill = this->iaPlay.angleTmpDrill - 5 } if (this->gameloop._tmpAngle != this->iaPlay.angleTmpDrill) { if (this->gameloop._tmpAngle < this->iaPlay.angleTmpDrill) this->weapons->addAngleCursor(-1); else this->weapons->addAngleCursor(1); } else { std::cout << "drill !" << std::endl; bool tmpAdvance = false; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) { if (this->testIfToMuchFalling(x, y + 1)) tmpAdvance = this->changeHoriz(x, y, idTeam, idWorms, 1); } else { if (this->testIfToMuchFalling(x, y - 1)) tmpAdvance = this->changeHoriz(x, y, idTeam, idWorms, -1); } //if (!tmpAdvance) this->actionRepeat(idTeam, idWorms, true); this->actionRepeat(idTeam, idWorms, true); } std::cout << "anglezfc: " << this->gameloop._tmpAngle << std::endl; }
30.194154
175
0.637212
usernameHed
3798209ae059cf42db81e73227fe89d750a5922f
8,860
cpp
C++
LLY/LLY/util/FuncUnitl.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
3
2015-07-04T03:35:51.000Z
2017-09-10T08:23:25.000Z
LLY/LLY/util/FuncUnitl.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
null
null
null
LLY/LLY/util/FuncUnitl.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
null
null
null
#include <glm/gtc/matrix_transform.hpp> #include "FuncUnitl.h" #include <fbxsdk.h> namespace lly_util { GLenum to_usage(lly::VertexUsage usage) { switch (usage) { case lly::VertexUsage::STATIC_DRAW: return GL_STATIC_DRAW; case lly::VertexUsage::STATIC_COPY: return GL_STATIC_COPY; case lly::VertexUsage::STATIC_READ: return GL_STATIC_READ; case lly::VertexUsage::STREAM_DRAW: return GL_STREAM_DRAW; case lly::VertexUsage::STREAM_COPY: return GL_STREAM_COPY; case lly::VertexUsage::STREAM_READ: return GL_STREAM_READ; case lly::VertexUsage::DYNAMIC_DRAW: return GL_DYNAMIC_DRAW; case lly::VertexUsage::DYNAMIC_COPY: return GL_DYNAMIC_COPY; case lly::VertexUsage::DYNAMIC_READ: return GL_DYNAMIC_READ; } return 0; } GLenum to_draw_mode(lly::DrawType mode) { switch (mode) { case lly::DrawType::POINTS: return GL_POINTS; case lly::DrawType::LINE_STRIP: return GL_LINE_STRIP; case lly::DrawType::LINE_LOOP: return GL_LINE_LOOP; case lly::DrawType::LINES: return GL_LINES; case lly::DrawType::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP; case lly::DrawType::TRIANGLE_FAN: return GL_TRIANGLE_FAN; case lly::DrawType::TRIANGLES: return GL_TRIANGLES; case lly::DrawType::QUAD_STRIP: return GL_QUAD_STRIP; case lly::DrawType::QUADS: return GL_QUADS; case lly::DrawType::POLYGON: return GL_POLYGON; } return 0; } GLenum to_color_format(lly::ColorFormat format) { switch (format) { case lly::ColorFormat::BGRA8888: return GL_BGRA; case lly::ColorFormat::RGBA8888: return GL_RGBA; case lly::ColorFormat::RGB888: return GL_RGB; case lly::ColorFormat::RGB565: return GL_RGB565; case lly::ColorFormat::A8: return GL_ALPHA; case lly::ColorFormat::I8: return GL_LUMINANCE; case lly::ColorFormat::AI88: return GL_LUMINANCE_ALPHA; case lly::ColorFormat::RGBA4444: return GL_RGBA; case lly::ColorFormat::RGB5A1: return GL_RGBA; case lly::ColorFormat::RG16: return GL_RG16; case lly::ColorFormat::RG16F: return GL_RG16F; case lly::ColorFormat::R32F: return GL_R32F; case lly::ColorFormat::DEPTH_COMPONENT: return GL_DEPTH_COMPONENT; } return GL_RGBA; } int to_color_bpp(lly::ColorFormat format) { switch (format) { case lly::ColorFormat::BGRA8888: return 32; case lly::ColorFormat::RGBA8888: return 32; case lly::ColorFormat::RG16: return 32; case lly::ColorFormat::RG16F: return 32; case lly::ColorFormat::R32F: return 32; case lly::ColorFormat::RGB888: return 24; case lly::ColorFormat::RGB565: return 16; case lly::ColorFormat::A8: return 8; case lly::ColorFormat::I8: return 8; case lly::ColorFormat::AI88: return 16; case lly::ColorFormat::RGBA4444: return 16; case lly::ColorFormat::RGB5A1: return 16; case lly::ColorFormat::DEPTH_COMPONENT: return 32; } return 32; } GLenum to_color_type(lly::ColorFormat format) { switch (format) { case lly::ColorFormat::BGRA8888: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RGBA8888: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RG16: return GL_UNSIGNED_SHORT; case lly::ColorFormat::RG16F: return GL_HALF_FLOAT; case lly::ColorFormat::R32F: return GL_FLOAT; case lly::ColorFormat::RGB888: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RGB565: return GL_UNSIGNED_SHORT_5_6_5; case lly::ColorFormat::A8: return GL_UNSIGNED_BYTE; case lly::ColorFormat::I8: return GL_UNSIGNED_BYTE; case lly::ColorFormat::AI88: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RGBA4444: return GL_UNSIGNED_SHORT_4_4_4_4; case lly::ColorFormat::RGB5A1: return GL_UNSIGNED_SHORT_5_5_5_1; case lly::ColorFormat::DEPTH_COMPONENT: return GL_FLOAT; } return GL_UNSIGNED_BYTE; } GLenum to_min_filter(lly::TextureMinFilter filter) { return GL_LINEAR; } GLenum to_mag_filter(lly::TextureMagFilter filter) { return GL_LINEAR; } GLuint to_position(lly::VertexAttribPosition position) { switch (position) { case lly::VertexAttribPosition::POSITION: return 0; case lly::VertexAttribPosition::NORMAL: return 1; case lly::VertexAttribPosition::COLOR: return 2; case lly::VertexAttribPosition::TANGENT: return 3; case lly::VertexAttribPosition::TEXCOOD0: return 4; case lly::VertexAttribPosition::TEXCOOD1: return 5; case lly::VertexAttribPosition::TEXCOOD2: return 6; case lly::VertexAttribPosition::TEXCOOD3: return 7; case lly::VertexAttribPosition::TEXCOOD4: return 8; case lly::VertexAttribPosition::TEXCOOD5: return 9; case lly::VertexAttribPosition::TEXCOOD6: return 10; case lly::VertexAttribPosition::TEXCOOD7: return 11; case lly::VertexAttribPosition::WEIGHT0: return 12; case lly::VertexAttribPosition::WEIGHT1: return 13; case lly::VertexAttribPosition::WEIGHT2: return 14; case lly::VertexAttribPosition::WEIGHT3: return 15; } return 0; } GLenum to_data_type(lly::DataType type) { switch (type) { case lly::DataType::BYTE: return GL_BYTE; case lly::DataType::UNSIGNED_BYTE: return GL_UNSIGNED_BYTE; case lly::DataType::SHORT: return GL_SHORT; case lly::DataType::UNSIGNED_SHORT: return GL_UNSIGNED_SHORT; case lly::DataType::FIXED: return GL_FIXED; case lly::DataType::FLOAT: return GL_FLOAT; } return GL_FLOAT; } GLenum to_blend_factor(lly::BlendFactor factor) { switch (factor) { case lly::BlendFactor::DST_ALPHA: return GL_DST_ALPHA; case lly::BlendFactor::DST_COLOR: return GL_DST_COLOR; case lly::BlendFactor::ONE: return GL_ONE; case lly::BlendFactor::ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA; case lly::BlendFactor::ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR; case lly::BlendFactor::ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA; case lly::BlendFactor::SRC_ALPHA: return GL_SRC_ALPHA; case lly::BlendFactor::SRC_ALPHA_SATURATE: return GL_SRC_ALPHA_SATURATE; case lly::BlendFactor::ZERO: return GL_ZERO; } return GL_ZERO; } GLenum to_alpha_test_func(lly::AlphaTestFunc func) { switch (func) { case lly::AlphaTestFunc::ALWAYS: return GL_ALWAYS; case lly::AlphaTestFunc::NEVER: return GL_NEVER; case lly::AlphaTestFunc::LESS: return GL_LESS; case lly::AlphaTestFunc::LEQUAL: return GL_LEQUAL; case lly::AlphaTestFunc::EQUAL: return GL_EQUAL; case lly::AlphaTestFunc::GREATER: return GL_GREATER; case lly::AlphaTestFunc::GEQUAL: return GL_GEQUAL; case lly::AlphaTestFunc::NOTEQUAL: return GL_NOTEQUAL; } return GL_ALWAYS; } GLenum to_depth_func(lly::DepthFunc func) { switch (func) { case lly::DepthFunc::ALWAYS: return GL_ALWAYS; case lly::DepthFunc::NEVER: return GL_NEVER; case lly::DepthFunc::LESS: return GL_LESS; case lly::DepthFunc::LEQUAL: return GL_LEQUAL; case lly::DepthFunc::EQUAL: return GL_EQUAL; case lly::DepthFunc::GREATER: return GL_GREATER; case lly::DepthFunc::GEQUAL: return GL_GEQUAL; case lly::DepthFunc::NOTEQUAL: return GL_NOTEQUAL; } return GL_ALWAYS; } GLenum to_cull_fase_side(lly::CullFaceSide side) { switch (side) { case lly::CullFaceSide::FRONT: return GL_FRONT; case lly::CullFaceSide::BACK: return GL_BACK; } return GL_BACK; } GLenum to_front_face(lly::FrontFace front) { switch (front) { case lly::FrontFace::CCW: return GL_CCW; case lly::FrontFace::CW: return GL_CW; } return GL_CCW; } GLenum to_stencil_func(lly::StencilFuncType func) { switch (func) { case lly::StencilFuncType::ALWAYS: return GL_ALWAYS; case lly::StencilFuncType::NEVER: return GL_NEVER; case lly::StencilFuncType::LESS: return GL_LESS; case lly::StencilFuncType::LEQUAL: return GL_LEQUAL; case lly::StencilFuncType::EQUAL: return GL_EQUAL; case lly::StencilFuncType::GREATER: return GL_GREATER; case lly::StencilFuncType::GEQUAL: return GL_GEQUAL; case lly::StencilFuncType::NOTEQUAL: return GL_NOTEQUAL; } return GL_ALWAYS; } GLenum to_stencil_op(lly::StencilOpType func) { switch (func) { case lly::StencilOpType::KEEP: return GL_KEEP; case lly::StencilOpType::ZERO: return GL_ZERO; case lly::StencilOpType::REPLACE: return GL_REPLACE; case lly::StencilOpType::INCR: return GL_INCR; case lly::StencilOpType::DECR: return GL_DECR; case lly::StencilOpType::INVERT: return GL_INVERT; } return GL_KEEP; } GLenum to_warp(lly::TextureWrap wrap) { switch (wrap) { case lly::TextureWrap::REPEAT: return GL_REPEAT; case lly::TextureWrap::CLAMP: return GL_CLAMP; case lly::TextureWrap::CLAMP_TO_EDGE: return GL_CLAMP_TO_EDGE; } return GL_CLAMP_TO_EDGE; } bool eq(float a, float b) { return fabs(a - b) < 0.0000000001; } glm::mat4 to_sqt(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale) { glm::mat4 ret = glm::mat4_cast(rotation); ret = glm::scale(ret, scale); //ret[0][0] *= scale.x; //ret[1][1] *= scale.y; //ret[2][2] *= scale.z; ret[3][0] = position.x; ret[3][1] = position.y; ret[3][2] = position.z; return ret; } }
30.979021
95
0.743567
ooeyusea
379adf1e3c6e043d387b79fecbcb391ca333c0d2
127
cpp
C++
ComponentsLayer/CAN/CANRegistration.cpp
bddwyx/CylinderLoop
05621336b1b2415d7e583d9847020abd06e3eed6
[ "MIT" ]
null
null
null
ComponentsLayer/CAN/CANRegistration.cpp
bddwyx/CylinderLoop
05621336b1b2415d7e583d9847020abd06e3eed6
[ "MIT" ]
null
null
null
ComponentsLayer/CAN/CANRegistration.cpp
bddwyx/CylinderLoop
05621336b1b2415d7e583d9847020abd06e3eed6
[ "MIT" ]
null
null
null
// // Created by bddwy on 2021/1/26. // #include "CANRegistration.h" //CANCommunication CANCommunication::CAN1Communication;
15.875
55
0.748031
bddwyx
37af0a4f38530af2840f6bdcd0bb83a91d08aa6f
2,053
cpp
C++
54288411-save-a-list-of-qpixmaps-to-ico-file/save_pixmaps_to_ico.cpp
cbuchart/stackoverflow
8de12ccb4ff60762955298dfa0e4c6eca63b63ae
[ "Unlicense" ]
2
2021-03-03T12:09:21.000Z
2021-06-19T03:18:53.000Z
54288411-save-a-list-of-qpixmaps-to-ico-file/save_pixmaps_to_ico.cpp
cbuchart/stackoverflow
8de12ccb4ff60762955298dfa0e4c6eca63b63ae
[ "Unlicense" ]
1
2018-07-23T14:14:59.000Z
2018-07-23T14:14:59.000Z
54288411-save-a-list-of-qpixmaps-to-ico-file/save_pixmaps_to_ico.cpp
cbuchart/stackoverflow
8de12ccb4ff60762955298dfa0e4c6eca63b63ae
[ "Unlicense" ]
3
2018-07-23T14:04:46.000Z
2021-12-19T22:53:37.000Z
#include <qlist.h> #include <qpixmap.h> #include <qfileinfo.h> #include <qfile.h> #include <qtemporaryfile.h> namespace { template<typename T> void write(QFile& f, const T t) { f.write((const char*)&t, sizeof(t)); } } bool savePixmapsToICO(const QList<QPixmap>& pixmaps, const QString& path) { static_assert(sizeof(short) == 2, "short int is not 2 bytes"); static_assert(sizeof(int) == 4, "int is not 4 bytes"); QFile f(path); if (!f.open(QFile::OpenModeFlag::WriteOnly)) return false; // Header write<short>(f, 0); write<short>(f, 1); write<short>(f, pixmaps.count()); QList<int> images_size; for (int ii = 0; ii < pixmaps.count(); ++ii) { QTemporaryFile temp; temp.setAutoRemove(true); if (!temp.open()) return false; const auto& pixmap = pixmaps[ii]; pixmap.save(&temp, "PNG"); temp.close(); images_size.push_back(QFileInfo(temp).size()); } // Images directory constexpr unsigned int entry_size = sizeof(char) + sizeof(char) + sizeof(char) + sizeof(char) + sizeof(short) + sizeof(short) + sizeof(unsigned int) + sizeof(unsigned int); static_assert(entry_size == 16, "wrong entry size"); unsigned int offset = 3 * sizeof(short) + pixmaps.count() * entry_size; for (int ii = 0; ii < pixmaps.count(); ++ii) { const auto& pixmap = pixmaps[ii]; if (pixmap.width() > 256 || pixmap.height() > 256) continue; write<char>(f, pixmap.width() == 256 ? 0 : pixmap.width()); write<char>(f, pixmap.height() == 256 ? 0 : pixmap.height()); write<char>(f, 0); // palette size write<char>(f, 0); // reserved write<short>(f, 1); // color planes write<short>(f, pixmap.depth()); // bits-per-pixel write<unsigned int>(f, images_size[ii]); // size of image in bytes write<unsigned int>(f, offset); // offset offset += images_size[ii]; } for (int ii = 0; ii < pixmaps.count(); ++ii) { const auto& pixmap = pixmaps[ii]; if (pixmap.width() > 256 || pixmap.height() > 256) continue; pixmap.save(&f, "PNG"); } return true; }
29.328571
174
0.627862
cbuchart
37af8092b4a0a0816a929b7d6407ee1eae772b08
9,597
cpp
C++
src/HtmlDOM.cpp
liferili/HTML-Formatter
3ebf2a9814c8e077f98e2ef6d8135292d6387a76
[ "MIT" ]
null
null
null
src/HtmlDOM.cpp
liferili/HTML-Formatter
3ebf2a9814c8e077f98e2ef6d8135292d6387a76
[ "MIT" ]
null
null
null
src/HtmlDOM.cpp
liferili/HTML-Formatter
3ebf2a9814c8e077f98e2ef6d8135292d6387a76
[ "MIT" ]
null
null
null
// // Created by Liferov Ilia (liferili) on 5/12/16. // #include <fstream> #include <sstream> #include <deque> #include "HtmlDOM.h" #include "DoctypeNode.h" #include "PairTagNode.h" #include "SingleTagNode.h" #include "CommentNode.h" #include "TextNode.h" #include "ErrorTagNode.h" #include <algorithm> #include "StringHelper.h" using namespace std; //factory method. chooses type of tree node, creates it and pushes it to the html DOM tree void AddTag(string& tag, int line, deque<shared_ptr<PairTagNode>>& nodeStack, const HtmlElementCollection& htmlElements, HtmlErrorList& errors){ if (tag.substr(0,1)!="/"){ //if it is a opening tag if (tag.substr(tag.length()-1,1)=="/") tag=tag.substr(0,tag.length()-1); string checker=tag.substr(0,9); StringHelper::toLower(checker); if (checker =="!doctype "){ // if it is a doctype shared_ptr<DoctypeNode> ptr (new DoctypeNode(tag,line)); (*nodeStack.begin())->pushChild(ptr); } else if (tag.length()>=5 && ((tag.substr(0,3)=="!--" && tag.substr(tag.length()-2,2)=="--") || (tag.substr(0,4)=="!--[" && tag.substr(tag.length()-1,1)=="]") || (tag.substr(0,2)=="![" && tag.substr(tag.length()-3,3)=="]--"))){ // if it is a (conditional) comment shared_ptr<CommentNode> ptr (new CommentNode(tag, line)); (*nodeStack.begin())->pushChild(ptr); } else{ //parsing element`s string to name and attributes vector<string> tokens; istringstream iss(tag); string tmp, token; getline(iss,tmp,' '); tokens.push_back(tmp); while(getline(iss,tmp,' ')){ token+=tmp; iss.seekg(-2,iss.cur); if (iss.peek()=='"'){ tokens.push_back(tmp); token.clear(); } else token+=" "; iss.seekg(2,iss.cur); } if (token!="") tokens.push_back(token); //---------------------------------------------- if (tokens.empty()){ //tag is empty <> errors.pushError(HtmlError("Empty tag", line)); string tagToText="<"+tag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } else{ //tag is not empty string forSearch=tokens[0]; StringHelper::toLower(forSearch); auto it=htmlElements.elementCollection.find(forSearch); if (it==htmlElements.elementCollection.end()){ //undefined tag, pushing it into DOM as ErrorTag string errorMessage="Undefined tag \""+tokens[0]+"\""; errors.pushError(HtmlError(errorMessage, line)); string tagToText="<"+tag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } else{ if (it->second->isPaired()){ //element requires closing tag shared_ptr<PairTagNode> ptr (new PairTagNode(tokens[0], line, tokens)); (*nodeStack.begin())->pushChild(ptr); nodeStack.push_front(ptr); } else{ //element doesnt require closing tag shared_ptr<SingleTagNode> ptr(new SingleTagNode(tokens[0], line, tokens)); (*nodeStack.begin())->pushChild(ptr); } } } } } else{ //if it is a closing tag string closingTag=tag.substr(1,tag.length()-1); string lastInStack=(*nodeStack.begin())->getTagName(); StringHelper::toLower(closingTag); StringHelper::toLower(lastInStack); if (closingTag==lastInStack){ // exact match with the top of the stack (*nodeStack.begin())->setClosingTag(tag); nodeStack.pop_front(); } else{ auto it=htmlElements.elementCollection.find(closingTag); if (it==htmlElements.elementCollection.end()){ //if closing tag is undefined. Just pushing it into DOM as ErrorTag string errorMessage="Undefined tag \"\\"+tag.substr(1,tag.length())+"\""; errors.pushError(HtmlError(errorMessage,line)); string tagToText="<"+tag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } else{ //known tag. Checking if it was opened somewhere earlier auto stackIterator=nodeStack.begin(); for(; stackIterator!=nodeStack.end(); stackIterator++){ string name=(*stackIterator)->getTagName(); StringHelper::toLower(name); if (name==closingTag) break; } if (stackIterator!=nodeStack.end()){ //appropriate tag is not the last in stack string errorMessage; int cnt=0; for(auto i=nodeStack.begin(); i!=stackIterator; i++){ errorMessage="Closing tag for element \""+(*i)->getTagName()+"\"(opened on line: "+to_string((*i)->getLineNumber())+") expected"; errors.pushError(HtmlError(errorMessage, line)); cnt++; } for(auto i=0; i<cnt; i++) nodeStack.pop_front(); (*nodeStack.begin())->setClosingTag(tag); nodeStack.pop_front(); } else{ //tag has not been opened string errorMessage="End tag for element \""+tag.substr(1,tag.length())+"\" which is not open"; errors.pushError(HtmlError(errorMessage,line)); string tagToText="<"+closingTag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } } } } } //creates text node and pushes it to the html DOM tree void AddText(string& text, int line, deque<shared_ptr<PairTagNode>>& nodeStack){ StringHelper::trim(text); if (text!=" " && text!="\n" && text!=""){ //we dont need empty I suppose shared_ptr<TextNode> ptr (new TextNode(text, line)); (*nodeStack.begin())->pushChild(ptr); } } //helping function. deletes spaces from string void DeleteSpaces(string& src){ if (src.length()>=5 && ((src.substr(0,3))!="!--" || (src.substr(src.length()-2,2))!="--")){ auto it= unique(src.begin(), src.end(), [](char l, char r){return (l==r) && (l==' ');}); src.erase(it,src.end()); } } void HtmlDOM::createDOM(string inputFileName, const HtmlElementCollection& htmlElements, HtmlErrorList& errors) { ifstream inFile(inputFileName); if (!inFile.good()) throw Error("Cannot open input file \""+inputFileName+"\"."); bool readingTag=false; int lineNumber=0; string tmp, tag, text, piece; //creating the TOP node (represents the whole html document) deque<shared_ptr<PairTagNode>> nodeStack; vector<string> shame; shared_ptr<TopNode> top (new TopNode(lineNumber, shame)); this->top=top; nodeStack.push_front(top); //parsing input file into tags nad character data while(getline(inFile,tmp)){ lineNumber++; istringstream tmpLine(tmp); while (1) { if (readingTag) { getline(tmpLine, piece, '>'); if (tmpLine.eof()) { tag += piece; break; } else { tag += piece; DeleteSpaces(tag); AddTag(tag, lineNumber, nodeStack, htmlElements, errors); tag.clear(); readingTag = false; } } else { getline(tmpLine, piece, '<'); if (tmpLine.eof()) { text += piece; break; } else { text += piece; DeleteSpaces(text); if (!text.empty()) AddText(text, lineNumber, nodeStack); text.clear(); readingTag = true; } } } } //check the stack if there are any elements that should be closed while(nodeStack.size()!=1){ string errorMessage="Missing closing tag for \""+(*nodeStack.begin())->getTagName()+"\". Tag opens on line "+to_string((*nodeStack.begin())->getLineNumber()); errors.pushError(HtmlError(errorMessage, lineNumber)); nodeStack.pop_front(); } inFile.close(); } void HtmlDOM::validateDocument(HtmlElementCollection &elements, HtmlErrorList &errors)const { this->top->validate(elements, errors); } void HtmlDOM::printHtmlDocument(const string &ofileName, Format &format, HtmlElementCollection& collection) const { ofstream ofile(ofileName); if (!ofile.good()) throw Error("Cannot open output file \""+ofileName+"\""); cout << "Printing formatted document to \""+ofileName+"\" ..." << endl; this->top->print(format, ofile, collection); cout << "Done!" << endl << endl; }
40.838298
166
0.530791
liferili
37b0c710dfe57fb3fec4ee13e1cf78a22226997e
4,296
cpp
C++
src/MeshDrawable.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
src/MeshDrawable.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
src/MeshDrawable.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
/** @file MeshDrawable.cpp Copyright 2016 Computational Topology Group, University of Kaiserslautern Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author(s): C.Garth, T.Biedert */ #include <vector> #include "ugl/GLHelper.hpp" #include "ugl/MeshDrawable.hpp" namespace ugl { MeshDrawable::MeshDrawable( MeshData& data) : m_boundingBox( data.getBoundingBox() ), m_drawSurface( true ), m_drawEdges( false ), m_alpha( 1.0f ) { prepareShaderProgram(); prepareVertexArrays( data ); } /** * @brief Returns the addresses of the parameters which should be GUI controllable. * @param drawSurface * @param drawEdges * @param alpha */ void MeshDrawable::getTweakableParameters(bool** drawSurface, bool** drawEdges, float** alpha) { *drawSurface = &this->m_drawSurface; *drawEdges = &this->m_drawEdges; *alpha = &this->m_alpha; } // ------------------------------------------------------------------------- void MeshDrawable::prepareShaderProgram() { m_program.addImportPath("shader"); // add shader m_program.addShaderFromSourceFile( COMBINED, "ugl/mesh.glsl" ); m_program.addAttributeLocation( "vertexPosition", 0u ); m_program.addAttributeLocation( "vertexNormal", 1u ); } // ------------------------------------------------------------------------- void MeshDrawable::prepareVertexArrays( MeshData& data ) { // set up the vertex arrays and attribute bindings glGenVertexArrays( 1, &m_vertexArray ); glBindVertexArray( m_vertexArray ); // prepare vertex position buffer m_vertexPositionBuffer = GLHelper::prepareStaticBuffer( data.getPoints() ); glBindBuffer( GL_ARRAY_BUFFER, m_vertexPositionBuffer ); glVertexAttribPointer( 0u, 3, GL_FLOAT, GL_FALSE, 0, nullptr ); glEnableVertexAttribArray( 0u ); glBindBuffer( GL_ARRAY_BUFFER, 0u ); // prepare vertex normal buffer m_vertexNormalBuffer = GLHelper::prepareStaticBuffer( data.getVertexNormals() ); glBindBuffer( GL_ARRAY_BUFFER, m_vertexNormalBuffer ); glVertexAttribPointer( 1u, 3, GL_FLOAT, GL_FALSE, 0, nullptr ); glEnableVertexAttribArray( 1u ); glBindBuffer( GL_ARRAY_BUFFER, 0u ); // prepare triangle index buffer m_triangleBuffer = GLHelper::prepareStaticBuffer( data.getTriangles() ); m_triangleCount = data.getTriangleCount() * 3; // prepare edge index buffer m_edgeBuffer = GLHelper::prepareStaticBuffer( data.getEdges() ); m_edgeCount = data.getEdgeCount() * 2; // NOTE: we do not bind an ELEMENT_ARRAY here, since we will switch // on the fly between triangle and edge indices depending on render mode glBindVertexArray( 0u ); } // ------------------------------------------------------------------------- void MeshDrawable::draw( const StateSet& state ) { m_stateSet.setParent(state); UniformSet& uniforms = m_stateSet.getOrCreateUniforms(); ModeSet& modes = m_stateSet.getOrCreateModes(); uniforms.set( "alpha", m_alpha ); // set render modes and issue draw calls glBindVertexArray( m_vertexArray ); if( m_drawSurface ) { modes.clear( "LINE_MODE" ); // bind program and add uniforms m_stateSet.apply( m_program ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_triangleBuffer ); glDrawElements( GL_TRIANGLES, m_triangleCount, GL_UNSIGNED_INT, nullptr ); } if( m_drawEdges ) { modes.set( "LINE_MODE", 1 ); // bind program and add uniforms m_stateSet.apply( m_program ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_edgeBuffer ); glDrawElements( GL_LINES, m_edgeCount, GL_UNSIGNED_INT, nullptr ); } glBindVertexArray( 0u ); // done drawing } } // namespace ugl
29.424658
94
0.661778
dermegges
37b3a9d320f0c5447242fbdcff4ff763dcec47e2
306
cpp
C++
learncpp_com/4-var_scopes/60-global_symbolic_constants/src/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
learncpp_com/4-var_scopes/60-global_symbolic_constants/src/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
learncpp_com/4-var_scopes/60-global_symbolic_constants/src/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
#include <iostream> #include "constants.h" int main(){ std::cout << "Constant pi have value:\t\t" << Constants::pi << "\n"; std::cout << "Constant avogadro have value:\t" << Constants::avogadro << "\n"; std::cout << "Constant my_gravity have value:\t" << Constants::my_gravity << "\n"; return 0; }
25.5
83
0.627451
mitsiu-carreno
37b562d25d15dcbaaba466745b5a895f67dac0ee
3,563
cpp
C++
SharedModule/Threads/threadeventshelper.cpp
HowCanidothis-zz/DevLib
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
[ "MIT" ]
null
null
null
SharedModule/Threads/threadeventshelper.cpp
HowCanidothis-zz/DevLib
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
[ "MIT" ]
null
null
null
SharedModule/Threads/threadeventshelper.cpp
HowCanidothis-zz/DevLib
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
[ "MIT" ]
1
2020-07-27T02:23:38.000Z
2020-07-27T02:23:38.000Z
#include "threadeventshelper.h" #include <QMutexLocker> #include "SharedModule/internal.hpp" ThreadEvent::ThreadEvent(ThreadEvent::FEventHandler handler, const AsyncResult& result) : m_handler(handler) , m_result(result) {} void ThreadEvent::call() { try { m_handler(); m_result.Resolve(true); } catch (...) { m_result.Resolve(false); } } TagThreadEvent::TagThreadEvent(TagThreadEvent::TagsCache* tagsCache, const Name& tag, ThreadEvent::FEventHandler handler, const AsyncResult& result) : ThreadEvent(handler, result) , m_tag(tag) , m_tagsCache(tagsCache) { Q_ASSERT(!tagsCache->contains(tag)); tagsCache->insert(tag, this); } void TagThreadEvent::removeTag() { m_tagsCache->remove(m_tag); } void TagThreadEvent::call() { try { m_handler(); m_result.Resolve(true); } catch (...) { m_result.Resolve(false); } } ThreadEventsContainer::ThreadEventsContainer() : m_isPaused(false) , m_interupted(false) { } void ThreadEventsContainer::Continue() { if(!m_isPaused) { return; } m_isPaused = false; m_eventsPaused.wakeAll(); } AsyncResult ThreadEventsContainer::Asynch(const Name& tag, ThreadEvent::FEventHandler handler) { QMutexLocker locker(&m_eventsMutex); AsyncResult result; auto find = m_tagEventsMap.find(tag); if(find == m_tagEventsMap.end()) { auto tagEvent = new TagThreadEvent(&m_tagEventsMap, tag, handler, result); m_events.push(tagEvent); } else { find.value()->m_handler = handler; result = find.value()->m_result; } return result; } void ThreadEventsContainer::Pause(const FOnPause& onPause) { if(m_isPaused) { return; } m_onPause = onPause; m_isPaused = true; if(m_events.empty()) { Asynch([]{}); } while (!m_events.empty() && m_eventsMutex.tryLock()) { m_eventsMutex.unlock(); } } AsyncResult ThreadEventsContainer::Asynch(ThreadEvent::FEventHandler handler) { QMutexLocker locker(&m_eventsMutex); AsyncResult result; m_events.push(new ThreadEvent(handler, result)); return result; } void ThreadEventsContainer::clearEvents() { m_interupted = true; ProcessEvents(); QMutexLocker locker(&m_eventsMutex); while(!m_events.empty()) { delete m_events.front(); m_events.pop(); } m_interupted = false; } void ThreadEventsContainer::ProcessEvents() { QMutexLocker locker(&m_eventsMutex); while(!m_interupted && !m_events.empty()) { // from spurious wakeups m_eventsProcessed.wait(&m_eventsMutex); } } void ThreadEventsContainer::callEvents() { while(!m_interupted && !m_events.empty()) { ScopedPointer<ThreadEvent> event; { QMutexLocker locker(&m_eventsMutex); event = m_events.front(); m_events.pop(); event->removeTag(); } event->call(); } m_eventsProcessed.wakeAll(); } void ThreadEventsContainer::callPauseableEvents() { while(!m_interupted && !m_events.empty()) { ScopedPointer<ThreadEvent> event; { if(m_isPaused) { m_onPause(); } QMutexLocker locker(&m_eventsMutex); event = m_events.front(); m_events.pop(); while(m_isPaused) { m_eventsPaused.wait(&m_eventsMutex); } event->removeTag(); } event->call(); } m_eventsProcessed.wakeAll(); }
22.408805
148
0.625596
HowCanidothis-zz
37bb8374d97ff3c0b171fe06c2696f5ccd27ddbf
1,944
cpp
C++
src/prod/test/BoostUnitTest/FabricGlobalsInitializationFixture.Test.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
1
2020-06-15T04:33:36.000Z
2020-06-15T04:33:36.000Z
src/prod/test/BoostUnitTest/FabricGlobalsInitializationFixture.Test.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
src/prod/test/BoostUnitTest/FabricGlobalsInitializationFixture.Test.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #include "stdafx.h" #include <boost/test/unit_test.hpp> #include "Common/FabricGlobals.h" using namespace std; using namespace Common; /* Global fixture used to initialize the fabric globals This runs before any test case runs and is used to mark the singleton instance of fabric globals in this module as primary. This is intended for use in any unit test that is testing a component that is below fabric common in the hierarchy It assumes that the config is in a .cfg file or store -> fails otherwise */ namespace { ConfigStoreDescriptionUPtr CreateTestConfigStore() { ConfigStoreType::Enum storeType; wstring storeLocation; auto error = FabricEnvironment::GetStoreTypeAndLocation(nullptr, storeType, storeLocation); if (!error.IsSuccess()) { throw std::runtime_error("Failed FabricEnv::GetStoreTypeAndLocation"); } if (storeType == ConfigStoreType::Cfg) { return make_unique<ConfigStoreDescription>( make_shared<FileConfigStore>(storeLocation), *FabricEnvironment::FileConfigStoreEnvironmentVariable, storeLocation); } if (storeType == ConfigStoreType::None) { return make_unique<ConfigStoreDescription>( make_shared<ConfigSettingsConfigStore>(move(ConfigSettings())), L"", L""); } throw std::invalid_argument("Unsupported config store type for test"); } } struct FabricGlobalsInit { FabricGlobalsInit() { FabricGlobals::InitializeAsMaster(&CreateTestConfigStore); } }; BOOST_GLOBAL_FIXTURE(FabricGlobalsInit);
30.375
99
0.609568
vishnuk007
37bcefe894653a0cffcdc28649dbde3c0ae68ac5
5,398
cpp
C++
cflw代码库/cflw音频_xa2.cpp
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
9
2018-10-18T18:13:14.000Z
2021-07-21T19:55:56.000Z
cflw代码库/cflw音频_xa2.cpp
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
1
2020-08-18T02:07:09.000Z
2020-08-19T12:50:55.000Z
cflw代码库/cflw音频_xa2.cpp
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
1
2019-04-22T20:35:04.000Z
2019-04-22T20:35:04.000Z
#include <cassert> #include <algorithm> #include "cflw音频_xa2.h" namespace cflw::音频::xa2 { using 多媒体::FindChunk; using 多媒体::ReadChunkData; //============================================================================== // 辅助函数 //============================================================================== void f销毁声音(IXAudio2Voice *a) { a->DestroyVoice(); } //============================================================================== // 音频引擎 //============================================================================== C音频::C音频() { }; C音频::~C音频() { if (m音频) { f销毁(); } }; HRESULT C音频::f初始化() { HRESULT hr; hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(hr)) { return hr; } hr = XAudio2Create(&m音频, 0, XAUDIO2_DEFAULT_PROCESSOR); if (FAILED(hr)) { return hr; } hr = m音频->CreateMasteringVoice(&m声音控制); if (FAILED(hr)) { return hr; } return S_OK; }; void C音频::f销毁() { f销毁声音(m声音控制); m声音控制 = nullptr; m音频.Reset(); CoUninitialize(); }; HRESULT C音频::f创建声音(tp声音 &a声音, const std::wstring_view &a文件) { HRESULT hr; C波形文件 v文件; hr = v文件.f打开(a文件); if (FAILED(hr)) { return hr; } if (!v文件.f检查类型()) { return E_FAIL; //不是波形格式 } tp声音 v声音 = std::make_shared<C声音>(); v声音->m格式 = v文件.f读取格式(); const auto &[v数据, v数据大小] = v文件.f读取数据(); v声音->m数据 = std::unique_ptr<std::byte>(v数据); v声音->m大小 = v数据大小; //填充缓冲 v声音->m缓冲.AudioBytes = (UINT32)v数据大小; v声音->m缓冲.pAudioData = (BYTE*)v数据; v声音->m缓冲.Flags = XAUDIO2_END_OF_STREAM; v声音->m缓冲.LoopBegin = XAUDIO2_NO_LOOP_REGION; v声音->m缓冲.LoopLength = 0; v声音->m缓冲.LoopCount = 0; //结束 a声音 = std::move(v声音); return S_OK; }; HRESULT C音频::f创建源声音(tp源声音 &a源声音, const C声音 &a声音, const C混合 &a混合) { IXAudio2SourceVoice *v源声音; HRESULT hr = m音频->CreateSourceVoice(&v源声音, (WAVEFORMATEX*)&a声音.m格式, 0, 2, nullptr, &a混合.m列表); if (FAILED(hr)) { return hr; } a源声音 = std::shared_ptr<IXAudio2SourceVoice>(v源声音, &f销毁声音); return S_OK; } HRESULT C音频::f创建混合(tp混合 &a混合) { tp混合 v混合 = std::make_shared<C混合>(); HRESULT hr = m音频->CreateSubmixVoice(&v混合->m声音, 1, 44100); if (FAILED(hr)) { return hr; } v混合->m发送.Flags = 0; v混合->m发送.pOutputVoice = v混合->m声音; v混合->m列表.pSends = &v混合->m发送; v混合->m列表.SendCount = 1; a混合 = std::move(v混合); return S_OK; } //============================================================================== // 播放控制 //============================================================================== C播放控制::C播放控制() { } void C播放控制::f初始化(C音频 &a) { m音频 = &a; m当前时间 = std::chrono::system_clock::now(); } void C播放控制::f刷新() { for (auto v迭代 = ma播放.begin(); v迭代 != ma播放.end();) { const auto &[v播放, v源声音] = *v迭代; ++v迭代; XAUDIO2_VOICE_STATE v状态; v源声音->GetState(&v状态); if (v状态.BuffersQueued <= 0) { ma播放.erase(v播放); } } m当前时间 = std::chrono::system_clock::now(); } tp播放 C播放控制::f播放(const C声音 &a声音, const C混合 &a混合) { //去重 if (const auto &v找声音 = m声音去重.find(&a声音); v找声音 != m声音去重.end()) { if (const float v时间差 = std::chrono::duration<float>(m当前时间 - v找声音->second).count(); v时间差 <= m声音间隔) { return 0; //重复,不播放 } } //播放 tp播放 v播放 = (++m序号); tp源声音 v源声音; m音频->f创建源声音(v源声音, a声音, a混合); v源声音->SubmitSourceBuffer(&a声音.m缓冲); v源声音->Start(); m声音去重[&a声音] = m当前时间; ma播放[v播放] = v源声音; return v播放; } void C播放控制::f暂停(tp播放 a) { if (const auto &v找播放 = ma播放.find(a); v找播放 != ma播放.end()) { v找播放->second->Stop(); } } void C播放控制::f恢复(tp播放 a) { if (const auto &v找播放 = ma播放.find(a); v找播放 != ma播放.end()) { v找播放->second->Start(); } } void C播放控制::f停止(tp播放 a) { if (const auto &v找播放 = ma播放.find(a); v找播放 != ma播放.end()) { v找播放->second->Stop(); ma播放.erase(a); } } void C播放控制::f停止全部() { for (const auto &[v播放, v源声音] : ma播放) { v源声音->Stop(); } ma播放.clear(); } bool C播放控制::fi播放(tp播放 a) { const auto &v找播放 = ma播放.find(a); return v找播放 != ma播放.end(); } void C播放控制::fs重复播放间隔(float a) { m声音间隔 = a; } //============================================================================== // 声音 //============================================================================== C混合::~C混合() { if (m声音) { f销毁声音(m声音); } } void C混合::f销毁() { f销毁声音(m声音); m声音 = nullptr; } void C混合::fs音量(float a) { m声音->SetVolume(a); } float C混合::fg音量() const { float v; m声音->GetVolume(&v); return v; } //============================================================================== // 波形文件 //============================================================================== HRESULT C波形文件::f打开(const std::wstring_view &a文件名) { m文件 = CreateFileW(a文件名.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (INVALID_HANDLE_VALUE == m文件) return HRESULT_FROM_WIN32(GetLastError()); if (INVALID_SET_FILE_POINTER == SetFilePointer(m文件, 0, nullptr, FILE_BEGIN)) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; }; bool C波形文件::f检查类型() const { DWORD v块大小; DWORD v块位置; DWORD v文件类型; FindChunk(m文件, 多媒体::c块RIFF, v块大小, v块位置); ReadChunkData(m文件, &v文件类型, sizeof(DWORD), v块位置); return v文件类型 == 多媒体::c块WAVE; }; WAVEFORMATEXTENSIBLE C波形文件::f读取格式() const { DWORD v块大小; DWORD v块位置; WAVEFORMATEXTENSIBLE v格式; FindChunk(m文件, 多媒体::c块fmt, v块大小, v块位置); ReadChunkData(m文件, &v格式, v块大小, v块位置); return v格式; }; std::pair<std::byte*, size_t> C波形文件::f读取数据() const { DWORD v块大小; DWORD v块位置; FindChunk(m文件, 多媒体::c块data, v块大小, v块位置); std::byte *v数据 = new std::byte[v块大小]; ReadChunkData(m文件, v数据, v块大小, v块位置); return {v数据, v块大小}; }; bool C波形文件::f关闭() { return CloseHandle(m文件); } } //namespace cflw::音频::xa2
24.761468
101
0.546684
cflw
37c825d359ca65f19879f852aa75cb8aea511cda
1,625
cpp
C++
d02/ex00/Fixed.class.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
5
2018-02-10T12:33:53.000Z
2021-03-28T09:27:05.000Z
d02/ex00/Fixed.class.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
null
null
null
d02/ex00/Fixed.class.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
6
2017-11-25T17:34:43.000Z
2020-12-20T12:00:04.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.class.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdarriga <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/17 12:26:20 by mdarriga #+# #+# */ /* Updated: 2015/06/17 13:55:56 by mdarriga ### ########.fr */ /* */ /* ************************************************************************** */ #include "Fixed.class.hpp" int const Fixed::_nBit = 8; Fixed::Fixed(void) { this->_rawBits = 0; std::cout << "Default Constructor called" << std::endl; return ; } Fixed::Fixed(Fixed const &src) { *this = src; std::cout << "Copy constructor called" << std::endl; return ; } Fixed::~Fixed() { std::cout << "Destructor called" << std::endl; return ; } int Fixed::getRawBits(void) const { std::cout << "getRawBits member function called" << std::endl; return this->_rawBits; } void Fixed::setRawBits(int const raw) { this->_rawBits = raw; } Fixed &Fixed::operator=(Fixed const &rhs) { std::cout << "Assignation operator called" << std::endl; if (this != &rhs) this->_rawBits = rhs.getRawBits(); return *this; }
33.163265
80
0.357538
ncoden
56cb13f92dbc1d68a78f29a4143a361e3ffd8184
10,202
cpp
C++
src/IsoGame/Play/Map.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Map.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Map.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
#include "Map.h" #include <Game.h> #include <Common\ResourceMgr.h> #include <Common\Random.h> #include "PlayScene.h" #include "Objects\Entities\Player.h" #include "Rooms\Room.h" #include "Rooms\BossRoom.h" #include "Rooms\FinalBossRoom.h" #include "Rooms\TreasureRoom.h" #include "Rooms\ZombieRoom.h" #include "Rooms\ShooterRoom.h" #include <SFML\Graphics.hpp> #include <conio.h> #include <stdarg.h> //#define MAP_GEN_DEBUG Map::Map(Player *player) : m_pPlayer(player) { m_pCurrentRoom = nullptr; m_pRoomShape = std::make_shared<sf::RectangleShape>(sf::Vector2f(15.f, 7.5f)); m_pRoomShape->setFillColor(sf::Color::Black); GenerateMap(); /*for (auto room : m_rooms) { if (room) { if (room->GetRoomType() == Room::FINAL_BOSS) LoadRoom(room.get()); } }*/ m_isFinalBossOpen = false; Map::LoadRoom(m_rooms[0].get()); } Map::~Map() { } void Map::GenerateMap(int seed) { Random random; if (seed != -1) random = Random(seed); int nAttempts = 0; while (true) { nAttempts++; m_mapRoom.clear(); m_rooms.clear(); m_nBossRooms = 3; m_nFinalBossRooms = 1; m_nTreasureRooms = 3; m_nEmptyRooms = 4; m_nZombieRooms = 5; m_nShooterRooms = 4; m_nRoomsToCreate = m_nRooms = GetNumberOfAvailableRooms(); sf::Vector2i pos; printf("Generating map... Rooms: %d\n", m_nRooms); Generate(Directions::NONE, random, pos, 0); //printf("%d %d\n", m_rooms.size(), m_nRoomsToCreate); if (m_rooms.size() == m_nRoomsToCreate) break; } // set desc for portals for (auto& room : m_rooms) { if (room) { auto pos = room->GetPos(); for (int num = 0; num < 4; ++num) { auto numDir = NumToDir(num); auto numPos = MoveInDir(pos, numDir); if (m_mapRoom.find(std::make_pair(numPos.x, numPos.y)) != m_mapRoom.end()) { room->SetPortalDest(numDir, m_mapRoom[std::make_pair(numPos.x, numPos.y)]); } else { room->CreateMeteor(numDir); } } room->ClosePortals(false); switch (room->GetRoomType()) { case Room::EMPTY: case Room::TREASURE: room->OpenPortals(false); } } } printf("Done in %d attempts!\n", nAttempts); } sf::Vector2i Map::MoveInDir(const sf::Vector2i &pos, Directions::Direction dir) { sf::Vector2i newPos = pos; switch (dir) { case Directions::NW: newPos += sf::Vector2i(-1, -1); break; case Directions::NE: newPos += sf::Vector2i(1, -1); break; case Directions::SE: newPos += sf::Vector2i(1, 1); break; case Directions::SW: newPos += sf::Vector2i(-1, 1); break; } return newPos; } Directions::Direction Map::NumToDir(int num) { switch (num) { case 0: return Directions::NW; case 1: return Directions::NE; case 2: return Directions::SE; case 3: return Directions::SW; } return Directions::NONE; } bool Map::IsNearToSpecialRoom(const sf::Vector2i &oldPos, const sf::Vector2i &newPos) { bool isSpecialRoomNear = false; for (int i = 0; i < 4; ++i) { auto _newPos = MoveInDir(newPos, NumToDir(i)); if (_newPos == oldPos) continue; if (m_mapRoom.find(std::make_pair(_newPos.x, _newPos.y)) != m_mapRoom.end()) { if (m_mapRoom[std::make_pair(_newPos.x, _newPos.y)]->IsSpecialRoom()) isSpecialRoomNear = true; } } return isSpecialRoomNear; } void Map::GenerateTree(Random &random, const sf::Vector2i &pos, int deepLevel, int min, int max) { int nNewRooms = random.Get<int>(std::min(min, m_nRooms), std::min(max, m_nRooms)); m_nRooms -= nNewRooms; PrintTab(deepLevel, "Generating tree: %d", nNewRooms); bool reserved[4] = { false }; for (int i = 0; i < nNewRooms; ++i) { PrintTab(deepLevel, "New: %d", i); sf::Vector2i newRoomPos; Directions::Direction newRoomDir; int nAttempts = 20; while (true) { if (nAttempts <= 0) break; nAttempts--; int num = random.Get<int>(0, 3); if (reserved[num]) continue; auto drawn = NumToDir(num); auto newPos = MoveInDir(pos, drawn); if (m_mapRoom.find(std::make_pair(newPos.x, newPos.y)) == m_mapRoom.end()) { if (IsNearToSpecialRoom(pos, newRoomPos)) continue; newRoomDir = drawn; newRoomPos = newPos; reserved[num] = true; break; } } if (nAttempts <= 0) { m_nRooms++; PrintTab(deepLevel, "Cannot %d", i); continue; } Generate(newRoomDir, random, newRoomPos, ++deepLevel, true); } } bool Map::Generate(Directions::Direction cameFrom, Random &random, const sf::Vector2i &pos, int deepLevel, bool reserved) { if (!reserved) { if (m_nRooms <= 0) return false; } PrintTab(deepLevel, "Creating room... (%d)", m_nRooms); Room *room = nullptr; if (GetNumberOfAvailableRooms() == 0) return false; while (true) { int roomType = 1; if (pos != sf::Vector2i(0, 0)) roomType = random.Get<int>(1, 6); bool created = false; switch (roomType) { case 1: // Empty Room if (m_nEmptyRooms > 0) { room = new Room(this, pos); m_nEmptyRooms--; created = true; } break; case 2: // Treasure Room if (m_nTreasureRooms > 0 && m_nRooms < m_nRoomsToCreate / 2) { room = new TreasureRoom(this, pos); m_nTreasureRooms--; created = true; } break; case 3: // Zombie Room if (m_nZombieRooms > 0) { room = new ZombieRoom(this, pos); m_nZombieRooms--; created = true; } break; case 4: // Boss Room { if (m_nBossRooms > 0 && m_nRooms < m_nRoomsToCreate / 3) { room = new BossRoom(this, pos); m_nBossRooms--; created = true; } break; } case 5: // Shooter Room { if (m_nShooterRooms > 0) { room = new ShooterRoom(this, pos); m_nShooterRooms--; created = true; } } break; case 6: // Final Boss { if (m_nFinalBossRooms > 0) { room = new FinalBossRoom(this, pos); m_nFinalBossRooms--; created = true; } } break; } if (created) break; } PrintTab(deepLevel, "Created: %d on (%d, %d)", room->GetRoomType(), pos.x, pos.y); m_rooms.push_back(std::shared_ptr<Room>(room)); m_mapRoom[std::make_pair(pos.x, pos.y)] = room; if (room->IsSpecialRoom()) { PrintTab(deepLevel, "Special room: Return without childs"); return true; } int generateNewTree = 2; if (cameFrom != Directions::NONE) generateNewTree = random.Get<int>(1, 4); if (generateNewTree == 2) { int min = 2; if (cameFrom == Directions::NONE) { min = 3; } GenerateTree(random, pos, ++deepLevel, min); } else { sf::Vector2i newRoomPos = MoveInDir(pos, cameFrom); PrintTab(deepLevel, "Next line"); deepLevel++; if (IsNearToSpecialRoom(pos, newRoomPos)) GenerateTree(random, pos, deepLevel); else { m_nRooms--; if (Generate(cameFrom, random, newRoomPos, deepLevel)) { GenerateTree(random, pos, deepLevel); } } } return false; } void Map::PrintTab(int deepLevel, char * str, ...) { #ifdef MAP_GEN_DEBUG for (int i = 0; i <= deepLevel; ++i) { printf(" "); } char buffer[256]; va_list args; va_start(args, str); vsnprintf(buffer, 256, str, args); va_end(args); char buffer2[512] = { 0 }; sprintf(buffer2, "[%d] %s (R: %d, T: %d B: %d Z: %d E: %d", deepLevel, buffer, m_nRooms, m_nTreasureRooms, m_nBossRooms, m_nZombieRooms, m_nEmptyRooms); puts(buffer2); #endif } int Map::GetNumberOfAvailableRooms() { return m_nEmptyRooms + m_nTreasureRooms + m_nZombieRooms + m_nShooterRooms + m_nBossRooms + m_nFinalBossRooms; } void Map::LoadRoom(Room *room) { if (room == nullptr) return; if (m_pCurrentRoom) m_pCurrentRoom->RemoveObject(m_pPlayer); m_pCurrentRoom = room; if (m_pCurrentRoom->GetVisibleStatus() != Room::SHOWN) PlayScene::Get()->AddScore(1000); m_pCurrentRoom->AddObject(m_pPlayer, false); m_pCurrentRoom->SetVisibleStatus(Room::SHOWN); auto setVisibity = [this] (Directions::Direction dir) { auto room = m_pCurrentRoom->GetPortalDest(dir); if (room && room->GetVisibleStatus() == Room::HIDDEN) room->SetVisibleStatus(Room::HALF); }; setVisibity(Directions::NE); setVisibity(Directions::NW); setVisibity(Directions::SE); setVisibity(Directions::SW); int notDiscoveredBosses = 0; for (auto room : m_rooms) { if (room) { if (room->GetRoomType() == Room::BOSS && room->GetVisibleStatus() != Room::SHOWN) notDiscoveredBosses++; } } if (notDiscoveredBosses == 0) m_isFinalBossOpen = true; } void Map::RenderHud(sf::RenderWindow *window) { if (m_pCurrentRoom) m_pCurrentRoom->RenderHud(window); sf::Vector2f centerPos; centerPos.x = Game::Get()->GetWindowSize().x / 2.f; centerPos.y = (Game::Get()->GetWindowSize().y - Game::Get()->GetPlayAreaSize().y) / 2.f; float offset = 1.f; auto currentPos = m_pCurrentRoom->GetPos(); for (auto& room : m_rooms) { if (room) { auto pos = room->GetPos() - currentPos; sf::Vector2f newPos; newPos.x = pos.x * (offset + m_pRoomShape->getSize().x) + 500.f; newPos.y = pos.y * (offset + m_pRoomShape->getSize().y); if ((centerPos + newPos).y > 130) continue; if (room.get() == m_pCurrentRoom) m_pRoomShape->setFillColor(sf::Color::White); else { if (room->GetVisibleStatus() == Room::SHOWN) m_pRoomShape->setFillColor(room->GetRoomColor()); else if (room->GetVisibleStatus() == Room::HALF) m_pRoomShape->setFillColor(sf::Color(255, 255, 255, 50)); else m_pRoomShape->setFillColor(sf::Color::Transparent); } m_pRoomShape->setPosition(centerPos + newPos); window->draw(*m_pRoomShape); } } } void Map::RenderGame(sf::RenderWindow *window) { if (m_pCurrentRoom) m_pCurrentRoom->RenderGame(window); } void Map::Pulse(float deltaTime) { if (m_pCurrentRoom) m_pCurrentRoom->Pulse(deltaTime); } void Map::Event(sf::Event *e) { if (m_pCurrentRoom) m_pCurrentRoom->Event(e); #ifdef _DEBUG if (e->type == sf::Event::KeyPressed) { switch (e->key.code) { case sf::Keyboard::G: { m_pCurrentRoom = nullptr; GenerateMap(); Map::LoadRoom(m_rooms[0].get()); } break; case sf::Keyboard::X: { for (auto room : m_rooms) { if (room) { room->SetVisibleStatus(Room::SHOWN); } } } break; } } #endif }
18.684982
153
0.63517
Harry09
56cf1dd19f125028f80f65ce8b1c857f59aca332
1,083
cpp
C++
src/core/Environment.cpp
phoenixwxy/markdown
dfafa68524a639cb492b464146e83c256807a356
[ "MIT" ]
null
null
null
src/core/Environment.cpp
phoenixwxy/markdown
dfafa68524a639cb492b464146e83c256807a356
[ "MIT" ]
null
null
null
src/core/Environment.cpp
phoenixwxy/markdown
dfafa68524a639cb492b464146e83c256807a356
[ "MIT" ]
null
null
null
// // Created by mi on 2021/4/8. // #include "Environment.h" Environment *Environment::GetInstance() { static Environment s_Environment; if (EnvStatus::Initialize == s_Environment.m_CurrentStatus) { s_Environment.InitCaps(); } return &s_Environment; } Environment::Environment() : m_Version("0.0.0") , m_CurrentStatus(EnvStatus::Invalid) { Initialize(); } Environment::~Environment() { m_CurrentStatus = EnvStatus::Invalid; } void Environment::Initialize() { m_CurrentStatus = EnvStatus::Initialize; } void Environment::InitCaps() { m_CurrentStatus = EnvStatus::Running; m_CurrentStatus = EnvStatus::Done; } std::string Environment::GetVersion() { if (!m_Version.empty()) { m_Version.clear(); } m_Version.append(std::to_string(MAJOR_VERSION)); m_Version.append("."); m_Version.append(std::to_string(MINOR_VERSION)); m_Version.append("."); m_Version.append(std::to_string(PATCH_VERSION)); if (m_Version.empty()) { m_Version.assign("0.0.0"); } return m_Version; }
19.690909
65
0.662973
phoenixwxy
56d096a390d722384d54795ab77357c4e7250d7a
1,174
cpp
C++
EasyCpp/Net/Services/Microsoft/Cognitive/CVTagImageResult.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
3
2018-02-06T05:12:41.000Z
2020-05-12T20:57:32.000Z
EasyCpp/Net/Services/Microsoft/Cognitive/CVTagImageResult.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
41
2016-07-11T12:19:10.000Z
2017-08-08T07:43:12.000Z
EasyCpp/Net/Services/Microsoft/Cognitive/CVTagImageResult.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
2
2019-08-02T10:24:36.000Z
2020-09-11T01:45:12.000Z
#include "CVTagImageResult.h" #include "../../../../Bundle.h" #include "../../../../AnyArray.h" namespace EasyCpp { namespace Net { namespace Services { namespace Microsoft { namespace Cognitive { CVTagImageResult::CVTagImageResult() { } CVTagImageResult::~CVTagImageResult() { } const std::vector<CVImageTag>& CVTagImageResult::getTags() const { return _tags; } const CVImageMetadata & CVTagImageResult::getMetadata() const { return _metadata; } const std::string & CVTagImageResult::getRequestId() const { return _request_id; } AnyValue CVTagImageResult::toAnyValue() const { return Bundle({ { "tags", toAnyArraySerialize(_tags) }, { "requestId", _request_id }, { "metadata", _metadata.toAnyValue() } }); } void CVTagImageResult::fromAnyValue(const AnyValue & state) { Bundle b = state.as<Bundle>(); _tags = fromAnyArray<CVImageTag>(b.get("tags")); _request_id = b.get<std::string>("requestId"); _metadata = b.get<CVImageMetadata>("metadata"); } } } } } }
20.241379
69
0.59029
Thalhammer
56d300c32f1ad29c49c26264cdb88ead90ce3ea8
5,229
cpp
C++
Export/macos/obj/src/EReg.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/src/EReg.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/src/EReg.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
// Generated by Haxe 4.2.0-rc.1+cb30bd580 #include <hxcpp.h> #ifndef INCLUDED_EReg #include <EReg.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_359fe5fd855fee60_28_new,"EReg","new",0x8b859e81,"EReg.new","/usr/local/lib/haxe/std/cpp/_std/EReg.hx",28,0x5a2fdacd) HX_LOCAL_STACK_FRAME(_hx_pos_359fe5fd855fee60_36_match,"EReg","match",0x18fda1a6,"EReg.match","/usr/local/lib/haxe/std/cpp/_std/EReg.hx",36,0x5a2fdacd) HX_LOCAL_STACK_FRAME(_hx_pos_359fe5fd855fee60_45_matched,"EReg","matched",0x8ce62f85,"EReg.matched","/usr/local/lib/haxe/std/cpp/_std/EReg.hx",45,0x5a2fdacd) void EReg_obj::__construct(::String r,::String opt){ HX_STACKFRAME(&_hx_pos_359fe5fd855fee60_28_new) HXLINE( 29) ::Array< ::String > a = opt.split(HX_("g",67,00,00,00)); HXLINE( 30) this->global = (a->length > 1); HXLINE( 31) if (this->global) { HXLINE( 32) opt = a->join(HX_("",00,00,00,00)); } HXLINE( 33) this->r = _hx_regexp_new_options(r,opt); } Dynamic EReg_obj::__CreateEmpty() { return new EReg_obj; } void *EReg_obj::_hx_vtable = 0; Dynamic EReg_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< EReg_obj > _hx_result = new EReg_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool EReg_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x022d4033; } bool EReg_obj::match(::String s){ HX_STACKFRAME(&_hx_pos_359fe5fd855fee60_36_match) HXLINE( 37) bool p = _hx_regexp_match(this->r,s,0,s.length); HXLINE( 38) if (p) { HXLINE( 39) this->last = s; } else { HXLINE( 41) this->last = null(); } HXLINE( 42) return p; } HX_DEFINE_DYNAMIC_FUNC1(EReg_obj,match,return ) ::String EReg_obj::matched(int n){ HX_STACKFRAME(&_hx_pos_359fe5fd855fee60_45_matched) HXLINE( 46) ::String m = _hx_regexp_matched(this->r,n); HXLINE( 47) return m; } HX_DEFINE_DYNAMIC_FUNC1(EReg_obj,matched,return ) EReg_obj::EReg_obj() { } void EReg_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(EReg); HX_MARK_MEMBER_NAME(r,"r"); HX_MARK_MEMBER_NAME(last,"last"); HX_MARK_MEMBER_NAME(global,"global"); HX_MARK_END_CLASS(); } void EReg_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(r,"r"); HX_VISIT_MEMBER_NAME(last,"last"); HX_VISIT_MEMBER_NAME(global,"global"); } ::hx::Val EReg_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"r") ) { return ::hx::Val( r ); } break; case 4: if (HX_FIELD_EQ(inName,"last") ) { return ::hx::Val( last ); } break; case 5: if (HX_FIELD_EQ(inName,"match") ) { return ::hx::Val( match_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"global") ) { return ::hx::Val( global ); } break; case 7: if (HX_FIELD_EQ(inName,"matched") ) { return ::hx::Val( matched_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val EReg_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"r") ) { r=inValue.Cast< ::Dynamic >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"last") ) { last=inValue.Cast< ::String >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"global") ) { global=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void EReg_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("r",72,00,00,00)); outFields->push(HX_("last",56,0a,ad,47)); outFields->push(HX_("global",63,31,b2,a7)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo EReg_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(EReg_obj,r),HX_("r",72,00,00,00)}, {::hx::fsString,(int)offsetof(EReg_obj,last),HX_("last",56,0a,ad,47)}, {::hx::fsBool,(int)offsetof(EReg_obj,global),HX_("global",63,31,b2,a7)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *EReg_obj_sStaticStorageInfo = 0; #endif static ::String EReg_obj_sMemberFields[] = { HX_("r",72,00,00,00), HX_("last",56,0a,ad,47), HX_("global",63,31,b2,a7), HX_("match",45,49,23,03), HX_("matched",e4,3c,7c,89), ::String(null()) }; ::hx::Class EReg_obj::__mClass; void EReg_obj::__register() { EReg_obj _hx_dummy; EReg_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("EReg",0f,4a,da,2d); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(EReg_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< EReg_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = EReg_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = EReg_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
30.940828
157
0.689233
TrilateralX
56d99f5671a754fde3e62047fcf4a395f7b0e351
109,845
hpp
C++
src/tree_for_force_impl_force.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
src/tree_for_force_impl_force.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
src/tree_for_force_impl_force.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
#pragma once #include"tree_walk.hpp" namespace ParticleSimulator{ /////////////////////////////////////////////////// // // FUNCTIONS OF WALK+FORCE WITH DOUBLE BUFFERING // /////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// //////////// Walk+Force, Kernel:Index, List:Index //////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndex(Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ if(tag_max <= 0){ PARTICLE_SIMULATOR_PRINT_ERROR("tag_max is illegal. In currente version, tag_max must be 1"); Abort(-1); } force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } S32 ret = 0; const F64 wtime_offset = GetWtime(); ret = calcForceMultiWalkIndexImpl(typename TSM::force_type(), pfunc_dispatch, pfunc_retrieve, tag_max, n_walk_limit, flag_keep_list, clear); time_profile_.calc_force += GetWtime() - wtime_offset; return ret; } //////////// Walk+Force, Kernel:Index, List:Index, Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); // send all epj and spj Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; S32 ** id_spj_dummy = NULL; S32 * n_spj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, (const S32**)id_spj_dummy, n_spj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), true); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); interaction_list_.n_sp_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_sp_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_sp_.clearSize(); } //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk+1] static S32 ** n_spj_disp_thread;// [n_thread][n_walk+1] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S32 * n_sp_cum_thread; static S64 * n_interaction_ep_ep_ar; static S64 * n_interaction_ep_sp_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_spj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; //static ReallocatableArray<S32> * n_disp_epj_tmp; //static ReallocatableArray<S32> * n_disp_spj_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_spj_ar; id_spj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; n_spj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; n_spj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_sp_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; n_interaction_ep_sp_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_spj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; //n_disp_epj_tmp = new ReallocatableArray<S32>[n_thread]; //n_disp_spj_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; const S32 wg_tmp = n_ipg > 0 ? n_ipg%n_loop_max : 0; //for(int wg=0; wg<n_ipg%n_loop_max; wg++){ for(int wg=0; wg<wg_tmp; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } //for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ for(int wg=wg_tmp; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = n_interaction_ep_sp_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); const S32 adr_tree_sp_first = spj_org_.size(); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = n_sp_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; n_spj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_spj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); //n_disp_epj_tmp[ith].clearSize(); //n_disp_spj_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, Tspj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], spj_sorted_, adr_spj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, adr_tree_sp_first, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } for(S32 i=0; i<adr_spj_tmp[ith].size(); i++){ mass_tmp += spj_sorted_[ adr_spj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ //if(Comm::getRank()==0) std::cerr<<"mass_tmp= "<<mass_tmp<<std::endl; //n_epj_array[iw] = epj_for_force_[ith].size() - n_ep_cum_thread[ith]; //n_spj_array[iw] = spj_for_force_[ith].size() - n_sp_cum_thread[ith]; //interaction_list_.n_ep_[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; //interaction_list_.n_sp_[iw] = adr_spj_tmp[ith].size() - n_sp_cum_thread[ith]; n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_spj_ar[iw] = adr_spj_tmp[ith].size() - n_sp_cum_thread[ith]; #if 0 if(Comm::getRank()==0){ std::cout<<"Multi:yes, index:yes id_ipg= "<<id_ipg <<" target_box= "<<target_box.vertex_ <<" n_epi= "<<ipg_[id_ipg].n_ptcl_ <<" n_epj= "<<n_epj_ar[iw] <<" n_spj= "<<n_spj_ar[iw] <<" tc_glb_[0].mom_.vertex_out_= "<<tc_glb_[0].mom_.vertex_out_ <<" tc_glb_[0].n_ptcl_= "<<tc_glb_[0].n_ptcl_ <<std::endl; } #endif n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_sp_cum_thread[ith] = adr_spj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_spj_disp_thread[ith][cnt_thread[ith]+1] = n_sp_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_ar[ith] += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope //if(Comm::getRank()==0) std::cerr<<"OK"<<std::endl; //Comm::barrier(); //exit(1); if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = interaction_list_.n_disp_sp_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; interaction_list_.n_sp_[id_ipg] = n_spj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; interaction_list_.n_disp_sp_[id_ipg+1] = interaction_list_.n_disp_sp_[id_ipg] + interaction_list_.n_sp_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); interaction_list_.adr_sp_.resizeNoInitialize( interaction_list_.n_disp_sp_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } S32 adr_sp = interaction_list_.n_disp_sp_[adr_ipg]; const S32 k_sp_h = n_spj_disp_thread[i][j]; const S32 k_sp_e = n_spj_disp_thread[i][j+1]; for(S32 k=k_sp_h; k<k_sp_e; k++, adr_sp++){ interaction_list_.adr_sp_[adr_sp] = adr_spj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); id_spj_ar[iw] = adr_spj_tmp[ith].getPointer(n_sp_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); id_spj_ar[iw] = adr_spj_tmp[ith].getPointer(n_sp_head); } #endif pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), (const S32**)id_spj_ar.getPointer(), n_spj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), false); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; n_interaction_ep_sp_local_ += n_interaction_ep_sp_ar[i]; } //std::cerr<<"(A) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Walk+Force, Kernel:Index, List:Index, Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), true); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); } //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S64 * n_interaction_ep_ep_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; const S32 wg_tmp = n_ipg > 0 ? n_ipg%n_loop_max : 0; //for(int wg=0; wg<n_ipg%n_loop_max; wg++){ for(int wg=0; wg<wg_tmp; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } //for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ for(int wg=wg_tmp; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); } #endif pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), false); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = 0; n_interaction_ep_ep_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; } //std::cerr<<"(B) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } ////////////////////////////////////////////////////////////// //////////// Walk+Force, Kernel:Ptcl, List:Ptcl ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalk(Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool clear){ if(tag_max <= 0){ PARTICLE_SIMULATOR_PRINT_ERROR("tag_max is illegal. In currente version, tag_max must be 1"); Abort(-1); } force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } S32 ret = 0; const F64 wtime_offset = GetWtime(); ret = calcForceMultiWalkImpl(typename TSM::force_type(), pfunc_dispatch, pfunc_retrieve, tag_max, n_walk_limit, clear); time_profile_.calc_force += GetWtime() - wtime_offset; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Ptcl, Force:Long////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool clear){ const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); //const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; if(n_ipg <= 0) return 0; n_walk_local_ += n_ipg; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> walk_grp; static std::vector<S32> walk_grp_disp; walk_grp.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) walk_grp_disp.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 * n_epi_array; static S32 * n_epi_array_prev; static S32 * n_epj_array; static S32 * n_spj_array; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static S32 ** n_spj_disp_thread;// [n_thread][n_walk] static Tepi ** epi_array; // array of pointer *[n_walk] static Tepj ** epj_array; // array of pointer *[n_walk] static Tspj ** spj_array; // array of pointer *[n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S32 * n_sp_cum_thread; static S64 * n_interaction_ep_ep_array; static S64 * n_interaction_ep_sp_array; if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epi_array = new S32[n_walk_limit]; n_epi_array_prev = new S32[n_walk_limit]; n_epj_array = new S32[n_walk_limit]; n_spj_array = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; n_spj_disp_thread = new S32*[n_thread]; epi_array = new Tepi*[n_walk_limit]; epj_array = new Tepj*[n_walk_limit]; spj_array = new Tspj*[n_walk_limit]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; n_spj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_sp_cum_thread = new S32[n_thread]; n_interaction_ep_ep_array = new S64[n_thread]; n_interaction_ep_sp_array = new S64[n_thread]; first = false; } walk_grp_disp[0] = 0; //const S32 wg_tmp = n_ipg > 0 ? n_ipg%n_loop_max : 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ //for(int wg=0; wg<wg_tmp; wg++){ walk_grp[wg] = n_ipg / n_loop_max + 1; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ //for(int wg=wg_tmp; wg<n_loop_max; wg++){ walk_grp[wg] = n_ipg / n_loop_max; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_array[i] = n_interaction_ep_sp_array[i] = 0; } bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = walk_grp[wg]; const S32 walk_grp_head = walk_grp_disp[wg]; for(int i=0; i<n_thread; i++){ n_ep_cum_thread[i] = n_sp_cum_thread[i] = cnt_thread[i] = 0; n_epj_disp_thread[i][0] = 0; n_spj_disp_thread[i][0] = 0; epj_for_force_[i].clearSize(); spj_for_force_[i].clearSize(); } const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_array[iw] = ipg_[id_ipg].n_ptcl_; epi_array[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); makeInteractionList(id_ipg, false); n_epj_array[iw] = epj_for_force_[ith].size() - n_ep_cum_thread[ith]; n_spj_array[iw] = spj_for_force_[ith].size() - n_sp_cum_thread[ith]; n_ep_cum_thread[ith] = epj_for_force_[ith].size(); n_sp_cum_thread[ith] = spj_for_force_[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_spj_disp_thread[ith][cnt_thread[ith]+1] = n_sp_cum_thread[ith]; n_interaction_ep_ep_array[ith] += ((S64)n_epj_array[iw]*(S64)n_epi_array[iw]); n_interaction_ep_sp_array[ith] += ((S64)n_spj_array[iw]*(S64)n_epi_array[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); spj_array[iw] = spj_for_force_[ith].getPointer(n_sp_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve #else //original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); spj_array[iw] = spj_for_force_[ith].getPointer(n_sp_head); } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_array, n_epi_array, (const Tepj**)epj_array, n_epj_array, (const Tspj**)spj_array, n_spj_array); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_array_prev[iw] = n_epi_array[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_array[i]; n_interaction_ep_sp_local_ += n_interaction_ep_sp_array[i]; } //std::cerr<<"(C) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Ptcl, Force:Short////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool clear){ //std::cerr<<"rank(A)= "<<Comm::getRank()<<std::endl; const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; //const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; n_walk_local_ += n_ipg; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> walk_grp; static std::vector<S32> walk_grp_disp; walk_grp.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) walk_grp_disp.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 * n_epi_array; static S32 * n_epi_array_prev; static S32 * n_epj_array; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static Tepi ** epi_array; // array of pointer *[n_walk] static Tepj ** epj_array; // array of pointer *[n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S64 * n_interaction_ep_ep_array; if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epi_array = new S32[n_walk_limit]; n_epi_array_prev = new S32[n_walk_limit]; n_epj_array = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; epi_array = new Tepi*[n_walk_limit]; epj_array = new Tepj*[n_walk_limit]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_interaction_ep_ep_array = new S64[n_thread]; first = false; } walk_grp_disp[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ walk_grp[wg] = (n_ipg/n_loop_max) + 1; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ walk_grp[wg] = n_ipg / n_loop_max; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_array[i] = 0; } bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = walk_grp[wg]; const S32 walk_grp_head = walk_grp_disp[wg]; for(int i=0; i<n_thread; i++){ n_ep_cum_thread[i] = cnt_thread[i] = 0; n_epj_disp_thread[i][0] = 0; epj_for_force_[i].clearSize(); } const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_array[iw] = ipg_[id_ipg].n_ptcl_; epi_array[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); makeInteractionList(id_ipg, false); n_epj_array[iw] = epj_for_force_[ith].size() - n_ep_cum_thread[ith]; n_ep_cum_thread[ith] = epj_for_force_[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_interaction_ep_ep_array[ith] += (S64)n_epj_array[iw]*(S64)n_epi_array[iw]; iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_array, n_epi_array, (const Tepj**)epj_array, n_epj_array); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_array_prev[iw] = n_epi_array[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; //std::cerr<<"rank(E)= "<<Comm::getRank()<<std::endl; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_array[i]; } //std::cerr<<"(D) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; //std::cerr<<"rank(Z)= "<<Comm::getRank()<<std::endl; return ret; } ////////////////////////////////////////////////// //////////// Walk+Force, Kernel:Ptcl, List:Index ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexNew(Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ if(tag_max <= 0){ PARTICLE_SIMULATOR_PRINT_ERROR("tag_max is illegal. In currente version, tag_max must be 1"); Abort(-1); } force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } S32 ret = 0; const F64 time_offset = GetWtime(); ret = calcForceMultiWalkIndexNewImpl(typename TSM::force_type(), pfunc_dispatch, pfunc_retrieve, tag_max, n_walk_limit, flag_keep_list, clear); time_profile_.calc_force += GetWtime() - time_offset; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Index Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexNewImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); interaction_list_.n_sp_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_sp_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_sp_.clearSize(); } const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static S32 ** n_spj_disp_thread;// [n_thread][n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S32 * n_sp_cum_thread; static S64 * n_interaction_ep_ep_ar; static S64 * n_interaction_ep_sp_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_spj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tspj*> spj_ar; spj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; n_spj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; n_spj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_sp_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; n_interaction_ep_sp_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_spj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = n_interaction_ep_sp_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); const S32 adr_tree_sp_first = spj_org_.size(); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = n_sp_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; n_spj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_spj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, Tspj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], spj_sorted_, adr_spj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, adr_tree_sp_first, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } for(S32 i=0; i<adr_spj_tmp[ith].size(); i++){ mass_tmp += spj_sorted_[ adr_spj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_spj_ar[iw] = adr_spj_tmp[ith].size() - n_sp_cum_thread[ith]; #if 0 if(Comm::getRank()==0){ std::cout<<"Multi:yes, index:no id_ipg= "<<id_ipg <<" target_box= "<<target_box.vertex_ <<" n_epi= "<<ipg_[id_ipg].n_ptcl_ <<" n_epj= "<<n_epj_ar[iw] <<" n_spj= "<<n_spj_ar[iw] <<" tc_glb_[0].mom_.vertex_out_= "<<tc_glb_[0].mom_.vertex_out_ <<" tc_glb_[0].n_ptcl_= "<<tc_glb_[0].n_ptcl_ <<std::endl; } #endif n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_sp_cum_thread[ith] = adr_spj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_spj_disp_thread[ith][cnt_thread[ith]+1] = n_sp_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_ar[ith] += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = interaction_list_.n_disp_sp_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; interaction_list_.n_sp_[id_ipg] = n_spj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; interaction_list_.n_disp_sp_[id_ipg+1] = interaction_list_.n_disp_sp_[id_ipg] + interaction_list_.n_sp_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); interaction_list_.adr_sp_.resizeNoInitialize( interaction_list_.n_disp_sp_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } S32 adr_sp = interaction_list_.n_disp_sp_[adr_ipg]; const S32 k_sp_h = n_spj_disp_thread[i][j]; const S32 k_sp_e = n_spj_disp_thread[i][j+1]; for(S32 k=k_sp_h; k<k_sp_e; k++, adr_sp++){ interaction_list_.adr_sp_[adr_sp] = adr_spj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #if 1 epj_for_force_[0].clearSize(); spj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } S32 * id_spj = adr_spj_tmp[ith].getPointer(n_sp_head); for(S32 jp=0; jp<n_spj_ar[iw]; jp++){ spj_for_force_[0].push_back( spj_sorted_[id_spj[jp]] ); } } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve epj_for_force_[0].clearSize(); spj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } S32 * id_spj = adr_spj_tmp[ith].getPointer(n_sp_head); for(S32 jp=0; jp<n_spj_ar[iw]; jp++){ spj_for_force_[0].push_back( spj_sorted_[id_spj[jp]] ); } } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer(), (const Tspj**)spj_ar.getPointer(), n_spj_ar.getPointer()); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; n_interaction_ep_sp_local_ += n_interaction_ep_sp_ar[i]; } //std::cerr<<"(E) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Index Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexNewImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); } const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S64 * n_interaction_ep_ep_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 epj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } } S64 n_epj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve epj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } } S64 n_epj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer()); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = 0; n_interaction_ep_ep_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; } //std::cerr<<"(F) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Kernel:Ptcl, List:Index ////////////// ////////////////////////////////////////////////// /////////////////////////////////////////////////// // // FUNCTIONS OF FORCE WITHOUT WALK // (MUST BE USED AFTER WALK) // /////////////////////////////////////////////////// //////////////////////////////////////////////////// //////////// Force Only, Kernel:Index, List:Index ////////////// //////////// Force Only, Kernel:Index, List:Index, Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_spj_ar; id_spj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; S32 ** id_spj_dummy = NULL; S32 * n_spj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, (const S32**)id_spj_dummy, n_spj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), true); const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; id_spj_ar[iw] = interaction_list_.adr_sp_.getPointer(interaction_list_.n_disp_sp_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), (const S32**)id_spj_ar.getPointer(), n_spj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), false); n_walk_prev = n_walk; first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else //original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; id_spj_ar[iw] = interaction_list_.adr_sp_.getPointer(interaction_list_.n_disp_sp_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), (const S32**)id_spj_ar.getPointer(), n_spj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), false); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } time_profile_.calc_force__core += GetWtime() - time_offset; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; } //////////// Force Only, Kernel:Index, List:Index, Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), true); const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), false); n_walk_prev = n_walk; first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else // original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); //S32 n_ep_head = interaction_list_.n_disp_ep_[id_walk]; n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), false); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } time_profile_.calc_force__core += GetWtime() - time_offset; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; } /////////////////////////////////////////////////// //////////// Force Only, Kernel:Ptcl, List:Index ////////////// //////////// Force Only, Kernel:Ptcl, List:Index, Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkNewImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ //F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tspj*> spj_ar; spj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; n_walk_prev = (wg>0) ? n_walk_ar[wg-1] : 0; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } const S64 n_sp_head = interaction_list_.n_disp_sp_[n_walk_head]; const S64 n_sp_end = interaction_list_.n_disp_sp_[n_walk_head+n_walk]; const S64 n_spj_tot = n_sp_end - n_sp_head; spj_for_force_[0].resizeNoInitialize(n_spj_tot); for(S32 jp=0; jp<n_spj_tot; jp++){ spj_for_force_[0][jp] = spj_sorted_[ interaction_list_.adr_sp_[jp+n_sp_head] ]; } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); spj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer(), (const Tspj**)spj_ar.getPointer(), n_spj_ar.getPointer()); first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else // original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; //id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; //id_spj_ar[iw] = interaction_list_.adr_sp_.getPointer(interaction_list_.n_disp_sp_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } const S64 n_sp_head = interaction_list_.n_disp_sp_[n_walk_head]; const S64 n_sp_end = interaction_list_.n_disp_sp_[n_walk_head+n_walk]; const S64 n_spj_tot = n_sp_end - n_sp_head; spj_for_force_[0].resizeNoInitialize(n_spj_tot); for(S32 jp=0; jp<n_spj_tot; jp++){ spj_for_force_[0][jp] = spj_sorted_[ interaction_list_.adr_sp_[jp+n_sp_head] ]; } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); spj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } /* const S64 n_epj_tot = interaction_list_.adr_ep_.size(); epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp] ]; } const S64 n_spj_tot = interaction_list_.adr_sp_.size(); spj_for_force_[0].resizeNoInitialize(n_spj_tot); for(S32 jp=0; jp<n_spj_tot; jp++){ spj_for_force_[0][jp] = spj_sorted_[ interaction_list_.adr_sp_[jp] ]; } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); spj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } */ ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer(), (const Tspj**)spj_ar.getPointer(), n_spj_ar.getPointer()); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } /* std::cerr<<"epj_sorted_.size()= "<<epj_sorted_.size() <<" spj_sorted_.size()= "<<spj_sorted_.size()<<std::endl; */ copyForceOriginalOrder(); //time_profile_.calc_force += GetWtime() - time_offset; } //////////// Force Only, Kernel:Ptcl, List:Index, Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkNewImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; n_walk_prev = (wg>0) ? n_walk_ar[wg-1] : 0; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } S64 n_epj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer()); first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else // original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); //S32 n_ep_head = interaction_list_.n_disp_ep_[id_walk]; n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } S64 n_epj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer()); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } time_profile_.calc_force__core += GetWtime() - time_offset; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; } }
48.198771
165
0.537694
Guo-astro
56e03753132a571f60eb153d39a3093b7563e714
1,457
hpp
C++
src/core/stores/preferences_store.hpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
3
2019-04-26T17:48:24.000Z
2021-11-08T20:21:51.000Z
src/core/stores/preferences_store.hpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
90
2019-04-25T17:23:10.000Z
2022-02-12T19:49:55.000Z
src/core/stores/preferences_store.hpp
judoassistant/judoassistant
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
[ "MIT" ]
null
null
null
#pragma once #include "core/serialize.hpp" #include "core/draw_systems/draw_system_identifier.hpp" class DrawSystem; struct DrawSystemPreference { std::size_t playerLowerLimit; DrawSystemIdentifier drawSystem; DrawSystemPreference() = default; DrawSystemPreference(std::size_t playerLowerLimit, DrawSystemIdentifier drawSystem); template<typename Archive> void serialize(Archive& ar, uint32_t const version) { ar(playerLowerLimit, drawSystem); } }; enum class ScoreboardStylePreference { NATIONAL, INTERNATIONAL }; enum class MatchCardStylePreference { NATIONAL }; class PreferencesStore { public: PreferencesStore(); template<typename Archive> void serialize(Archive& ar, uint32_t const version) { ar(mPreferredDrawSystems, mScoreboardStyle, mMatchCardStyle); } const std::vector<DrawSystemPreference>& getPreferredDrawSystems() const; std::vector<DrawSystemPreference>& getPreferredDrawSystems(); DrawSystemIdentifier getPreferredDrawSystem(std::size_t size) const; ScoreboardStylePreference getScoreboardStyle() const; void setScoreboardStyle(ScoreboardStylePreference style); MatchCardStylePreference getMatchCardStyle() const; void setMatchCardStyle(MatchCardStylePreference style); private: std::vector<DrawSystemPreference> mPreferredDrawSystems; ScoreboardStylePreference mScoreboardStyle; MatchCardStylePreference mMatchCardStyle; };
29.14
88
0.780371
svendcsvendsen
56e1bb2c38688018ae446fdfbdf16fecc19f6f1e
2,371
hpp
C++
headers/USRP_file_writer.hpp
zjc263/GPU_SDR
a57a29925b915c6eb995eb3c76c4ec34f96c3a0b
[ "Apache-2.0" ]
9
2019-07-23T10:31:18.000Z
2022-03-15T19:29:26.000Z
headers/USRP_file_writer.hpp
zjc263/GPU_SDR
a57a29925b915c6eb995eb3c76c4ec34f96c3a0b
[ "Apache-2.0" ]
5
2019-09-11T22:31:29.000Z
2022-01-25T18:26:56.000Z
headers/USRP_file_writer.hpp
zjc263/GPU_SDR
a57a29925b915c6eb995eb3c76c4ec34f96c3a0b
[ "Apache-2.0" ]
7
2019-08-29T20:47:56.000Z
2021-06-10T15:07:35.000Z
#pragma once #ifndef FILE_WRITER_INCLUDED #define FILE_WRITER_INCLUDED #include "USRP_server_settings.hpp" #include "USRP_server_diagnostic.hpp" #include "USRP_server_memory_management.hpp" #include "USRP_server_network.hpp" #include <ctime> #include "H5Cpp.h" #include "H5CompType.h" using namespace H5; class H5_file_writer{ public: rx_queue* stream_queue; //the initialization needs a rx queue to get packets and a memory to dispose of them //NOTE: the file writer should always be the last element of the chain unless using a very fast storage support H5_file_writer(rx_queue* init_queue, preallocator<float2>* init_memory); H5_file_writer(Sync_server *streaming_server); void start(usrp_param* global_params); bool stop(bool force = false); void close(); //in case of pointers update in the TXRX class method set() those functions have to be called //this is because memory size adjustments on rx_output preallocator void update_pointers(rx_queue* init_queue, preallocator<float2>* init_memory); void update_pointers(Sync_server *streaming_server); private: //datatype used by HDF5 api CompType *complex_data_type;//(sizeof(float2)); //pointer to the h5 file H5File *file; //pointer to the raw_data group (single USRP writer) Group *group; //pointers to possible groups for representing USRP X300 data Group *A_TXRX; Group *B_TXRX; Group *A_RX2; Group *B_RX2; //dataspace for H5 file writing DataSpace *dataspace; //rank of the raw_data's datasets and dimensions int dspace_rank; hsize_t *dimsf; //pointer to the memory recycler preallocator<float2>* memory; //pointer to the thread boost::thread* binary_writer; std::atomic<bool> writing_in_progress; void write_properties(Group *measure_group, param* parameters_group); std::string get_name(); void clean_queue(); //force the joining of the thread std::atomic<bool> force_close; void write_files(); }; #endif
29.6375
119
0.628005
zjc263
56ebb968ba92f8bfbfed3c459f23b269fdb50ab0
579
cpp
C++
Lab_7/Q2/function_overloading.cpp
pranav2012/Object-Oriented-Programming-In-C
6ff8fc15ea9f0a44659bdf630975ccfdf6ab1ffb
[ "MIT" ]
3
2020-08-27T03:55:40.000Z
2020-09-28T17:29:48.000Z
Lab_7/Q2/function_overloading.cpp
pranav2012/Object-Oriented-Programming-In-C
6ff8fc15ea9f0a44659bdf630975ccfdf6ab1ffb
[ "MIT" ]
null
null
null
Lab_7/Q2/function_overloading.cpp
pranav2012/Object-Oriented-Programming-In-C
6ff8fc15ea9f0a44659bdf630975ccfdf6ab1ffb
[ "MIT" ]
1
2020-12-08T11:35:17.000Z
2020-12-08T11:35:17.000Z
#include<iostream> using namespace std; int area(int); int area(int,int); float area(float,float); int main() { int s,l,b; float bs,ht; cout<<"Enter side of a square: "; cin>>s; cout<<"Enter length and breadth of rectangle: "; cin>>l>>b; cout<<"Enter base and height of triangle: "; cin>>bs>>ht; cout<<"Area of square is "<<area(s); cout<<"\nArea of rectangle is "<<area(l,b); cout<<"\nArea of triangle is "<<area(bs,ht)<<"\n"; } int area(int s) { return(s*s); } int area(int l,int b) { return(l*b); } float area(float bs,float ht) { return((bs*ht)/2); }
18.677419
54
0.620035
pranav2012
56ec7bc330ab4bef20982ad0244d497b49547411
147
hpp
C++
include/natalie/types.hpp
davidot/natalie
e5159bacb3831c1720063360570810c0fd2c3ae9
[ "MIT" ]
1
2021-11-17T22:01:36.000Z
2021-11-17T22:01:36.000Z
include/natalie/types.hpp
jcs/natalie
36dae5954b80be2af107840de2b1c76b69bf6ac0
[ "MIT" ]
null
null
null
include/natalie/types.hpp
jcs/natalie
36dae5954b80be2af107840de2b1c76b69bf6ac0
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #define NAT_INT_MIN INT64_MIN #define NAT_INT_MAX INT64_MAX namespace Natalie { using nat_int_t = int64_t; }
11.307692
29
0.768707
davidot
56f34317250f150f24f5135f02fea980b0f3b444
106
cpp
C++
src/opera/tcppacket.cpp
Flasew/opera-sim
1f64017883689c115b8442acab7ef52846ab2c18
[ "BSD-3-Clause" ]
null
null
null
src/opera/tcppacket.cpp
Flasew/opera-sim
1f64017883689c115b8442acab7ef52846ab2c18
[ "BSD-3-Clause" ]
null
null
null
src/opera/tcppacket.cpp
Flasew/opera-sim
1f64017883689c115b8442acab7ef52846ab2c18
[ "BSD-3-Clause" ]
null
null
null
#include "tcppacket.h" PacketDB<TcpPacket> TcpPacket::_packetdb; PacketDB<TcpAck> TcpAck::_packetdb;
21.2
42
0.764151
Flasew
56f5669f234a76ed22fd3e56c98b758224877344
679
cpp
C++
ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp
luohenyueji/OpenCV-Practical-Exercise
8a747b05b5c56d5be4611c5e72c8983f6b96d81d
[ "MIT" ]
293
2019-04-05T14:31:22.000Z
2022-03-30T10:04:51.000Z
ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp
hktkfly6/OpenCV-Practical-Exercise
8a747b05b5c56d5be4611c5e72c8983f6b96d81d
[ "MIT" ]
2
2019-04-05T14:31:04.000Z
2021-11-26T09:27:54.000Z
ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp
hktkfly6/OpenCV-Practical-Exercise
8a747b05b5c56d5be4611c5e72c8983f6b96d81d
[ "MIT" ]
149
2019-04-06T10:51:13.000Z
2022-03-31T01:34:47.000Z
#include "pch.h" #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { Mat im1 = imread("./image/S0.png",IMREAD_GRAYSCALE); Mat im2 = imread("./image/K0.png",IMREAD_GRAYSCALE); Mat im3 = imread("./image/S4.png",IMREAD_GRAYSCALE); double m1 = matchShapes(im1, im1, CONTOURS_MATCH_I2, 0); double m2 = matchShapes(im1, im2, CONTOURS_MATCH_I2, 0); double m3 = matchShapes(im1, im3, CONTOURS_MATCH_I2, 0); cout << "Shape Distances Between " << endl << "-------------------------" << endl; cout << "S0.png and S0.png : " << m1 << endl; cout << "S0.png and K0.png : " << m2 << endl; cout << "S0.png and S4.png : " << m3 << endl; }
30.863636
84
0.617084
luohenyueji
56f74ff70e4a016d75d77729972c677f850f456a
1,942
cpp
C++
Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.cpp
RobertAcksel/UnrealCS
16d6f4989ef2f8622363009ebc6509b67c35a57e
[ "MIT" ]
1
2017-11-21T01:25:19.000Z
2017-11-21T01:25:19.000Z
Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.cpp
RobertAcksel/UnrealCS
16d6f4989ef2f8622363009ebc6509b67c35a57e
[ "MIT" ]
null
null
null
Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.cpp
RobertAcksel/UnrealCS
16d6f4989ef2f8622363009ebc6509b67c35a57e
[ "MIT" ]
null
null
null
#include "MonoCallbackScheduler.h" #include "MonoPluginPrivatePCH.h" bool MonoCallbackScheduler::AddTickableObject(MonoObject * obj) { if(obj == nullptr) return false; MonoClass * ObjectClass = mono_object_get_class(obj); TickObject Data; Data.removed = false; Data.Obj = obj; Data.TickMethod = mono_class_get_method_from_name(ObjectClass, "Tick", 1); if(Data.TickMethod == nullptr) return false; //attrs.name Data.gc_handle = mono_gchandle_new(obj, 1); for(int32 i = 0; i < TickObjects.Num(); i++) { if(TickObjects[i].removed) { TickObjects[i] = Data; return true; } } TickObjects.Add(Data); return true; } bool MonoCallbackScheduler::RemoveTickableObject(MonoObject * obj) { for(int32 i = 0; i < TickObjects.Num(); i++) { if(TickObjects[i].Obj == obj && !TickObjects[i].removed) { TickObjects[i].Obj = nullptr; mono_gchandle_free(TickObjects[i].gc_handle); TickObjects[i].removed = true; return true; } } return false; } void MonoCallbackScheduler::Tick(float DeltaTime) { for(int32 i = 0; i < TickObjects.Num(); i++) { if(!TickObjects[i].removed) { void * args[]{ &DeltaTime }; MonoObject * exception = nullptr; MonoObject * ret = mono_runtime_invoke(TickObjects[i].TickMethod, TickObjects[i].Obj, args, &exception); if(exception) { mono_print_unhandled_exception(exception); } } } } void MonoCallbackScheduler::HotReload() { //Remove all tickable objects for(int32 i = 0; i < TickObjects.Num(); i++) { if(!TickObjects[i].removed) { mono_gchandle_free(TickObjects[i].gc_handle); } } TickObjects.Empty(); }
28.558824
117
0.572091
RobertAcksel
56f826e8358547dcae3d8d04b66b055d28548051
2,789
cpp
C++
buildcc/lib/target/src/target/tasks.cpp
d-winsor/build_in_cpp
581c827fd8c69a7258175e360847676861a5c7b0
[ "Apache-2.0" ]
null
null
null
buildcc/lib/target/src/target/tasks.cpp
d-winsor/build_in_cpp
581c827fd8c69a7258175e360847676861a5c7b0
[ "Apache-2.0" ]
null
null
null
buildcc/lib/target/src/target/tasks.cpp
d-winsor/build_in_cpp
581c827fd8c69a7258175e360847676861a5c7b0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Niket Naidu. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "target/target.h" #include <algorithm> #include "env/assert_fatal.h" #include "env/logging.h" #include "target/util.h" #include "fmt/format.h" namespace { constexpr const char *const kPchTaskName = "Pch"; constexpr const char *const kCompileTaskName = "Objects"; constexpr const char *const kLinkTaskName = "Target"; } // namespace namespace buildcc::base { void CompilePch::Task() { task_ = target_.tf_.emplace([&](tf::Subflow &subflow) { BuildCompile(); // For Graph generation for (const auto &p : target_.GetCurrentPchFiles()) { std::string name = p.lexically_relative(env::get_project_root_dir()).string(); std::replace(name.begin(), name.end(), '\\', '/'); subflow.placeholder().name(name); } }); task_.name(kPchTaskName); } void CompileObject::Task() { compile_task_ = target_.tf_.emplace([&](tf::Subflow &subflow) { std::vector<fs::path> source_files; std::vector<fs::path> dummy_source_files; BuildObjectCompile(source_files, dummy_source_files); for (const auto &s : source_files) { std::string name = s.lexically_relative(env::get_project_root_dir()).string(); std::replace(name.begin(), name.end(), '\\', '/'); (void)subflow .emplace([this, s]() { bool success = Command::Execute(GetObjectData(s).command); env::assert_fatal(success, "Could not compile source"); }) .name(name); } // For graph generation for (const auto &ds : dummy_source_files) { std::string name = ds.lexically_relative(env::get_project_root_dir()).string(); std::replace(name.begin(), name.end(), '\\', '/'); (void)subflow.placeholder().name(name); } }); compile_task_.name(kCompileTaskName); } void LinkTarget::Task() { task_ = target_.tf_.emplace([&]() { BuildLink(); }); task_.name(kLinkTaskName); } void Target::TaskDeps() { // NOTE, PCH may not be used if (!compile_pch_.GetTask().empty()) { compile_object_.GetTask().succeed(compile_pch_.GetTask()); } link_target_.GetTask().succeed(compile_object_.GetTask()); } } // namespace buildcc::base
28.752577
75
0.662603
d-winsor
56fbc38ea543637a2e94ad8355f09036344b9d42
376
cpp
C++
src/mlcmst_solver.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
src/mlcmst_solver.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
src/mlcmst_solver.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
#include <mlcmst_solver.hpp> #include <utility> namespace MLCMST { MLCMST_Solver::~MLCMST_Solver() = default; MLCMST_Solver::Result::Result( std::optional<network::MLCST> mlcmst, std::optional<double> lower_bound, double wall_time, bool finished ) : mlcst(std::move(mlcmst)), lower_bound(std::move(lower_bound)), wall_time(wall_time), finished(finished) { } }
23.5
112
0.731383
qaskai
56ffdb1efbe44ece05cdf7a223b4597422a08c75
3,297
cpp
C++
snippets/0x01/work_string.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
snippets/0x01/work_string.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
snippets/0x01/work_string.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
// author: [email protected] #include <iostream> using namespace std; int main() { cout << endl << "--- " << __FILE__ << " ---" << endl << endl; string s{"Beispiel"}; // (A) cout << "01| s='" << s << "'" << endl; // (B) cout << "-----" << endl; cout << "02| s+s='" << s + s << "' (op+)" << endl; // (C) cout << "03| s[1]='" << s[1] << "' (op[])" << endl; // (D) s += "!"; // (E) cout << "04| s='" << s << "' (op+=)" << endl; cout << "-----" << endl; cout << "05| s.size()=" << s.size() << endl; // (F) cout << "06| s.empty()=" << s.empty() << endl; // (G) cout << "07| s.at(1)='" << s.at(1) << "'" << endl; // (H) cout << "08| s.substr(1,3)='" // (I) << s.substr(1, 3) << "'" << endl; cout << "-----" << endl; string::size_type pos; // (J) bool found; found = ((pos = s.find("spiel")) != string::npos); // (K), (L) cout << "09| find(\"spiel\") ok? " << found << ", pos=" << pos << endl; found = ((pos = s.find("Reis")) != string::npos); cout << "10| find(\"Reis\") ok? " << found << endl; found = ((pos = s.rfind("i")) != string::npos); // (M) cout << "11| rfind(\"i\") ok? " << found << ", pos=" << pos << endl; cout << "-----" << endl; string rep1{"Bei"}; pos = s.find(rep1); s.replace(pos, rep1.size(), "Fussball"); // (N) cout << "12| s.replace(...), s='" << s << "'" << endl; string rep2{"!"}; pos = s.find(rep2); s.erase(pos, rep2.size()); // (O) cout << "13| s.erase(...), s='" << s << "'" << endl; s.insert(0, "XXL-"); // (P) cout << "14| insert(0,\"XXL-\"), s='" << s << "'" << endl; s.append("e"); // (Q) cout << "15| append(\"e\"), s='" << s << "'" << endl; cout << endl << "--- " << __FILE__ << " ---" << endl << endl; return 0; } /* Kommentierung * * (A) Definition eines 'string'. * * (B) Die Ausgabe auf cout. * * (C) Strings können 'addiert' werden, d.h. über '+' werden sie * aneinander gehängt. * * (D) Über '[pos]' können einzelne Zeichen gelesen werden, ohne Test * der Grenzen. * * (E) Der Operator '+=' hängt Zeichen oder Texte an. * * (F) 'size' gibt die Länge des Strings zurück, 0 ist möglich. * * (G) 'empty' testet, ob der String leer ist (Größe 0). * * (H) 'at' liest Zeichen an einer Position, aber mit Test der Grenzen. * * (I) 'substr' liest einen Teilstring ab einer Position für eine * gegebene Länge. * * (J) 'size_type' ist der Datentyp, der eine Position im String aufnehmen * kann. * * (K) 'find' sucht ein Muster und gibt die Position zurück. * * (L) Die Konstante 'npos' wird zurück gegeben, wenn keine Muster * gefunden wurde. * * (M) 'rfind' sucht vom Ende. * * (N) 'replace' ersetzt im String ab einer Position für eine * gegebene Länge den dortigen Text mit einem neuen. * * (O) 'erase' löscht im String ab einer Position für eine * gegebene Länge. * * (P) 'insert' fügt an einer Position neuen Text ein. * * (Q) 'append' hängt Text an. * */
28.921053
75
0.451319
pblan