blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
780b57ae11b695cb1b0eab95c164c443dd50fc95
aca9b78a6fc46cf9c0a51be4c0caf694c7d3b4c6
/PyCTP_Client/PyQt_Demo/GAS_V20160904/GAS/frmconfig.cpp
9cfe16510f311a05c11a3010e77566c87ba9cdac
[]
no_license
15137359541/PyCTP-master
cd3842ef6a7dfe0f9abb888ee40ce5e53473318c
417617c232cdb274c8dec4dbc80ed6e015b1affe
refs/heads/master
2020-03-29T08:16:19.438755
2018-09-21T03:04:04
2018-09-21T03:04:04
149,702,241
0
2
null
null
null
null
UTF-8
C++
false
false
10,813
cpp
#include "frmconfig.h" #include "ui_frmconfig.h" #include "api/myhelper.h" #include "api/hostapi.h" #include "api/ntpapi.h" #include "inputnew/frminputnew.h" frmConfig::frmConfig(QWidget *parent) : QWidget(parent), ui(new Ui::frmConfig) { ui->setupUi(this); this->InitForm(); QTimer::singleShot(3000,this,SLOT(on_btnNTP_clicked())); } frmConfig::~frmConfig() { delete ui; } void frmConfig::InitForm() { #ifdef __arm__ ui->widget_left->setMinimumWidth(150); ui->widget_left->setMaximumWidth(150); #endif QList<QPushButton *> btns = ui->widget_left->findChildren<QPushButton *>(); foreach (QPushButton * btn, btns) { connect(btn, SIGNAL(clicked()), this, SLOT(button_clicked())); } ui->btnConfig->click(); //加载配置文件对应界面展示信息 ui->btnUseInput->SetCheck(App::UseInput); connect(ui->btnUseInput, SIGNAL(pressed()), this, SLOT(SaveConfig())); ui->cboxInputPosition->addItem("控件下方"); ui->cboxInputPosition->addItem("底部填充"); ui->cboxInputPosition->addItem("屏幕居中"); int index = 0; if (App::InputPosition == "control") { index = 0; } else if (App::InputPosition == "bottom") { index = 1; } else if (App::InputPosition == "center") { index = 2; } ui->cboxInputPosition->setCurrentIndex(index); connect(ui->cboxInputPosition, SIGNAL(currentIndexChanged(int)), this, SLOT(SaveConfig())); ui->txtTitle->setText(App::Title); connect(ui->txtTitle, SIGNAL(textChanged(QString)), this, SLOT(SaveConfig())); ui->txtVersion->setText(App::Version); connect(ui->txtVersion, SIGNAL(textChanged(QString)), this, SLOT(SaveConfig())); QStringList qssName; qssName << "黑色风格" << "淡蓝色风格" << "蓝色风格" << "灰黑色风格" << "灰色风格" << "浅灰色风格" << "深灰色风格" << "银色风格"; ui->cboxStyleName->addItems(qssName); if (App::StyleName == ":/qss/black.css") { ui->cboxStyleName->setCurrentIndex(0); } else if (App::StyleName == ":/qss/blue.css") { ui->cboxStyleName->setCurrentIndex(1); } else if (App::StyleName == ":/qss/dev.css") { ui->cboxStyleName->setCurrentIndex(2); } else if (App::StyleName == ":/qss/brown.css") { ui->cboxStyleName->setCurrentIndex(3); } else if (App::StyleName == ":/qss/gray.css") { ui->cboxStyleName->setCurrentIndex(4); } else if (App::StyleName == ":/qss/lightgray.css") { ui->cboxStyleName->setCurrentIndex(5); } else if (App::StyleName == ":/qss/darkgray.css") { ui->cboxStyleName->setCurrentIndex(6); } else if (App::StyleName == ":/qss/silvery.css") { ui->cboxStyleName->setCurrentIndex(7); } connect(ui->cboxStyleName, SIGNAL(currentIndexChanged(int)), this, SLOT(SaveConfig())); ui->txtAuthor->setText(App::Author); connect(ui->txtAuthor, SIGNAL(textChanged(QString)), this, SLOT(SaveConfig())); ui->btnUseNTP->SetCheck(App::UseNTP); connect(ui->btnUseNTP, SIGNAL(pressed()), this, SLOT(SaveConfig())); ui->txtNTPIP->setText(App::NTPIP); connect(ui->txtNTPIP, SIGNAL(textChanged(QString)), this, SLOT(SaveConfig())); for (int i = 0; i <= 24; i++) { ui->cboxNTPInterval->addItem(QString("%1小时").arg(i)); } ui->cboxNTPInterval->setCurrentIndex(App::NTPInterval); connect(ui->cboxNTPInterval, SIGNAL(currentIndexChanged(int)), this, SLOT(SaveConfig())); for (int i = 2015; i <= 2025; i++) { ui->cboxYear->addItem(QString::number(i)); } for (int i = 1; i <= 12; i++) { ui->cboxMonth->addItem(QString::number(i)); } for (int i = 1; i <= 31; i++) { ui->cboxDay->addItem(QString::number(i)); } for (int i = 0; i < 24; i++) { ui->cboxHour->addItem(QString::number(i)); } for (int i = 0; i < 60; i++) { ui->cboxMin->addItem(QString::number(i)); ui->cboxSec->addItem(QString::number(i)); } QString now = QDateTime::currentDateTime().toString("yyyy-M-d-H-m-s"); QStringList str = now.split("-"); ui->cboxYear->setCurrentIndex(ui->cboxYear->findText(str.at(0))); ui->cboxMonth->setCurrentIndex(ui->cboxMonth->findText(str.at(1))); ui->cboxDay->setCurrentIndex(ui->cboxDay->findText(str.at(2))); ui->cboxHour->setCurrentIndex(ui->cboxHour->findText(str.at(3))); ui->cboxMin->setCurrentIndex(ui->cboxMin->findText(str.at(4))); ui->cboxSec->setCurrentIndex(ui->cboxSec->findText(str.at(5))); //读取IP地址等信息 QString fileName("/etc/eth0-setting"); QFile file(fileName); file.open(QFile::ReadOnly); QString netInfo = QLatin1String(file.readAll()); file.close(); QStringList list = netInfo.split("\n"); if (list.count() >= 4) { QString netIP = list.at(0).split("=").at(1); QString netMask = list.at(1).split("=").at(1); QString netGateway = list.at(2).split("=").at(1); QString netDNS = list.at(3).split("=").at(1); QString netMac = list.at(4).split("=").at(1); ui->txtNetIP->setText(netIP); ui->txtNetMask->setText(netMask); ui->txtNetGateway->setText(netGateway); ui->txtNetDNS->setText(netDNS); ui->txtNetMac->setText(netMac); } connect(NTPAPI::Instance(), SIGNAL(ReceiveTime(QDateTime)), this, SLOT(ReceiveTime(QDateTime))); } void frmConfig::button_clicked() { QPushButton *btn = (QPushButton *)sender(); QString name = btn->text(); QList<QPushButton *> btns = ui->widget_left->findChildren<QPushButton *>(); foreach (QPushButton * b, btns) { b->setChecked(false); } btn->setChecked(true); if (name == "主界面") { ui->stackedWidget->setCurrentIndex(0); } else if (name == "记录查询") { ui->stackedWidget->setCurrentIndex(1); } else if (name == "系统设置") { ui->stackedWidget->setCurrentIndex(2); } } void frmConfig::SaveConfig() { //保存配置文件信息 App::UseInput = ui->btnUseInput->GetCheck(); if (!App::UseInput) { frmInputNew::Instance()->hide(); } QString str = ui->cboxInputPosition->currentText(); QString position ; if (str == "控件下方") { position = "control"; } else if (str == "底部填充") { position = "bottom"; } else if (str == "屏幕居中") { position = "center"; } if (position != App::InputPosition) { App::InputPosition = position; #ifdef __arm__ frmInputNew::Instance()->init(App::InputPosition, "black", App::FontSize + 2, App::FontSize - 2, 800, 230, 20, 20, 6, 45); #else frmInputNew::Instance()->init(App::InputPosition, "black", App::FontSize + 2, App::FontSize, 700, 230, 20, 20, 6, 45); #endif } App::Title = ui->txtTitle->text(); App::Version = ui->txtVersion->text(); QString style; int styleIndex = ui->cboxStyleName->currentIndex(); if (styleIndex == 0) { style = ":/qss/black.css"; } else if (styleIndex == 1) { style = ":/qss/blue.css"; } else if (styleIndex == 2) { style = ":/qss/dev.css"; } else if (styleIndex == 3) { style = ":/qss/brown.css"; } else if (styleIndex == 4) { style = ":/qss/gray.css"; } else if (styleIndex == 5) { style = ":/qss/lightgray.css"; } else if (styleIndex == 6) { style = ":/qss/darkgray.css"; } else if (styleIndex == 7) { style = ":/qss/silvery.css"; } if (style != App::StyleName) { App::StyleName = style; myHelper::SetStyle(App::StyleName); } App::Author = ui->txtAuthor->text(); App::UseNTP = ui->btnUseNTP->GetCheck(); App::NTPIP = ui->txtNTPIP->text(); App::NTPInterval = ui->cboxNTPInterval->currentIndex(); HostAPI::Instance()->SetNTPInterval(); //调用保存配置文件函数 App::WriteConfig(); } void frmConfig::on_btnSetTime_clicked() { QString year = QString("%1").arg(ui->cboxYear->currentText()); QString month = QString("%1").arg(ui->cboxMonth->currentText().toInt(), 2, 10, QChar('0')); QString day = QString("%1").arg(ui->cboxDay->currentText().toInt(), 2, 10, QChar('0')); QString hour = QString("%1").arg(ui->cboxHour->currentText().toInt(), 2, 10, QChar('0')); QString min = QString("%1").arg(ui->cboxMin->currentText().toInt(), 2, 10, QChar('0')); QString sec = QString("%1").arg(ui->cboxSec->currentText().toInt(), 2, 10, QChar('0')); myHelper::SetSystemDateTime(year, month, day, hour, min, sec); } void frmConfig::on_btnSetNet_clicked() { #ifndef __arm__ return; #endif QString netIP = ui->txtNetIP->text(); QString netMask = ui->txtNetMask->text(); QString netGateway = ui->txtNetGateway->text(); QString netDNS = ui->txtNetDNS->text(); QString netMac = ui->txtNetMac->text(); if (netIP.length() == 0 || netMask.length() == 0 || netGateway.length() == 0 || netDNS.length() == 0) { myHelper::ShowMessageBoxError("网络参数不能为空!"); return; } if (!myHelper::IsIP(netIP)) { myHelper::ShowMessageBoxError("IP地址不合法!"); ui->txtNetIP->setFocus(); return; } if (!myHelper::IsIP(netGateway)) { myHelper::ShowMessageBoxError("网关地址不合法!"); ui->txtNetGateway->setFocus(); return; } if (!myHelper::IsIP(netDNS)) { myHelper::ShowMessageBoxError("DNS地址不合法!"); ui->txtNetDNS->setFocus(); return; } QStringList list; list << QString("IP=%1\n").arg(netIP); list << QString("Mask=%1\n").arg(netMask); list << QString("Gateway=%1\n").arg(netGateway); list << QString("DNS=%1\n").arg(netDNS); list << QString("MAC=%1\n").arg(netMac); QString netInfo = list.join(""); QString fileName("/etc/eth0-setting"); QFile file(fileName); file.open(QFile::WriteOnly | QIODevice::Text); QTextStream out(&file); out << netInfo; file.close(); myHelper::ShowMessageBoxInfoX("设置成功,稍后重启!"); myHelper::Sleep(2000); system("reboot"); } void frmConfig::on_btnNTP_clicked() { NTPAPI::Instance()->GetTime(App::NTPIP); } void frmConfig::ReceiveTime(QDateTime dateTime) { QString now = dateTime.toString("yyyy-M-d-H-m-s"); QStringList str = now.split("-"); ui->cboxYear->setCurrentIndex(ui->cboxYear->findText(str.at(0))); ui->cboxMonth->setCurrentIndex(ui->cboxMonth->findText(str.at(1))); ui->cboxDay->setCurrentIndex(ui->cboxDay->findText(str.at(2))); ui->cboxHour->setCurrentIndex(ui->cboxHour->findText(str.at(3))); ui->cboxMin->setCurrentIndex(ui->cboxMin->findText(str.at(4))); ui->cboxSec->setCurrentIndex(ui->cboxSec->findText(str.at(5))); }
[ "1715338780@qq.com" ]
1715338780@qq.com
35111e0f61b44fe22602916e4406294abdb60f4e
e69111f9e39e173ec578e702c15ab77b915701aa
/looper_audio_video/srcs/audio_sampler_main.cpp
7bcd18ffbf3a125830c7332c88da073f5399c0aa
[]
no_license
pmike2/main
26435e3f3b18691e27f891bd8624627d99aa5763
b113f29fb0e7b6aab90142c72522038ff0e9a4d8
refs/heads/master
2023-07-20T01:45:17.224162
2023-07-13T14:40:17
2023-07-13T14:40:17
198,828,251
0
0
null
null
null
null
UTF-8
C++
false
false
3,225
cpp
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <signal.h> #include "portaudio.h" #ifdef WIN32 #include <windows.h> #if PA_USE_ASIO #include "pa_asio.h" #endif #endif #include "json.hpp" #include "constantes.h" #include "audio_sampler.h" #include "pa_utils.h" #include "sio_util.h" using namespace std; using json = nlohmann::json; // nombre de frames dans 1s d'audio const unsigned int SAMPLE_RATE= 44100; // nombre de frames a traiter a chaque appel du callback const unsigned int FRAMES_PER_BUFFER= 64; PaStream * stream; AudioSampler * audio_sampler; SocketIOUtil * sio_util; // callback PortAudio int pa_callback(const void * input, void * output, unsigned long frame_count, const PaStreamCallbackTimeInfo * time_info, PaStreamCallbackFlags status_flags, void * user_data) { AudioSampler * s= (AudioSampler *)user_data; //float * in= (float *)input; float * out= (float *)output; for (unsigned int i=0; i<frame_count; ++i) { out[2* i+ 0]= 0.0f; out[2* i+ 1]= 0.0f; for (unsigned int idx_track=0; idx_track<N_TRACKS; ++idx_track) { if (s->_track_samples[idx_track]->_playing) { if (DEBUG) { if (s->_track_samples[idx_track]->_frame_idx== 0) { time_type t= chrono::system_clock::now()- s->_debug_start_point; s->_debug[s->_compt_debug++]= t; if (s->_compt_debug>= N_DEBUG) { s->_compt_debug= 0; } } } key_type key= s->_track_samples[idx_track]->_info._key; amplitude_type amplitude= s->_track_samples[idx_track]->_info._amplitude; AudioSubSample * sub_sample= audio_sampler->get_subsample(key); if (!sub_sample) { continue; } AudioSample * audio_sample= sub_sample->_sample; if (audio_sample->_n_channels== 1) { out[2* i+ 0]+= audio_sample->_data[s->_track_samples[idx_track]->_frame_idx]* amplitude; out[2* i+ 1]+= audio_sample->_data[s->_track_samples[idx_track]->_frame_idx]* amplitude; } else { out[2* i+ 0]+= audio_sample->_data[2* s->_track_samples[idx_track]->_frame_idx+ 0]* amplitude; out[2* i+ 1]+= audio_sample->_data[2* s->_track_samples[idx_track]->_frame_idx+ 1]* amplitude; } s->_track_samples[idx_track]->_frame_idx++; if (s->_track_samples[idx_track]->_frame_idx>= audio_sample->_n_frames) { s->note_off(idx_track); } } } } return 0; } void clean() { pa_close(stream); delete sio_util; delete audio_sampler; } void interruption_handler(sig_atomic_t s) { clean(); exit(1); } void init(int idx_device_output, string json_path) { signal(SIGINT, interruption_handler); audio_sampler= new AudioSampler(json_path); stream= pa_init(-1, idx_device_output, SAMPLE_RATE, FRAMES_PER_BUFFER, pa_callback, audio_sampler); sio_util= new SocketIOUtil("http://127.0.0.1:3001", "server2client_config_changed", 2000); } void main_loop() { while (true) { if (sio_util->update()) { audio_sampler->load_json(json::parse(sio_util->_last_msg)); } audio_sampler->update(); } } int main(int argc, char **argv) { if (argc!= 3) { cout << "donner 1- idx_device_output; 2- le chemin d'un json en entrée\n"; return 1; } init(atoi(argv[1]), string(argv[2])); main_loop(); clean(); return 0; }
[ "pierre-michael.beau@ign.fr" ]
pierre-michael.beau@ign.fr
9931e9812f273bbbc0cc7944c09f15d76f76ef9e
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1483488_0/C++/Sammax/code_jam_2012_qual_C.cpp
77b2254ef605b8790a8fe6eb7b63de44d2cf6630
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,121
cpp
#include <iostream> #include <fstream> #include <sstream> #include <cstdio> #include <cmath> #include <algorithm> #include <complex> #include <string> #include <vector> #include <set> #include <map> #include <queue> #include <deque> #include <complex> #include <stdio.h> #include <cstdlib> #include <memory.h> #ifdef SAMMAX #include <ctime> clock_t beg; #endif const double pi = 3.1415926535897932384626433832795; //#pragma comment(linker, "/stack:1000000000") #define sz size() #define mp make_pair #define pb push_back #define ALL(a) (a).begin(), (a).end() #define RALL(a) (a).rbegin(), (a).rend() #define MEMS(a,b) memset(a,b,sizeof(a)) #define sqr(a) ((a)*(a)) #define HAS(a,b) ((a).find(b)!=(a).end()) #define MAX(a,b) ((a>=b)?a:b) #define MIN(a,b) ((a<=b)?a:b) #define ABS(a) ((a<0)?-(a):a) #define FOR(i,a,b) for (int i=(a);i<(b);++i) #define FORD(i,a,b) for (int i=(a);i>(b);--i) #define VVI vector < vector <int> > #define VI vector <int> #define LL long long #define U unsigned #define pnt pair <int,int> int gcd(int a,int b){if (a==0) return b;return gcd(b%a,a);} using namespace std; void ifd() { #ifdef SAMMAX freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); beg = clock(); #else #endif } void tme() { #ifdef SAMMAX fprintf(stderr,"*** Total time: %.3lf ***\n",1.0*(clock()-beg)/CLOCKS_PER_SEC); #endif } int t, ans, a, b, n, f; int d[8]; set <pnt> ss; int main() { ifd(); d[0] = 1; FOR(i, 1, 8) d[i] = d[i - 1] * 10; cin >> t; FOR(cas, 1, t + 1) { ans = 0; cin >> a >> b; ss.clear(); FOR(i, a, b + 1) { VI c; f = i; do { c.push_back(f % 10); f /= 10; } while (f); n = c.size(); FOR(j, 0, n - 1) { int m = 0; int dd = d[n - 1]; for (int k = j; k >= 0; k--) { m += c[k] * dd; dd /= 10; } for (int k = n - 1; k > j; k--) { m += c[k] * dd; dd /= 10; } if (m > i && m <= b) { ss.insert(mp(i, m)); } } } printf("Case #%d: %d\n", cas, ss.size()); } tme(); return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
27cc0cacd8d5f4714ed77a12b8a6602a53ff5ea5
9ab722e6b9e4ce741cc6f865ba97e0fdc0ad14e5
/library/third_party/skia/include/core/SkScalerContext.h
dc8a7587a0264de8dea150d58c06a5f76c64268d
[ "MIT" ]
permissive
csjy309450/PuTTY-ng
b892c6474c8ff797f1d0bf555b08351da4fe617b
0af73729d45d51936810f675d481c47e5588407b
refs/heads/master
2022-12-24T13:31:22.786842
2020-03-08T16:53:51
2020-03-08T16:53:51
296,880,184
1
0
MIT
2020-09-19T13:54:25
2020-09-19T13:54:24
null
UTF-8
C++
false
false
9,342
h
/* * Copyright (C) 2006 The Android Open Source Project * * 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 SkScalerContext_DEFINED #define SkScalerContext_DEFINED #include "SkMask.h" #include "SkMatrix.h" #include "SkPaint.h" #include "SkPath.h" #include "SkPoint.h" class SkDescriptor; class SkMaskFilter; class SkPathEffect; class SkRasterizer; // needs to be != to any valid SkMask::Format #define MASK_FORMAT_UNKNOWN (0xFF) #define MASK_FORMAT_JUST_ADVANCE MASK_FORMAT_UNKNOWN #define kMaxGlyphWidth (1<<13) struct SkGlyph { void* fImage; SkPath* fPath; SkFixed fAdvanceX, fAdvanceY; uint32_t fID; uint16_t fWidth, fHeight; int16_t fTop, fLeft; uint8_t fMaskFormat; int8_t fRsbDelta, fLsbDelta; // used by auto-kerning void init(uint32_t id) { fID = id; fImage = NULL; fPath = NULL; fMaskFormat = MASK_FORMAT_UNKNOWN; } /** * Compute the rowbytes for the specified width and mask-format. */ static unsigned ComputeRowBytes(unsigned width, SkMask::Format format) { unsigned rb = width; if (SkMask::kBW_Format == format) { rb = (rb + 7) >> 3; } else if (SkMask::kARGB32_Format == format || SkMask::kLCD32_Format == format) { rb <<= 2; } else if (SkMask::kLCD16_Format == format) { rb = SkAlign4(rb << 1); } else { rb = SkAlign4(rb); } return rb; } unsigned rowBytes() const { return ComputeRowBytes(fWidth, (SkMask::Format)fMaskFormat); } bool isJustAdvance() const { return MASK_FORMAT_JUST_ADVANCE == fMaskFormat; } bool isFullMetrics() const { return MASK_FORMAT_JUST_ADVANCE != fMaskFormat; } uint16_t getGlyphID() const { return ID2Code(fID); } unsigned getGlyphID(unsigned baseGlyphCount) const { unsigned code = ID2Code(fID); SkASSERT(code >= baseGlyphCount); return code - baseGlyphCount; } unsigned getSubX() const { return ID2SubX(fID); } SkFixed getSubXFixed() const { return SubToFixed(ID2SubX(fID)); } SkFixed getSubYFixed() const { return SubToFixed(ID2SubY(fID)); } size_t computeImageSize() const; /** Call this to set all of the metrics fields to 0 (e.g. if the scaler encounters an error measuring a glyph). Note: this does not alter the fImage, fPath, fID, fMaskFormat fields. */ void zeroMetrics(); enum { kSubBits = 2, kSubMask = ((1 << kSubBits) - 1), kSubShift = 24, // must be large enough for glyphs and unichars kCodeMask = ((1 << kSubShift) - 1), // relative offsets for X and Y subpixel bits kSubShiftX = kSubBits, kSubShiftY = 0 }; static unsigned ID2Code(uint32_t id) { return id & kCodeMask; } static unsigned ID2SubX(uint32_t id) { return id >> (kSubShift + kSubShiftX); } static unsigned ID2SubY(uint32_t id) { return (id >> (kSubShift + kSubShiftY)) & kSubMask; } static unsigned FixedToSub(SkFixed n) { return (n >> (16 - kSubBits)) & kSubMask; } static SkFixed SubToFixed(unsigned sub) { SkASSERT(sub <= kSubMask); return sub << (16 - kSubBits); } static uint32_t MakeID(unsigned code) { return code; } static uint32_t MakeID(unsigned code, SkFixed x, SkFixed y) { SkASSERT(code <= kCodeMask); x = FixedToSub(x); y = FixedToSub(y); return (x << (kSubShift + kSubShiftX)) | (y << (kSubShift + kSubShiftY)) | code; } void toMask(SkMask* mask) const; }; class SkScalerContext { public: enum Flags { kFrameAndFill_Flag = 0x01, kDevKernText_Flag = 0x02, kGammaForBlack_Flag = 0x04, // illegal to set both Gamma flags kGammaForWhite_Flag = 0x08, // illegal to set both Gamma flags // together, these two flags resulting in a two bit value which matches // up with the SkPaint::Hinting enum. kHintingBit1_Flag = 0x10, kHintingBit2_Flag = 0x20, kEmbeddedBitmapText_Flag = 0x40, kEmbolden_Flag = 0x80, kSubpixelPositioning_Flag = 0x100, kAutohinting_Flag = 0x200, // these should only ever be set if fMaskFormat is LCD16 or LCD32 kLCD_Vertical_Flag = 0x400, // else Horizontal kLCD_BGROrder_Flag = 0x800, // else RGB order }; private: enum { kHintingMask = kHintingBit1_Flag | kHintingBit2_Flag }; public: struct Rec { uint32_t fOrigFontID; uint32_t fFontID; SkScalar fTextSize, fPreScaleX, fPreSkewX; SkScalar fPost2x2[2][2]; SkScalar fFrameWidth, fMiterLimit; uint8_t fMaskFormat; uint8_t fStrokeJoin; uint16_t fFlags; // Warning: when adding members note that the size of this structure // must be a multiple of 4. SkDescriptor requires that its arguments be // multiples of four and this structure is put in an SkDescriptor in // SkPaint::MakeRec. void getMatrixFrom2x2(SkMatrix*) const; void getLocalMatrix(SkMatrix*) const; void getSingleMatrix(SkMatrix*) const; SkPaint::Hinting getHinting() const { return static_cast<SkPaint::Hinting>((fFlags & kHintingMask) >> 4); } void setHinting(SkPaint::Hinting hinting) { fFlags = (fFlags & ~kHintingMask) | (hinting << 4); } SkMask::Format getFormat() const { return static_cast<SkMask::Format>(fMaskFormat); } }; SkScalerContext(const SkDescriptor* desc); virtual ~SkScalerContext(); SkMask::Format getMaskFormat() const { return (SkMask::Format)fRec.fMaskFormat; } // remember our glyph offset/base void setBaseGlyphCount(unsigned baseGlyphCount) { fBaseGlyphCount = baseGlyphCount; } /** Return the corresponding glyph for the specified unichar. Since contexts may be chained (under the hood), the glyphID that is returned may in fact correspond to a different font/context. In that case, we use the base-glyph-count to know how to translate back into local glyph space. */ uint16_t charToGlyphID(SkUnichar uni); /** Map the glyphID to its glyph index, and then to its char code. Unmapped glyphs return zero. */ SkUnichar glyphIDToChar(uint16_t glyphID); unsigned getGlyphCount() { return this->generateGlyphCount(); } void getAdvance(SkGlyph*); void getMetrics(SkGlyph*); void getImage(const SkGlyph&); void getPath(const SkGlyph&, SkPath*); void getFontMetrics(SkPaint::FontMetrics* mX, SkPaint::FontMetrics* mY); static inline void MakeRec(const SkPaint&, const SkMatrix*, Rec* rec); static SkScalerContext* Create(const SkDescriptor*); protected: Rec fRec; unsigned fBaseGlyphCount; virtual unsigned generateGlyphCount() = 0; virtual uint16_t generateCharToGlyph(SkUnichar) = 0; virtual void generateAdvance(SkGlyph*) = 0; virtual void generateMetrics(SkGlyph*) = 0; virtual void generateImage(const SkGlyph&) = 0; virtual void generatePath(const SkGlyph&, SkPath*) = 0; virtual void generateFontMetrics(SkPaint::FontMetrics* mX, SkPaint::FontMetrics* mY) = 0; // default impl returns 0, indicating failure. virtual SkUnichar generateGlyphToChar(uint16_t); private: SkPathEffect* fPathEffect; SkMaskFilter* fMaskFilter; SkRasterizer* fRasterizer; SkScalar fDevFrameWidth; void internalGetPath(const SkGlyph& glyph, SkPath* fillPath, SkPath* devPath, SkMatrix* fillToDevMatrix); // return the next context, treating fNextContext as a cache of the answer SkScalerContext* getNextContext(); // returns the right context from our link-list for this glyph. If no match // is found, just returns the original context (this) SkScalerContext* getGlyphContext(const SkGlyph& glyph); // link-list of context, to handle missing chars. null-terminated. SkScalerContext* fNextContext; }; #define kRec_SkDescriptorTag SkSetFourByteTag('s', 'r', 'e', 'c') #define kPathEffect_SkDescriptorTag SkSetFourByteTag('p', 't', 'h', 'e') #define kMaskFilter_SkDescriptorTag SkSetFourByteTag('m', 's', 'k', 'f') #define kRasterizer_SkDescriptorTag SkSetFourByteTag('r', 'a', 's', 't') #endif
[ "wlwlxj@gmail.com@b2b8c3b8-ce47-b78c-ec54-380d862a5473" ]
wlwlxj@gmail.com@b2b8c3b8-ce47-b78c-ec54-380d862a5473
3ac65a47c6419e58c01033896c8284ce933de3bf
dc92e40a17b301cda243bdb27cb4da1f3ebc77d6
/src/libpropertyTest/cpp/main.cpp
207d7b04b58398435a54dd530e433700236e56b8
[]
no_license
westelh/property
d7b3251486a908d996a34481b285a7542fcf8535
0599751947f6d910dd4e755734cb2c5f75207fab
refs/heads/master
2020-03-17T09:57:56.166734
2018-05-23T16:43:18
2018-05-23T16:43:18
133,494,973
5
0
null
null
null
null
UTF-8
C++
false
false
157
cpp
#include "gtest/gtest.h" #include "property.hpp" int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "westelh@gmail.com" ]
westelh@gmail.com
fc5b11eb05bdbe2d3319c19f33945581b58a353d
a1a5f706dab00877adf22c4656881de909bb7131
/tests/01-simple-library/LeapTestCase.cpp
0e66c7b587fb1e4501028713454575f4c3b22eb7
[]
no_license
Overcastan/KIS-Testing-fall2020
6265122275cd12302c0f1988c76f70e321766128
2990e44a54e3989250c959b30b26c7bee1252609
refs/heads/main
2023-01-27T20:55:01.636791
2020-12-10T19:56:42
2020-12-10T19:56:42
320,272,665
0
0
null
null
null
null
UTF-8
C++
false
false
473
cpp
// // Created by akhtyamovpavel on 5/1/20. // #include "LeapTestCase.h" #include <Functions.h> #include <gtest/gtest.h> TEST(Leap, Invalid_year) { ASSERT_THROW(IsLeap(-1), std::invalid_argument); } TEST(Leap, not_divisible_by_4) { ASSERT_EQ(false, IsLeap(3)); } TEST(Leap, not_divisible_by_100) { ASSERT_EQ(true, IsLeap(8)); } TEST(Leap, not_divisible_by_400) { ASSERT_EQ(false, IsLeap(300)); } TEST(Leap, divisible_by_400) { ASSERT_EQ(true, IsLeap(800)); }
[ "akhmuro@gmail.com" ]
akhmuro@gmail.com
2431462b6a1d6c3ba00e46b2d5bb8adc6f4769b6
f6f346ba37deb395b87bc12bd96762460780e850
/queue.h
9caa61de2e6715b0685e5433cfbb100d00850941
[]
no_license
zshwuhan/HotTopicPrediction
ee8ff3713533c98e324deb89e77edcd3e21dace7
dde64225380a986755c4ecfa516b8409b835eef5
refs/heads/master
2021-01-01T17:34:56.358026
2015-06-17T10:56:36
2015-06-17T10:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
414
h
#ifndef QUEUE_H #define QUEUE_H #include "global.h" using namespace std; template<class T> struct Node { T info; struct Node<T> *next; }; template<class T> class Queue { private: Node<T> *head; Node<T> *tail; public: Queue(); Queue(const T &data); ~Queue(); bool IsEmpty(); bool EnQueue(const T &data); T GetQueue(); T GetHead(); void Test(); }; #endif // QUEUE_H
[ "yinzelong.leon@gmail.com" ]
yinzelong.leon@gmail.com
7f526d2821a854ffa7cbd57addce3b01c28caa1d
a08f16f650e6158ac719527d15c804988818cbb5
/Kattis/A Real Challenge.cpp
0bdb2ceb780f98fd882103ee3330db5a0baa483f
[]
no_license
emae18/pc-Key
d2651dad02ce268ea24ab845b8634eeb334515bb
3b79a3bb16afebcbbda3f27a872e619a82f1ce0a
refs/heads/master
2020-04-16T09:01:19.009218
2020-03-30T04:34:19
2020-03-30T04:34:19
165,447,519
0
0
null
2020-02-28T05:34:05
2019-01-12T23:43:31
C++
UTF-8
C++
false
false
581
cpp
#include<bits/stdc++.h> #define forin(i,n) for(int i=0;i<n;i++) #define forisn(i,s,n) for(int i=s;i<int(n);i++) #define foritv(i,n) for(vector<int>::iterator i=n.begin();i!=n.end();i++) #define foritset(i,n) for(set<int>::iterator i=n.begin();i!=n.end();i++) using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pii> vii; typedef set<int> si; typedef map<string, int> msi; int main() { ios::sync_with_stdio(0); cin.tie(0); ll a; cin>>a; cout<<fixed<<setprecision(20)<<sqrt(a)*4.0<<"\n"; return 0; }
[ "eliasvilte1@gmail.com" ]
eliasvilte1@gmail.com
5f72b8c3f4d98823bbef082990ec1087648f2b97
7e6afb4986a53c420d40a2039240f8c5ed3f9549
/libs/config/src/config_parser.cpp
fb18b39b9e32f754a02b42e9fed5786d79abba6c
[ "BSD-3-Clause" ]
permissive
MRPT/mrpt
9ea3c39a76de78eacaca61a10e7e96646647a6da
34077ec74a90b593b587f2057d3280ea520a3609
refs/heads/develop
2023-08-17T23:37:29.722496
2023-08-17T15:39:54
2023-08-17T15:39:54
13,708,826
1,695
646
BSD-3-Clause
2023-09-12T22:02:53
2013-10-19T21:09:23
C++
UTF-8
C++
false
false
7,006
cpp
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2023, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "config-precomp.h" // Precompiled headers // #include <mrpt/config/config_parser.h> #include <mrpt/core/exceptions.h> #include <mrpt/expr/CRuntimeCompiledExpression.h> #include <mrpt/system/string_utils.h> #include <cstring> // strncmp #include <map> namespace mrpt::config::internal { struct ParseContext { std::map<std::string, std::string> defined_vars; std::map<std::string, double> defined_vars_values; unsigned int line_count = 1; }; std::string parse_process_var_eval(const ParseContext& pc, std::string expr); void parse_process_var_define( ParseContext& pc, const std::string& var_name, const std::string& var_value); } // namespace mrpt::config::internal namespace mci = mrpt::config::internal; // Return a string or a number (as string) if expr = "$eval{...}" std::string mci::parse_process_var_eval( const mci::ParseContext& pc, std::string expr) { expr = mrpt::system::trim(expr); while (expr.size() > 5) { auto p = expr.find("$env{"); if (p != std::string::npos) { auto pend = expr.find("}", p); if (pend == std::string::npos) throw std::runtime_error(mrpt::format( "Line %u: Expected closing `}` near: `%s`", pc.line_count, expr.c_str())); const auto substr = expr.substr(p + 5, pend - p - 5); std::string new_expr = expr.substr(0, p); auto env_val = ::getenv(substr.c_str()); if (env_val) new_expr += std::string(env_val); new_expr += expr.substr(pend + 1); new_expr.swap(expr); } else if ((p = expr.find("$eval{")) != std::string::npos) { auto pend = expr.find("}", p); if (pend == std::string::npos) throw std::runtime_error(mrpt::format( "Line %u: Expected closing `}` near: `%s`", pc.line_count, expr.c_str())); const auto substr = expr.substr(p + 6, pend - p - 6); mrpt::expr::CRuntimeCompiledExpression cexpr; cexpr.compile( substr, pc.defined_vars_values, mrpt::format("Line %u: ", pc.line_count)); std::string new_expr = expr.substr(0, p); new_expr += mrpt::format("%e", cexpr.eval()); new_expr += expr.substr(pend + 1); new_expr.swap(expr); } else break; // nothing else to evaluate } return expr; } void mci::parse_process_var_define( mci::ParseContext& pc, const std::string& var_name, const std::string& var_value) { if (!var_name.empty()) { pc.defined_vars[var_name] = var_value; if (!var_value.empty()) { pc.defined_vars_values[var_name] = ::atof(parse_process_var_eval(pc, var_value).c_str()); } } } std::string mrpt::config::config_parser(const std::string& input) { const auto in_str = input.data(); const auto in_len = input.size(); std::string output; output.reserve(in_len); mci::ParseContext pc; size_t i = 0; while (i < in_len) { const char c = in_str[i]; if (c == '\n') { pc.line_count++; } if (c == '\\' && i < in_len - 1 && (in_str[i + 1] == '\r' || in_str[i + 1] == '\n')) { // Skip the backslash + one newline: CR "\r", LF "\n", CR+LF // "\r\n" if (i < in_len - 2 && in_str[i + 1] == '\r' && in_str[i + 2] == '\n') { // out_len += 0; i += 3; } else if (in_str[i + 1] == '\r' || in_str[i + 1] == '\n') { // out_len += 0; i += 2; } else { throw std::runtime_error( "[mrpt::config::config_parser] parse error, shouldn't " "reach here!"); } } else { // Handle "@define varname value" if (in_len > i + 7 && !::strncmp(in_str + i, "@define", 7)) { // Extract rest of this line: i += 7; std::string var_name, var_value; bool in_var_name = false, done_var_name = false; while (i < in_len && in_str[i] != '\r' && in_str[i] != '\n') { const char ch = in_str[i]; i++; if (ch != ' ' && ch != '\t') { // not whitespace if (!in_var_name && !done_var_name) { in_var_name = true; } } else { // whitespace if (in_var_name) { in_var_name = false; done_var_name = true; } } if (in_var_name) { var_name += ch; } if (done_var_name) { var_value += ch; } } parse_process_var_define(pc, var_name, var_value); continue; } // Handle "${varname}" if (in_len > i + 4 && in_str[i] == '$' && in_str[i + 1] == '{') { // extract varname: i += 2; std::string varname; bool end_ok = false; while (i < in_len && in_str[i] != '\n' && in_str[i] != '\r') { const char ch = in_str[i]; i++; if (ch == '}') { end_ok = true; break; } varname += ch; } if (!end_ok) { throw std::runtime_error(mrpt::format( "Line %u: Expected closing `}` near: `%s`", pc.line_count, varname.c_str())); } const auto it = pc.defined_vars.find(varname); if (it == pc.defined_vars.end()) throw std::runtime_error(mrpt::format( "Line %u: Unknown variable `${%s}`", pc.line_count, varname.c_str())); const auto str_out = parse_process_var_eval(pc, it->second); output += str_out; continue; } // Handle "$eval{expression}" if (in_len > i + 7 && !strncmp(in_str + i, "$eval{", 6)) { // extract expression: std::string expr; bool end_ok = false; while (i < in_len && in_str[i] != '\n' && in_str[i] != '\r') { const char ch = in_str[i]; i++; expr += ch; if (ch == '}') { end_ok = true; break; } } if (!end_ok) { throw std::runtime_error(mrpt::format( "Line %u: Expected closing `}` near: `%s`", pc.line_count, expr.c_str())); } const std::string res = parse_process_var_eval(pc, expr); output += res; continue; } // Handle "$env{var}" if (in_len > i + 6 && !strncmp(in_str + i, "$env{", 5)) { // extract expression: std::string expr; bool end_ok = false; while (i < in_len && in_str[i] != '\n' && in_str[i] != '\r') { const char ch = in_str[i]; i++; expr += ch; if (ch == '}') { end_ok = true; break; } } if (!end_ok) { throw std::runtime_error(mrpt::format( "Line %u: Expected closing `}` near: `%s`", pc.line_count, expr.c_str())); } const std::string res = parse_process_var_eval(pc, expr); output += res; continue; } // Normal case: output += c; i++; } } return output; }
[ "joseluisblancoc@gmail.com" ]
joseluisblancoc@gmail.com
badecd965ad2eb7f99a314b18dea8a4aeee0635a
6a2686efe30bd1b25c8c5dcea7aafa9535570783
/src/test/miner_tests.cpp
e007f47154c88b6874f20865f2de445f33e320b4
[ "MIT" ]
permissive
bumbacoin/cream
493b9203c7d5cf73f67f2357dbecc25a1ae3088c
f3e72b58a3b5ae108e2e9c1675f95aacb2599711
refs/heads/master
2020-04-17T17:29:34.657525
2019-01-22T05:28:22
2019-01-22T05:28:22
166,779,886
0
0
MIT
2019-01-21T08:52:49
2019-01-21T08:52:46
null
UTF-8
C++
false
false
24,637
cpp
// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2018 The Cream developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <coins.h> #include <consensus/consensus.h> #include <consensus/merkle.h> #include <consensus/tx_verify.h> #include <consensus/validation.h> #include <validation.h> #include <miner.h> #include <policy/policy.h> #include <pubkey.h> #include <script/standard.h> #include <txmempool.h> #include <uint256.h> #include <util.h> #include <utilstrencodings.h> #include <test/test_bitcoin.h> #include <memory> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(miner_tests, TestingSetup) // BOOST_CHECK_EXCEPTION predicates to check the specific validation error class HasReason { public: HasReason(const std::string& reason) : m_reason(reason) {} bool operator() (const std::runtime_error& e) const { return std::string(e.what()).find(m_reason) != std::string::npos; }; private: const std::string m_reason; }; static CFeeRate blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); static BlockAssembler AssemblerForTest(const CChainParams& params) { BlockAssembler::Options options; options.nBlockMaxWeight = MAX_BLOCK_WEIGHT; options.blockMinFeeRate = blockMinFeeRate; return BlockAssembler(params, options); } static struct { unsigned char extranonce; unsigned int nonce; } blockinfo[] = { {4, 0xa4a3e223}, {2, 0x15c32f9e}, {1, 0x0375b547}, {1, 0x7004a8a5}, {2, 0xce440296}, {2, 0x52cfe198}, {1, 0x77a72cd0}, {2, 0xbb5d6f84}, {2, 0x83f30c2c}, {1, 0x48a73d5b}, {1, 0xef7dcd01}, {2, 0x6809c6c4}, {2, 0x0883ab3c}, {1, 0x087bbbe2}, {2, 0x2104a814}, {2, 0xdffb6daa}, {1, 0xee8a0a08}, {2, 0xba4237c1}, {1, 0xa70349dc}, {1, 0x344722bb}, {3, 0xd6294733}, {2, 0xec9f5c94}, {2, 0xca2fbc28}, {1, 0x6ba4f406}, {2, 0x015d4532}, {1, 0x6e119b7c}, {2, 0x43e8f314}, {2, 0x27962f38}, {2, 0xb571b51b}, {2, 0xb36bee23}, {2, 0xd17924a8}, {2, 0x6bc212d9}, {1, 0x630d4948}, {2, 0x9a4c4ebb}, {2, 0x554be537}, {1, 0xd63ddfc7}, {2, 0xa10acc11}, {1, 0x759a8363}, {2, 0xfb73090d}, {1, 0xe82c6a34}, {1, 0xe33e92d7}, {3, 0x658ef5cb}, {2, 0xba32ff22}, {5, 0x0227a10c}, {1, 0xa9a70155}, {5, 0xd096d809}, {1, 0x37176174}, {1, 0x830b8d0f}, {1, 0xc6e3910e}, {2, 0x823f3ca8}, {1, 0x99850849}, {1, 0x7521fb81}, {1, 0xaacaabab}, {1, 0xd645a2eb}, {5, 0x7aea1781}, {5, 0x9d6e4b78}, {1, 0x4ce90fd8}, {1, 0xabdc832d}, {6, 0x4a34f32a}, {2, 0xf2524c1c}, {2, 0x1bbeb08a}, {1, 0xad47f480}, {1, 0x9f026aeb}, {1, 0x15a95049}, {2, 0xd1cb95b2}, {2, 0xf84bbda5}, {1, 0x0fa62cd1}, {1, 0xe05f9169}, {1, 0x78d194a9}, {5, 0x3e38147b}, {5, 0x737ba0d4}, {1, 0x63378e10}, {1, 0x6d5f91cf}, {2, 0x88612eb8}, {2, 0xe9639484}, {1, 0xb7fabc9d}, {2, 0x19b01592}, {1, 0x5a90dd31}, {2, 0x5bd7e028}, {2, 0x94d00323}, {1, 0xa9b9c01a}, {1, 0x3a40de61}, {1, 0x56e7eec7}, {5, 0x859f7ef6}, {1, 0xfd8e5630}, {1, 0x2b0c9f7f}, {1, 0xba700e26}, {1, 0x7170a408}, {1, 0x70de86a8}, {1, 0x74d64cd5}, {1, 0x49e738a1}, {2, 0x6910b602}, {0, 0x643c565f}, {1, 0x54264b3f}, {2, 0x97ea6396}, {2, 0x55174459}, {2, 0x03e8779a}, {1, 0x98f34d8f}, {1, 0xc07b2b07}, {1, 0xdfe29668}, {1, 0x3141c7c1}, {1, 0xb3b595f4}, {1, 0x735abf08}, {5, 0x623bfbce}, {2, 0xd351e722}, {1, 0xf4ca48c9}, {1, 0x5b19c670}, {1, 0xa164bf0e}, {2, 0xbbbeb305}, {2, 0xfe1c810a}, }; static CBlockIndex CreateBlockIndex(int nHeight) { CBlockIndex index; index.nHeight = nHeight; index.pprev = chainActive.Tip(); return index; } static bool TestSequenceLocks(const CTransaction &tx, int flags) { LOCK(mempool.cs); return CheckSequenceLocks(tx, flags); } // Test suite for ancestor feerate transaction selection. // Implemented as an additional function, rather than a separate test case, // to allow reusing the blockchain created in CreateNewBlock_validity. static void TestPackageSelection(const CChainParams& chainparams, const CScript& scriptPubKey, const std::vector<CTransactionRef>& txFirst) EXCLUSIVE_LOCKS_REQUIRED(::mempool.cs) { // Test the ancestor feerate transaction selection. TestMemPoolEntryHelper entry; // Test that a medium fee transaction will be selected after a higher fee // rate package with a low fee rate parent. CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vout.resize(1); tx.vout[0].nValue = 5000000000LL - 1000; // This tx has a low fee: 1000 satoshis uint256 hashParentTx = tx.GetHash(); // save this txid for later use mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); // This tx has a medium fee: 10000 satoshis tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vout[0].nValue = 5000000000LL - 10000; uint256 hashMediumFeeTx = tx.GetHash(); mempool.addUnchecked(hashMediumFeeTx, entry.Fee(10000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); // This tx has a high fee, but depends on the first transaction tx.vin[0].prevout.hash = hashParentTx; tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 50k satoshi fee uint256 hashHighFeeTx = tx.GetHash(); mempool.addUnchecked(hashHighFeeTx, entry.Fee(50000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); std::unique_ptr<CBlockTemplate> pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); BOOST_CHECK(pblocktemplate->block.vtx[1]->GetHash() == hashParentTx); BOOST_CHECK(pblocktemplate->block.vtx[2]->GetHash() == hashHighFeeTx); BOOST_CHECK(pblocktemplate->block.vtx[3]->GetHash() == hashMediumFeeTx); // Test that a package below the block min tx fee doesn't get included tx.vin[0].prevout.hash = hashHighFeeTx; tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 0 fee uint256 hashFreeTx = tx.GetHash(); mempool.addUnchecked(hashFreeTx, entry.Fee(0).FromTx(tx)); size_t freeTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Calculate a fee on child transaction that will put the package just // below the block min tx fee (assuming 1 child tx of the same size). CAmount feeToUse = blockMinFeeRate.GetFee(2*freeTxSize) - 1; tx.vin[0].prevout.hash = hashFreeTx; tx.vout[0].nValue = 5000000000LL - 1000 - 50000 - feeToUse; uint256 hashLowFeeTx = tx.GetHash(); mempool.addUnchecked(hashLowFeeTx, entry.Fee(feeToUse).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); // Verify that the free tx and the low fee tx didn't get selected for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) { BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx); BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx); } // Test that packages above the min relay fee do get included, even if one // of the transactions is below the min relay fee // Remove the low fee transaction and replace with a higher fee transaction mempool.removeRecursive(tx); tx.vout[0].nValue -= 2; // Now we should be just over the min relay fee hashLowFeeTx = tx.GetHash(); mempool.addUnchecked(hashLowFeeTx, entry.Fee(feeToUse+2).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); BOOST_CHECK(pblocktemplate->block.vtx[4]->GetHash() == hashFreeTx); BOOST_CHECK(pblocktemplate->block.vtx[5]->GetHash() == hashLowFeeTx); // Test that transaction selection properly updates ancestor fee // calculations as ancestor transactions get included in a block. // Add a 0-fee transaction that has 2 outputs. tx.vin[0].prevout.hash = txFirst[2]->GetHash(); tx.vout.resize(2); tx.vout[0].nValue = 5000000000LL - 100000000; tx.vout[1].nValue = 100000000; // 1CRM output uint256 hashFreeTx2 = tx.GetHash(); mempool.addUnchecked(hashFreeTx2, entry.Fee(0).SpendsCoinbase(true).FromTx(tx)); // This tx can't be mined by itself tx.vin[0].prevout.hash = hashFreeTx2; tx.vout.resize(1); feeToUse = blockMinFeeRate.GetFee(freeTxSize); tx.vout[0].nValue = 5000000000LL - 100000000 - feeToUse; uint256 hashLowFeeTx2 = tx.GetHash(); mempool.addUnchecked(hashLowFeeTx2, entry.Fee(feeToUse).SpendsCoinbase(false).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); // Verify that this tx isn't selected. for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) { BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx2); BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx2); } // This tx will be mineable, and should cause hashLowFeeTx2 to be selected // as well. tx.vin[0].prevout.n = 1; tx.vout[0].nValue = 100000000 - 10000; // 10k satoshi fee mempool.addUnchecked(tx.GetHash(), entry.Fee(10000).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); BOOST_CHECK(pblocktemplate->block.vtx[8]->GetHash() == hashLowFeeTx2); } // NOTE: These tests rely on CreateNewBlock doing its own self-validation! BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) { // Note that by default, these tests run with size accounting enabled. const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); const CChainParams& chainparams = *chainParams; CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; std::unique_ptr<CBlockTemplate> pblocktemplate; CMutableTransaction tx; CScript script; uint256 hash; TestMemPoolEntryHelper entry; entry.nFee = 11; entry.nHeight = 11; fCheckpointsEnabled = false; // Simple block creation, nothing special yet: BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // We can't make transactions until we have inputs // Therefore, load 100 blocks :) int baseheight = 0; std::vector<CTransactionRef> txFirst; for (unsigned int i = 0; i < sizeof(blockinfo)/sizeof(*blockinfo); ++i) { CBlock *pblock = &pblocktemplate->block; // pointer for convenience { LOCK(cs_main); pblock->nVersion = 1; pblock->nTime = chainActive.Tip()->GetMedianTimePast()+1; CMutableTransaction txCoinbase(*pblock->vtx[0]); txCoinbase.nVersion = 1; txCoinbase.vin[0].scriptSig = CScript(); txCoinbase.vin[0].scriptSig.push_back(blockinfo[i].extranonce); txCoinbase.vin[0].scriptSig.push_back(chainActive.Height()); txCoinbase.vout.resize(1); // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this) txCoinbase.vout[0].scriptPubKey = CScript(); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); if (txFirst.size() == 0) baseheight = chainActive.Height(); if (txFirst.size() < 4) txFirst.push_back(pblock->vtx[0]); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); pblock->nNonce = blockinfo[i].nonce; } std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock); BOOST_CHECK(ProcessNewBlock(chainparams, shared_pblock, true, nullptr)); pblock->hashPrevBlock = pblock->GetHash(); } LOCK(cs_main); LOCK(::mempool.cs); // Just to make sure we can still make simple blocks BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); const CAmount BLOCKSUBSIDY = 50*COIN; const CAmount LOWFEE = CENT; const CAmount HIGHFEE = COIN; const CAmount HIGHERFEE = 4*COIN; // block sigops > limit: 1000 CHECKMULTISIG + 1 tx.vin.resize(1); // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vout.resize(1); tx.vout[0].nValue = BLOCKSUBSIDY; for (unsigned int i = 0; i < 1001; ++i) { tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); bool spendsCoinbase = i == 0; // only first tx spends coinbase // If we don't set the # of sig ops in the CTxMemPoolEntry, template creation fails mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx)); tx.vin[0].prevout.hash = hash; } BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-blk-sigops")); mempool.clear(); tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vout[0].nValue = BLOCKSUBSIDY; for (unsigned int i = 0; i < 1001; ++i) { tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); bool spendsCoinbase = i == 0; // only first tx spends coinbase // If we do set the # of sig ops in the CTxMemPoolEntry, template creation passes mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).SigOpsCost(80).FromTx(tx)); tx.vin[0].prevout.hash = hash; } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); mempool.clear(); // block size > limit tx.vin[0].scriptSig = CScript(); // 18 * (520char + DROP) + OP_1 = 9433 bytes std::vector<unsigned char> vchData(520); for (unsigned int i = 0; i < 18; ++i) tx.vin[0].scriptSig << vchData << OP_DROP; tx.vin[0].scriptSig << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vout[0].nValue = BLOCKSUBSIDY; for (unsigned int i = 0; i < 128; ++i) { tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); bool spendsCoinbase = i == 0; // only first tx spends coinbase mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx)); tx.vin[0].prevout.hash = hash; } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); mempool.clear(); // orphan in mempool, template creation fails hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).FromTx(tx)); BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-txns-inputs-missingorspent")); mempool.clear(); // child with higher feerate than parent tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vin[0].prevout.hash = hash; tx.vin.resize(2); tx.vin[1].scriptSig = CScript() << OP_1; tx.vin[1].prevout.hash = txFirst[0]->GetHash(); tx.vin[1].prevout.n = 0; tx.vout[0].nValue = tx.vout[0].nValue+BLOCKSUBSIDY-HIGHERFEE; //First txn output + fresh coinbase - new txn fee hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHERFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); mempool.clear(); // coinbase in mempool, template creation fails tx.vin.resize(1); tx.vin[0].prevout.SetNull(); tx.vin[0].scriptSig = CScript() << OP_0 << OP_1; tx.vout[0].nValue = 0; hash = tx.GetHash(); // give it a fee so it'll get mined mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); // Should throw bad-cb-multiple BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-cb-multiple")); mempool.clear(); // double spend txn pair in mempool, template creation fails tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].scriptSig = CScript() << OP_1; tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; tx.vout[0].scriptPubKey = CScript() << OP_1; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vout[0].scriptPubKey = CScript() << OP_2; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-txns-inputs-missingorspent")); mempool.clear(); // subsidy changing int nHeight = chainActive.Height(); // Create an actual 209999-long block chain (without valid blocks). while (chainActive.Tip()->nHeight < 209999) { CBlockIndex* prev = chainActive.Tip(); CBlockIndex* next = new CBlockIndex(); next->phashBlock = new uint256(InsecureRand256()); pcoinsTip->SetBestBlock(next->GetBlockHash()); next->pprev = prev; next->nHeight = prev->nHeight + 1; next->BuildSkip(); chainActive.SetTip(next); } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // Extend to a 210000-long block chain. while (chainActive.Tip()->nHeight < 210000) { CBlockIndex* prev = chainActive.Tip(); CBlockIndex* next = new CBlockIndex(); next->phashBlock = new uint256(InsecureRand256()); pcoinsTip->SetBestBlock(next->GetBlockHash()); next->pprev = prev; next->nHeight = prev->nHeight + 1; next->BuildSkip(); chainActive.SetTip(next); } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // invalid p2sh txn in mempool, template creation fails tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript() << OP_1; tx.vout[0].nValue = BLOCKSUBSIDY-LOWFEE; script = CScript() << OP_0; tx.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(script)); hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vin[0].prevout.hash = hash; tx.vin[0].scriptSig = CScript() << std::vector<unsigned char>(script.begin(), script.end()); tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); // Should throw block-validation-failed BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("block-validation-failed")); mempool.clear(); // Delete the dummy blocks again. while (chainActive.Tip()->nHeight > nHeight) { CBlockIndex* del = chainActive.Tip(); chainActive.SetTip(del->pprev); pcoinsTip->SetBestBlock(del->pprev->GetBlockHash()); delete del->phashBlock; delete del; } // non-final txs in mempool SetMockTime(chainActive.Tip()->GetMedianTimePast()+1); int flags = LOCKTIME_VERIFY_SEQUENCE|LOCKTIME_MEDIAN_TIME_PAST; // height map std::vector<int> prevheights; // relative height locked tx.nVersion = 2; tx.vin.resize(1); prevheights.resize(1); tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].nSequence = chainActive.Tip()->nHeight + 1; // txFirst[0] is the 2nd block prevheights[0] = baseheight + 1; tx.vout.resize(1); tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; tx.vout[0].scriptPubKey = CScript() << OP_1; tx.nLockTime = 0; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 2))); // Sequence locks pass on 2nd block // relative time locked tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((chainActive.Tip()->GetMedianTimePast()+1-chainActive[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block prevheights[0] = baseheight + 2; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 1))); // Sequence locks pass 512 seconds later for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP // absolute height locked tx.vin[0].prevout.hash = txFirst[2]->GetHash(); tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1; prevheights[0] = baseheight + 3; tx.nLockTime = chainActive.Tip()->nHeight + 1; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast())); // Locktime passes on 2nd block // absolute time locked tx.vin[0].prevout.hash = txFirst[3]->GetHash(); tx.nLockTime = chainActive.Tip()->GetMedianTimePast(); prevheights.resize(1); prevheights[0] = baseheight + 4; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later // mempool-dependent transactions (not added) tx.vin[0].prevout.hash = hash; prevheights[0] = chainActive.Tip()->nHeight + 1; tx.nLockTime = 0; tx.vin[0].nSequence = 0; BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass tx.vin[0].nSequence = 1; BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG; BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1; BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // None of the of the absolute height/time locked tx should have made // it into the template because we still check IsFinalTx in CreateNewBlock, // but relative locked txs will if inconsistently added to mempool. // For now these will still generate a valid template until BIP68 soft fork BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3U); // However if we advance height by 1 and time by 512, all of them should be mined for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast chainActive.Tip()->nHeight++; SetMockTime(chainActive.Tip()->GetMedianTimePast() + 1); BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5U); chainActive.Tip()->nHeight--; SetMockTime(0); mempool.clear(); TestPackageSelection(chainparams, scriptPubKey, txFirst); fCheckpointsEnabled = true; } BOOST_AUTO_TEST_SUITE_END()
[ "creamcoin@gmail.com" ]
creamcoin@gmail.com
e518389188d93e88b89d7d5504592c816c1b035f
bc44db07b8b197879ee36bde98adc0cc1b37c177
/Algorithm/P1317(1).cpp
9118693eb7576c6bb8c45fa7cf6839495f5f9c24
[]
no_license
littlekokko/AlgorithmCode
4a5358f814f50b5eec0dc5b2fb683ad8faf3f6c8
f19eccbae1326c54a909e796f2765c9d40cad8e6
refs/heads/main
2023-02-18T15:31:45.534323
2021-01-20T05:04:35
2021-01-20T05:04:35
331,198,043
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int MAXN=105; const int MAXV=2005; int f[MAXV][MAXV]; int h[MAXN]; int sum; int n; void init() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&h[i]); sum+=h[i]; } } void DP() { f[0][0]=1; for(int k=1;k<=n;k++) for(int i=sum;i>=0;i--) for(int j=sum;j>=0;j--) if(f[i][j]) { f[i+h[k]][j]=1; f[i][j+h[k]]=1; } for(int i=sum;i>=1;i--) if(f[i][i]) { printf("%d\n",i); return; } printf("Impossible\n"); } int main() { init(); DP(); }
[ "lv-kokko@hotmail.com" ]
lv-kokko@hotmail.com
adc1950f3609335ca4ec1a26e5139680e39dc447
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/content/common/gpu/media/video_encode_accelerator_unittest.cc
410c67a64d6c74a1033aac3145b49ed8240aa9db
[ "BSD-3-Clause", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
20,528
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/bind.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/files/memory_mapped_file.h" #include "base/memory/scoped_vector.h" #include "base/process/process.h" #include "base/safe_numerics.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "content/common/gpu/media/exynos_video_encode_accelerator.h" #include "content/common/gpu/media/h264_parser.h" #include "content/common/gpu/media/video_accelerator_unittest_helpers.h" #include "media/base/bind_to_loop.h" #include "media/base/bitstream_buffer.h" #include "media/video/video_encode_accelerator.h" #include "testing/gtest/include/gtest/gtest.h" using media::VideoEncodeAccelerator; namespace content { namespace { // Arbitrarily chosen to add some depth to the pipeline. const unsigned int kNumOutputBuffers = 4; const unsigned int kNumExtraInputFrames = 4; // Maximum delay between requesting a keyframe and receiving one, in frames. // Arbitrarily chosen as a reasonable requirement. const unsigned int kMaxKeyframeDelay = 4; // Value to use as max frame number for keyframe detection. const unsigned int kMaxFrameNum = std::numeric_limits<unsigned int>::max() - kMaxKeyframeDelay; const uint32 kDefaultBitrate = 2000000; // Tolerance factor for how encoded bitrate can differ from requested bitrate. const double kBitrateTolerance = 0.1; const uint32 kDefaultFPS = 30; // The syntax of each test stream is: // "in_filename:width:height:out_filename:requested_bitrate" // - |in_filename| must be an I420 (YUV planar) raw stream // (see http://www.fourcc.org/yuv.php#IYUV). // - |width| and |height| are in pixels. // - |out_filename| filename to save the encoded stream to. // Output stream is only saved in the simple encode test. // - |requested_bitrate| requested bitrate in bits per second (optional). // Bitrate is only forced for tests that test bitrate. const base::FilePath::CharType* test_stream_data = FILE_PATH_LITERAL("sync_192p_20frames.yuv:320:192:out.h264:100000"); struct TestStream { explicit TestStream(base::FilePath::StringType filename) : requested_bitrate(0) {} ~TestStream() {} gfx::Size size; base::MemoryMappedFile input_file; std::string out_filename; unsigned int requested_bitrate; }; static void ParseAndReadTestStreamData(base::FilePath::StringType data, TestStream* test_stream) { std::vector<base::FilePath::StringType> fields; base::SplitString(data, ':', &fields); CHECK_GE(fields.size(), 4U) << data; CHECK_LE(fields.size(), 5U) << data; base::FilePath::StringType filename = fields[0]; int width, height; CHECK(base::StringToInt(fields[1], &width)); CHECK(base::StringToInt(fields[2], &height)); test_stream->size = gfx::Size(width, height); CHECK(!test_stream->size.IsEmpty()); test_stream->out_filename = fields[3]; if (!fields[4].empty()) CHECK(base::StringToUint(fields[4], &test_stream->requested_bitrate)); CHECK(test_stream->input_file.Initialize(base::FilePath(filename))); } enum ClientState { CS_CREATED, CS_ENCODER_SET, CS_INITIALIZED, CS_ENCODING, CS_FINISHING, CS_FINISHED, CS_ERROR, }; class VEAClient : public VideoEncodeAccelerator::Client { public: VEAClient(const TestStream& test_stream, ClientStateNotification<ClientState>* note, bool save_to_file, unsigned int keyframe_period, bool force_bitrate); virtual ~VEAClient(); void CreateEncoder(); void DestroyEncoder(); // VideoDecodeAccelerator::Client implementation. void NotifyInitializeDone() OVERRIDE; void RequireBitstreamBuffers(unsigned int input_count, const gfx::Size& input_coded_size, size_t output_buffer_size) OVERRIDE; void BitstreamBufferReady(int32 bitstream_buffer_id, size_t payload_size, bool key_frame) OVERRIDE; void NotifyError(VideoEncodeAccelerator::Error error) OVERRIDE; private: bool has_encoder() { return encoder_.get(); } void SetState(ClientState new_state); // Called before starting encode to set initial configuration of the encoder. void SetInitialConfiguration(); // Called when encoder is done with a VideoFrame. void InputNoLongerNeededCallback(int32 input_id); // Ensure encoder has at least as many inputs as it asked for // via RequireBitstreamBuffers(). void FeedEncoderWithInputs(); // Provide the encoder with a new output buffer. void FeedEncoderWithOutput(base::SharedMemory* shm); // Feed the encoder with num_required_input_buffers_ of black frames to force // it to encode and return all inputs that came before this, effectively // flushing it. void FlushEncoder(); // Perform any checks required at the end of the stream, called after // receiving the last frame from the encoder. void ChecksAtFinish(); ClientState state_; scoped_ptr<VideoEncodeAccelerator> encoder_; const TestStream& test_stream_; ClientStateNotification<ClientState>* note_; // Ids assigned to VideoFrames (start at 1 for easy comparison with // num_encoded_slices_). std::set<int32> inputs_at_client_; int32 next_input_id_; // Ids for output BitstreamBuffers. typedef std::map<int32, base::SharedMemory*> IdToSHM; ScopedVector<base::SharedMemory> output_shms_; IdToSHM output_buffers_at_client_; int32 next_output_buffer_id_; // Current offset into input stream. off_t pos_in_input_stream_; // Calculated from input_coded_size_, in bytes. size_t input_buffer_size_; gfx::Size input_coded_size_; // Requested by encoder. unsigned int num_required_input_buffers_; size_t output_buffer_size_; // Calculated number of frames in the stream. unsigned int num_frames_in_stream_; // Number of encoded slices we got from encoder thus far. unsigned int num_encoded_slices_; // Set to true when encoder provides us with the corresponding NALU type. bool seen_sps_; bool seen_pps_; bool seen_idr_; // True if we are to save the encoded stream to a file. bool save_to_file_; // Request a keyframe every keyframe_period_ frames. const unsigned int keyframe_period_; // Frame number for which we requested a keyframe. unsigned int keyframe_requested_at_; // True if we are asking encoder for a particular bitrate. bool force_bitrate_; // Byte size of the encoded stream (for bitrate calculation). size_t encoded_stream_size_; content::H264Parser h264_parser_; // All methods of this class should be run on the same thread. base::ThreadChecker thread_checker_; }; VEAClient::VEAClient(const TestStream& test_stream, ClientStateNotification<ClientState>* note, bool save_to_file, unsigned int keyframe_period, bool force_bitrate) : state_(CS_CREATED), test_stream_(test_stream), note_(note), next_input_id_(1), next_output_buffer_id_(0), pos_in_input_stream_(0), input_buffer_size_(0), num_required_input_buffers_(0), output_buffer_size_(0), num_frames_in_stream_(0), num_encoded_slices_(0), seen_sps_(false), seen_pps_(false), seen_idr_(false), save_to_file_(save_to_file), keyframe_period_(keyframe_period), keyframe_requested_at_(kMaxFrameNum), force_bitrate_(force_bitrate), encoded_stream_size_(0) { if (keyframe_period_) CHECK_LT(kMaxKeyframeDelay, keyframe_period_); if (save_to_file_) { CHECK(!test_stream_.out_filename.empty()); base::FilePath out_filename(test_stream_.out_filename); // This creates or truncates out_filename. // Without it, AppendToFile() will not work. EXPECT_EQ(0, file_util::WriteFile(out_filename, NULL, 0)); } thread_checker_.DetachFromThread(); } VEAClient::~VEAClient() { CHECK(!has_encoder()); } void VEAClient::CreateEncoder() { DCHECK(thread_checker_.CalledOnValidThread()); CHECK(!has_encoder()); encoder_.reset(new ExynosVideoEncodeAccelerator(this)); SetState(CS_ENCODER_SET); encoder_->Initialize(media::VideoFrame::I420, test_stream_.size, media::H264PROFILE_MAIN, kDefaultBitrate); } void VEAClient::DestroyEncoder() { DCHECK(thread_checker_.CalledOnValidThread()); if (!has_encoder()) return; encoder_.release()->Destroy(); } void VEAClient::NotifyInitializeDone() { DCHECK(thread_checker_.CalledOnValidThread()); SetInitialConfiguration(); SetState(CS_INITIALIZED); } static size_t I420ByteSize(const gfx::Size& d) { CHECK((d.width() % 2 == 0) && (d.height() % 2 == 0)); return d.width() * d.height() * 3 / 2; } void VEAClient::RequireBitstreamBuffers(unsigned int input_count, const gfx::Size& input_coded_size, size_t output_size) { DCHECK(thread_checker_.CalledOnValidThread()); ASSERT_EQ(state_, CS_INITIALIZED); SetState(CS_ENCODING); // TODO(posciak): For now we only support input streams that meet encoder // size requirements exactly (i.e. coded size == visible size). input_coded_size_ = input_coded_size; ASSERT_EQ(input_coded_size_, test_stream_.size); num_required_input_buffers_ = input_count; ASSERT_GT(num_required_input_buffers_, 0UL); input_buffer_size_ = I420ByteSize(input_coded_size_); CHECK_GT(input_buffer_size_, 0UL); num_frames_in_stream_ = test_stream_.input_file.length() / input_buffer_size_; CHECK_GT(num_frames_in_stream_, 0UL); CHECK_LE(num_frames_in_stream_, kMaxFrameNum); CHECK_EQ(num_frames_in_stream_ * input_buffer_size_, test_stream_.input_file.length()); output_buffer_size_ = output_size; ASSERT_GT(output_buffer_size_, 0UL); for (unsigned int i = 0; i < kNumOutputBuffers; ++i) { base::SharedMemory* shm = new base::SharedMemory(); CHECK(shm->CreateAndMapAnonymous(output_buffer_size_)); output_shms_.push_back(shm); FeedEncoderWithOutput(shm); } FeedEncoderWithInputs(); } void VEAClient::BitstreamBufferReady(int32 bitstream_buffer_id, size_t payload_size, bool key_frame) { DCHECK(thread_checker_.CalledOnValidThread()); ASSERT_LE(payload_size, output_buffer_size_); EXPECT_GT(payload_size, 0UL); IdToSHM::iterator it = output_buffers_at_client_.find(bitstream_buffer_id); ASSERT_NE(it, output_buffers_at_client_.end()); base::SharedMemory* shm = it->second; output_buffers_at_client_.erase(it); if (state_ == CS_FINISHED) return; encoded_stream_size_ += payload_size; h264_parser_.SetStream(static_cast<uint8*>(shm->memory()), payload_size); bool seen_idr_in_this_buffer = false; while (1) { content::H264NALU nalu; content::H264Parser::Result result; result = h264_parser_.AdvanceToNextNALU(&nalu); if (result == content::H264Parser::kEOStream) break; ASSERT_EQ(result, content::H264Parser::kOk); switch (nalu.nal_unit_type) { case content::H264NALU::kIDRSlice: ASSERT_TRUE(seen_sps_); ASSERT_TRUE(seen_pps_); seen_idr_ = seen_idr_in_this_buffer = true; // Got keyframe, reset keyframe detection regardless of whether we // got a frame in time or not. keyframe_requested_at_ = kMaxFrameNum; // fallthrough case content::H264NALU::kNonIDRSlice: ASSERT_TRUE(seen_idr_); ++num_encoded_slices_; // Because the keyframe behavior requirements are loose, we give // the encoder more freedom here. It could either deliver a keyframe // immediately after we requested it, which could be for a frame number // before the one we requested it for (if the keyframe request // is asynchronous, i.e. not bound to any concrete frame, and because // the pipeline can be deeper that one frame), at that frame, or after. // So the only constraints we put here is that we get a keyframe not // earlier than we requested one (in time), and not later than // kMaxKeyframeDelay frames after the frame for which we requested // it comes back as encoded slice. EXPECT_LE(num_encoded_slices_, keyframe_requested_at_ + kMaxKeyframeDelay); break; case content::H264NALU::kSPS: seen_sps_ = true; break; case content::H264NALU::kPPS: ASSERT_TRUE(seen_sps_); seen_pps_ = true; break; default: break; } if (num_encoded_slices_ == num_frames_in_stream_) { ASSERT_EQ(state_, CS_FINISHING); ChecksAtFinish(); SetState(CS_FINISHED); break; } } EXPECT_EQ(key_frame, seen_idr_in_this_buffer); if (save_to_file_) { int size = base::checked_numeric_cast<int>(payload_size); EXPECT_EQ(file_util::AppendToFile( base::FilePath::FromUTF8Unsafe(test_stream_.out_filename), static_cast<char*>(shm->memory()), size), size); } FeedEncoderWithOutput(shm); } void VEAClient::NotifyError(VideoEncodeAccelerator::Error error) { DCHECK(thread_checker_.CalledOnValidThread()); SetState(CS_ERROR); } void VEAClient::SetState(ClientState new_state) { note_->Notify(new_state); state_ = new_state; } void VEAClient::SetInitialConfiguration() { if (force_bitrate_) { CHECK_GT(test_stream_.requested_bitrate, 0UL); encoder_->RequestEncodingParametersChange(test_stream_.requested_bitrate, kDefaultFPS); } } void VEAClient::InputNoLongerNeededCallback(int32 input_id) { std::set<int32>::iterator it = inputs_at_client_.find(input_id); ASSERT_NE(it, inputs_at_client_.end()); inputs_at_client_.erase(it); FeedEncoderWithInputs(); } void VEAClient::FeedEncoderWithInputs() { if (!has_encoder()) return; if (state_ != CS_ENCODING) return; while (inputs_at_client_.size() < num_required_input_buffers_ + kNumExtraInputFrames) { size_t bytes_left = test_stream_.input_file.length() - pos_in_input_stream_; if (bytes_left < input_buffer_size_) { DCHECK_EQ(bytes_left, 0UL); FlushEncoder(); return; } uint8* frame_data = const_cast<uint8*>(test_stream_.input_file.data() + pos_in_input_stream_); scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::WrapExternalYuvData( media::VideoFrame::I420, input_coded_size_, gfx::Rect(test_stream_.size), test_stream_.size, input_coded_size_.width(), input_coded_size_.width() / 2, input_coded_size_.width() / 2, frame_data, frame_data + input_coded_size_.GetArea(), frame_data + (input_coded_size_.GetArea() * 5 / 4), base::TimeDelta(), media::BindToCurrentLoop( base::Bind(&VEAClient::InputNoLongerNeededCallback, base::Unretained(this), next_input_id_))); CHECK(inputs_at_client_.insert(next_input_id_).second); pos_in_input_stream_ += input_buffer_size_; bool force_keyframe = false; if (keyframe_period_ && next_input_id_ % keyframe_period_ == 0) { keyframe_requested_at_ = next_input_id_; force_keyframe = true; } encoder_->Encode(video_frame, force_keyframe); ++next_input_id_; } } void VEAClient::FeedEncoderWithOutput(base::SharedMemory* shm) { if (!has_encoder()) return; if (state_ != CS_ENCODING && state_ != CS_FINISHING) return; base::SharedMemoryHandle dup_handle; CHECK(shm->ShareToProcess(base::Process::Current().handle(), &dup_handle)); media::BitstreamBuffer bitstream_buffer( next_output_buffer_id_++, dup_handle, output_buffer_size_); CHECK(output_buffers_at_client_.insert( std::make_pair(bitstream_buffer.id(), shm)).second); encoder_->UseOutputBitstreamBuffer(bitstream_buffer); } void VEAClient::FlushEncoder() { ASSERT_EQ(state_, CS_ENCODING); SetState(CS_FINISHING); // Feed encoder with a set of black frames to flush it. for (unsigned int i = 0; i < num_required_input_buffers_; ++i) { scoped_refptr<media::VideoFrame> frame = media::VideoFrame::CreateBlackFrame(input_coded_size_); CHECK(inputs_at_client_.insert(next_input_id_).second); ++next_input_id_; encoder_->Encode(frame, false); } } void VEAClient::ChecksAtFinish() { if (force_bitrate_) { EXPECT_NEAR(encoded_stream_size_ * 8 * kDefaultFPS / num_frames_in_stream_, test_stream_.requested_bitrate, kBitrateTolerance * test_stream_.requested_bitrate); } } // Test parameters: // - If true, save output to file. // - Force keyframe every n frames. // - Force bitrate; the actual required value is provided as a property // of the input stream, because it depends on stream type/resolution/etc. class VideoEncodeAcceleratorTest : public ::testing::TestWithParam<Tuple3<bool, int, bool> > {}; TEST_P(VideoEncodeAcceleratorTest, TestSimpleEncode) { const bool save_to_file = GetParam().a; const unsigned int keyframe_period = GetParam().b; bool force_bitrate = GetParam().c; TestStream test_stream(test_stream_data); ParseAndReadTestStreamData(test_stream_data, &test_stream); if (test_stream.requested_bitrate == 0) force_bitrate = false; base::Thread encoder_thread("EncoderThread"); encoder_thread.Start(); ClientStateNotification<ClientState> note; scoped_ptr<VEAClient> client(new VEAClient(test_stream, &note, save_to_file, keyframe_period, force_bitrate)); encoder_thread.message_loop()->PostTask( FROM_HERE, base::Bind(&VEAClient::CreateEncoder, base::Unretained(client.get()))); ASSERT_EQ(note.Wait(), CS_ENCODER_SET); ASSERT_EQ(note.Wait(), CS_INITIALIZED); ASSERT_EQ(note.Wait(), CS_ENCODING); ASSERT_EQ(note.Wait(), CS_FINISHING); ASSERT_EQ(note.Wait(), CS_FINISHED); encoder_thread.message_loop()->PostTask( FROM_HERE, base::Bind(&VEAClient::DestroyEncoder, base::Unretained(client.get()))); encoder_thread.Stop(); } INSTANTIATE_TEST_CASE_P(SimpleEncode, VideoEncodeAcceleratorTest, ::testing::Values(MakeTuple(true, 0, false))); INSTANTIATE_TEST_CASE_P(ForceKeyframes, VideoEncodeAcceleratorTest, ::testing::Values(MakeTuple(false, 10, false))); INSTANTIATE_TEST_CASE_P(ForceBitrate, VideoEncodeAcceleratorTest, ::testing::Values(MakeTuple(false, 0, true))); // TODO(posciak): more tests: // - async FeedEncoderWithOutput // - out-of-order return of outputs to encoder // - dynamic, runtime bitrate changes // - multiple encoders // - multiple encoders + decoders // - mid-stream encoder_->Destroy() } // namespace } // namespace content int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); // Removes gtest-specific args. CommandLine::Init(argc, argv); // Needed to enable DVLOG through --vmodule. logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; settings.dcheck_state = logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS; CHECK(logging::InitLogging(settings)); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); DCHECK(cmd_line); CommandLine::SwitchMap switches = cmd_line->GetSwitches(); for (CommandLine::SwitchMap::const_iterator it = switches.begin(); it != switches.end(); ++it) { if (it->first == "test_stream_data") { content::test_stream_data = it->second.c_str(); continue; } if (it->first == "v" || it->first == "vmodule") continue; LOG(FATAL) << "Unexpected switch: " << it->first << ":" << it->second; } base::ShadowingAtExitManager at_exit_manager; return RUN_ALL_TESTS(); }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
b11abcda7db70d4e205bfc916fd9ecbd72cb4e6c
52d1d52ad396db163d72c3ec11b8c675e75e11d8
/gp-practical-7/exercise.cpp
d3bb7389b209f7cdcd74421099ca1d8a770074ec
[]
no_license
liho98/gp-practical
7c1c1b36222f7adea626f5f5024b1a7d64226d5d
3a52ea02a0538abea1b0460f2a166b53604ddf92
refs/heads/master
2021-02-08T14:16:00.789269
2020-03-05T15:07:19
2020-03-05T15:07:19
244,160,663
1
0
null
null
null
null
UTF-8
C++
false
false
31,198
cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <math.h> #include <iostream> #if defined(__APPLE__) #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #define STB_IMAGE_IMPLEMENTATION #include <stb/stb_image.h> void framebuffer_size_callback(GLFWwindow *window, int width, int height); void processInput(GLFWwindow *window); void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods); void mouse_callback(GLFWwindow *window, double xpos, double ypos); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); void mouse_button_callback(GLFWwindow *window, int button, int action, int mods); void cursorPositionCallback(GLFWwindow *window, double xPos, double yPos); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) std::string slash = "\\"; // get dir path of project root std::string file_path = __FILE__; std::string dir_path = file_path.substr(0, file_path.rfind("\\")); #else std::string slash = "/"; // get dir path of project root std::string file_path = __FILE__; std::string dir_path = file_path.substr(0, file_path.rfind("/")); #endif char temp[100]; GLuint LoadJpgTexture(const char *filename[], GLuint *texture, int size); GLuint LoadPngTexture(const char *filename[], GLuint *texture, int size); GLuint LoadBmpTexture(const char *filename[], GLuint *texture, int size); void drawCube(float size); void drawPyramid(float size); void drawIceCream(); void drawTowerBridge(); void display(); // settings const unsigned int SCR_WIDTH = 1920; const unsigned int SCR_HEIGHT = 1080; float zoomLevel = -0.3f; const char *bmpFilenames[] = { "res/bmp/Brick.bmp", "res/bmp/Box.bmp", "res/bmp/Metal.bmp", "res/bmp/Wood.bmp", "res/bmp/sky.bmp"}; const char *jpgFilenames[] = { "res/jpg&png/cone.jpg", "res/jpg&png/ice-cream-2.jpg", "res/jpg&png/grape.jpg", "res/jpg&png/chocolate.jpg", "res/jpg&png/bg.jpg", "res/bmp/sky.jpg"}; const char *pngFilenames[] = {"res/jpg&png/tzuyu-coverjpg.png"}; GLuint *bmpTextures = new GLuint[4]; GLuint *jpgTextures = new GLuint[5]; GLuint *pngTextures = new GLuint[5]; int width, height, nrChannels; bool rotate = true; bool pyramid = false, rotateClockwise = true; int bmpTextureIndex = 0, textureIndex = 0; float rotateObj[] = {0.0, 0.0, 0.0, 0.0}; float rotateObj1 = 0.0; char question = '1'; GLUquadricObj *var = NULL; double rotateCam = 0, bridgeDegree = 0; bool isOrtho = false; // camera float lastX = SCR_WIDTH / 2.0f; float lastY = SCR_HEIGHT / 2.0f; // camera bool firstMouse = false; float xPosf = 0.0, yPosf = 0.0; void init() { glEnable(GL_DEPTH_TEST); // Enable depth testing for z-culling glEnable(GL_TEXTURE_2D); // std::cout << sizeof(textures) << std::endl; LoadBmpTexture(bmpFilenames, bmpTextures, (sizeof(bmpFilenames) / sizeof(*bmpFilenames))); LoadJpgTexture(jpgFilenames, jpgTextures, (sizeof(jpgFilenames) / sizeof(*jpgFilenames))); LoadPngTexture(pngFilenames, pngTextures, (sizeof(pngFilenames) / sizeof(*pngFilenames))); } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_SAMPLES, 4); // #ifdef __APPLE__ // glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X // #endif // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Practical 7", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // configure global opengl state // ----------------------------- init(); // render loop // ----------- while (!glfwWindowShouldClose(window)) { processInput(window); // rotateObj[0] = sin(glfwGetTime()) * 90.0; // render // ------ // glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // // background texture // // glOrtho(0.0, glfwwid, 0.0, glutGet(GLUT_WINDOW_HEIGHT), -1.0, 1.0); // glBindTexture(GL_TEXTURE_2D, jpgTextures[4]); // glBegin(GL_QUADS); // glTexCoord2f(0, 0); // glVertex2f(-1, -1); // glTexCoord2f(1, 0); // glVertex2f(1, -1); // glTexCoord2f(1, 1); // glVertex2f(1, 1); // glTexCoord2f(0, 1); // glVertex2f(-1, 1); // glEnd(); // glBindTexture(GL_TEXTURE_2D, 0); // glDeleteTextures(0, &jpgTextures[4]); // glPopMatrix(); // glMatrixMode(GL_PROJECTION); // glPopMatrix(); // gluLookAt(camera.x, camera.y, camera.z, lookat.x, lookat.y, lookat.z, 0, 1, 0); glPushMatrix(); glMatrixMode(GL_MODELVIEW); // To operate on model-view matrix glPopMatrix(); glLoadIdentity(); GLUquadricObj *sphere = NULL; sphere = gluNewQuadric(); gluQuadricTexture(sphere, GLU_TRUE); gluQuadricDrawStyle(sphere, GLU_FILL); glBindTexture(GL_TEXTURE_2D, jpgTextures[5]); gluSphere(sphere, 95, 40, 40); gluDeleteQuadric(sphere); glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); glTranslatef(0.0f, 0.0f, zoomLevel); display(); glPopMatrix(); glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDisable(GL_TEXTURE_2D); glfwTerminate(); return 0; } void display() { glPushMatrix(); { if (rotate) { glRotatef(-rotateObj[0], rotateObj[1], rotateObj[2], rotateObj[3]); } else { glRotatef(rotateObj[0], rotateObj[1], rotateObj[2], rotateObj[3]); } if (rotateClockwise) { glRotatef(-rotateObj[0], rotateObj[1], rotateObj[2], rotateObj[3]); } else { glRotatef(rotateObj[0], rotateObj[1], rotateObj[2], rotateObj[3]); } switch (question) { case '1': glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, bmpTextures[0]); glPushMatrix(); drawPyramid(0.6); glPopMatrix(); glBindTexture(GL_TEXTURE_2D, 0); break; case '2': glBindTexture(GL_TEXTURE_2D, bmpTextures[bmpTextureIndex]); glPushMatrix(); drawCube(0.6); glPopMatrix(); glBindTexture(GL_TEXTURE_2D, 0); break; case '3': glPushMatrix(); drawIceCream(); glPopMatrix(); gluDeleteQuadric(var); break; case '4': glPushMatrix(); drawTowerBridge(); glPopMatrix(); gluDeleteQuadric(var); break; default: break; } } glPopMatrix(); } void building() { glBegin(GL_QUADS); //front // glColor3f(0.94, 0.89, 0.69); glTexCoord2f(1, 1); glVertex3f(0, 0.6, 0); glTexCoord2f(0, 1); glVertex3f(0.3, 0.6, 0); glTexCoord2f(0, 0); glVertex3f(0.3, 0, 0); glTexCoord2f(1, 0); glVertex3f(0, 0, 0); //left glTexCoord2f(1, 1); glVertex3f(0, 0.6, 0); glTexCoord2f(0, 1); glVertex3f(0, 0.6, 0.3); glTexCoord2f(0, 0); glVertex3f(0, 0, 0.3); glTexCoord2f(1, 0); glVertex3f(0, 0, 0); //back glTexCoord2f(1, 1); glVertex3f(0, 0.6, 0.3); glTexCoord2f(0, 1); glVertex3f(0.3, 0.6, 0.3); glTexCoord2f(0, 0); glVertex3f(0.3, 0, 0.3); glTexCoord2f(1, 0); glVertex3f(0, 0, 0.3); //right glTexCoord2f(1, 1); glVertex3f(0.3, 0.6, 0.3); glTexCoord2f(0, 1); glVertex3f(0.3, 0.6, 0); glTexCoord2f(0, 0); glVertex3f(0.3, 0, 0); glTexCoord2f(1, 0); glVertex3f(0.3, 0, 0.3); //top glTexCoord2f(1, 1); glVertex3f(0, 0.6, 0.3); glTexCoord2f(0, 1); glVertex3f(0.3, 0.6, 0.3); glTexCoord2f(0, 0); glVertex3f(0.3, 0.6, 0); glTexCoord2f(1, 0); glVertex3f(0, 0.6, 0); //bottom glTexCoord2f(1, 1); glVertex3f(0, 0, 0.3); glTexCoord2f(0, 1); glVertex3f(0.3, 0, 0.3); glTexCoord2f(0, 0); glVertex3f(0.3, 0, 0); glTexCoord2f(1, 0); glVertex3f(0, 0, 0); glEnd(); } void longBridge() { glBegin(GL_QUADS); // glColor3f(0.55, 1, 0.98); //front glTexCoord2f(0, 0); glVertex3f(0, 0.6, 0); glTexCoord2f(1, 0); glVertex3f(0.3, 0.6, 0); glTexCoord2f(1, 1); glVertex3f(0.3, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, 0, 0); //left glTexCoord2f(0, 0); glVertex3f(0, 0.6, 0); glTexCoord2f(1, 0); glTexCoord2f(1, 0); glVertex3f(0, 0.6, 0.3); glTexCoord2f(1, 1); glVertex3f(0, 0, 0.3); glTexCoord2f(0, 1); glVertex3f(0, 0, 0); //back glTexCoord2f(0, 0); glVertex3f(0, 0.6, 0.3); glTexCoord2f(1, 0); glTexCoord2f(1, 0); glVertex3f(0.3, 0.6, 0.3); glTexCoord2f(1, 1); glVertex3f(0.3, 0, 0.3); glTexCoord2f(0, 1); glVertex3f(0, 0, 0.3); //right glTexCoord2f(0, 0); glVertex3f(0.3, 0.6, 0.3); glTexCoord2f(1, 0); glVertex3f(0.3, 0.6, 0); glTexCoord2f(1, 1); glVertex3f(0.3, 0, 0); glTexCoord2f(0, 1); glVertex3f(0.3, 0, 0.3); //top glTexCoord2f(0, 0); glVertex3f(0, 0.6, 0.3); glTexCoord2f(1, 0); glVertex3f(0.3, 0.6, 0.3); glTexCoord2f(1, 1); glVertex3f(0.3, 0.6, 0); glTexCoord2f(0, 1); glVertex3f(0, 0.6, 0); //bottom glTexCoord2f(0, 0); glVertex3f(0, 0, 0.3); glTexCoord2f(1, 0); glVertex3f(0.3, 0, 0.3); glTexCoord2f(1, 1); glVertex3f(0.3, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, 0, 0); glEnd(); } void cylinderBase() { glBindTexture(GL_TEXTURE_2D, jpgTextures[1]); gluCylinder(var, 0.3, 0.3, 0.3, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); } void cylinderTop() { glBindTexture(GL_TEXTURE_2D, jpgTextures[2]); gluCylinder(var, 0.05, 0.05, 0.65, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); } void coneTop() { glBindTexture(GL_TEXTURE_2D, jpgTextures[0]); gluCylinder(var, 0, 0.07, 0.1, 40, 40); glBindTexture(GL_TEXTURE_2D, 0); } void coneTopBig() { glBindTexture(GL_TEXTURE_2D, jpgTextures[1]); gluCylinder(var, 0, 0.1, 0.2, 40, 40); glBindTexture(GL_TEXTURE_2D, 0); } void bridgeString() { gluCylinder(var, 0, 0.3, 0.3, 2, 3); } void drawBridgeCuboid(float size, float widthScale, float thinness, float longness) { glBegin(GL_QUADS); // front glTexCoord2f(0, 0); glVertex3f(0, 0, size / widthScale); glTexCoord2f(1, 0); glVertex3f(size / thinness, 0, size / widthScale); glTexCoord2f(1, 1); glVertex3f(size / thinness, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, 0, 0); // left glTexCoord2f(0, 0); glVertex3f(0, size * longness, size / widthScale); glTexCoord2f(1, 0); glVertex3f(0, 0, size / widthScale); glTexCoord2f(1, 1); glVertex3f(0, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, size * longness, 0); // bottom glTexCoord2f(0, 0); glVertex3f(0, size * longness, 0); glTexCoord2f(1, 0); glVertex3f(size / thinness, size * longness, 0); glTexCoord2f(1, 1); glVertex3f(size / thinness, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, 0, 0); // right glTexCoord2f(0, 0); glVertex3f(size / thinness, 0, size / widthScale); glTexCoord2f(1, 0); glVertex3f(size / thinness, size * longness, size / widthScale); glTexCoord2f(1, 1); glVertex3f(size / thinness, size * longness, 0); glTexCoord2f(0, 1); glVertex3f(size / thinness, 0, 0); // behind glTexCoord2f(0, 0); glVertex3f(size / thinness, size * longness, size / widthScale); glTexCoord2f(1, 0); glVertex3f(0, size * longness, size / widthScale); glTexCoord2f(1, 1); glVertex3f(0, size * longness, 0); glTexCoord2f(0, 1); glVertex3f(size / thinness, size * longness, 0); // top glTexCoord2f(0, 0); glVertex3f(0, size * longness, size / widthScale); glTexCoord2f(1, 0); glVertex3f(size / thinness, size * longness, size / widthScale); glTexCoord2f(1, 1); glVertex3f(size / thinness, 0, size / widthScale); glTexCoord2f(0, 1); glVertex3f(0, 0, size / widthScale); glEnd(); } void drawTowerBridge() { var = gluNewQuadric(); gluQuadricTexture(var, GL_TRUE); glPushMatrix(); { glTranslatef(-0.6, -0.4, 0); glBindTexture(GL_TEXTURE_2D, pngTextures[0]); building(); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); glPushMatrix(); { glTranslatef(0.3, 0.05, 0); glScalef(1, 0.20, 0.25); glRotatef(90, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, bmpTextures[3]); longBridge(); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); // open close bridge glPushMatrix(); { glTranslatef(-0.55, -0.4 + 0.05, 0.1); glRotatef(bridgeDegree, 0, 0, 1); glRotatef(270, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, bmpTextures[2]); drawBridgeCuboid(1.5, 6, 30, 0.37); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); // open close bridge glPushMatrix(); { glTranslatef(0.55, -0.4, 0.1); glRotatef(-bridgeDegree, 0, 0, 1); glRotatef(-270, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, bmpTextures[2]); drawBridgeCuboid(1.5, 6, 30, 0.37); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(-0.45, -0.4, 0); glRotatef(90, 1, 0, 0); cylinderBase(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(-0.45, 0.40, 0); glRotatef(90, 1, 0, 0); coneTopBig(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(255, 255, 255); glTranslatef(-0.55, 0.25, 0); glRotatef(90, 1, 0, 0); cylinderTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(-0.55, 0.35, 0); glRotatef(90, 1, 0, 0); coneTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(255, 255, 255); glTranslatef(-0.35, 0.25, 0); glRotatef(90, 1, 0, 0); cylinderTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(-0.35, 0.35, 0); glRotatef(90, 1, 0, 0); coneTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_LINE); // glColor3ub(255, 255, 255); glTranslatef(-0.6, -0.4, 0); glRotatef(270, 0, 1, 1); bridgeString(); } glPopMatrix(); glPushMatrix(); { glTranslatef(-0.6, -0.46, 0); // glColor3ub(156, 250, 255); glRotatef(90, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, bmpTextures[2]); drawBridgeCuboid(1.5, 4, 30, 0.37); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(0.45, -0.4, 0); glRotatef(90, 1, 0, 0); cylinderBase(); } glPopMatrix(); glPushMatrix(); { glTranslatef(1.17, -0.46, 0); // glColor3ub(156, 250, 255); glRotatef(90, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, bmpTextures[2]); drawBridgeCuboid(1.5, 4, 30, 0.37); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_LINE); // glColor3ub(255, 255, 255); glTranslatef(0.6, -0.4, 0); glRotatef(-270, 0, 1, 1); bridgeString(); } glPopMatrix(); glPushMatrix(); { glTranslatef(0.30, -0.4, 0); glBindTexture(GL_TEXTURE_2D, pngTextures[0]); building(); glBindTexture(GL_TEXTURE_2D, 0); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(0.45, 0.40, 0); glRotatef(90, 1, 0, 0); coneTopBig(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(255, 255, 255); glTranslatef(0.55, 0.25, 0); glRotatef(90, 1, 0, 0); cylinderTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(0.55, 0.35, 0); glRotatef(90, 1, 0, 0); coneTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(255, 255, 255); glTranslatef(0.35, 0.25, 0); glRotatef(90, 1, 0, 0); cylinderTop(); } glPopMatrix(); glPushMatrix(); { gluQuadricDrawStyle(var, GLU_FILL); // glColor3ub(0, 157, 255); glTranslatef(0.35, 0.35, 0); glRotatef(90, 1, 0, 0); coneTop(); } glPopMatrix(); } void drawIceCream() { var = gluNewQuadric(); gluQuadricTexture(var, GL_TRUE); // cream topping gluQuadricDrawStyle(var, GLU_FILL); glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslatef(-0.1, 0, 1.3); gluCylinder(var, 0.05, 0.05, 0.1, 40, 40); glPopMatrix(); // cream topping glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslatef(-0.1, 0, 1); gluCylinder(var, 0.05, 0.05, 0.1, 40, 40); glPopMatrix(); // chocolate topping glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslatef(-0.1, 0, 0.8); glBindTexture(GL_TEXTURE_2D, jpgTextures[3]); gluCylinder(var, 0.05, 0.05, 0.8, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); // fruit topping glPushMatrix(); glRotatef(90, 1, 0, 0); glTranslatef(0.3, 0, -1); glBindTexture(GL_TEXTURE_2D, jpgTextures[2]); gluSphere(var, 0.2, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); // top scope glPushMatrix(); glRotatef(90, 1, 0, 0); glTranslatef(0, 0, -0.5); glBindTexture(GL_TEXTURE_2D, jpgTextures[1]); gluSphere(var, 0.5, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); // top topping gluQuadricDrawStyle(var, GLU_POINT); glPushMatrix(); glRotatef(90, 1, 0, 0); glTranslatef(0, 0, -0.5); gluSphere(var, 0.5, 20, 20); glPopMatrix(); // bottom scope gluQuadricDrawStyle(var, GLU_FILL); glPushMatrix(); glRotatef(-90.0, 1.0, 0.0, 0.0); glBindTexture(GL_TEXTURE_2D, jpgTextures[1]); gluSphere(var, 0.6, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); // cone glPushMatrix(); glRotatef(-90.0, 1.0, 0.0, 0.0); glTranslatef(0, 0, -2); glBindTexture(GL_TEXTURE_2D, jpgTextures[0]); gluCylinder(var, 0.001, 0.6, 2, 20, 20); glBindTexture(GL_TEXTURE_2D, 0); // cone line // gluQuadricDrawStyle(var, GLU_LINE); // glColor3f(0.94, 0.91, 0.87); // gluCylinder(var, 0.001, 0.50, 1.66, 25, 10); // glPopMatrix(); } void drawPyramid(float size) { glBegin(GL_POLYGON); // Bottom face // glColor3f(1.0f, 0.5f, 0.0f); // Orange glTexCoord2f(0, 0); //bottom left glVertex3f(size, -size, size); glTexCoord2f(1, 0); //top left glVertex3f(-size, -size, size); glTexCoord2f(1, 1); //top right glVertex3f(-size, -size, -size); glTexCoord2f(0, 1); //bottom right glVertex3f(size, -size, -size); glEnd(); glBegin(GL_TRIANGLES); // Left face // glColor3f(0.0f, 0.0f, 1.0f); // Blue glTexCoord2f(0, 0); //bottom left glVertex3f(0.0f, size, 0.0f); glTexCoord2f(1, 1); //top right glVertex3f(-size, -size, -size); glTexCoord2f(0, 1); //bottom right glVertex3f(-size, -size, size); // Back face // glColor3f(1.0f, 1.0f, 0.0f); // Yellow glTexCoord2f(0, 0); //bottom left glVertex3f(0.0f, size, 0.0f); glTexCoord2f(1, 1); //top right glVertex3f(-size, -size, -size); glTexCoord2f(0, 1); //bottom right glVertex3f(size, -size, -size); // Right face // glColor3f(1.0f, 0.0f, 1.0f); // Magenta glTexCoord2f(0, 0); //bottom left glVertex3f(0.0f, size, 0.0f); glTexCoord2f(1, 1); //top right glVertex3f(size, -size, size); glTexCoord2f(0, 1); //bottom right glVertex3f(size, -size, -size); // Front face // glColor3f(1.0f, 0.0f, 0.0f); // Red glTexCoord2f(0, 0); //bottom left glVertex3f(0.0f, size, 0.0f); glTexCoord2f(1, 1); //top right glVertex3f(size, -size, size); glTexCoord2f(0, 1); //bottom right glVertex3f(-size, -size, size); glEnd(); } void drawCube(float size) { glBegin(GL_QUADS); // Begin drawing the color cube with 6 quads // Top face (y = 1.0f) // Define vertices in counter-clockwise (CCW) order with normal pointing out glTexCoord2f(0, 0); glVertex3f(size, size, -size); glTexCoord2f(1, 0); glVertex3f(-size, size, -size); glTexCoord2f(1, 1); glVertex3f(-size, size, size); glTexCoord2f(0, 1); glVertex3f(size, size, size); // Bottom face (y = -1.0f) glTexCoord2f(0, 0); glVertex3f(size, -size, size); glTexCoord2f(1, 0); glVertex3f(-size, -size, size); glTexCoord2f(1, 1); glVertex3f(-size, -size, -size); glTexCoord2f(0, 1); glVertex3f(size, -size, -size); // Front face (z = 1.0f) glTexCoord2f(0, 0); glVertex3f(size, size, size); glTexCoord2f(1, 0); glVertex3f(-size, size, size); glTexCoord2f(1, 1); glVertex3f(-size, -size, size); glTexCoord2f(0, 1); glVertex3f(size, -size, size); // Back face (z = -1.0f) glTexCoord2f(0, 0); glVertex3f(size, -size, -size); glTexCoord2f(1, 0); glVertex3f(-size, -size, -size); glTexCoord2f(1, 1); glVertex3f(-size, size, -size); glTexCoord2f(0, 1); glVertex3f(size, size, -size); // Left face (x = -1.0f) glTexCoord2f(0, 0); glVertex3f(-size, size, size); glTexCoord2f(1, 0); glVertex3f(-size, size, -size); glTexCoord2f(1, 1); glVertex3f(-size, -size, -size); glTexCoord2f(0, 1); glVertex3f(-size, -size, size); // Right face (x = 1.0f) glTexCoord2f(0, 0); glVertex3f(size, size, -size); glTexCoord2f(1, 0); glVertex3f(size, size, size); glTexCoord2f(1, 1); glVertex3f(size, -size, size); glTexCoord2f(0, 1); glVertex3f(size, -size, -size); glEnd(); // End of drawing color-cube } GLuint LoadJpgTexture(const char *filename[], GLuint *texture, int size) { // set the texture wrapping/filtering options (on the currently bound texture object) // load and generate the texture unsigned char *data; stbi_set_flip_vertically_on_load(true); for (int i = 0; i < size; i++) { strcpy(temp, dir_path.c_str()); strcat(temp, slash.c_str()); strcat(temp, filename[i]); data = stbi_load(temp, &width, &height, &nrChannels, 0); if (data) { glGenTextures(1, &texture[i]); glBindTexture(GL_TEXTURE_2D, texture[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glDeleteTextures(1, &textureBuffer[i]); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); glBindTexture(GL_TEXTURE_2D, 0); } } GLuint LoadPngTexture(const char *filename[], GLuint *texture, int size) { // set the texture wrapping/filtering options (on the currently bound texture object) // load and generate the texture unsigned char *data; stbi_set_flip_vertically_on_load(true); for (int i = 0; i < size; i++) { strcpy(temp, dir_path.c_str()); strcat(temp, slash.c_str()); strcat(temp, filename[i]); data = stbi_load(temp, &width, &height, &nrChannels, 0); if (data) { glGenTextures(1, &texture[i]); glBindTexture(GL_TEXTURE_2D, texture[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glDeleteTextures(1, &textureBuffer[i]); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); glBindTexture(GL_TEXTURE_2D, 0); } } GLuint LoadBmpTexture(const char *filename[], GLuint *texture, int size) { // set the texture wrapping/filtering options (on the currently bound texture object) // load and generate the texture unsigned char *data; stbi_set_flip_vertically_on_load(true); for (int i = 0; i < size; i++) { strcpy(temp, dir_path.c_str()); strcat(temp, slash.c_str()); strcat(temp, filename[i]); data = stbi_load(temp, &width, &height, &nrChannels, 0); if (data) { glGenTextures(1, &texture[i]); glBindTexture(GL_TEXTURE_2D, texture[i]); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); // glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // default glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glDeleteTextures(1, &textureBuffer[i]); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); glBindTexture(GL_TEXTURE_2D, 0); } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow *window, int width, int height) { if (height == 0) height = 1; // To prevent divide by 0 GLfloat aspect = (GLfloat)width / (GLfloat)height; // Set the viewport to cover the new window glViewport(0, 0, width, height); // Set the aspect ratio of the clipping volume to match the viewport glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix glLoadIdentity(); // Reset // Enable perspective projection with fovy, aspect, zNear and zFar gluPerspective(45.0f, aspect, 0.1f, 100.0f); } void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, true); break; case GLFW_KEY_SPACE: rotate = !rotate; break; case GLFW_KEY_LEFT: bmpTextureIndex = (bmpTextureIndex + 4 - 1) % 4; break; case GLFW_KEY_RIGHT: bmpTextureIndex = (bmpTextureIndex + 4 + 1) % 4; break; case GLFW_KEY_1: question = '1'; break; case GLFW_KEY_2: question = '2'; break; case GLFW_KEY_3: question = '3'; break; case GLFW_KEY_4: question = '4'; break; default: break; } } } void processInput(GLFWwindow *window) { if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { rotateObj[1] = 0.0; rotateObj[2] = 1.0; rotateObj[3] = 0.0; rotateObj[0] += xPosf - lastX; lastX = xPosf; lastY = yPosf; } if (glfwGetKey(window, GLFW_KEY_O) == GLFW_PRESS) pyramid = false; if (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS) pyramid = true; if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) rotateClockwise = true; if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) rotateClockwise = false; if (glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) { rotateObj[0] += 1.0; rotateObj[1] = 1.0; rotateObj[2] = 0.0; rotateObj[3] = 0.0; } if (glfwGetKey(window, GLFW_KEY_Y) == GLFW_PRESS) { rotateObj[0] += 1.0; rotateObj[1] = 0.0; rotateObj[2] = 1.0; rotateObj[3] = 0.0; } if (glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) { rotateObj[0] += 1.0; rotateObj[1] = 0.0; rotateObj[2] = 0.0; rotateObj[3] = 1.0; } } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- void mouse_callback(GLFWwindow *window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; // camera.ProcessMouseMovement(xoffset, yoffset); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { // camera.ProcessMouseScroll(yoffset); zoomLevel += yoffset; } void cursorPositionCallback(GLFWwindow *window, double xPos, double yPos) { xPosf = xPos; yPosf = yPos; } void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { lastX = xPosf; lastY = yPosf; } }
[ "tanlh-wa16@student.tarc.edu.my" ]
tanlh-wa16@student.tarc.edu.my
87819d208c761f76a0a1390652f7047080497fe4
ed2f89fc0bfb136cbbd5a49733b7e46aadfdc0fd
/_SHADERS/marble/geod_A/geod_A_SHADER_SHUTDOWN.cpp
e2191b7b21e2d123b1e0320a0d6390ef9fbf5e00
[]
no_license
marcclintdion/a7_3D_CUBE
40975879cf0840286ad1c37d80f906db581e60c4
1ba081bf93485523221da32038cad718a1f823ea
refs/heads/master
2021-01-20T12:00:32.550585
2015-09-19T03:25:14
2015-09-19T03:25:14
42,757,927
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
if(geod_A_SHADER != 0) { glDeleteProgram(geod_A_SHADER); geod_A_SHADER = 0; }
[ "marcclintdion@Marcs-iMac.local" ]
marcclintdion@Marcs-iMac.local
f0b0f56be9bfcffce508d443f78c7d7b381b891a
1f54a7112c2a48fca15401c989839bad4fa27f27
/vctick.h
e9ba40a6e3af788a7f67b8d5f7d2ff043b5313d7
[]
no_license
nelbren/Cache2020
12951684d658914cbbf6530ca0d2580d8aaa2683
c2b63bd4e1b03ec1f05bb475b949964bceb294af
refs/heads/master
2022-07-06T21:03:31.422845
2020-05-18T19:23:25
2020-05-18T19:23:25
265,010,499
0
0
null
null
null
null
UTF-8
C++
false
false
1,157
h
#if !defined(AFX_VCTICK_H__9D940371_C194_4983_BF61_85088B20AE00__INCLUDED_) #define AFX_VCTICK_H__9D940371_C194_4983_BF61_85088B20AE00__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. ///////////////////////////////////////////////////////////////////////////// // CVcTick wrapper class class CVcTick : public COleDispatchDriver { public: CVcTick() {} // Calls COleDispatchDriver default constructor CVcTick(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CVcTick(const CVcTick& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: float GetLength(); void SetLength(float newValue); long GetStyle(); void SetStyle(long nNewValue); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_VCTICK_H__9D940371_C194_4983_BF61_85088B20AE00__INCLUDED_)
[ "nelbren@gmail.com" ]
nelbren@gmail.com
75232eb364e75893bc85bb053ccde884a456b0d4
18dccc3d9637edc45ce696682284c707b6e8a170
/Source/WebKit/chromium/src/WebKit.cpp
6a4d7d4b61cbfca6bfa2394e8f8c71042fa77f08
[ "BSD-2-Clause" ]
permissive
MastaG/webkit
19ef8431cca115ae5482c4d01e5561b6a654ffae
1c567be6144228b511852e3cab689fc41b052875
refs/heads/master
2020-12-02T21:25:35.881875
2015-08-11T01:08:31
2015-08-11T01:08:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,158
cpp
/* * Copyright (C) 2009 Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebKit.h" #include "Logging.h" #include "Page.h" #include "RuntimeEnabledFeatures.h" #include "Settings.h" #include "TextEncoding.h" #include "V8Binding.h" #include "WebKitPlatformSupport.h" #include "WebMediaPlayerClientImpl.h" #include "WebSocket.h" #include "WorkerContextExecutionProxy.h" #include "v8.h" #include <wtf/Assertions.h> #include <wtf/MainThread.h> #include <wtf/Threading.h> #include <wtf/text/AtomicString.h> namespace WebKit { // Make sure we are not re-initialized in the same address space. // Doing so may cause hard to reproduce crashes. static bool s_webKitInitialized = false; static WebKitPlatformSupport* s_webKitPlatformSupport = 0; static bool s_layoutTestMode = false; static bool generateEntropy(unsigned char* buffer, size_t length) { if (s_webKitPlatformSupport) { s_webKitPlatformSupport->cryptographicallyRandomValues(buffer, length); return true; } return false; } void initialize(WebKitPlatformSupport* webKitPlatformSupport) { ASSERT(!s_webKitInitialized); s_webKitInitialized = true; ASSERT(webKitPlatformSupport); ASSERT(!s_webKitPlatformSupport); s_webKitPlatformSupport = webKitPlatformSupport; WTF::initializeThreading(); WTF::initializeMainThread(); WTF::AtomicString::init(); // There are some code paths (for example, running WebKit in the browser // process and calling into LocalStorage before anything else) where the // UTF8 string encoding tables are used on a background thread before // they're set up. This is a problem because their set up routines assert // they're running on the main WebKitThread. It might be possible to make // the initialization thread-safe, but given that so many code paths use // this, initializing this lazily probably doesn't buy us much. WebCore::UTF8Encoding(); v8::V8::SetEntropySource(&generateEntropy); v8::V8::Initialize(); WebCore::V8BindingPerIsolateData::ensureInitialized(v8::Isolate::GetCurrent()); } void shutdown() { s_webKitPlatformSupport = 0; } WebKitPlatformSupport* webKitPlatformSupport() { return s_webKitPlatformSupport; } void setLayoutTestMode(bool value) { s_layoutTestMode = value; } bool layoutTestMode() { return s_layoutTestMode; } void enableLogChannel(const char* name) { WTFLogChannel* channel = WebCore::getChannelFromName(name); if (channel) channel->state = WTFLogChannelOn; } void resetPluginCache(bool reloadPages) { WebCore::Page::refreshPlugins(reloadPages); } } // namespace WebKit
[ "oskwon@dev3" ]
oskwon@dev3
a254a858572101c0785c9098bf9d139f0f318d3e
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/web/winhttp/winhttppostsample/WinHttpPostSample.cpp
87b30dd2895a7364dec827924eb6a768724a7c8f
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
18,733
cpp
// WinHttpPostSample.cpp : Defines the entry point for the console application. // // Copyright (c) Microsoft Corporation. All rights reserved. #include <tchar.h> #include <windows.h> #include <stdio.h> #include "winhttp.h" #ifndef UNICODE #error This sample was written as a Unicode only application." #endif BOOL WinHttpSamplePost( LPCWSTR szServerUrl, LPCWSTR szFile, LPCWSTR szProxyUrl); class CQuickStringWrap { LPWSTR _szAlloc; public: CQuickStringWrap() { _szAlloc = NULL; } ~CQuickStringWrap() { if (_szAlloc != NULL) delete [] _szAlloc; } operator LPCWSTR() const { return _szAlloc;} BOOL Set(LPCWSTR szIn, DWORD dwLen) { LPWSTR szNew; szNew = new WCHAR[dwLen+1]; if (szNew == NULL) { SetLastError( ERROR_OUTOFMEMORY); return FALSE; } memcpy(szNew, szIn, dwLen*sizeof(WCHAR)); szNew[dwLen] = L'\0'; if (_szAlloc != NULL) delete [] _szAlloc; _szAlloc = szNew; return TRUE; } }; int _tmain(int argc, _TCHAR* argv[]) { LPWSTR szServerUrl = argv[1]; LPWSTR szFilename = argv[2]; LPWSTR szProxyUrl = NULL; // optional argv[3]; URL_COMPONENTS urlComponents; BOOL fShowHelp = FALSE; DWORD dwTemp; // // Make sure we got three or four params //(the first is the executeable name, rest are user params) // if (argc != 4) { if (argc == 3) { szProxyUrl = NULL; } else { fShowHelp = TRUE; goto done; } } else { szProxyUrl = argv[3]; } // // Do some validation on the input URLs.. // memset(&urlComponents,0,sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.dwUserNameLength = 1; urlComponents.dwPasswordLength = 1; urlComponents.dwHostNameLength = 1; urlComponents.dwUrlPathLength = 1; if( !WinHttpCrackUrl(szServerUrl, 0, 0, &urlComponents)) { printf("\nThere was a problem with the Server URL %S.\n", szServerUrl); fShowHelp = TRUE; goto done; } memset(&urlComponents,0,sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.dwUserNameLength = 1; urlComponents.dwPasswordLength = 1; urlComponents.dwHostNameLength = 1; urlComponents.dwUrlPathLength = 1; if (szProxyUrl != NULL && (!WinHttpCrackUrl(szProxyUrl, 0, 0, &urlComponents) || urlComponents.dwUrlPathLength > 1 || urlComponents.nScheme != INTERNET_SCHEME_HTTP)) { printf("\nThere was a problem with the Proxy URL %S." " It should be a http:// url, and should have" " an empty path.\n", szProxyUrl); fShowHelp = TRUE; goto done; } // // Make sure a file was passed in... // if ((DWORD)-1 == GetFileAttributes(szFilename)) { printf("\nThe specified file, \"%S\", was not found.\n", szFilename); fShowHelp = TRUE; goto done; } if (!WinHttpSamplePost(szServerUrl, szFilename, szProxyUrl)) goto done; SetLastError(NO_ERROR); done: dwTemp = GetLastError(); if (dwTemp != NO_ERROR) { printf( "\nWinHttpPostSample failed with error code %i.", dwTemp); } if (fShowHelp) { printf( "\n\n Proper usage of this example is \"Post <url1> <filename> [url2]\",\n" "Where <url1> is the target HTTP URL and <filename> is the name of a file\n" "which will be POST'd to <url1>. [url2] is optional and indicates the proxy\n" "to use.\n" " Urls are of the form http://[username]:[password]@<server>[:port]/<path>."); } printf("\n\n"); return 0; } BOOL GetFileHandleAndSize(LPWSTR szFilename, OUT HANDLE* pHandle, OUT DWORD* pdwSize) { BOOL returnValue = FALSE; HANDLE hFile = INVALID_HANDLE_VALUE; LARGE_INTEGER liSize; liSize.LowPart = 0; liSize.HighPart = 0; hFile = CreateFile(szFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) goto done; if (!GetFileSizeEx(hFile, &liSize)) goto done; if (liSize.HighPart != 0 || liSize.LowPart > 0x7FFFFFFF) { // Lets not try to send anything larger than 2 gigs SetLastError(ERROR_OPEN_FAILED); } returnValue = TRUE; done: if (returnValue) { *pHandle = hFile; *pdwSize = liSize.LowPart; return TRUE; } else { if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); return FALSE; } } DWORD ChooseAuthScheme( HINTERNET hRequest, DWORD dwSupportedSchemes) { // It is the servers responsibility to only accept authentication schemes //which provide the level of security needed to protect the server's //resource. // However the client has some obligation when picking an authentication //scheme to ensure it provides the level of security needed to protect //the client's username and password from being revealed. The Basic authentication //scheme is risky because it sends the username and password across the //wire in a format anyone can read. This is not an issue for SSL connections though. if (dwSupportedSchemes & WINHTTP_AUTH_SCHEME_NEGOTIATE) return WINHTTP_AUTH_SCHEME_NEGOTIATE; else if (dwSupportedSchemes & WINHTTP_AUTH_SCHEME_NTLM) return WINHTTP_AUTH_SCHEME_NTLM; else if (dwSupportedSchemes & WINHTTP_AUTH_SCHEME_PASSPORT) return WINHTTP_AUTH_SCHEME_PASSPORT; else if (dwSupportedSchemes & WINHTTP_AUTH_SCHEME_DIGEST) return WINHTTP_AUTH_SCHEME_DIGEST; else if (dwSupportedSchemes & WINHTTP_AUTH_SCHEME_BASIC) { DWORD dwValue; DWORD dwSize = sizeof(dwValue); if (WinHttpQueryOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &dwValue,&dwSize) && (dwValue & SECURITY_FLAG_SECURE)) { return WINHTTP_AUTH_SCHEME_BASIC; } else return 0; } else return 0; } BOOL WinHttpSamplePost( LPCWSTR szServerUrl, LPCWSTR szFile, LPCWSTR szProxyUrl) { BOOL returnValue = FALSE; DWORD dwTemp; URL_COMPONENTS urlServerComponents; URL_COMPONENTS urlProxyComponents; CQuickStringWrap strTargetServer; CQuickStringWrap strTargetPath; CQuickStringWrap strTargetUsername; CQuickStringWrap strTargetPassword; CQuickStringWrap strProxyServer; CQuickStringWrap strProxyUsername; CQuickStringWrap strProxyPassword; HANDLE hFile = INVALID_HANDLE_VALUE; DWORD dwFileSize; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; DWORD dwProxyAuthScheme = 0; DWORD dwStatusCode = 0; if (!GetFileHandleAndSize((LPWSTR)szFile, &hFile, &dwFileSize)) goto done; // // Its a long but straightforward chunk of code below that //splits szServerUrl and szProxyUrl into the various //strTarget*,strProxy* components. They need to be put //into the separate str* variables so that they are individually //NULL-terminated. // // From the server URL, we need a host, path, username and password. memset (&urlServerComponents, 0, sizeof(urlServerComponents)); urlServerComponents.dwStructSize = sizeof(urlServerComponents); urlServerComponents.dwHostNameLength = 1; urlServerComponents.dwUrlPathLength = 1; urlServerComponents.dwUserNameLength = 1; urlServerComponents.dwPasswordLength = 1; if (!WinHttpCrackUrl(szServerUrl, 0, 0, &urlServerComponents)) goto done; // // An earlier version of WinHttp v5.1 has a bug where it misreports //the length of the username or password if they are not present. // if (urlServerComponents.lpszUserName == NULL) urlServerComponents.dwUserNameLength = 0; if (urlServerComponents.lpszPassword == NULL) urlServerComponents.dwPasswordLength = 0; if (!strTargetServer.Set(urlServerComponents.lpszHostName, urlServerComponents.dwHostNameLength) || !strTargetPath.Set(urlServerComponents.lpszUrlPath, urlServerComponents.dwUrlPathLength)) { goto done; } // for the username and password, if they are empty, leave the string pointers as NULL. // This allows for the current process's default credentials to be used. if (urlServerComponents.dwUserNameLength != 0 && !strTargetUsername.Set(urlServerComponents.lpszUserName, urlServerComponents.dwUserNameLength)) { goto done; } if (urlServerComponents.dwPasswordLength != 0 && !strTargetPassword.Set(urlServerComponents.lpszPassword, urlServerComponents.dwPasswordLength)) { goto done; } if (szProxyUrl != NULL) { // From the proxy URL, we need a host, username and password. memset (&urlProxyComponents, 0, sizeof(urlProxyComponents)); urlProxyComponents.dwStructSize = sizeof(urlProxyComponents); urlProxyComponents.dwHostNameLength = 1; urlProxyComponents.dwUserNameLength = 1; urlProxyComponents.dwPasswordLength = 1; if (!WinHttpCrackUrl(szProxyUrl, 0, 0, &urlProxyComponents)) goto done; // // An earlier version of WinHttp v5.1 has a bug where it misreports //the length of the username or password if they are not present. // if (urlProxyComponents.lpszUserName == NULL) urlProxyComponents.dwUserNameLength = 0; if (urlProxyComponents.lpszPassword == NULL) urlProxyComponents.dwPasswordLength = 0; // We do something tricky here, taking from the host beginning //to the beginning of the path as the strProxyServer. What this //does, is if you have urls like "http://proxy","http://proxy/", //"http://proxy:8080" is copy them as "proxy","proxy","proxy:8080" //respectively. This makes the port available for WinHttpOpen. if (urlProxyComponents.lpszUrlPath == NULL) { urlProxyComponents.lpszUrlPath = wcschr(urlProxyComponents.lpszHostName, L'/'); if(urlProxyComponents.lpszUrlPath == NULL) { urlProxyComponents.lpszUrlPath = urlProxyComponents.lpszHostName + wcslen(urlProxyComponents.lpszHostName); } } if (!strProxyServer.Set(urlProxyComponents.lpszHostName, (DWORD)(urlProxyComponents.lpszUrlPath - urlProxyComponents.lpszHostName))) { goto done; } // for the username and password, if they are empty, leave the string pointers as NULL. // This allows for the current process's default credentials to be used. if (urlProxyComponents.dwUserNameLength != 0 && !strProxyUsername.Set(urlProxyComponents.lpszUserName, urlProxyComponents.dwUserNameLength)) { goto done; } if (urlProxyComponents.dwPasswordLength != 0 && !strProxyPassword.Set(urlProxyComponents.lpszPassword, urlProxyComponents.dwPasswordLength)) { goto done; } } // // whew, now we can go on and start the request. // // // Open a WinHttp session using the specified proxy // if (szProxyUrl != NULL) { hSession = WinHttpOpen(L"WinHttpPostSample",WINHTTP_ACCESS_TYPE_NAMED_PROXY, strProxyServer, L"<local>", 0); } else { hSession = WinHttpOpen(L"WinHttpPostSample",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL,NULL,0); } if (hSession == NULL) goto done; // // Open a connection to the target server // hConnect = WinHttpConnect( hSession, strTargetServer, urlServerComponents.nPort, 0); if (hConnect == NULL) goto done; // // Open the request // hRequest = WinHttpOpenRequest(hConnect, L"POST", strTargetPath, NULL, NULL, NULL, urlServerComponents.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0); if (hRequest == NULL) goto done; // // Send the request. // // This is done in a loop so that authentication challenges can be handled. // BOOL bDone; DWORD dwLastStatusCode = 0; bDone = FALSE; while (!bDone) { // If a proxy auth challenge was responded to, reset those credentials //before each SendRequest. This is done because after responding to a 401 //or perhaps a redirect the proxy may require re-authentication. You //could get into a 407,401,407,401,etc loop otherwise. if (dwProxyAuthScheme != 0) { if( !WinHttpSetCredentials( hRequest, WINHTTP_AUTH_TARGET_PROXY, dwProxyAuthScheme, strProxyUsername, strProxyPassword, NULL)) { goto done; } } // Send a request. if (!WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, dwFileSize, 0)) { goto done; } // // Now we send the contents of the file. We may have to redo this //after an auth challenge, and so we will reset the file position //to the beginning on each loop. // if(INVALID_SET_FILE_POINTER == SetFilePointer(hFile,0,NULL,FILE_BEGIN)) goto done; // Load the file 4k at a time and write it. fwFileLeft will track //how much more needs to be written. DWORD dwFileLeft; dwFileLeft = dwFileSize; while(dwFileLeft > 0) { DWORD dwBytesRead; BYTE buffer[4096]; if (!ReadFile(hFile, buffer, sizeof(buffer), &dwBytesRead, NULL)) goto done; if (dwBytesRead == 0) { dwFileLeft = 0; continue; } else if (dwBytesRead > dwFileLeft) { // unexpectedly read more from the file than we expected to find.. bail out goto done; } else dwFileLeft -= dwBytesRead; if (!WinHttpWriteData(hRequest, buffer, dwBytesRead, &dwBytesRead)) goto done; } // End the request. if (!WinHttpReceiveResponse( hRequest, NULL)) { // There is a special error we can get here indicating we need to try again if (GetLastError() == ERROR_WINHTTP_RESEND_REQUEST) continue; else goto done; } // Check the status code. dwTemp = sizeof(dwStatusCode); if (!WinHttpQueryHeaders( hRequest, WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwStatusCode, &dwTemp, NULL)) { goto done; } DWORD dwSupportedSchemes, dwFirstScheme, dwTarget, dwSelectedScheme; switch (dwStatusCode) { case 200: // The resource was successfully retrieved. // You could use WinHttpReadData to read the contents of the server's response. printf("\nThe POST was successfully completed."); bDone = TRUE; break; case 401: // The server requires authentication. printf("\nThe server requires authentication. Sending credentials..."); // Obtain the supported and preferred schemes. if( !WinHttpQueryAuthSchemes(hRequest, &dwSupportedSchemes, &dwFirstScheme, &dwTarget)) goto done; // Set the credentials before resending the request. dwSelectedScheme = ChooseAuthScheme(hRequest, dwSupportedSchemes); if (dwSelectedScheme == 0) { bDone = TRUE; } else { if (!WinHttpSetCredentials( hRequest, dwTarget, dwSelectedScheme, strTargetUsername, strTargetPassword, NULL)) { goto done; } } // If the same credentials are requested twice, abort the // request. For simplicity, this sample does not check for // a repeated sequence of status codes. if (dwLastStatusCode==401) { printf("\nServer Authentication failed."); bDone = TRUE; } break; case 407: // The proxy requires authentication. printf("\nThe proxy requires authentication. Sending credentials..."); // Obtain the supported and preferred schemes. if (!WinHttpQueryAuthSchemes( hRequest, &dwSupportedSchemes, &dwFirstScheme, &dwTarget)) goto done; // Set the credentials before resending the request. dwProxyAuthScheme = ChooseAuthScheme(hRequest, dwSupportedSchemes); // If the same credentials are requested twice, abort the // request. For simplicity, this sample does not check for // a repeated sequence of status codes. if (dwLastStatusCode==407) { printf("\nProxy Authentication failed."); bDone = TRUE; } break; default: // The status code does not indicate success. printf("\nStatus code %d returned.\n", dwStatusCode); bDone = TRUE; } // Keep track of the last status code. dwLastStatusCode = dwStatusCode; } returnValue = TRUE; done: dwTemp = GetLastError(); if (hRequest != NULL) WinHttpCloseHandle(hRequest); if (hConnect != NULL) WinHttpCloseHandle(hConnect); if (hSession != NULL) WinHttpCloseHandle(hSession); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(INVALID_HANDLE_VALUE); SetLastError(dwTemp); return returnValue; }
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com
3aa4d0ab144e6678eaf5dba2d95a174265122d68
9d851f5315bce6e24c8adcf6d2d2b834f288d2b2
/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/VQueueReasonableReadyValid.cpp
5ddcf244dce85e8b6aa57ae329f57ff6b99289d8
[ "BSD-3-Clause" ]
permissive
ajis01/systolicMM
b9830b4b00cb7f68d49fb039a5a53c04dcaf3e60
d444d0b8cae525501911e8d3c8ad76dac7fb445c
refs/heads/master
2021-08-17T22:54:34.204694
2020-03-18T03:31:59
2020-03-18T03:31:59
247,648,431
0
1
null
2021-03-29T22:26:24
2020-03-16T08:27:34
C++
UTF-8
C++
false
false
24,676
cpp
// Verilated -*- C++ -*- // DESCRIPTION: Verilator output: Design implementation internals // See VQueueReasonableReadyValid.h for the primary calling header #include "VQueueReasonableReadyValid.h" // For This #include "VQueueReasonableReadyValid__Syms.h" //-------------------- // STATIC VARIABLES //-------------------- VL_CTOR_IMP(VQueueReasonableReadyValid) { VQueueReasonableReadyValid__Syms* __restrict vlSymsp = __VlSymsp = new VQueueReasonableReadyValid__Syms(this, name()); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Reset internal values // Reset structure values _ctor_var_reset(); } void VQueueReasonableReadyValid::__Vconfigure(VQueueReasonableReadyValid__Syms* vlSymsp, bool first) { if (0 && first) {} // Prevent unused this->__VlSymsp = vlSymsp; } VQueueReasonableReadyValid::~VQueueReasonableReadyValid() { delete __VlSymsp; __VlSymsp=NULL; } //-------------------- void VQueueReasonableReadyValid::eval() { VL_DEBUG_IF(VL_DBG_MSGF("+++++TOP Evaluate VQueueReasonableReadyValid::eval\n"); ); VQueueReasonableReadyValid__Syms* __restrict vlSymsp = this->__VlSymsp; // Setup global symbol table VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; #ifdef VL_DEBUG // Debug assertions _eval_debug_assertions(); #endif // VL_DEBUG // Initialize if (VL_UNLIKELY(!vlSymsp->__Vm_didInit)) _eval_initial_loop(vlSymsp); // Evaluate till stable int __VclockLoop = 0; QData __Vchange = 1; while (VL_LIKELY(__Vchange)) { VL_DEBUG_IF(VL_DBG_MSGF("+ Clock loop\n");); vlSymsp->__Vm_activity = true; _eval(vlSymsp); __Vchange = _change_request(vlSymsp); if (VL_UNLIKELY(++__VclockLoop > 100)) VL_FATAL_MT(__FILE__,__LINE__,__FILE__,"Verilated model didn't converge"); } } void VQueueReasonableReadyValid::_eval_initial_loop(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { vlSymsp->__Vm_didInit = true; _eval_initial(vlSymsp); vlSymsp->__Vm_activity = true; int __VclockLoop = 0; QData __Vchange = 1; while (VL_LIKELY(__Vchange)) { _eval_settle(vlSymsp); _eval(vlSymsp); __Vchange = _change_request(vlSymsp); if (VL_UNLIKELY(++__VclockLoop > 100)) VL_FATAL_MT(__FILE__,__LINE__,__FILE__,"Verilated model didn't DC converge"); } } //-------------------- // Internal Methods VL_INLINE_OPT void VQueueReasonableReadyValid::_sequent__TOP__1(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_sequent__TOP__1\n"); ); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Variables VL_SIG8(__Vdly__QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0,0,0); // Body __Vdly__QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0 = vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0; // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:462 if (vlTOPp->reset) { vlTOPp->QueueReasonableReadyValid__DOT__value = 0U; } else { if (vlTOPp->QueueReasonableReadyValid__DOT___T_27) { vlTOPp->QueueReasonableReadyValid__DOT__value = ((IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_28) ? 0U : (IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_30)); } } if (vlTOPp->reset) { vlTOPp->QueueReasonableReadyValid__DOT__value_1 = 0U; } else { if ((((IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_20) >> 8U) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1))) { vlTOPp->QueueReasonableReadyValid__DOT__value_1 = ((IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_32) ? 0U : (IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_34)); } } if ((1U & (~ (IData)(vlTOPp->reset)))) { if (VL_UNLIKELY((1U & (~ (((~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) | (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) | (IData)(vlTOPp->reset)))))) { VL_FWRITEF(0x80000002U,"Assertion failed\n at QueueSpec.scala:47 assert(q.io.enq.ready || q.io.count === queueDepth.U)\n"); } } if ((1U & (~ (IData)(vlTOPp->reset)))) { if (VL_UNLIKELY((1U & (~ (((~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) | (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) | (IData)(vlTOPp->reset)))))) { VL_WRITEF("[%0t] %%Error: QueueReasonableReadyValid.v:501: Assertion failed in %NQueueReasonableReadyValid\n", 64,VL_TIME_Q(),vlSymsp->name()); VL_STOP_MT("/home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v",501,""); } } if ((1U & (~ (IData)(vlTOPp->reset)))) { if (VL_UNLIKELY((1U & (~ (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1) | (~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1))) | (IData)(vlTOPp->reset)))))) { VL_FWRITEF(0x80000002U,"Assertion failed\n at QueueSpec.scala:51 assert(q.io.deq.valid || q.io.count === 0.U)\n"); } } if ((1U & (~ (IData)(vlTOPp->reset)))) { if (VL_UNLIKELY((1U & (~ (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1) | (~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1))) | (IData)(vlTOPp->reset)))))) { VL_WRITEF("[%0t] %%Error: QueueReasonableReadyValid.v:523: Assertion failed in %NQueueReasonableReadyValid\n", 64,VL_TIME_Q(),vlSymsp->name()); VL_STOP_MT("/home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v",523,""); } } if ((1U & (~ (IData)(vlTOPp->reset)))) { if (VL_UNLIKELY(((IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_32) & (~ (IData)(vlTOPp->reset))))) { VL_FINISH_MT("/home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v",534,""); } } // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 __Vdly__QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0 = ((IData)(vlTOPp->reset) | ((((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_15) ^ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_13)) ^ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_12)) ^ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_10))); vlTOPp->QueueReasonableReadyValid__DOT___T_32 = (0x14U == (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value_1)); vlTOPp->QueueReasonableReadyValid__DOT___T_34 = (0x1fU & ((IData)(1U) + (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value_1))); vlTOPp->QueueReasonableReadyValid__DOT___T_28 = (0x14U == (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value)); vlTOPp->QueueReasonableReadyValid__DOT___T_30 = (0x1fU & ((IData)(1U) + (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value))); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:61 if (vlTOPp->reset) { vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1 = 0U; } else { if (vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_11) { vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1 = vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_6; } } // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_15 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_14)); vlTOPp->QueueReasonableReadyValid__DOT___T_27 = ((~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) & (0x14U > (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value))); vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_6 = ((~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) & (0x14U > (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value))); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_14 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_13)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_13 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_12)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_12 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_11)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_11 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_10)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_10 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_9)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_9 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_8)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_8 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_7)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_7 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_6)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_6 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_5)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_5 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_4)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_4 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_3)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_3 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_2)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_2 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_1)); // ALWAYS at /home/ajis01/scratch/CS252A_Project/chipyard/tools/chisel3/test_run_dir/QueueReasonableReadyValid/2020030621343613677621383309714749/QueueReasonableReadyValid.v:242 vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_1 = ((~ (IData)(vlTOPp->reset)) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0)); vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0 = __Vdly__QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0; vlTOPp->QueueReasonableReadyValid__DOT___T_20 = (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_15) << 0xfU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_14) << 0xeU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_13) << 0xdU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_12) << 0xcU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_11) << 0xbU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_10) << 0xaU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_9) << 9U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_8) << 8U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_7) << 7U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_6) << 6U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_5) << 5U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_4) << 4U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_3) << 3U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_2) << 2U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_1) << 1U) | (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0)))))))))))))))); vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_11 = ((IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_6) != (((IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_20) >> 8U) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1))); } void VQueueReasonableReadyValid::_settle__TOP__2(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_settle__TOP__2\n"); ); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body vlTOPp->QueueReasonableReadyValid__DOT___T_28 = (0x14U == (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value)); vlTOPp->QueueReasonableReadyValid__DOT___T_30 = (0x1fU & ((IData)(1U) + (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value))); vlTOPp->QueueReasonableReadyValid__DOT___T_32 = (0x14U == (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value_1)); vlTOPp->QueueReasonableReadyValid__DOT___T_34 = (0x1fU & ((IData)(1U) + (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value_1))); vlTOPp->QueueReasonableReadyValid__DOT___T_27 = ((~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) & (0x14U > (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value))); vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_6 = ((~ (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1)) & (0x14U > (IData)(vlTOPp->QueueReasonableReadyValid__DOT__value))); vlTOPp->QueueReasonableReadyValid__DOT___T_20 = (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_15) << 0xfU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_14) << 0xeU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_13) << 0xdU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_12) << 0xcU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_11) << 0xbU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_10) << 0xaU) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_9) << 9U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_8) << 8U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_7) << 7U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_6) << 6U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_5) << 5U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_4) << 4U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_3) << 3U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_2) << 2U) | (((IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_1) << 1U) | (IData)(vlTOPp->QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0)))))))))))))))); vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_11 = ((IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_6) != (((IData)(vlTOPp->QueueReasonableReadyValid__DOT___T_20) >> 8U) & (IData)(vlTOPp->QueueReasonableReadyValid__DOT__q__DOT___T_1))); } void VQueueReasonableReadyValid::_eval(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_eval\n"); ); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body if (((IData)(vlTOPp->clock) & (~ (IData)(vlTOPp->__Vclklast__TOP__clock)))) { vlTOPp->_sequent__TOP__1(vlSymsp); vlTOPp->__Vm_traceActivity = (2U | vlTOPp->__Vm_traceActivity); } // Final vlTOPp->__Vclklast__TOP__clock = vlTOPp->clock; } void VQueueReasonableReadyValid::_eval_initial(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_eval_initial\n"); ); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; } void VQueueReasonableReadyValid::final() { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::final\n"); ); // Variables VQueueReasonableReadyValid__Syms* __restrict vlSymsp = this->__VlSymsp; VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; } void VQueueReasonableReadyValid::_eval_settle(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_eval_settle\n"); ); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body vlTOPp->_settle__TOP__2(vlSymsp); vlTOPp->__Vm_traceActivity = (1U | vlTOPp->__Vm_traceActivity); } VL_INLINE_OPT QData VQueueReasonableReadyValid::_change_request(VQueueReasonableReadyValid__Syms* __restrict vlSymsp) { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_change_request\n"); ); VQueueReasonableReadyValid* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; // Body // Change detection QData __req = false; // Logically a bool return __req; } #ifdef VL_DEBUG void VQueueReasonableReadyValid::_eval_debug_assertions() { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_eval_debug_assertions\n"); ); // Body if (VL_UNLIKELY((clock & 0xfeU))) { Verilated::overWidthError("clock");} if (VL_UNLIKELY((reset & 0xfeU))) { Verilated::overWidthError("reset");} } #endif // VL_DEBUG void VQueueReasonableReadyValid::_ctor_var_reset() { VL_DEBUG_IF(VL_DBG_MSGF("+ VQueueReasonableReadyValid::_ctor_var_reset\n"); ); // Body clock = VL_RAND_RESET_I(1); reset = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__value = VL_RAND_RESET_I(5); QueueReasonableReadyValid__DOT__value_1 = VL_RAND_RESET_I(5); QueueReasonableReadyValid__DOT___T_20 = VL_RAND_RESET_I(16); QueueReasonableReadyValid__DOT___T_27 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT___T_28 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT___T_30 = VL_RAND_RESET_I(5); QueueReasonableReadyValid__DOT___T_32 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT___T_34 = VL_RAND_RESET_I(5); QueueReasonableReadyValid__DOT__q__DOT___T_1 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__q__DOT___T_6 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__q__DOT___T_11 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_0 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_1 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_2 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_3 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_4 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_5 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_6 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_7 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_8 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_9 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_10 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_11 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_12 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_13 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_14 = VL_RAND_RESET_I(1); QueueReasonableReadyValid__DOT__MaxPeriodFibonacciLFSR__DOT__state_15 = VL_RAND_RESET_I(1); __Vclklast__TOP__clock = VL_RAND_RESET_I(1); __Vm_traceActivity = VL_RAND_RESET_I(32); }
[ "ajithkumar.sreekumar94@gmail.com" ]
ajithkumar.sreekumar94@gmail.com
1fc5ecf84e6a6af642ede40b5f8f30d4177bb08b
842f035ed2b207bc0068098ff43777a4c8bd261c
/simdcsv/src/fmt/format-inl.h
c5adc34b089d764adf8c6137a0f3f5bc55722646
[]
no_license
jonlin00/simdcsv
972d66a6e471389b6683a539a4af653fda1c007d
582a16f12059048c0c3b3aeef0c984bfc13ef0ce
refs/heads/master
2022-11-14T15:22:49.883422
2020-06-19T19:48:59
2020-06-19T19:48:59
273,567,101
0
0
null
null
null
null
UTF-8
C++
false
false
50,893
h
// Formatting library for C++ - implementation // // Copyright (c) 2012 - 2016, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #ifndef FMT_FORMAT_INL_H_ #define FMT_FORMAT_INL_H_ #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdarg> #include <cstring> // for std::memmove #include <cwchar> #include "format.h" #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) # include <locale> #endif #ifdef _WIN32 # if defined(NOMINMAX) # include <windows.h> # else # define NOMINMAX # include <windows.h> # undef NOMINMAX # endif # include <io.h> #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4702) // unreachable code #endif // Dummy implementations of strerror_r and strerror_s called if corresponding // system functions are not available. inline Wikinger::fmt::internal::null<> strerror_r(int, char*, ...) { return {}; } inline Wikinger::fmt::internal::null<> strerror_s(char*, std::size_t, ...) { return {}; } FMT_BEGIN_NAMESPACE namespace internal { FMT_FUNC void assert_fail(const char* file, int line, const char* message) { print(stderr, "{}:{}: assertion failed: {}", file, line, message); std::abort(); } #ifndef _MSC_VER # define FMT_SNPRINTF snprintf #else // _MSC_VER inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) { va_list args; va_start(args, format); int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); va_end(args); return result; } # define FMT_SNPRINTF fmt_snprintf #endif // _MSC_VER // A portable thread-safe version of strerror. // Sets buffer to point to a string describing the error code. // This can be either a pointer to a string stored in buffer, // or a pointer to some static immutable string. // Returns one of the following values: // 0 - success // ERANGE - buffer is not large enough to store the error message // other - failure // Buffer should be at least of size 1. FMT_FUNC int safe_strerror(int error_code, char*& buffer, std::size_t buffer_size) FMT_NOEXCEPT { FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer"); class dispatcher { private: int error_code_; char*& buffer_; std::size_t buffer_size_; // A noop assignment operator to avoid bogus warnings. void operator=(const dispatcher&) {} // Handle the result of XSI-compliant version of strerror_r. int handle(int result) { // glibc versions before 2.13 return result in errno. return result == -1 ? errno : result; } // Handle the result of GNU-specific version of strerror_r. FMT_MAYBE_UNUSED int handle(char* message) { // If the buffer is full then the message is probably truncated. if(message == buffer_ && strlen(buffer_) == buffer_size_ - 1) return ERANGE; buffer_ = message; return 0; } // Handle the case when strerror_r is not available. FMT_MAYBE_UNUSED int handle(internal::null<>) { return fallback(strerror_s(buffer_, buffer_size_, error_code_)); } // Fallback to strerror_s when strerror_r is not available. FMT_MAYBE_UNUSED int fallback(int result) { // If the buffer is full then the message is probably truncated. return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE : result; } #if !FMT_MSC_VER // Fallback to strerror if strerror_r and strerror_s are not available. int fallback(internal::null<>) { errno = 0; buffer_ = strerror(error_code_); return errno; } #endif public: dispatcher(int err_code, char*& buf, std::size_t buf_size) : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); } }; return dispatcher(error_code, buffer, buffer_size).run(); } FMT_FUNC void format_error_code(internal::buffer<char>& out, int error_code, string_view message) FMT_NOEXCEPT { // Report error code making sure that the output fits into // inline_buffer_size to avoid dynamic memory allocation and potential // bad_alloc. out.resize(0); static const char SEP[] = ": "; static const char ERROR_STR[] = "error "; // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code); if(internal::is_negative(error_code)) { abs_value = 0 - abs_value; ++error_code_size; } error_code_size += internal::to_unsigned(internal::count_digits(abs_value)); internal::writer w(out); if(message.size() <= inline_buffer_size - error_code_size) { w.write(message); w.write(SEP); } w.write(ERROR_STR); w.write(error_code); assert(out.size() <= inline_buffer_size); } FMT_FUNC void report_error(format_func func, int error_code, string_view message) FMT_NOEXCEPT { memory_buffer full_message; func(full_message, error_code, message); // Don't use fwrite_fully because the latter may throw. (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr); std::fputc('\n', stderr); } // A wrapper around fwrite that throws on error. FMT_FUNC void fwrite_fully(const void* ptr, size_t size, size_t count, FILE* stream) { size_t written = std::fwrite(ptr, size, count, stream); if(written < count) FMT_THROW(system_error(errno, "cannot write to file")); } } // namespace internal #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) namespace internal { template <typename Locale> locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { static_assert(std::is_same<Locale, std::locale>::value, ""); } template <typename Locale> Locale locale_ref::get() const { static_assert(std::is_same<Locale, std::locale>::value, ""); return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale(); } template <typename Char> FMT_FUNC std::string grouping_impl(locale_ref loc) { return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()).grouping(); } template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) { return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()) .thousands_sep(); } template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) { return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()) .decimal_point(); } } // namespace internal #else template <typename Char> FMT_FUNC std::string internal::grouping_impl(locale_ref) { return "\03"; } template <typename Char> FMT_FUNC Char internal::thousands_sep_impl(locale_ref) { return FMT_STATIC_THOUSANDS_SEPARATOR; } template <typename Char> FMT_FUNC Char internal::decimal_point_impl(locale_ref) { return '.'; } #endif FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default; FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT = default; FMT_FUNC void system_error::init(int err_code, string_view format_str, format_args args) { error_code_ = err_code; memory_buffer buffer; format_system_error(buffer, err_code, vformat(format_str, args)); std::runtime_error& base = *this; base = std::runtime_error(to_string(buffer)); } namespace internal { template <> FMT_FUNC int count_digits<4>(internal::fallback_uintptr n) { // fallback_uintptr is always stored in little endian. int i = static_cast<int>(sizeof(void*)) - 1; while(i > 0 && n.value[i] == 0) --i; auto char_digits = std::numeric_limits<unsigned char>::digits / 4; return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1; } template <typename T> const char basic_data<T>::digits[] = "0001020304050607080910111213141516171819" "2021222324252627282930313233343536373839" "4041424344454647484950515253545556575859" "6061626364656667686970717273747576777879" "8081828384858687888990919293949596979899"; template <typename T> const char basic_data<T>::hex_digits[] = "0123456789abcdef"; #define FMT_POWERS_OF_10(factor) \ factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \ (factor)*1000000, (factor)*10000000, (factor)*100000000, \ (factor)*1000000000 template <typename T> const uint64_t basic_data<T>::powers_of_10_64[] = { 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), 10000000000000000000ULL }; template <typename T> const uint32_t basic_data<T>::zero_or_powers_of_10_32[] = { 0, FMT_POWERS_OF_10(1) }; template <typename T> const uint64_t basic_data<T>::zero_or_powers_of_10_64[] = { 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL), 10000000000000000000ULL }; // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340. // These are generated by support/compute-powers.py. template <typename T> const uint64_t basic_data<T>::pow10_significands[] = { 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7, 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053, 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb, 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984, 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85, 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25, 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a, 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129, 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b, }; // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding // to significands above. template <typename T> const int16_t basic_data<T>::pow10_exponents[] = { -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066 }; template <typename T> const char basic_data<T>::foreground_color[] = "\x1b[38;2;"; template <typename T> const char basic_data<T>::background_color[] = "\x1b[48;2;"; template <typename T> const char basic_data<T>::reset_color[] = "\x1b[0m"; template <typename T> const wchar_t basic_data<T>::wreset_color[] = L"\x1b[0m"; template <typename T> const char basic_data<T>::signs[] = { 0, '-', '+', ' ' }; template <typename T> struct bits { static FMT_CONSTEXPR_DECL const int value = static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits); }; class fp; template <int SHIFT = 0> fp normalize(fp value); // Lower (upper) boundary is a value half way between a floating-point value // and its predecessor (successor). Boundaries have the same exponent as the // value so only significands are stored. struct boundaries { uint64_t lower; uint64_t upper; }; // A handmade floating-point number f * pow(2, e). class fp { private: using significand_type = uint64_t; public: significand_type f; int e; // All sizes are in bits. // Subtract 1 to account for an implicit most significant bit in the // normalized form. static FMT_CONSTEXPR_DECL const int double_significand_size = std::numeric_limits<double>::digits - 1; static FMT_CONSTEXPR_DECL const uint64_t implicit_bit = 1ULL << double_significand_size; static FMT_CONSTEXPR_DECL const int significand_size = bits<significand_type>::value; fp() : f(0), e(0) {} fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} // Constructs fp from an IEEE754 double. It is a template to prevent compile // errors on platforms where double is not IEEE754. template <typename Double> explicit fp(Double d) { assign(d); } // Assigns d to this and return true iff predecessor is closer than successor. template <typename Double, FMT_ENABLE_IF(sizeof(Double) == sizeof(uint64_t))> bool assign(Double d) { // Assume double is in the format [sign][exponent][significand]. using limits = std::numeric_limits<Double>; const int exponent_size = bits<Double>::value - double_significand_size - 1; // -1 for sign const uint64_t significand_mask = implicit_bit - 1; const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask; const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1; auto u = bit_cast<uint64_t>(d); f = u & significand_mask; int biased_e = static_cast<int>((u & exponent_mask) >> double_significand_size); // Predecessor is closer if d is a normalized power of 2 (f == 0) other than // the smallest normalized number (biased_e > 1). bool is_predecessor_closer = f == 0 && biased_e > 1; if(biased_e != 0) f += implicit_bit; else biased_e = 1; // Subnormals use biased exponent 1 (min exponent). e = biased_e - exponent_bias - double_significand_size; return is_predecessor_closer; } template <typename Double, FMT_ENABLE_IF(sizeof(Double) != sizeof(uint64_t))> bool assign(Double) { *this = fp(); return false; } // Assigns d to this together with computing lower and upper boundaries, // where a boundary is a value half way between the number and its predecessor // (lower) or successor (upper). The upper boundary is normalized and lower // has the same exponent but may be not normalized. template <typename Double> boundaries assign_with_boundaries(Double d) { bool is_lower_closer = assign(d); fp lower = is_lower_closer ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1); // 1 in normalize accounts for the exponent shift above. fp upper = normalize<1>(fp((f << 1) + 1, e - 1)); lower.f <<= lower.e - upper.e; return boundaries{ lower.f, upper.f }; } template <typename Double> boundaries assign_float_with_boundaries(Double d) { assign(d); constexpr int min_normal_e = std::numeric_limits<float>::min_exponent - std::numeric_limits<double>::digits; significand_type half_ulp = 1 << (std::numeric_limits<double>::digits - std::numeric_limits<float>::digits - 1); if(min_normal_e > e) half_ulp <<= min_normal_e - e; fp upper = normalize<0>(fp(f + half_ulp, e)); fp lower = fp( f - (half_ulp >> ((f == implicit_bit && e > min_normal_e) ? 1 : 0)), e); lower.f <<= lower.e - upper.e; return boundaries{ lower.f, upper.f }; } }; // Normalizes the value converted from double and multiplied by (1 << SHIFT). template <int SHIFT> fp normalize(fp value) { // Handle subnormals. const auto shifted_implicit_bit = fp::implicit_bit << SHIFT; while((value.f & shifted_implicit_bit) == 0) { value.f <<= 1; --value.e; } // Subtract 1 to account for hidden bit. const auto offset = fp::significand_size - fp::double_significand_size - SHIFT - 1; value.f <<= offset; value.e -= offset; return value; } inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; } // Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. inline uint64_t multiply(uint64_t lhs, uint64_t rhs) { #if FMT_USE_INT128 auto product = static_cast<__uint128_t>(lhs) * rhs; auto f = static_cast<uint64_t>(product >> 64); return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f; #else // Multiply 32-bit parts of significands. uint64_t mask = (1ULL << 32) - 1; uint64_t a = lhs >> 32, b = lhs & mask; uint64_t c = rhs >> 32, d = rhs & mask; uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; // Compute mid 64-bit of result and round. uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); #endif } inline fp operator*(fp x, fp y) { return { multiply(x.f, y.f), x.e + y.e + 64 }; } // Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its // (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`. inline fp get_cached_power(int min_exponent, int& pow10_exponent) { const int64_t one_over_log2_10 = 0x4d104d42; // round(pow(2, 32) / log2(10)) int index = static_cast<int>( ((min_exponent + fp::significand_size - 1) * one_over_log2_10 + ((int64_t(1) << 32) - 1)) // ceil >> 32 // arithmetic shift ); // Decimal exponent of the first (smallest) cached power of 10. const int first_dec_exp = -348; // Difference between 2 consecutive decimal exponents in cached powers of 10. const int dec_exp_step = 8; index = (index - first_dec_exp - 1) / dec_exp_step + 1; pow10_exponent = first_dec_exp + index * dec_exp_step; return { data::pow10_significands[index], data::pow10_exponents[index] }; } // A simple accumulator to hold the sums of terms in bigint::square if uint128_t // is not available. struct accumulator { uint64_t lower; uint64_t upper; accumulator() : lower(0), upper(0) {} explicit operator uint32_t() const { return static_cast<uint32_t>(lower); } void operator+=(uint64_t n) { lower += n; if(lower < n) ++upper; } void operator>>=(int shift) { assert(shift == 32); (void)shift; lower = (upper << 32) | (lower >> 32); upper >>= 32; } }; class bigint { private: // A bigint is stored as an array of bigits (big digits), with bigit at index // 0 being the least significant one. using bigit = uint32_t; using double_bigit = uint64_t; enum { bigits_capacity = 32 }; basic_memory_buffer<bigit, bigits_capacity> bigits_; int exp_; bigit operator[](int index) const { return bigits_[to_unsigned(index)]; } bigit& operator[](int index) { return bigits_[to_unsigned(index)]; } static FMT_CONSTEXPR_DECL const int bigit_bits = bits<bigit>::value; friend struct formatter<bigint>; void subtract_bigits(int index, bigit other, bigit& borrow) { auto result = static_cast<double_bigit>((*this)[index]) - other - borrow; (*this)[index] = static_cast<bigit>(result); borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1)); } void remove_leading_zeros() { int num_bigits = static_cast<int>(bigits_.size()) - 1; while(num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits; bigits_.resize(to_unsigned(num_bigits + 1)); } // Computes *this -= other assuming aligned bigints and *this >= other. void subtract_aligned(const bigint& other) { FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); FMT_ASSERT(compare(*this, other) >= 0, ""); bigit borrow = 0; int i = other.exp_ - exp_; for(size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j) { subtract_bigits(i, other.bigits_[j], borrow); } while(borrow > 0) subtract_bigits(i, 0, borrow); remove_leading_zeros(); } void multiply(uint32_t value) { const double_bigit wide_value = value; bigit carry = 0; for(size_t i = 0, n = bigits_.size(); i < n; ++i) { double_bigit result = bigits_[i] * wide_value + carry; bigits_[i] = static_cast<bigit>(result); carry = static_cast<bigit>(result >> bigit_bits); } if(carry != 0) bigits_.push_back(carry); } void multiply(uint64_t value) { const bigit mask = ~bigit(0); const double_bigit lower = value & mask; const double_bigit upper = value >> bigit_bits; double_bigit carry = 0; for(size_t i = 0, n = bigits_.size(); i < n; ++i) { double_bigit result = bigits_[i] * lower + (carry & mask); carry = bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits); bigits_[i] = static_cast<bigit>(result); } while(carry != 0) { bigits_.push_back(carry & mask); carry >>= bigit_bits; } } public: bigint() : exp_(0) {} explicit bigint(uint64_t n) { assign(n); } ~bigint() { assert(bigits_.capacity() <= bigits_capacity); } bigint(const bigint&) = delete; void operator=(const bigint&) = delete; void assign(const bigint& other) { bigits_.resize(other.bigits_.size()); auto data = other.bigits_.data(); std::copy(data, data + other.bigits_.size(), bigits_.data()); exp_ = other.exp_; } void assign(uint64_t n) { size_t num_bigits = 0; do { bigits_[num_bigits++] = n & ~bigit(0); n >>= bigit_bits; } while(n != 0); bigits_.resize(num_bigits); exp_ = 0; } int num_bigits() const { return static_cast<int>(bigits_.size()) + exp_; } bigint& operator<<=(int shift) { assert(shift >= 0); exp_ += shift / bigit_bits; shift %= bigit_bits; if(shift == 0) return *this; bigit carry = 0; for(size_t i = 0, n = bigits_.size(); i < n; ++i) { bigit c = bigits_[i] >> (bigit_bits - shift); bigits_[i] = (bigits_[i] << shift) + carry; carry = c; } if(carry != 0) bigits_.push_back(carry); return *this; } template <typename Int> bigint& operator*=(Int value) { FMT_ASSERT(value > 0, ""); multiply(uint32_or_64_or_128_t<Int>(value)); return *this; } friend int compare(const bigint& lhs, const bigint& rhs) { int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits(); if(num_lhs_bigits != num_rhs_bigits) return num_lhs_bigits > num_rhs_bigits ? 1 : -1; int i = static_cast<int>(lhs.bigits_.size()) - 1; int j = static_cast<int>(rhs.bigits_.size()) - 1; int end = i - j; if(end < 0) end = 0; for(; i >= end; --i, --j) { bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j]; if(lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1; } if(i != j) return i > j ? 1 : -1; return 0; } // Returns compare(lhs1 + lhs2, rhs). friend int add_compare(const bigint& lhs1, const bigint& lhs2, const bigint& rhs) { int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits()); int num_rhs_bigits = rhs.num_bigits(); if(max_lhs_bigits + 1 < num_rhs_bigits) return -1; if(max_lhs_bigits > num_rhs_bigits) return 1; auto get_bigit = [](const bigint& n, int i) -> bigit { return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0; }; double_bigit borrow = 0; int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_); for(int i = num_rhs_bigits - 1; i >= min_exp; --i) { double_bigit sum = static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i); bigit rhs_bigit = get_bigit(rhs, i); if(sum > rhs_bigit + borrow) return 1; borrow = rhs_bigit + borrow - sum; if(borrow > 1) return -1; borrow <<= bigit_bits; } return borrow != 0 ? -1 : 0; } // Assigns pow(10, exp) to this bigint. void assign_pow10(int exp) { assert(exp >= 0); if(exp == 0) return assign(1); // Find the top bit. int bitmask = 1; while(exp >= bitmask) bitmask <<= 1; bitmask >>= 1; // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by // repeated squaring and multiplication. assign(5); bitmask >>= 1; while(bitmask != 0) { square(); if((exp & bitmask) != 0) *this *= 5; bitmask >>= 1; } *this <<= exp; // Multiply by pow(2, exp) by shifting. } void square() { basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_)); int num_bigits = static_cast<int>(bigits_.size()); int num_result_bigits = 2 * num_bigits; bigits_.resize(to_unsigned(num_result_bigits)); using accumulator_t = conditional_t<FMT_USE_INT128, uint128_t, accumulator>; auto sum = accumulator_t(); for(int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { // Compute bigit at position bigit_index of the result by adding // cross-product terms n[i] * n[j] such that i + j == bigit_index. for(int i = 0, j = bigit_index; j >= 0; ++i, --j) { // Most terms are multiplied twice which can be optimized in the future. sum += static_cast<double_bigit>(n[i]) * n[j]; } (*this)[bigit_index] = static_cast<bigit>(sum); sum >>= bits<bigit>::value; // Compute the carry. } // Do the same for the top half. for(int bigit_index = num_bigits; bigit_index < num_result_bigits; ++bigit_index) { for(int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) sum += static_cast<double_bigit>(n[i++]) * n[j--]; (*this)[bigit_index] = static_cast<bigit>(sum); sum >>= bits<bigit>::value; } --num_result_bigits; remove_leading_zeros(); exp_ *= 2; } // Divides this bignum by divisor, assigning the remainder to this and // returning the quotient. int divmod_assign(const bigint& divisor) { FMT_ASSERT(this != &divisor, ""); if(compare(*this, divisor) < 0) return 0; int num_bigits = static_cast<int>(bigits_.size()); FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); int exp_difference = exp_ - divisor.exp_; if(exp_difference > 0) { // Align bigints by adding trailing zeros to simplify subtraction. bigits_.resize(to_unsigned(num_bigits + exp_difference)); for(int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j) bigits_[j] = bigits_[i]; std::uninitialized_fill_n(bigits_.data(), exp_difference, 0); exp_ -= exp_difference; } int quotient = 0; do { subtract_aligned(divisor); ++quotient; } while(compare(*this, divisor) >= 0); return quotient; } }; enum class round_direction { unknown, up, down }; // Given the divisor (normally a power of 10), the remainder = v % divisor for // some number v and the error, returns whether v should be rounded up, down, or // whether the rounding direction can't be determined due to error. // error should be less than divisor / 2. inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder, uint64_t error) { FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow. FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow. FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow. // Round down if (remainder + error) * 2 <= divisor. if(remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2) return round_direction::down; // Round up if (remainder - error) * 2 >= divisor. if(remainder >= error && remainder - error >= divisor - (remainder - error)) { return round_direction::up; } return round_direction::unknown; } namespace digits { enum result { more, // Generate more digits. done, // Done generating digits. error // Digit generation cancelled due to an error. }; } // A version of count_digits optimized for grisu_gen_digits. inline int grisu_count_digits(uint32_t n) { if(n < 10) return 1; if(n < 100) return 2; if(n < 1000) return 3; if(n < 10000) return 4; if(n < 100000) return 5; if(n < 1000000) return 6; if(n < 10000000) return 7; if(n < 100000000) return 8; if(n < 1000000000) return 9; return 10; } // Generates output using the Grisu digit-gen algorithm. // error: the size of the region (lower, upper) outside of which numbers // definitely do not round to value (Delta in Grisu3). template <typename Handler> FMT_ALWAYS_INLINE digits::result grisu_gen_digits(fp value, uint64_t error, int& exp, Handler& handler) { const fp one(1ULL << -value.e, value.e); // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be // zero because it contains a product of two 64-bit numbers with MSB set (due // to normalization) - 1, shifted right by at most 60 bits. auto integral = static_cast<uint32_t>(value.f >> -one.e); FMT_ASSERT(integral != 0, ""); FMT_ASSERT(integral == value.f >> -one.e, ""); // The fractional part of scaled value (p2 in Grisu) c = value % one. uint64_t fractional = value.f & (one.f - 1); exp = grisu_count_digits(integral); // kappa in Grisu. // Divide by 10 to prevent overflow. auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e, value.f / 10, error * 10, exp); if(result != digits::more) return result; // Generate digits for the integral part. This can produce up to 10 digits. do { uint32_t digit = 0; auto divmod_integral = [&](uint32_t divisor) { digit = integral / divisor; integral %= divisor; }; // This optimization by Milo Yip reduces the number of integer divisions by // one per iteration. switch(exp) { case 10: divmod_integral(1000000000); break; case 9: divmod_integral(100000000); break; case 8: divmod_integral(10000000); break; case 7: divmod_integral(1000000); break; case 6: divmod_integral(100000); break; case 5: divmod_integral(10000); break; case 4: divmod_integral(1000); break; case 3: divmod_integral(100); break; case 2: divmod_integral(10); break; case 1: digit = integral; integral = 0; break; default: FMT_ASSERT(false, "invalid number of digits"); } --exp; uint64_t remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional; result = handler.on_digit(static_cast<char>('0' + digit), data::powers_of_10_64[exp] << -one.e, remainder, error, exp, true); if(result != digits::more) return result; } while(exp > 0); // Generate digits for the fractional part. for(;;) { fractional *= 10; error *= 10; char digit = static_cast<char>('0' + static_cast<char>(fractional >> -one.e)); fractional &= one.f - 1; --exp; result = handler.on_digit(digit, one.f, fractional, error, exp, false); if(result != digits::more) return result; } } // The fixed precision digit handler. struct fixed_handler { char* buf; int size; int precision; int exp10; bool fixed; digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error, int& exp) { // Non-fixed formats require at least one digit and no precision adjustment. if(!fixed) return digits::more; // Adjust fixed precision by exponent because it is relative to decimal // point. precision += exp + exp10; // Check if precision is satisfied just by leading zeros, e.g. // format("{:.2f}", 0.001) gives "0.00" without generating any digits. if(precision > 0) return digits::more; if(precision < 0) return digits::done; auto dir = get_round_direction(divisor, remainder, error); if(dir == round_direction::unknown) return digits::error; buf[size++] = dir == round_direction::up ? '1' : '0'; return digits::done; } digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, uint64_t error, int, bool integral) { FMT_ASSERT(remainder < divisor, ""); buf[size++] = digit; if(size < precision) return digits::more; if(!integral) { // Check if error * 2 < divisor with overflow prevention. // The check is not needed for the integral part because error = 1 // and divisor > (1 << 32) there. if(error >= divisor || error >= divisor - error) return digits::error; } else { FMT_ASSERT(error == 1 && divisor > 2, ""); } auto dir = get_round_direction(divisor, remainder, error); if(dir != round_direction::up) return dir == round_direction::down ? digits::done : digits::error; ++buf[size - 1]; for(int i = size - 1; i > 0 && buf[i] > '9'; --i) { buf[i] = '0'; ++buf[i - 1]; } if(buf[0] > '9') { buf[0] = '1'; buf[size++] = '0'; } return digits::done; } }; // The shortest representation digit handler. struct grisu_shortest_handler { char* buf; int size; // Distance between scaled value and upper bound (wp_W in Grisu3). uint64_t diff; digits::result on_start(uint64_t, uint64_t, uint64_t, int&) { return digits::more; } // Decrement the generated number approaching value from above. void round(uint64_t d, uint64_t divisor, uint64_t& remainder, uint64_t error) { while( remainder < d && error - remainder >= divisor && (remainder + divisor < d || d - remainder >= remainder + divisor - d)) { --buf[size - 1]; remainder += divisor; } } // Implements Grisu's round_weed. digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder, uint64_t error, int exp, bool integral) { buf[size++] = digit; if(remainder >= error) return digits::more; uint64_t unit = integral ? 1 : data::powers_of_10_64[-exp]; uint64_t up = (diff - 1) * unit; // wp_Wup round(up, divisor, remainder, error); uint64_t down = (diff + 1) * unit; // wp_Wdown if(remainder < down && error - remainder >= divisor && (remainder + divisor < down || down - remainder > remainder + divisor - down)) { return digits::error; } return 2 * unit <= remainder && remainder <= error - 4 * unit ? digits::done : digits::error; } }; // Formats value using a variation of the Fixed-Precision Positive // Floating-Point Printout ((FPP)^2) algorithm by Steele & White: // https://fmt.dev/p372-steele.pdf. template <typename Double> void fallback_format(Double d, buffer<char>& buf, int& exp10) { bigint numerator; // 2 * R in (FPP)^2. bigint denominator; // 2 * S in (FPP)^2. // lower and upper are differences between value and corresponding boundaries. bigint lower; // (M^- in (FPP)^2). bigint upper_store; // upper's value if different from lower. bigint* upper = nullptr; // (M^+ in (FPP)^2). fp value; // Shift numerator and denominator by an extra bit or two (if lower boundary // is closer) to make lower and upper integers. This eliminates multiplication // by 2 during later computations. // TODO: handle float int shift = value.assign(d) ? 2 : 1; uint64_t significand = value.f << shift; if(value.e >= 0) { numerator.assign(significand); numerator <<= value.e; lower.assign(1); lower <<= value.e; if(shift != 1) { upper_store.assign(1); upper_store <<= value.e + 1; upper = &upper_store; } denominator.assign_pow10(exp10); denominator <<= 1; } else if(exp10 < 0) { numerator.assign_pow10(-exp10); lower.assign(numerator); if(shift != 1) { upper_store.assign(numerator); upper_store <<= 1; upper = &upper_store; } numerator *= significand; denominator.assign(1); denominator <<= shift - value.e; } else { numerator.assign(significand); denominator.assign_pow10(exp10); denominator <<= shift - value.e; lower.assign(1); if(shift != 1) { upper_store.assign(1ULL << 1); upper = &upper_store; } } if(!upper) upper = &lower; // Invariant: value == (numerator / denominator) * pow(10, exp10). bool even = (value.f & 1) == 0; int num_digits = 0; char* data = buf.data(); for(;;) { int digit = numerator.divmod_assign(denominator); bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower. // numerator + upper >[=] pow10: bool high = add_compare(numerator, *upper, denominator) + even > 0; data[num_digits++] = static_cast<char>('0' + digit); if(low || high) { if(!low) { ++data[num_digits - 1]; } else if(high) { int result = add_compare(numerator, numerator, denominator); // Round half to even. if(result > 0 || (result == 0 && (digit % 2) != 0)) ++data[num_digits - 1]; } buf.resize(to_unsigned(num_digits)); exp10 -= num_digits - 1; return; } numerator *= 10; lower *= 10; if(upper != &lower) *upper *= 10; } } // Formats value using the Grisu algorithm // (https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf) // if T is a IEEE754 binary32 or binary64 and snprintf otherwise. template <typename T> int format_float(T value, int precision, float_specs specs, buffer<char>& buf) { static_assert(!std::is_same<T, float>::value, ""); FMT_ASSERT(value >= 0, "value is negative"); const bool fixed = specs.format == float_format::fixed; if(value <= 0) { // <= instead of == to silence a warning. if(precision <= 0 || !fixed) { buf.push_back('0'); return 0; } buf.resize(to_unsigned(precision)); std::uninitialized_fill_n(buf.data(), precision, '0'); return -precision; } if(!specs.use_grisu) return snprintf_float(value, precision, specs, buf); int exp = 0; const int min_exp = -60; // alpha in Grisu. int cached_exp10 = 0; // K in Grisu. if(precision < 0) { fp fp_value; auto boundaries = specs.binary32 ? fp_value.assign_float_with_boundaries(value) : fp_value.assign_with_boundaries(value); fp_value = normalize(fp_value); // Find a cached power of 10 such that multiplying value by it will bring // the exponent in the range [min_exp, -32]. const fp cached_pow = get_cached_power( min_exp - (fp_value.e + fp::significand_size), cached_exp10); // Multiply value and boundaries by the cached power of 10. fp_value = fp_value * cached_pow; boundaries.lower = multiply(boundaries.lower, cached_pow.f); boundaries.upper = multiply(boundaries.upper, cached_pow.f); assert(min_exp <= fp_value.e && fp_value.e <= -32); --boundaries.lower; // \tilde{M}^- - 1 ulp -> M^-_{\downarrow}. ++boundaries.upper; // \tilde{M}^+ + 1 ulp -> M^+_{\uparrow}. // Numbers outside of (lower, upper) definitely do not round to value. grisu_shortest_handler handler{ buf.data(), 0, boundaries.upper - fp_value.f }; auto result = grisu_gen_digits(fp(boundaries.upper, fp_value.e), boundaries.upper - boundaries.lower, exp, handler); if(result == digits::error) { exp += handler.size - cached_exp10 - 1; fallback_format(value, buf, exp); return exp; } buf.resize(to_unsigned(handler.size)); } else { if(precision > 17) return snprintf_float(value, precision, specs, buf); fp normalized = normalize(fp(value)); const auto cached_pow = get_cached_power( min_exp - (normalized.e + fp::significand_size), cached_exp10); normalized = normalized * cached_pow; fixed_handler handler{ buf.data(), 0, precision, -cached_exp10, fixed }; if(grisu_gen_digits(normalized, 1, exp, handler) == digits::error) return snprintf_float(value, precision, specs, buf); int num_digits = handler.size; if(!fixed) { // Remove trailing zeros. while(num_digits > 0 && buf[num_digits - 1] == '0') { --num_digits; ++exp; } } buf.resize(to_unsigned(num_digits)); } return exp - cached_exp10; } template <typename T> int snprintf_float(T value, int precision, float_specs specs, buffer<char>& buf) { // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail. FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer"); static_assert(!std::is_same<T, float>::value, ""); // Subtract 1 to account for the difference in precision since we use %e for // both general and exponent format. if(specs.format == float_format::general || specs.format == float_format::exp) precision = (precision >= 0 ? precision : 6) - 1; // Build the format string. enum { max_format_size = 7 }; // Ths longest format is "%#.*Le". char format[max_format_size]; char* format_ptr = format; *format_ptr++ = '%'; if(specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#'; if(precision >= 0) { *format_ptr++ = '.'; *format_ptr++ = '*'; } if(std::is_same<T, long double>()) *format_ptr++ = 'L'; *format_ptr++ = specs.format != float_format::hex ? (specs.format == float_format::fixed ? 'f' : 'e') : (specs.upper ? 'A' : 'a'); *format_ptr = '\0'; // Format using snprintf. auto offset = buf.size(); for(;;) { auto begin = buf.data() + offset; auto capacity = buf.capacity() - offset; #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION if(precision > 100000) throw std::runtime_error( "fuzz mode - avoid large allocation inside snprintf"); #endif // Suppress the warning about a nonliteral format string. // Cannot use auto becase of a bug in MinGW (#1532). int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF; int result = precision >= 0 ? snprintf_ptr(begin, capacity, format, precision, value) : snprintf_ptr(begin, capacity, format, value); if(result < 0) { buf.reserve(buf.capacity() + 1); // The buffer will grow exponentially. continue; } auto size = to_unsigned(result); // Size equal to capacity means that the last character was truncated. if(size >= capacity) { buf.reserve(size + offset + 1); // Add 1 for the terminating '\0'. continue; } auto is_digit = [](char c) { return c >= '0' && c <= '9'; }; if(specs.format == float_format::fixed) { if(precision == 0) { buf.resize(size); return 0; } // Find and remove the decimal point. auto end = begin + size, p = end; do { --p; } while(is_digit(*p)); int fraction_size = static_cast<int>(end - p - 1); std::memmove(p, p + 1, to_unsigned(fraction_size)); buf.resize(size - 1); return -fraction_size; } if(specs.format == float_format::hex) { buf.resize(size + offset); return 0; } // Find and parse the exponent. auto end = begin + size, exp_pos = end; do { --exp_pos; } while(*exp_pos != 'e'); char sign = exp_pos[1]; assert(sign == '+' || sign == '-'); int exp = 0; auto p = exp_pos + 2; // Skip 'e' and sign. do { assert(is_digit(*p)); exp = exp * 10 + (*p++ - '0'); } while(p != end); if(sign == '-') exp = -exp; int fraction_size = 0; if(exp_pos != begin + 1) { // Remove trailing zeros. auto fraction_end = exp_pos - 1; while(*fraction_end == '0') --fraction_end; // Move the fractional part left to get rid of the decimal point. fraction_size = static_cast<int>(fraction_end - begin - 1); std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size)); } buf.resize(to_unsigned(fraction_size) + offset + 1); return exp - fraction_size; } } // A public domain branchless UTF-8 decoder by Christopher Wellons: // https://github.com/skeeto/branchless-utf8 /* Decode the next character, c, from buf, reporting errors in e. * * Since this is a branchless decoder, four bytes will be read from the * buffer regardless of the actual length of the next character. This * means the buffer _must_ have at least three bytes of zero padding * following the end of the data stream. * * Errors are reported in e, which will be non-zero if the parsed * character was somehow invalid: invalid byte sequence, non-canonical * encoding, or a surrogate half. * * The function returns a pointer to the next character. When an error * occurs, this pointer will be a guess that depends on the particular * error, but it will always advance at least one byte. */ FMT_FUNC const char* utf8_decode(const char* buf, uint32_t* c, int* e) { static const char lengths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; static const uint32_t mins[] = { 4194304, 0, 128, 2048, 65536 }; static const int shiftc[] = { 0, 18, 12, 6, 0 }; static const int shifte[] = { 0, 6, 4, 2, 0 }; auto s = reinterpret_cast<const unsigned char*>(buf); int len = lengths[s[0] >> 3]; // Compute the pointer to the next character early so that the next // iteration can start working on the next character. Neither Clang // nor GCC figure out this reordering on their own. const char* next = buf + len + !len; // Assume a four-byte character and load four bytes. Unused bits are // shifted out. *c = uint32_t(s[0] & masks[len]) << 18; *c |= uint32_t(s[1] & 0x3f) << 12; *c |= uint32_t(s[2] & 0x3f) << 6; *c |= uint32_t(s[3] & 0x3f) << 0; *c >>= shiftc[len]; // Accumulate the various error conditions. *e = (*c < mins[len]) << 6; // non-canonical encoding *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? *e |= (*c > 0x10FFFF) << 8; // out of range? *e |= (s[1] & 0xc0) >> 2; *e |= (s[2] & 0xc0) >> 4; *e |= (s[3]) >> 6; *e ^= 0x2a; // top two bits of each tail byte correct? *e >>= shifte[len]; return next; } } // namespace internal template <> struct formatter<internal::bigint> { format_parse_context::iterator parse(format_parse_context& ctx) { return ctx.begin(); } format_context::iterator format(const internal::bigint& n, format_context& ctx) { auto out = ctx.out(); bool first = true; for(auto i = n.bigits_.size(); i > 0; --i) { auto value = n.bigits_[i - 1u]; if(first) { out = format_to(out, "{:x}", value); first = false; continue; } out = format_to(out, "{:08x}", value); } if(n.exp_ > 0) out = format_to(out, "p{}", n.exp_ * internal::bigint::bigit_bits); return out; } }; FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) { auto transcode = [this](const char* p) { auto cp = uint32_t(); auto error = 0; p = utf8_decode(p, &cp, &error); if(error != 0) FMT_THROW(std::runtime_error("invalid utf8")); if(cp <= 0xFFFF) { buffer_.push_back(static_cast<wchar_t>(cp)); } else { cp -= 0x10000; buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10))); buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF))); } return p; }; auto p = s.data(); const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. if(s.size() >= block_size) { for(auto end = p + s.size() - block_size + 1; p < end;) p = transcode(p); } if(auto num_chars_left = s.data() + s.size() - p) { char buf[2 * block_size - 1] = {}; memcpy(buf, p, to_unsigned(num_chars_left)); p = buf; do { p = transcode(p); } while(p - buf < num_chars_left); } buffer_.push_back(0); } FMT_FUNC void format_system_error(internal::buffer<char> & out, int error_code, string_view message) FMT_NOEXCEPT { FMT_TRY{ memory_buffer buf; buf.resize(inline_buffer_size); for(;;) { char* system_message = &buf[0]; int result = internal::safe_strerror(error_code, system_message, buf.size()); if(result == 0) { internal::writer w(out); w.write(message); w.write(": "); w.write(system_message); return; } if(result != ERANGE) break; // Can't get error message, report error code instead. buf.resize(buf.size() * 2); } } FMT_CATCH(...) {} format_error_code(out, error_code, message); } FMT_FUNC void internal::error_handler::on_error(const char* message) { FMT_THROW(format_error(message)); } FMT_FUNC void report_system_error(int error_code, fmt::string_view message) FMT_NOEXCEPT { report_error(format_system_error, error_code, message); } FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) { memory_buffer buffer; internal::vformat_to(buffer, format_str, basic_format_args<buffer_context<char>>(args)); #ifdef _WIN32 auto fd = _fileno(f); if(_isatty(fd)) { internal::utf8_to_utf16 u16(string_view(buffer.data(), buffer.size())); auto written = DWORD(); if(!WriteConsoleW(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), u16.c_str(), static_cast<DWORD>(u16.size()), &written, nullptr)) { FMT_THROW(format_error("failed to write to console")); } return; } #endif internal::fwrite_fully(buffer.data(), 1, buffer.size(), f); } #ifdef _WIN32 // Print assuming legacy (non-Unicode) encoding. FMT_FUNC void internal::vprint_mojibake(std::FILE* f, string_view format_str, format_args args) { memory_buffer buffer; internal::vformat_to(buffer, format_str, basic_format_args<buffer_context<char>>(args)); fwrite_fully(buffer.data(), 1, buffer.size(), f); } #endif FMT_FUNC void vprint(string_view format_str, format_args args) { vprint(stdout, format_str, args); } FMT_END_NAMESPACE #ifdef _MSC_VER # pragma warning(pop) #endif #endif // FMT_FORMAT_INL_H_
[ "jonatan@familjenlind.com" ]
jonatan@familjenlind.com
f9d7c08688c0ddb4b46a8650507feadba1081840
8ed61980185397f8a11ad5851e3ffff09682c501
/thirdparty/GeometricTools/WildMagic5/SamplePhysics/FlowingSkirt/FlowingSkirt.cpp
728bb20821a38cd94d83f298face203b8dc1c947
[ "BSD-2-Clause-Views" ]
permissive
SoMa-Project/vision
8975a2b368f69538a05bd57b0c3eda553b783b55
ea8199d98edc363b2be79baa7c691da3a5a6cc86
refs/heads/melodic
2023-04-12T22:49:13.125788
2021-01-11T15:28:30
2021-01-11T15:28:30
80,823,825
1
0
NOASSERTION
2021-04-20T21:27:03
2017-02-03T11:36:44
C++
UTF-8
C++
false
false
8,426
cpp
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) #include "FlowingSkirt.h" WM5_WINDOW_APPLICATION(FlowingSkirt); //#define SINGLE_STEP //---------------------------------------------------------------------------- FlowingSkirt::FlowingSkirt () : WindowApplication3("SamplePhysics/FlowingSkirt", 0, 0, 640, 480, Float4(0.75f, 0.75f, 0.75f, 1.0f)), mTextColor(0.0f, 0.0f, 0.0f, 1.0f) { mNumCtrl = 32; mDegree = 3; mATop = 1.0f; mBTop = 1.5f; mABot = 2.0f; mBBot = 3.0f; mSkirtTop = 0; mSkirtBot = 0; mFrequencies = new1<float>(mNumCtrl); } //---------------------------------------------------------------------------- FlowingSkirt::~FlowingSkirt () { delete1(mFrequencies); } //---------------------------------------------------------------------------- bool FlowingSkirt::OnInitialize () { if (!WindowApplication3::OnInitialize()) { return false; } CreateScene(); // Center-and-fit for camera viewing. mScene->Update(); mTrnNode->LocalTransform.SetTranslate(-mScene->WorldBound.GetCenter()); mCamera->SetFrustum(60.0f, GetAspectRatio(), 0.1f, 100.0f); AVector camDVector(0.0f, 0.0f, 1.0f); AVector camUVector(0.0f, 1.0f, 0.0f); AVector camRVector = camDVector.Cross(camUVector); APoint camPosition = APoint::ORIGIN - 2.5f*mScene->WorldBound.GetRadius()*camDVector; mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector); // Initial update of objects. mScene->Update(); // Initial culling of scene. mCuller.SetCamera(mCamera); mCuller.ComputeVisibleSet(mScene); InitializeCameraMotion(0.005f, 0.01f); InitializeObjectMotion(mScene); return true; } //---------------------------------------------------------------------------- void FlowingSkirt::OnTerminate () { delete0(mSkirtTop); delete0(mSkirtBot); mScene = 0; mTrnNode = 0; mSkirt = 0; mWireState = 0; WindowApplication3::OnTerminate(); } //---------------------------------------------------------------------------- void FlowingSkirt::OnIdle () { MeasureTime(); MoveCamera(); if (MoveObject()) { mScene->Update(); } #ifndef SINGLE_STEP ModifyCurves(); #endif mCuller.ComputeVisibleSet(mScene); if (mRenderer->PreDraw()) { mRenderer->ClearBuffers(); mRenderer->Draw(mCuller.GetVisibleSet()); DrawFrameRate(8, GetHeight()-8, mTextColor); mRenderer->PostDraw(); mRenderer->DisplayColorBuffer(); } UpdateFrameCount(); } //---------------------------------------------------------------------------- bool FlowingSkirt::OnKeyDown (unsigned char key, int x, int y) { if (WindowApplication3::OnKeyDown(key, x, y)) { return true; } switch (key) { case 'w': // toggle wireframe case 'W': mWireState->Enabled = !mWireState->Enabled; return true; #ifdef SINGLE_STEP case 'g': case 'G': ModifyCurves(); return true; #endif } return false; } //---------------------------------------------------------------------------- void FlowingSkirt::CreateScene () { mScene = new0 Node(); mTrnNode = new0 Node(); mScene->AttachChild(mTrnNode); mWireState = new0 WireState(); mRenderer->SetOverrideWireState(mWireState); // The skirt top and bottom boundary curves are chosen to be periodic, // looped B-spline curves. The top control points are generated on an // ellipse (x/a0)^2 + (z/b0)^2 = 1 with y = 4. The bottom control points // are generated on an ellipse (x/a1)^2 + (z/b1)^2 = 1 with y = 0. // The vertex storage is used for the B-spline control points. The // curve objects make a copy of the input points. The vertex storage is // then used for the skirt mesh vertices themselves. VertexFormat* vformat = VertexFormat::Create(2, VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0, VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0); int vstride = vformat->GetStride(); int numVertices = 2*mNumCtrl; Vector3f* vertices = new1<Vector3f>(numVertices); VertexBuffer* vbuffer = new0 VertexBuffer(numVertices, vstride); VertexBufferAccessor vba(vformat, vbuffer); int i, j; for (i = 0, j = mNumCtrl; i < mNumCtrl; ++i, ++j) { float ratio = ((float)i)/((float)mNumCtrl); float angle = Mathf::TWO_PI*ratio; float sn = Mathf::Sin(angle); float cs = Mathf::Cos(angle); float v = 1.0f - Mathf::FAbs(2.0f*ratio - 1.0f); // Set a vertex for the skirt top. vertices[i] = Vector3f(mATop*cs, 4.0f, mBTop*sn); vba.Position<Vector3f>(i) = vertices[i]; vba.TCoord<Vector2f>(0, i) = Vector2f(1.0f, v); // Set a vertex for the skirt bottom. vertices[j] = Vector3f(mABot*cs, 0.0f, mBBot*sn); vba.Position<Vector3f>(j) = vertices[j]; vba.TCoord<Float2>(0, j) = Float2(0.0f, v); // Frequency of sinusoidal motion for skirt bottom. mFrequencies[i] = 0.5f*(1.0f + Mathf::UnitRandom()); } // The control points are copied by the curve objects. mSkirtTop = new0 BSplineCurve3f(mNumCtrl, vertices, mDegree, true, false); mSkirtBot = new0 BSplineCurve3f(mNumCtrl, &vertices[mNumCtrl], mDegree, true, false); delete1(vertices); // Generate the triangle connectivity (cylinder connectivity). int numTriangles = numVertices; int numIndices = 3*numTriangles; IndexBuffer* ibuffer = new0 IndexBuffer(numIndices, sizeof(int)); int* indices = (int*)ibuffer->GetData(); int i0 = 0, i1 = 1, i2 = mNumCtrl, i3 = mNumCtrl + 1; for (i = 0; i1 < mNumCtrl; i0 = i1++, i2 = i3++) { indices[i++] = i0; indices[i++] = i1; indices[i++] = i3; indices[i++] = i0; indices[i++] = i3; indices[i++] = i2; } indices[i++] = mNumCtrl - 1; indices[i++] = 0; indices[i++] = mNumCtrl; indices[i++] = mNumCtrl - 1; indices[i++] = mNumCtrl; indices[i++] = 2*mNumCtrl - 1; mSkirt = new0 TriMesh(vformat, vbuffer, ibuffer); std::string path = Environment::GetPathR("Flower.wmtf"); Texture2D* texture = Texture2D::LoadWMTF(path); VisualEffectInstance* instance = Texture2DEffect::CreateUniqueInstance( texture, Shader::SF_LINEAR, Shader::SC_CLAMP_EDGE, Shader::SC_CLAMP_EDGE); mSkirt->SetEffectInstance(instance); // Double-sided triangles. instance->GetEffect()->GetCullState(0, 0)->Enabled = false; // Compute the vertex values for the current B-spline curves. UpdateSkirt(); mTrnNode->AttachChild(mSkirt); } //---------------------------------------------------------------------------- void FlowingSkirt::UpdateSkirt () { VertexBufferAccessor vba(mSkirt); for (int i = 0, j = mNumCtrl; i < mNumCtrl; ++i, ++j) { float t = ((float)i)/((float)mNumCtrl); vba.Position<Vector3f>(i) = mSkirtTop->GetPosition(t); vba.Position<Vector3f>(j) = mSkirtBot->GetPosition(t); } mSkirt->UpdateModelSpace(Visual::GU_MODEL_BOUND_ONLY); mSkirt->Update(0.0f); mRenderer->Update(mSkirt->GetVertexBuffer()); } //---------------------------------------------------------------------------- void FlowingSkirt::ModifyCurves () { // Perturb the skirt bottom. float time = (float)GetTimeInSeconds(); for (int i = 0; i < mNumCtrl; ++i) { float ratio = ((float)i)/((float)mNumCtrl); float angle = Mathf::TWO_PI*ratio; float sn = Mathf::Sin(angle); float cs = Mathf::Cos(angle); float amplitude = 1.0f + 0.25f*Mathf::Cos(mFrequencies[i]*time); mSkirtBot->SetControlPoint(i, Vector3f(amplitude*mABot*cs, 0.0f, amplitude*mBBot*sn)); } UpdateSkirt(); } //----------------------------------------------------------------------------
[ "j.abele@tu-berlin.de" ]
j.abele@tu-berlin.de
e0af90e7ad5c303e7a3f5aa41d46318c82df1658
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_2445.cpp
c36da6b92e86c3dbbb384a9280acd496474a4b7f
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
*/ return DECLINED; } } else if (auth_result == AUTHZ_DENIED || auth_result == AUTHZ_NEUTRAL) { if (!after_authn || ap_auth_type(r) == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_SUCCESS, r, "client denied by server configuration: %s%s", r->filename ? "" : "uri ", r->filename ? r->filename : r->uri); return HTTP_FORBIDDEN; } else { /* XXX: maybe we want to return FORBIDDEN here, too??? */ ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_SUCCESS, r, "user %s: authorization failure for \"%s\": ", r->user, r->uri); /* * If we're returning 401 to an authenticated user, tell them to * try again. If unauthenticated, note_auth_failure has already * been called during auth. */ if (r->user) ap_note_auth_failure(r); return HTTP_UNAUTHORIZED; } } else { /* We'll assume that the module has already said what its * error was in the logs. */
[ "993273596@qq.com" ]
993273596@qq.com
2d5f65cc2cc0cf6d0c804ede52d187d1c9cdfcd5
0e40a0486826825c2c8adba9a538e16ad3efafaf
/lib/wxWidgets/include/wx/dynload.h
2b08fe227e2a4ba3f0c8d0e0051ba2cbe4ddf64c
[ "MIT" ]
permissive
iraqigeek/iZ3D
4c45e69a6e476ad434d5477f21f5b5eb48336727
ced8b3a4b0a152d0177f2e94008918efc76935d5
refs/heads/master
2023-05-25T19:04:06.082744
2020-12-28T03:27:55
2020-12-28T03:27:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,258
h
///////////////////////////////////////////////////////////////////////////// // Name: dynload.h // Purpose: Dynamic loading framework // Author: Ron Lee, David Falkinder, Vadim Zeitlin and a cast of 1000's // (derived in part from dynlib.cpp (c) 1998 Guilhem Lavaux) // Modified by: // Created: 03/12/01 // RCS-ID: $Id$ // Copyright: (c) 2001 Ron Lee <ron@debian.org> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_DYNAMICLOADER_H__ #define _WX_DYNAMICLOADER_H__ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "wx/defs.h" #if wxUSE_DYNAMIC_LOADER #include "wx/dynlib.h" #include "wx/hashmap.h" #include "wx/module.h" class WXDLLIMPEXP_FWD_BASE wxPluginLibrary; WX_DECLARE_STRING_HASH_MAP_WITH_DECL(wxPluginLibrary *, wxDLManifest, class WXDLLIMPEXP_BASE); typedef wxDLManifest wxDLImports; // --------------------------------------------------------------------------- // wxPluginLibrary // --------------------------------------------------------------------------- // NOTE: Do not attempt to use a base class pointer to this class. // wxDL is not virtual and we deliberately hide some of it's // methods here. // // Unless you know exacty why you need to, you probably shouldn't // instantiate this class directly anyway, use wxPluginManager // instead. class WXDLLIMPEXP_BASE wxPluginLibrary : public wxDynamicLibrary { public: static wxDLImports* ms_classes; // Static hash of all imported classes. wxPluginLibrary( const wxString &libname, int flags = wxDL_DEFAULT ); ~wxPluginLibrary(); wxPluginLibrary *RefLib(); bool UnrefLib(); // These two are called by the PluginSentinel on (PLUGGABLE) object // creation/destruction. There is usually no reason for the user to // call them directly. We have to separate this from the link count, // since the two are not interchangeable. // FIXME: for even better debugging PluginSentinel should register // the name of the class created too, then we can state // exactly which object was not destroyed which may be // difficult to find otherwise. Also this code should // probably only be active in DEBUG mode, but let's just // get it right first. void RefObj() { ++m_objcount; } void UnrefObj() { wxASSERT_MSG( m_objcount > 0, _T("Too many objects deleted??") ); --m_objcount; } // Override/hide some base class methods bool IsLoaded() const { return m_linkcount > 0; } void Unload() { UnrefLib(); } private: wxClassInfo *m_before; // sm_first before loading this lib wxClassInfo *m_after; // ..and after. size_t m_linkcount; // Ref count of library link calls size_t m_objcount; // ..and (pluggable) object instantiations. wxModuleList m_wxmodules; // any wxModules that we initialised. void UpdateClasses(); // Update ms_classes void RestoreClasses(); // Removes this library from ms_classes void RegisterModules(); // Init any wxModules in the lib. void UnregisterModules(); // Cleanup any wxModules we installed. DECLARE_NO_COPY_CLASS(wxPluginLibrary) }; class WXDLLIMPEXP_BASE wxPluginManager { public: // Static accessors. static wxPluginLibrary *LoadLibrary( const wxString &libname, int flags = wxDL_DEFAULT ); static bool UnloadLibrary(const wxString &libname); // Instance methods. wxPluginManager() : m_entry(NULL) {} wxPluginManager(const wxString &libname, int flags = wxDL_DEFAULT) { Load(libname, flags); } ~wxPluginManager() { if ( IsLoaded() ) Unload(); } bool Load(const wxString &libname, int flags = wxDL_DEFAULT); void Unload(); bool IsLoaded() const { return m_entry && m_entry->IsLoaded(); } void *GetSymbol(const wxString &symbol, bool *success = 0) { return m_entry->GetSymbol( symbol, success ); } static void CreateManifest() { ms_manifest = new wxDLManifest(wxKEY_STRING); } static void ClearManifest() { delete ms_manifest; ms_manifest = NULL; } private: // return the pointer to the entry for the library with given name in // ms_manifest or NULL if none static wxPluginLibrary *FindByName(const wxString& name) { const wxDLManifest::iterator i = ms_manifest->find(name); return i == ms_manifest->end() ? NULL : i->second; } static wxDLManifest* ms_manifest; // Static hash of loaded libs. wxPluginLibrary* m_entry; // Cache our entry in the manifest. // We could allow this class to be copied if we really // wanted to, but not without modification. DECLARE_NO_COPY_CLASS(wxPluginManager) }; #endif // wxUSE_DYNAMIC_LOADER #endif // _WX_DYNAMICLOADER_H__
[ "github@bo3b.net" ]
github@bo3b.net
1624488c5e7aca7d96e8666319eec554a00d2e21
6a305e60a609e3c071d2c594f939e6be4ce25e57
/boost_asio/reactive_socket_send_op.hpp
89c4895f271cb999ef24c5fbb69ec2f2cf6d7239
[]
no_license
zgbzsu2008/boost_asio
5060baad52fa2b54578e0af69e692905d87ae5c5
e4a19c606cc5652db2544c11e63dc0337adeb735
refs/heads/master
2020-05-27T19:50:07.291518
2019-06-05T00:09:46
2019-06-05T00:09:46
188,767,038
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
hpp
#ifndef BOOST_ASIO_DETAIL_REACTIVE_SOCKET_SEND_OP_HPP #define BOOST_ASIO_DETAIL_REACTIVE_SOCKET_SEND_OP_HPP #include "buffer_sequence_adapter.hpp" #include "reactor_op.hpp" #include "socket_base.hpp" #include "socket_ops.hpp" namespace boost::asio::detail { template <typename ConstBufferSequence> class reactive_socket_send_op_base : public reactor_op { public: static status do_perform(reactor_op* base) { reactive_socket_send_op_base* o = static_cast<reactive_socket_send_op_base*>(base); buffer_sequence_adapter<boost::asio::const_buffer, ConstBufferSequence> bufs(o->buffers_); status result = socket_ops::non_blocking_send(o->socket_, bufs.buffers(), bufs.count(), o->flags_, o->ec_, o->bytes_transferred_) ? done : not_done; if (result == done) { if ((o - state_ & socket_ops::stream_oriented) != 0) { if (o->bytes_transferred_ < bufs.total_buffer_size_) { result = done_and_exhausted; } } } return result; } private: socket_type socket_; socket_ops::state_type state_; ConstBufferSequence buffers_; socket_base::message_flags flags; }; template <typename ConstBufferSequence, typename Handler> class reactive_socket_send_op : public reactive_socket_send_op_base<ConstBufferSequence> {}; } // namespace boost::asio::detail #endif
[ "zgbzsu2008@163.com" ]
zgbzsu2008@163.com
6b8418cd9d7de5192526a725ccbf081a048a4e90
e98a1cd9cee64c1957c96ec4a357dd3e6c9c2bb4
/file_generator/export_func_to_lua_generate.cpp
a211163fb0f7f3add8e508f19bd8055e992b178a
[ "MIT" ]
permissive
coolshuiping/oolua
1df835d985ef7433a9948544c5b4bafa7014e14a
437b0911e00ff07b74b93bf115026c688af6f31d
refs/heads/master
2021-01-10T20:06:49.711326
2013-06-14T20:42:31
2013-06-14T20:42:31
33,646,236
1
0
null
null
null
null
UTF-8
C++
false
false
3,794
cpp
#include "common_generate.h" #include "export_func_to_lua_generate.h" void export_func_to_lua_header(std::string & save_directory,int amount) { std::string macro_start("LUA_MEMBER_FUNC_"); std::string fileName("export_func_to_lua.h"); std::string file = save_directory + fileName; std::ofstream f( file.c_str() ,std::ios_base::out | std::ios::trunc); include_guard_top(f,"EXPORT_FUNC_TO_LUA_H_"); add_file_header(f,"export_func_to_lua.h"); f<<"#define "<<macro_start<<1<<"(class,func"<<1<<") " <<"{#func"<<1<<", &class::func"<<1<<"}," <<std::endl; for(int i = 2; i <=amount;++i) { f<<"#define " <<macro_start<<i<<"(class"; for(int j = 1;j<=i;++j) { f<<",func"<<j; } f<<") "<<macro_start <<i-1<<"(class"; for(int j =1;j<i;++j) { f<<",func"<<j; } f<<")"; f<<macro_start<<1<<"(class,func" <<i<<")" <<std::endl; } f<<std::endl <<std::endl; f<<"/// @def end the assigning of functions to the array\n" <<"#define CLASS_LIST_MEMBERS_END {0,0}};}\n\n" <<"/// @def define the constants in the class, which are the the class name and the member function array\n" <<"#define CLASS_LIST_MEMBERS_START_OOLUA_NON_CONST(Class)\\" <<std::endl <<"namespace OOLUA { \\" <<std::endl <<"char const OOLUA::Proxy_class< Class >::class_name[] = #Class;\\" <<std::endl <<"int const OOLUA::Proxy_class< Class >::name_size = sizeof(#Class)-1; \\" <<std::endl <<"OOLUA::Proxy_class< Class >::Reg_type OOLUA::Proxy_class< Class >::class_methods[]={" <<std::endl <<std::endl <<"#define CLASS_LIST_MEMBERS_START_OOLUA_CONST(Class)\\" <<std::endl <<"namespace OOLUA { \\" <<std::endl <<"char const OOLUA::Proxy_class< Class >::class_name_const[] = #Class \"_const\";\\" <<std::endl <<"OOLUA::Proxy_class< Class >::Reg_type_const OOLUA::Proxy_class< Class >::class_methods_const[]={"<<std::endl<<std::endl; f<<"/// \\addtogroup EXPORT_OOLUA_FUNCTIONS_X\n" <<"/// @{\n" <<"/// Makes functions available to Lua, where X is the number of functions to register\n\n\n"; f<<"#define EXPORT_OOLUA_FUNCTIONS_0_(mod,Class)\\"<<std::endl <<"CLASS_LIST_MEMBERS_START_ ##mod (Class)\\" <<std::endl <<"CLASS_LIST_MEMBERS_END" <<std::endl<<std::endl; /* #define EXPORT_OOLUA_FUNCTIONS_4_(mod,Class,p1,p2,p3,p4) CLASS_LIST_MEMBERS_START_##mod(Class) LUA_MEMBER_FUNC_4(OOLUA::Proxy_class< Class > ,p1,p2,p3,p4) CLASS_LIST_MEMBERS_END */ for(int i = 1;i <=amount; ++i) { f<<"#define EXPORT_OOLUA_FUNCTIONS_" <<i<<"_(mod,Class"; for(int j = 1; j <=i; ++j) { f<<",p"<<j; } f<<")\\"<<std::endl <<"CLASS_LIST_MEMBERS_START_ ##mod(Class)\\" <<std::endl <<"LUA_MEMBER_FUNC_"<<i <<"(OOLUA::Proxy_class< Class > "; for(int j = 1; j <=i; ++j) { f<<",p"<<j; } f<<")\\" <<std::endl <<"CLASS_LIST_MEMBERS_END" <<std::endl<<std::endl; } f<<"#define EXPORT_OOLUA_FUNCTIONS_0_CONST(Class)\\" <<std::endl <<"EXPORT_OOLUA_FUNCTIONS_0_(OOLUA_CONST,Class)" <<std::endl<<std::endl; f<<"#define EXPORT_OOLUA_FUNCTIONS_0_NON_CONST(Class)\\" <<std::endl <<"EXPORT_OOLUA_FUNCTIONS_0_(OOLUA_NON_CONST,Class)" <<std::endl<<std::endl; for(int i = 1;i <=amount; ++i) { for(int k = 0; k<2; ++k) { f<<"#define EXPORT_OOLUA_FUNCTIONS_" <<i ; if(k == 0)f<<"_CONST"; else f<<"_NON_CONST"; f<<"(Class"; for(int j = 1; j <=i; ++j) { f<<",p"<<j; } f<<")\\"<<std::endl <<"EXPORT_OOLUA_FUNCTIONS_"<<i <<"_("; if(k == 0)f<<"OOLUA_CONST"; else f<<"OOLUA_NON_CONST"; f<<",Class"; for(int j = 1; j <=i; ++j) { f<<",p"<<j; } f<<")" <<std::endl<<std::endl; } } f<<"#define EXPORT_OOLUA_NO_FUNCTIONS(Class)\\"<<std::endl <<"EXPORT_OOLUA_FUNCTIONS_0_NON_CONST(Class)\\"<<std::endl <<"EXPORT_OOLUA_FUNCTIONS_0_CONST(Class)"<<std::endl; f<<"/// @}\n\n"; include_guard_bottom(f); }
[ "liam.list@gmail.com@078c8882-b850-11de-b71e-ab0a53e69959" ]
liam.list@gmail.com@078c8882-b850-11de-b71e-ab0a53e69959
146f412d7d9cb625a11cf8404a031fd87b53c14b
a4940d45e77efe16c1afbf9dc456c620048e63a6
/FacePrep/TestYourSkill/Strings/AutomatedDictationEvaluationI.cpp
0661fee4ba23c4d7e4c776cb52e98e1399679a70
[]
no_license
gshanbhag525/CP_Practice
b0ca4d5e55c4a3c25df035d56b6a42032c970206
bb5dd97edd6872ca1aae6fafa3e399c48d22c8e1
refs/heads/master
2023-06-29T03:56:09.888912
2021-08-05T13:04:26
2021-08-05T13:04:26
268,477,179
1
0
null
null
null
null
UTF-8
C++
false
false
1,152
cpp
#include <iostream> #include <string.h> using namespace std; int main() { char str[50], str1[50]; cin >> str >> str1; if ((strcmp(str, str1) == 0)) cout << "It is correct"; else cout << "It is wrong"; return 0; } /* Automated Dictation Evaluation I These days kids are introduced to computers at a very early age and in some schools, the dictation test is conducted using computers. The teachers found it a bit difficult to evaluate these tests and they requested the school management to lessen their burden by automating this task. The 12th class students are learning C++ programming and they took up the task of automating the dictation evaluation. You need to check if the given string is equal to the correct string to evaluate each student. Can you please help them out? Write a C++ program to compare 2 strings using strcmp() function. INPUT FORMAT: Input consists of two strings. Assume that the maximum length of the string is 50 and it contains only alphabets. OUTPUT FORMAT: Refer sample input and output for formatting specifications. SAMPLE INPUT & OUTPUT: Excellent Excellent It is corre */
[ "17478096+gshanbhag525@users.noreply.github.com" ]
17478096+gshanbhag525@users.noreply.github.com
9b927dc1151374a958cc56840bb7faa8ba3db81a
922f615f1e8a4783974cf85416cc64c25d51cbf6
/catnip-api/main.cpp
55ae61a5246689f11d3cdd5a3f494c364a3206ab
[]
no_license
vrace/catnip-api
5a5a6c880a2cb08594131bafb405cf8181f16477
e795a95436626291b4fd9939a0f36d222ca821fa
refs/heads/master
2021-07-13T10:56:01.733926
2017-10-09T07:58:58
2017-10-09T07:58:58
104,853,362
0
0
null
null
null
null
UTF-8
C++
false
false
76
cpp
#include "CatnipApi.h" int main() { CatnipApi().Run(); return 0; }
[ "vrace_studios@hotmail.com" ]
vrace_studios@hotmail.com
7b43ae38bc0334cf0303015f994532f21fa67473
fd31e32581fb91444e9819d9a218e731b0d03d01
/test/process/hello_2.cc
0cde415068be5eac6a7d8874c81670bbc7a1f049
[]
no_license
ThinCats/ffrdma
00d2419c734ee9dbb91575027a71b1edada908f8
c9d050a681a053b874189e14bfbdca4c3b3bb70f
refs/heads/master
2023-03-11T18:37:08.362657
2019-10-10T17:01:35
2019-10-10T17:01:35
212,863,513
2
0
null
2023-02-25T00:54:50
2019-10-04T16:58:17
C++
UTF-8
C++
false
false
1,310
cc
#include "amessage.h" #include "mpi.hpp" #include "rdma_socket.h" #include "stdio.h" int main(int argc, char **argv) { RDMA_Comm rootComm = 0; RDMA_Init(&argc, &argv); int local_rank = RDMA_Rank(rootComm); printf("local_rank = %d\n", local_rank); int other_rank = local_rank ? 0 : 1; Socket *socket = RDMA_Socket(other_rank, rootComm); printf("socket: %x\n", socket); if (local_rank == 0) { const char *msg = "Hello"; AMessage *amsg = AMessage_create((void *)msg, 6, 0); if (send_(socket, amsg)) { printf("Error to send"); } else { printf("nodeid: %d\n", amsg->node_id); } Socket *newSocket = RDMA_Reconnect(other_rank, rootComm); if (send_(newSocket, amsg)) { printf("Error to send with new socket"); } else { printf("nodeid: %d\n", amsg->node_id); } AMessage_destroy(amsg); } else { AMessage *recv; int cnt = 0; while (true) { recv = recv_(socket); if (recv == nullptr) { printf("Stop\n"); break; } printf("%s, nodeId: %d\n", recv->buffer, recv->node_id); AMessage_destroy(recv); if (cnt++ < 1) { socket = RDMA_Reconnect(other_rank, rootComm); } } } printf("Reach end\n"); if (local_rank == 0) { getchar(); } RDMA_Finalize(); }
[ "thincats@163.com" ]
thincats@163.com
6abc29d00cdeb0e049e0fbdfb44d7482a76d7983
01a8d4f2dd5de176287699b5e659b646011427a2
/FELICITY/Demo/Stokes_2D/Assembly_Code_AutoGen/FE_Matrices/Block_Assemble_BC_Matrix_Data_Type.cc
f83e1ba851dca4d7cde8d4a1b8ccfcfd5017034c
[ "BSD-3-Clause", "MIT" ]
permissive
brianchowlab/BcLOV4-FEM
2bd2286011f5d09d01a9973c59023031612b63b2
27432974422d42b4fe3c8cc79bcdd5cb14a800a7
refs/heads/main
2023-04-16T08:27:57.927561
2022-05-27T15:26:46
2022-05-27T15:26:46
318,320,689
0
0
null
null
null
null
UTF-8
C++
false
false
10,077
cc
/* ============================================================================================ This file contains an implementation of a derived C++ Class from the abstract base class in 'Block_Global_FE_Matrix.cc'. NOTE: portions of this code are automatically generated! Copyright (c) 06-14-2016, Shawn W. Walker ============================================================================================ */ /*------------ BEGIN: Auto Generate ------------*/ // Block Global matrix contains: // //BC_Matrix // /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ // define the name of the block FE matrix (should be the same as the filename of this file) #define SpecificFEM Block_Assemble_BC_Matrix_Data_Type #define SpecificFEM_str "BC_Matrix" // the row function space is Type = CG, Name = "lagrange_deg2_dim2" // set the number of blocks along the row dimension #define ROW_Num_Block 1 // set the number of basis functions on each element #define ROW_NB 6 // the col function space is Type = constant_one, Name = "constant_one" // set the number of blocks along the col dimension #define COL_Num_Block 1 // set the number of basis functions on each element #define COL_NB 1 /*------------ END: Auto Generate ------------*/ /***************************************************************************************/ /* C++ (Specific) Block Global FE matrix class definition */ class SpecificFEM: public Block_Assemble_FE_MATRIX_Class // derive from base class { public: // data structure for sub-blocks of the block FE matrix: // offsets for inserting sub-blocks into the global block matrix int Block_Row_Shift[ROW_Num_Block]; int Block_Col_Shift[COL_Num_Block]; /*------------ BEGIN: Auto Generate ------------*/ // constructor SpecificFEM (const PTR_TO_SPARSE*, const Base_BC_Matrix_Data_Type*); ~SpecificFEM (); // destructor void Init_Matrix_Assembler_Object(bool); void Add_Entries_To_Global_Matrix_Outlet (const Base_BC_Matrix_Data_Type*); /*------------ END: Auto Generate ------------*/ private: }; /***************************************************************************************/ /* constructor */ /*------------ BEGIN: Auto Generate ------------*/ SpecificFEM::SpecificFEM (const PTR_TO_SPARSE* Prev_Sparse_Data, const Base_BC_Matrix_Data_Type* Block_00 ) : /*------------ END: Auto Generate ------------*/ Block_Assemble_FE_MATRIX_Class () // call the base class constructor { // set the 'Name' of this Global matrix Name = (char*) SpecificFEM_str; // this should be similar to the Class identifier // record the number of block matrices (in the global matrix) Num_Blocks = 1; Sparse_Data = Prev_Sparse_Data; bool simple_assembler; /*------------ BEGIN: Auto Generate ------------*/ simple_assembler = true; // better to use a full matrix // record the size of the block global matrix (only for ONE block) global_num_row = Block_00->get_global_num_row(); global_num_col = Block_00->get_global_num_col(); /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ // input information for offsetting the sub-blocks Block_Row_Shift[0] = 0*Block_00->get_global_num_row(); Block_Col_Shift[0] = 0*Block_00->get_global_num_col(); /*------------ END: Auto Generate ------------*/ Init_Matrix_Assembler_Object(simple_assembler); } /***************************************************************************************/ /***************************************************************************************/ /* destructor: should not usually need to be modified */ SpecificFEM::~SpecificFEM () { delete(MAT); } /***************************************************************************************/ /***************************************************************************************/ /* this initializes the object that handles matrix assembly */ void SpecificFEM::Init_Matrix_Assembler_Object(bool use_simple_assembler) { if (use_simple_assembler) // create SimpleMatrixAssembler object MAT = new SimpleMatrixAssembler(global_num_row,global_num_col); // assemble from scratch else if (Sparse_Data->valid) { int str_diff = strcmp(Sparse_Data->name,Name); if (str_diff!=0) { mexPrintf("Matrix names do not match!\n"); mexPrintf("Previously assembled matrix name is: %s.\n", Sparse_Data->name); mexPrintf("The name SHOULD have been: %s.\n", Name); mexErrMsgTxt("Check the previously assembled matrix structure!\n"); } if (Sparse_Data->m!=global_num_row) { mexPrintf("Error with this matrix: %s.\n", Name); mexErrMsgTxt("Number of rows in previous matrix does not match what the new matrix should be.\n"); } if (Sparse_Data->n!=global_num_col) { mexPrintf("Error with this matrix: %s.\n", Name); mexErrMsgTxt("Number of columns in previous matrix does not match what the new matrix should be.\n"); } // create MatrixReassembler object (cf. David Bindel) MAT = new MatrixReassembler(Sparse_Data->jc,Sparse_Data->ir,Sparse_Data->pr,global_num_row,global_num_col); // use previous sparse structure } else // create MatrixAssembler object (cf. David Bindel) MAT = new MatrixAssembler(global_num_row,global_num_col); // assemble from scratch } /***************************************************************************************/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* assemble a local FE matrix on the domain Outlet */ void SpecificFEM::Add_Entries_To_Global_Matrix_Outlet(const Base_BC_Matrix_Data_Type* Block_00) { // get local to global index map for the current ROW element int Row_Indices_0[ROW_NB]; const int row_elem_index = Block_00->Vector_P2_phi_restricted_to_Outlet->Mesh->Domain->Sub_Cell_Index; Block_00->Vector_P2_phi_restricted_to_Outlet->Get_Local_to_Global_DoFmap(row_elem_index, Row_Indices_0); // shift Row_Indices_0 to account for the block matrix offset for (unsigned int ri = 0; ri < ROW_NB; ++ri) Row_Indices_0[ri] += Block_Row_Shift[0]; // get local to global index map for the current COL element int Col_Indices_0[COL_NB]; Col_Indices_0[0] = 0; // shift Col_Indices_0 to account for the block matrix offset for (unsigned int ci = 0; ci < COL_NB; ++ci) Col_Indices_0[ci] += Block_Col_Shift[0]; // sort row indices (ascending order) int Local_Row_Ind[ROW_NB] = {0, 1, 2, 3, 4, 5}; std::sort(Local_Row_Ind, Local_Row_Ind+ROW_NB, [&Row_Indices_0](int kk, int qq) { return (Row_Indices_0[kk] < Row_Indices_0[qq]); }); // sort col indices (ascending order) int Local_Col_Ind[COL_NB] = {0}; std::sort(Local_Col_Ind, Local_Col_Ind+COL_NB, [&Col_Indices_0](int kk, int qq) { return (Col_Indices_0[kk] < Col_Indices_0[qq]); }); // allocate (I,J,V) arrays to hold "big" local matrix int COO_I[2*ROW_NB*COL_NB]; int COO_J[1*COL_NB]; int COO_J_IV_Range[1*COL_NB + 1]; // indicates what parts I,V correspond to J double COO_V[2*ROW_NB*COL_NB]; /* fill the (I,J,V) arrays (sorted) */ // write column #0 // write (I,J,V) data for Block_00->FE_Tensor_0, i.e. the (0,0) block // write the data directly COO_I[0] = Row_Indices_0[Local_Row_Ind[0]]; COO_J[0] = Col_Indices_0[Local_Col_Ind[0]]; COO_J_IV_Range[0] = 0; COO_V[0] = Block_00->FE_Tensor_0[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[0]]; COO_I[1] = Row_Indices_0[Local_Row_Ind[1]]; COO_V[1] = Block_00->FE_Tensor_0[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[1]]; COO_I[2] = Row_Indices_0[Local_Row_Ind[2]]; COO_V[2] = Block_00->FE_Tensor_0[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[2]]; COO_I[3] = Row_Indices_0[Local_Row_Ind[3]]; COO_V[3] = Block_00->FE_Tensor_0[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[3]]; COO_I[4] = Row_Indices_0[Local_Row_Ind[4]]; COO_V[4] = Block_00->FE_Tensor_0[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[4]]; COO_I[5] = Row_Indices_0[Local_Row_Ind[5]]; COO_V[5] = Block_00->FE_Tensor_0[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[5]]; // write (I,J,V) data for Block_00->FE_Tensor_1, i.e. the (1,0) block // write the data directly COO_I[6] = Row_Indices_0[Local_Row_Ind[0]] + Block_00->Row_Shift[1]; COO_V[6] = Block_00->FE_Tensor_1[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[0]]; COO_I[7] = Row_Indices_0[Local_Row_Ind[1]] + Block_00->Row_Shift[1]; COO_V[7] = Block_00->FE_Tensor_1[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[1]]; COO_I[8] = Row_Indices_0[Local_Row_Ind[2]] + Block_00->Row_Shift[1]; COO_V[8] = Block_00->FE_Tensor_1[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[2]]; COO_I[9] = Row_Indices_0[Local_Row_Ind[3]] + Block_00->Row_Shift[1]; COO_V[9] = Block_00->FE_Tensor_1[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[3]]; COO_I[10] = Row_Indices_0[Local_Row_Ind[4]] + Block_00->Row_Shift[1]; COO_V[10] = Block_00->FE_Tensor_1[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[4]]; COO_I[11] = Row_Indices_0[Local_Row_Ind[5]] + Block_00->Row_Shift[1]; COO_V[11] = Block_00->FE_Tensor_1[Local_Col_Ind[0]*ROW_NB + Local_Row_Ind[5]]; COO_J_IV_Range[1] = 12; // end of range // now insert into the matrix! MAT->add_entries(COO_I, COO_J, COO_J_IV_Range, COO_V, 1*COL_NB); } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ // remove those macros! #undef SpecificFEM #undef SpecificFEM_str #undef ROW_Num_Block #undef ROW_NB #undef COL_Num_Block #undef COL_NB /***/
[ "ikuznet1@users.noreply.github.com" ]
ikuznet1@users.noreply.github.com
a5ee11099c4d689b28237faa2e688acb0fa80815
1f19d51cbb43154906890407d1bc0f44d231e033
/CMSIS/DSP/Testing/Source/Tests/NNSupport.cpp
550d96d912c386d82e037ea2132cf6d8a0581ae0
[ "Apache-2.0" ]
permissive
mintisan/CMSIS_5
7c8076b590975d5d505c16a37092140b3e64f720
2df723647a1f629b7be1394bfc13c9ea9119a8f8
refs/heads/develop
2020-09-08T23:08:47.066343
2019-11-12T17:15:05
2019-11-12T17:15:05
221,270,784
0
0
Apache-2.0
2019-11-12T17:15:07
2019-11-12T17:10:22
null
UTF-8
C++
false
false
591
cpp
#include "NNSupport.h" #include "Error.h" #include "arm_nnfunctions.h" #include "Test.h" #include <cstdio> void NNSupport::test_nn_elementwise_add_s8() { } void NNSupport::setUp(Testing::testID_t id,std::vector<Testing::param_t>& paramsArgs,Client::PatternMgr *mgr) { switch(id) { case NNSupport::TEST_NN_ELEMENTWISE_ADD_S8_1: { } break; } } void NNSupport::tearDown(Testing::testID_t id,Client::PatternMgr *mgr) { }
[ "Christophe.Favergeon@arm.com" ]
Christophe.Favergeon@arm.com
2665a4b0343202b04ab5360466dd920dbd9b3428
e9329cc9907e1bda72e55c97af98a4ce949a807f
/ports/Gulden/files/patch-src_Gulden_Common_scrypt.cpp
34810c879e52eef1a8f8e3df7703250e01b356ca
[ "BSD-2-Clause" ]
permissive
AndyLavr/FreeBSD-Coin-Ports
b2a71c2e8dc379a8e0eb22484f0bedd27762da7e
81d30bb176f43428f1056f65e22b368e352041da
refs/heads/master
2020-12-03T00:20:33.925583
2017-03-12T03:24:40
2017-03-12T03:24:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
882
cpp
--- src/Gulden/Common/scrypt.cpp.orig 2017-01-14 15:55:04 UTC +++ src/Gulden/Common/scrypt.cpp @@ -28,10 +28,11 @@ */ #include "scrypt.h" -#include "util.h" +//#include "util.h" #include <stdlib.h> #include <stdint.h> #include <string.h> +#include <sys/endian.h> #include <openssl/sha.h> #if defined(USE_SSE2) && !defined(USE_SSE2_ALWAYS) @@ -44,21 +45,6 @@ #endif #endif -static inline uint32_t be32dec(const void* pp) -{ - const uint8_t* p = (uint8_t const*)pp; - return ((uint32_t)(p[3]) + ((uint32_t)(p[2]) << 8) + ((uint32_t)(p[1]) << 16) + ((uint32_t)(p[0]) << 24)); -} - -static inline void be32enc(void* pp, uint32_t x) -{ - uint8_t* p = (uint8_t*)pp; - p[3] = x & 0xff; - p[2] = (x >> 8) & 0xff; - p[1] = (x >> 16) & 0xff; - p[0] = (x >> 24) & 0xff; -} - typedef struct HMAC_SHA256Context { SHA256_CTX ictx; SHA256_CTX octx;
[ "daniel@morante.net" ]
daniel@morante.net
48ddc08e0dd41b947f6aa0abad2ba5f31df4d51e
fe53e5f79eecee85718a1c5d8df87fa25cdccb89
/bindings/cpp/opencv_34/text.cpp
ae32c19c508e860d48bf246107c0dbcd4c17d5e7
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
rongcuid/opencv-rust
692f6dfe09e60dcae60384d00a6e6d0ea758903e
f151c2476183af6cd68e3df77ccd15fb966b1054
refs/heads/master
2022-10-29T11:15:43.081859
2020-06-06T12:26:56
2020-06-13T08:29:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,306
cpp
#include "common.hpp" #include <opencv2/text.hpp> #include "text_types.hpp" extern "C" { Result_void cv_text_MSERsToERStats_const__InputArrayX_vector_vector_Point__X_vector_vector_ERStat__X(const cv::_InputArray* image, std::vector<std::vector<cv::Point>>* contours, std::vector<std::vector<cv::text::ERStat>>* regions) { try { cv::text::MSERsToERStats(*image, *contours, *regions); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_computeNMChannels_const__InputArrayX_const__OutputArrayX_int(const cv::_InputArray* _src, const cv::_OutputArray* _channels, int _mode) { try { cv::text::computeNMChannels(*_src, *_channels, _mode); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::Ptr<cv::text::ERFilter>*> cv_text_createERFilterNM1_const_Ptr_Callback_X_int_float_float_float_bool_float(const cv::Ptr<cv::text::ERFilter::Callback>* cb, int thresholdDelta, float minArea, float maxArea, float minProbability, bool nonMaxSuppression, float minProbabilityDiff) { try { cv::Ptr<cv::text::ERFilter> ret = cv::text::createERFilterNM1(*cb, thresholdDelta, minArea, maxArea, minProbability, nonMaxSuppression, minProbabilityDiff); return Ok(new cv::Ptr<cv::text::ERFilter>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::ERFilter>*>)) } Result<cv::Ptr<cv::text::ERFilter>*> cv_text_createERFilterNM1_const_StringX_int_float_float_float_bool_float(const char* filename, int thresholdDelta, float minArea, float maxArea, float minProbability, bool nonMaxSuppression, float minProbabilityDiff) { try { cv::Ptr<cv::text::ERFilter> ret = cv::text::createERFilterNM1(cv::String(filename), thresholdDelta, minArea, maxArea, minProbability, nonMaxSuppression, minProbabilityDiff); return Ok(new cv::Ptr<cv::text::ERFilter>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::ERFilter>*>)) } Result<cv::Ptr<cv::text::ERFilter>*> cv_text_createERFilterNM2_const_Ptr_Callback_X_float(const cv::Ptr<cv::text::ERFilter::Callback>* cb, float minProbability) { try { cv::Ptr<cv::text::ERFilter> ret = cv::text::createERFilterNM2(*cb, minProbability); return Ok(new cv::Ptr<cv::text::ERFilter>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::ERFilter>*>)) } Result<cv::Ptr<cv::text::ERFilter>*> cv_text_createERFilterNM2_const_StringX_float(const char* filename, float minProbability) { try { cv::Ptr<cv::text::ERFilter> ret = cv::text::createERFilterNM2(cv::String(filename), minProbability); return Ok(new cv::Ptr<cv::text::ERFilter>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::ERFilter>*>)) } Result<cv::Mat*> cv_text_createOCRHMMTransitionsTable_const_StringX_vector_String_X(const char* vocabulary, std::vector<cv::String>* lexicon) { try { cv::Mat ret = cv::text::createOCRHMMTransitionsTable(cv::String(vocabulary), *lexicon); return Ok(new cv::Mat(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Mat*>)) } Result_void cv_text_createOCRHMMTransitionsTable_stringX_vector_string_X_const__OutputArrayX(void** vocabulary, std::vector<std::string>* lexicon, const cv::_OutputArray* transition_probabilities_table) { try { std::string vocabulary_out; cv::text::createOCRHMMTransitionsTable(vocabulary_out, *lexicon, *transition_probabilities_table); *vocabulary = ocvrs_create_string(vocabulary_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_detectRegions_const__InputArrayX_const_Ptr_ERFilter_X_const_Ptr_ERFilter_X_vector_Rect_X_int_const_StringX_float(const cv::_InputArray* image, const cv::Ptr<cv::text::ERFilter>* er_filter1, const cv::Ptr<cv::text::ERFilter>* er_filter2, std::vector<cv::Rect>* groups_rects, int method, const char* filename, float minProbability) { try { cv::text::detectRegions(*image, *er_filter1, *er_filter2, *groups_rects, method, cv::String(filename), minProbability); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_detectRegions_const__InputArrayX_const_Ptr_ERFilter_X_const_Ptr_ERFilter_X_vector_vector_Point__X(const cv::_InputArray* image, const cv::Ptr<cv::text::ERFilter>* er_filter1, const cv::Ptr<cv::text::ERFilter>* er_filter2, std::vector<std::vector<cv::Point>>* regions) { try { cv::text::detectRegions(*image, *er_filter1, *er_filter2, *regions); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_erGrouping_const__InputArrayX_const__InputArrayX_vector_vector_ERStat__X_vector_vector_Vec2i__X_vector_Rect_X_int_const_stringX_float(const cv::_InputArray* img, const cv::_InputArray* channels, std::vector<std::vector<cv::text::ERStat>>* regions, std::vector<std::vector<cv::Vec2i>>* groups, std::vector<cv::Rect>* groups_rects, int method, const char* filename, float minProbablity) { try { cv::text::erGrouping(*img, *channels, *regions, *groups, *groups_rects, method, std::string(filename), minProbablity); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_erGrouping_const__InputArrayX_const__InputArrayX_vector_vector_Point___vector_Rect_X_int_const_StringX_float(const cv::_InputArray* image, const cv::_InputArray* channel, std::vector<std::vector<cv::Point>>* regions, std::vector<cv::Rect>* groups_rects, int method, const char* filename, float minProbablity) { try { cv::text::erGrouping(*image, *channel, *regions, *groups_rects, method, cv::String(filename), minProbablity); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::Ptr<cv::text::ERFilter::Callback>*> cv_text_loadClassifierNM1_const_StringX(const char* filename) { try { cv::Ptr<cv::text::ERFilter::Callback> ret = cv::text::loadClassifierNM1(cv::String(filename)); return Ok(new cv::Ptr<cv::text::ERFilter::Callback>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::ERFilter::Callback>*>)) } Result<cv::Ptr<cv::text::ERFilter::Callback>*> cv_text_loadClassifierNM2_const_StringX(const char* filename) { try { cv::Ptr<cv::text::ERFilter::Callback> ret = cv::text::loadClassifierNM2(cv::String(filename)); return Ok(new cv::Ptr<cv::text::ERFilter::Callback>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::ERFilter::Callback>*>)) } Result<cv::Ptr<cv::text::OCRBeamSearchDecoder::ClassifierCallback>*> cv_text_loadOCRBeamSearchClassifierCNN_const_StringX(const char* filename) { try { cv::Ptr<cv::text::OCRBeamSearchDecoder::ClassifierCallback> ret = cv::text::loadOCRBeamSearchClassifierCNN(cv::String(filename)); return Ok(new cv::Ptr<cv::text::OCRBeamSearchDecoder::ClassifierCallback>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRBeamSearchDecoder::ClassifierCallback>*>)) } Result<cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>*> cv_text_loadOCRHMMClassifierCNN_const_StringX(const char* filename) { try { cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback> ret = cv::text::loadOCRHMMClassifierCNN(cv::String(filename)); return Ok(new cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>*>)) } Result<cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>*> cv_text_loadOCRHMMClassifierNM_const_StringX(const char* filename) { try { cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback> ret = cv::text::loadOCRHMMClassifierNM(cv::String(filename)); return Ok(new cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>*>)) } Result<cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>*> cv_text_loadOCRHMMClassifier_const_StringX_int(const char* filename, int classifier) { try { cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback> ret = cv::text::loadOCRHMMClassifier(cv::String(filename), classifier); return Ok(new cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>*>)) } Result_void cv_text_BaseOCR_run_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::BaseOCR* instance, cv::Mat* image, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_BaseOCR_run_MatX_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::BaseOCR* instance, cv::Mat* image, cv::Mat* mask, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, *mask, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_run_const__InputArrayX_vector_ERStat_X(cv::text::ERFilter* instance, const cv::_InputArray* image, std::vector<cv::text::ERStat>* regions) { try { instance->run(*image, *regions); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setCallback_const_Ptr_Callback_X(cv::text::ERFilter* instance, const cv::Ptr<cv::text::ERFilter::Callback>* cb) { try { instance->setCallback(*cb); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setThresholdDelta_int(cv::text::ERFilter* instance, int thresholdDelta) { try { instance->setThresholdDelta(thresholdDelta); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setMinArea_float(cv::text::ERFilter* instance, float minArea) { try { instance->setMinArea(minArea); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setMaxArea_float(cv::text::ERFilter* instance, float maxArea) { try { instance->setMaxArea(maxArea); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setMinProbability_float(cv::text::ERFilter* instance, float minProbability) { try { instance->setMinProbability(minProbability); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setMinProbabilityDiff_float(cv::text::ERFilter* instance, float minProbabilityDiff) { try { instance->setMinProbabilityDiff(minProbabilityDiff); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_ERFilter_setNonMaxSuppression_bool(cv::text::ERFilter* instance, bool nonMaxSuppression) { try { instance->setNonMaxSuppression(nonMaxSuppression); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_text_ERFilter_getNumRejected_const(const cv::text::ERFilter* instance) { try { int ret = instance->getNumRejected(); return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result<double> cv_text_ERFilter_Callback_eval_const_ERStatX(cv::text::ERFilter::Callback* instance, const cv::text::ERStat* stat) { try { double ret = instance->eval(*stat); return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double>)) } Result<int> cv_text_ERStat_getPropPixel_const(const cv::text::ERStat* instance) { try { int ret = instance->pixel; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_text_ERStat_setPropPixel_int(cv::text::ERStat* instance, int val) { try { instance->pixel = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_text_ERStat_getPropLevel_const(const cv::text::ERStat* instance) { try { int ret = instance->level; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_text_ERStat_setPropLevel_int(cv::text::ERStat* instance, int val) { try { instance->level = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_text_ERStat_getPropArea_const(const cv::text::ERStat* instance) { try { int ret = instance->area; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_text_ERStat_setPropArea_int(cv::text::ERStat* instance, int val) { try { instance->area = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_text_ERStat_getPropPerimeter_const(const cv::text::ERStat* instance) { try { int ret = instance->perimeter; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_text_ERStat_setPropPerimeter_int(cv::text::ERStat* instance, int val) { try { instance->perimeter = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_text_ERStat_getPropEuler_const(const cv::text::ERStat* instance) { try { int ret = instance->euler; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_text_ERStat_setPropEuler_int(cv::text::ERStat* instance, int val) { try { instance->euler = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::Rect> cv_text_ERStat_getPropRect_const(const cv::text::ERStat* instance) { try { cv::Rect ret = instance->rect; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Rect>)) } Result_void cv_text_ERStat_setPropRect_Rect(cv::text::ERStat* instance, const cv::Rect* val) { try { instance->rect = *val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<double(*)[2]> cv_text_ERStat_getPropRaw_moments(cv::text::ERStat* instance) { try { double(*ret)[2] = &instance->raw_moments; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double(*)[2]>)) } Result<double(*)[3]> cv_text_ERStat_getPropCentral_moments(cv::text::ERStat* instance) { try { double(*ret)[3] = &instance->central_moments; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double(*)[3]>)) } Result<float> cv_text_ERStat_getPropMed_crossings_const(const cv::text::ERStat* instance) { try { float ret = instance->med_crossings; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<float>)) } Result_void cv_text_ERStat_setPropMed_crossings_float(cv::text::ERStat* instance, float val) { try { instance->med_crossings = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<float> cv_text_ERStat_getPropHole_area_ratio_const(const cv::text::ERStat* instance) { try { float ret = instance->hole_area_ratio; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<float>)) } Result_void cv_text_ERStat_setPropHole_area_ratio_float(cv::text::ERStat* instance, float val) { try { instance->hole_area_ratio = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<float> cv_text_ERStat_getPropConvex_hull_ratio_const(const cv::text::ERStat* instance) { try { float ret = instance->convex_hull_ratio; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<float>)) } Result_void cv_text_ERStat_setPropConvex_hull_ratio_float(cv::text::ERStat* instance, float val) { try { instance->convex_hull_ratio = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<float> cv_text_ERStat_getPropNum_inflexion_points_const(const cv::text::ERStat* instance) { try { float ret = instance->num_inflexion_points; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<float>)) } Result_void cv_text_ERStat_setPropNum_inflexion_points_float(cv::text::ERStat* instance, float val) { try { instance->num_inflexion_points = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<double> cv_text_ERStat_getPropProbability_const(const cv::text::ERStat* instance) { try { double ret = instance->probability; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double>)) } Result_void cv_text_ERStat_setPropProbability_double(cv::text::ERStat* instance, double val) { try { instance->probability = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::text::ERStat**> cv_text_ERStat_getPropParent(cv::text::ERStat* instance) { try { cv::text::ERStat* ret = instance->parent; return Ok(new cv::text::ERStat*(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat**>)) } Result_void cv_text_ERStat_setPropParent_ERStatX(cv::text::ERStat* instance, cv::text::ERStat* val) { try { instance->parent = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::text::ERStat**> cv_text_ERStat_getPropChild(cv::text::ERStat* instance) { try { cv::text::ERStat* ret = instance->child; return Ok(new cv::text::ERStat*(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat**>)) } Result_void cv_text_ERStat_setPropChild_ERStatX(cv::text::ERStat* instance, cv::text::ERStat* val) { try { instance->child = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::text::ERStat**> cv_text_ERStat_getPropNext(cv::text::ERStat* instance) { try { cv::text::ERStat* ret = instance->next; return Ok(new cv::text::ERStat*(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat**>)) } Result_void cv_text_ERStat_setPropNext_ERStatX(cv::text::ERStat* instance, cv::text::ERStat* val) { try { instance->next = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::text::ERStat**> cv_text_ERStat_getPropPrev(cv::text::ERStat* instance) { try { cv::text::ERStat* ret = instance->prev; return Ok(new cv::text::ERStat*(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat**>)) } Result_void cv_text_ERStat_setPropPrev_ERStatX(cv::text::ERStat* instance, cv::text::ERStat* val) { try { instance->prev = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<bool> cv_text_ERStat_getPropLocal_maxima_const(const cv::text::ERStat* instance) { try { bool ret = instance->local_maxima; return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<bool>)) } Result_void cv_text_ERStat_setPropLocal_maxima_bool(cv::text::ERStat* instance, bool val) { try { instance->local_maxima = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::text::ERStat**> cv_text_ERStat_getPropMax_probability_ancestor(cv::text::ERStat* instance) { try { cv::text::ERStat* ret = instance->max_probability_ancestor; return Ok(new cv::text::ERStat*(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat**>)) } Result_void cv_text_ERStat_setPropMax_probability_ancestor_ERStatX(cv::text::ERStat* instance, cv::text::ERStat* val) { try { instance->max_probability_ancestor = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::text::ERStat**> cv_text_ERStat_getPropMin_probability_ancestor(cv::text::ERStat* instance) { try { cv::text::ERStat* ret = instance->min_probability_ancestor; return Ok(new cv::text::ERStat*(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat**>)) } Result_void cv_text_ERStat_setPropMin_probability_ancestor_ERStatX(cv::text::ERStat* instance, cv::text::ERStat* val) { try { instance->min_probability_ancestor = val; return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } void cv_ERStat_delete(cv::text::ERStat* instance) { delete instance; } Result<cv::text::ERStat*> cv_text_ERStat_ERStat_int_int_int_int(int level, int pixel, int x, int y) { try { cv::text::ERStat* ret = new cv::text::ERStat(level, pixel, x, y); return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::text::ERStat*>)) } void cv_OCRBeamSearchDecoder_delete(cv::text::OCRBeamSearchDecoder* instance) { delete instance; } Result_void cv_text_OCRBeamSearchDecoder_run_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRBeamSearchDecoder* instance, cv::Mat* image, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_OCRBeamSearchDecoder_run_MatX_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRBeamSearchDecoder* instance, cv::Mat* image, cv::Mat* mask, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, *mask, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<void*> cv_text_OCRBeamSearchDecoder_run_const__InputArrayX_int_int(cv::text::OCRBeamSearchDecoder* instance, const cv::_InputArray* image, int min_confidence, int component_level) { try { cv::String ret = instance->run(*image, min_confidence, component_level); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result<void*> cv_text_OCRBeamSearchDecoder_run_const__InputArrayX_const__InputArrayX_int_int(cv::text::OCRBeamSearchDecoder* instance, const cv::_InputArray* image, const cv::_InputArray* mask, int min_confidence, int component_level) { try { cv::String ret = instance->run(*image, *mask, min_confidence, component_level); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result<cv::Ptr<cv::text::OCRBeamSearchDecoder>*> cv_text_OCRBeamSearchDecoder_create_Ptr_ClassifierCallback__const_stringX_const__InputArrayX_const__InputArrayX_decoder_mode_int(const cv::Ptr<cv::text::OCRBeamSearchDecoder::ClassifierCallback>* classifier, const char* vocabulary, const cv::_InputArray* transition_probabilities_table, const cv::_InputArray* emission_probabilities_table, cv::text::decoder_mode mode, int beam_size) { try { cv::Ptr<cv::text::OCRBeamSearchDecoder> ret = cv::text::OCRBeamSearchDecoder::create(*classifier, std::string(vocabulary), *transition_probabilities_table, *emission_probabilities_table, mode, beam_size); return Ok(new cv::Ptr<cv::text::OCRBeamSearchDecoder>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRBeamSearchDecoder>*>)) } Result<cv::Ptr<cv::text::OCRBeamSearchDecoder>*> cv_text_OCRBeamSearchDecoder_create_Ptr_ClassifierCallback__const_StringX_const__InputArrayX_const__InputArrayX_int_int(const cv::Ptr<cv::text::OCRBeamSearchDecoder::ClassifierCallback>* classifier, const char* vocabulary, const cv::_InputArray* transition_probabilities_table, const cv::_InputArray* emission_probabilities_table, int mode, int beam_size) { try { cv::Ptr<cv::text::OCRBeamSearchDecoder> ret = cv::text::OCRBeamSearchDecoder::create(*classifier, cv::String(vocabulary), *transition_probabilities_table, *emission_probabilities_table, mode, beam_size); return Ok(new cv::Ptr<cv::text::OCRBeamSearchDecoder>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRBeamSearchDecoder>*>)) } Result<cv::Ptr<cv::text::OCRBeamSearchDecoder>*> cv_text_OCRBeamSearchDecoder_create_const_StringX_const_StringX_const__InputArrayX_const__InputArrayX_int_int(const char* filename, const char* vocabulary, const cv::_InputArray* transition_probabilities_table, const cv::_InputArray* emission_probabilities_table, int mode, int beam_size) { try { cv::Ptr<cv::text::OCRBeamSearchDecoder> ret = cv::text::OCRBeamSearchDecoder::create(cv::String(filename), cv::String(vocabulary), *transition_probabilities_table, *emission_probabilities_table, mode, beam_size); return Ok(new cv::Ptr<cv::text::OCRBeamSearchDecoder>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRBeamSearchDecoder>*>)) } void cv_OCRBeamSearchDecoder_ClassifierCallback_delete(cv::text::OCRBeamSearchDecoder::ClassifierCallback* instance) { delete instance; } Result_void cv_text_OCRBeamSearchDecoder_ClassifierCallback_eval_const__InputArrayX_vector_vector_double__X_vector_int_X(cv::text::OCRBeamSearchDecoder::ClassifierCallback* instance, const cv::_InputArray* image, std::vector<std::vector<double>>* recognition_probabilities, std::vector<int>* oversegmentation) { try { instance->eval(*image, *recognition_probabilities, *oversegmentation); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_text_OCRBeamSearchDecoder_ClassifierCallback_getWindowSize(cv::text::OCRBeamSearchDecoder::ClassifierCallback* instance) { try { int ret = instance->getWindowSize(); return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result<int> cv_text_OCRBeamSearchDecoder_ClassifierCallback_getStepSize(cv::text::OCRBeamSearchDecoder::ClassifierCallback* instance) { try { int ret = instance->getStepSize(); return Ok(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } void cv_OCRHMMDecoder_delete(cv::text::OCRHMMDecoder* instance) { delete instance; } Result_void cv_text_OCRHMMDecoder_run_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRHMMDecoder* instance, cv::Mat* image, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_OCRHMMDecoder_run_MatX_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRHMMDecoder* instance, cv::Mat* image, cv::Mat* mask, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, *mask, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<void*> cv_text_OCRHMMDecoder_run_const__InputArrayX_int_int(cv::text::OCRHMMDecoder* instance, const cv::_InputArray* image, int min_confidence, int component_level) { try { cv::String ret = instance->run(*image, min_confidence, component_level); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result<void*> cv_text_OCRHMMDecoder_run_const__InputArrayX_const__InputArrayX_int_int(cv::text::OCRHMMDecoder* instance, const cv::_InputArray* image, const cv::_InputArray* mask, int min_confidence, int component_level) { try { cv::String ret = instance->run(*image, *mask, min_confidence, component_level); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result<cv::Ptr<cv::text::OCRHMMDecoder>*> cv_text_OCRHMMDecoder_create_Ptr_ClassifierCallback__const_stringX_const__InputArrayX_const__InputArrayX_decoder_mode(const cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>* classifier, const char* vocabulary, const cv::_InputArray* transition_probabilities_table, const cv::_InputArray* emission_probabilities_table, cv::text::decoder_mode mode) { try { cv::Ptr<cv::text::OCRHMMDecoder> ret = cv::text::OCRHMMDecoder::create(*classifier, std::string(vocabulary), *transition_probabilities_table, *emission_probabilities_table, mode); return Ok(new cv::Ptr<cv::text::OCRHMMDecoder>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHMMDecoder>*>)) } Result<cv::Ptr<cv::text::OCRHMMDecoder>*> cv_text_OCRHMMDecoder_create_Ptr_ClassifierCallback__const_StringX_const__InputArrayX_const__InputArrayX_int(const cv::Ptr<cv::text::OCRHMMDecoder::ClassifierCallback>* classifier, const char* vocabulary, const cv::_InputArray* transition_probabilities_table, const cv::_InputArray* emission_probabilities_table, int mode) { try { cv::Ptr<cv::text::OCRHMMDecoder> ret = cv::text::OCRHMMDecoder::create(*classifier, cv::String(vocabulary), *transition_probabilities_table, *emission_probabilities_table, mode); return Ok(new cv::Ptr<cv::text::OCRHMMDecoder>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHMMDecoder>*>)) } Result<cv::Ptr<cv::text::OCRHMMDecoder>*> cv_text_OCRHMMDecoder_create_const_StringX_const_StringX_const__InputArrayX_const__InputArrayX_int_int(const char* filename, const char* vocabulary, const cv::_InputArray* transition_probabilities_table, const cv::_InputArray* emission_probabilities_table, int mode, int classifier) { try { cv::Ptr<cv::text::OCRHMMDecoder> ret = cv::text::OCRHMMDecoder::create(cv::String(filename), cv::String(vocabulary), *transition_probabilities_table, *emission_probabilities_table, mode, classifier); return Ok(new cv::Ptr<cv::text::OCRHMMDecoder>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHMMDecoder>*>)) } void cv_OCRHMMDecoder_ClassifierCallback_delete(cv::text::OCRHMMDecoder::ClassifierCallback* instance) { delete instance; } Result_void cv_text_OCRHMMDecoder_ClassifierCallback_eval_const__InputArrayX_vector_int_X_vector_double_X(cv::text::OCRHMMDecoder::ClassifierCallback* instance, const cv::_InputArray* image, std::vector<int>* out_class, std::vector<double>* out_confidence) { try { instance->eval(*image, *out_class, *out_confidence); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_OCRHolisticWordRecognizer_run_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRHolisticWordRecognizer* instance, cv::Mat* image, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_OCRHolisticWordRecognizer_run_MatX_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRHolisticWordRecognizer* instance, cv::Mat* image, cv::Mat* mask, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, *mask, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::Ptr<cv::text::OCRHolisticWordRecognizer>*> cv_text_OCRHolisticWordRecognizer_create_const_stringX_const_stringX_const_stringX(const char* archFilename, const char* weightsFilename, const char* wordsFilename) { try { cv::Ptr<cv::text::OCRHolisticWordRecognizer> ret = cv::text::OCRHolisticWordRecognizer::create(std::string(archFilename), std::string(weightsFilename), std::string(wordsFilename)); return Ok(new cv::Ptr<cv::text::OCRHolisticWordRecognizer>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRHolisticWordRecognizer>*>)) } Result_void cv_text_OCRTesseract_run_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRTesseract* instance, cv::Mat* image, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_OCRTesseract_run_MatX_MatX_stringX_vector_Rect_X_vector_string_X_vector_float_X_int(cv::text::OCRTesseract* instance, cv::Mat* image, cv::Mat* mask, void** output_text, std::vector<cv::Rect>* component_rects, std::vector<std::string>* component_texts, std::vector<float>* component_confidences, int component_level) { try { std::string output_text_out; instance->run(*image, *mask, output_text_out, component_rects, component_texts, component_confidences, component_level); *output_text = ocvrs_create_string(output_text_out.c_str()); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<void*> cv_text_OCRTesseract_run_const__InputArrayX_int_int(cv::text::OCRTesseract* instance, const cv::_InputArray* image, int min_confidence, int component_level) { try { cv::String ret = instance->run(*image, min_confidence, component_level); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result<void*> cv_text_OCRTesseract_run_const__InputArrayX_const__InputArrayX_int_int(cv::text::OCRTesseract* instance, const cv::_InputArray* image, const cv::_InputArray* mask, int min_confidence, int component_level) { try { cv::String ret = instance->run(*image, *mask, min_confidence, component_level); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result_void cv_text_OCRTesseract_setWhiteList_const_StringX(cv::text::OCRTesseract* instance, const char* char_whitelist) { try { instance->setWhiteList(cv::String(char_whitelist)); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::Ptr<cv::text::OCRTesseract>*> cv_text_OCRTesseract_create_const_charX_const_charX_const_charX_int_int(const char* datapath, const char* language, const char* char_whitelist, int oem, int psmode) { try { cv::Ptr<cv::text::OCRTesseract> ret = cv::text::OCRTesseract::create(datapath, language, char_whitelist, oem, psmode); return Ok(new cv::Ptr<cv::text::OCRTesseract>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::OCRTesseract>*>)) } Result_void cv_text_TextDetector_detect_const__InputArrayX_vector_Rect_X_vector_float_X(cv::text::TextDetector* instance, const cv::_InputArray* inputImage, std::vector<cv::Rect>* Bbox, std::vector<float>* confidence) { try { instance->detect(*inputImage, *Bbox, *confidence); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_text_TextDetectorCNN_detect_const__InputArrayX_vector_Rect_X_vector_float_X(cv::text::TextDetectorCNN* instance, const cv::_InputArray* inputImage, std::vector<cv::Rect>* Bbox, std::vector<float>* confidence) { try { instance->detect(*inputImage, *Bbox, *confidence); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<cv::Ptr<cv::text::TextDetectorCNN>*> cv_text_TextDetectorCNN_create_const_StringX_const_StringX_vector_Size_(const char* modelArchFilename, const char* modelWeightsFilename, std::vector<cv::Size>* detectionSizes) { try { cv::Ptr<cv::text::TextDetectorCNN> ret = cv::text::TextDetectorCNN::create(cv::String(modelArchFilename), cv::String(modelWeightsFilename), *detectionSizes); return Ok(new cv::Ptr<cv::text::TextDetectorCNN>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::TextDetectorCNN>*>)) } Result<cv::Ptr<cv::text::TextDetectorCNN>*> cv_text_TextDetectorCNN_create_const_StringX_const_StringX(const char* modelArchFilename, const char* modelWeightsFilename) { try { cv::Ptr<cv::text::TextDetectorCNN> ret = cv::text::TextDetectorCNN::create(cv::String(modelArchFilename), cv::String(modelWeightsFilename)); return Ok(new cv::Ptr<cv::text::TextDetectorCNN>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::text::TextDetectorCNN>*>)) } }
[ "twisted.fall@gmail.com" ]
twisted.fall@gmail.com
b8bcde23b58d2ed70b1647991cbb22b659bb320e
e3ce7ee313e46851d6a499ef2e6d5f934ff3605d
/source/Structural/Proxy.cpp
9d28be775445e156953f718026d429a48ddc0271
[]
no_license
jpiccoli/Design_Patterns
122dc89f3f07a1eb809b691b5a57cc3b7584111a
65fb8ca39b161a612f060de1d7533d29a566a849
refs/heads/master
2022-12-13T01:19:31.670899
2020-09-05T17:17:41
2020-09-05T17:17:41
273,745,980
0
0
null
null
null
null
UTF-8
C++
false
false
2,579
cpp
// A structural design pattern that lets you provide a substitute or placeholder for another object. // A proxy controls access to the original object, allowing you to perform something either before or // after the request gets through to the original object. #include "../../include/Structural/Proxy.h" std::vector<VideoInfo> ThirdPartyVideoClass::list_videos() const { std::cout << "ThirdPartyVideoClass::list_videos()\n"; return list_cache; } std::string ThirdPartyVideoClass::get_video_info(int id) const { std::cout << "ThirdPartyVideoClass::get_video_info()\n"; for(auto const& video : list_cache) { if(video.get_id() == id) { return video.get_info(); } } return ""; } void ThirdPartyVideoClass::download_video(int id) { std::cout << "ThirdPartyVideoClass::download_video()\n"; for(auto const& video : list_cache) { if(video.get_id() == id) { std::cout << "Downloading info for id " << id << '\n'; return; } } std::cout << "No information for id " << id << '\n'; } void Proxy::render_video_page(int id) const { std::cout << "Proxy::render_video_page()\n"; std::cout << service->get_video_info(id) << '\n'; } void Proxy::render_list_panel() const { std::cout << "Proxy::render_list_panel()\n"; auto video_list = service->list_videos(); for(auto const& element : video_list) { std::cout << element.get_info() << '\n'; } } void Proxy::react_on_user_input(int id) const { std::cout << "Proxy::react_on_user_input()\n"; check_access(); log_access(); render_video_page(id); render_list_panel(); } void Proxy::check_access() const { std::cout << "Proxy::check_access()\n"; } void Proxy::log_access() const { std::cout << "Proxy::log_access()\n"; } std::vector<VideoInfo> Proxy::list_videos() const { return service->list_videos(); } std::string Proxy::get_video_info(int id) const { return service->get_video_info(id); } void Proxy::download_video(int id) { return service->download_video(id); } void VideoManager::render_video_page(int id) const { std::cout << "VideoManager::render_video_page()\n"; std::cout << service->get_video_info(id) << '\n'; } void VideoManager::render_list_panel() const { std::cout << "VideoManager::render_list_panel()\n"; auto video_list = service->list_videos(); for(auto const& element : video_list) { std::cout << element.get_info() << '\n'; } } void VideoManager::react_on_user_input(int id) const { std::cout << "VideoManager::react_on_user_input()\n"; render_video_page(id); render_list_panel(); }
[ "joe13676@comcast.net" ]
joe13676@comcast.net
0ae12430b8e937b0a774bd56f26a4835a82085c2
9080e303edd97ad2238744121a66132c872f3ac6
/Gui/uploadwidget.h
5b29b84c7866097219540af03fdc92358f83a578
[]
no_license
jhonconal/newline-2nd-master
cd5d4c1b35d70bbb0e36ac197a084bbeb10477d8
89505da8398a247e3334e3cf2a53087ff0034ce9
refs/heads/master
2020-03-15T23:42:57.315797
2018-07-26T07:09:28
2018-07-26T07:09:28
132,399,457
0
0
null
null
null
null
UTF-8
C++
false
false
2,530
h
#ifndef UPLOADWIDGET_H #define UPLOADWIDGET_H #include <QWidget> #include <QPainter> #include <QTimer> #include <QMouseEvent> #include <QPaintEvent> #include "Gui/hintdialog.h" namespace Ui { class UploadWidget; } class UploadWidget : public QDialog { Q_OBJECT public: explicit UploadWidget(QDialog *parent = 0); ~UploadWidget(); // static UploadWidget* _instance; // static UploadWidget* Instance() // { // static QMutex mutex; // if (!_instance) { // QMutexLocker locker(&mutex); // if (!_instance) { // _instance = new UploadWidget; // } // } // return _instance; // } static const int PositionLeft = 180; static const int PositionTop = 90; static const int PositionRight = 0; static const int PositionBottom = -90; /**界面居中父窗口 * @brief showParentCenter * @param parentFrm */ void showParentCenter(QWidget *parentFrm); double nullPosition() const; void setNullPosition(double position); double value() const; double minimum() const; double maximum() const; bool isExist; double m_currentValue; void setRange(double min, double max); void setMinimum(double min); void setMaximum(double max); void setValue(double val); void setValue(int val); signals: void signal_closeUpload(); void signal_failedToUpload(); public slots: void SoltTotalPkgNum(int counts);//线程信号,成功发送数据包数量 void SoltCurrentPkgNum(int currentCounts); void SoltSendFileToAndroidFailed();//接收线程发送的向Android发送文件失败信号 void closeTimerEvent(); void closeTimer2Event(); void slot_closeUpload(); protected: virtual void paintEvent(QPaintEvent *event); virtual void mousePressEvent(QMouseEvent *event); private: Ui::UploadWidget *ui; QTimer *closeTimer ,*closeTimer2; bool m_successClose;//发送成功 bool m_failedClose;//发送失败 double m_min, m_max; double m_nullPosition; QPointF m_center; double m_value; qreal m_innerRadious,m_outRadious,m_perAngle; qreal m_colorRadious,m_coverColorRadious; QTimer *updateTimer; void initValue(); void drawOuterCircle(QPainter* painter); void drawInnerCircle(QPainter* painter); void drawRoundBarProgress(QPainter* painter); void drawTextValue(QPainter *painter); private slots: void updateWidget(); }; #endif // UPLOADWIDGET_H
[ "jhonconal@outlook.com" ]
jhonconal@outlook.com
40cfbc8cc52c7df4832a08c86e689246c2350c6e
b603a14c383ad30eab1d6db79db7f333b3b9d839
/src/devyatovskaya/Task1/cubeedges.h
3202c2998f918405fc99212419be13d62990be4d
[ "MIT" ]
permissive
sadads1337/fit-gl
37d66fff2c44664e67b8b43061f48dc18deace2e
88d9ae1f1935301d71ae6e090aff24e6829a7580
refs/heads/master
2023-05-03T17:23:25.170430
2021-05-23T18:26:56
2021-05-24T04:59:44
334,793,424
2
9
MIT
2021-05-24T06:55:24
2021-02-01T01:03:08
C++
UTF-8
C++
false
false
359
h
#pragma once #include "CubicGeometry.h" class CubeEdges : public CubicGeometry { public: CubeEdges() = delete; explicit CubeEdges(const GLfloat edge_len) : CubicGeometry(edge_len, 16) {} void DrawGeometry(QOpenGLShaderProgram *program) override; void InitGeometry() override; private: void setVertices() override; void setColor() override; };
[ "ilmaksad@gmail.com" ]
ilmaksad@gmail.com
7b680109635742eeb4caf9134b6759f7810f4df0
2afd103f20d8118fe595f5f6ba2f891e3cf92644
/ca/2014-14653/lab7/build/bdir/mkMemory.h
02a3544b98382f1bb1cdf387fabba0f6185a0ca7
[]
no_license
hoihoilee/Class-homeworks
c9e7d628ee3fecaad980cdfcc9c0b09a8353a493
f3656c5ac1ef107b8668f294165cc7498b556c6d
refs/heads/master
2020-04-14T11:43:51.320262
2019-10-28T12:36:56
2019-10-28T12:36:56
163,821,767
0
0
null
null
null
null
UTF-8
C++
false
false
27,715
h
/* * Generated by Bluespec Compiler, version 2014.07.A (build 34078, 2014-07-30) * * On Fri Jun 15 22:45:49 KST 2018 * */ /* Generation options: */ #ifndef __mkMemory_h__ #define __mkMemory_h__ #include "bluesim_types.h" #include "bs_module.h" #include "bluesim_primitives.h" #include "bs_vcd.h" /* Class declaration for the mkMemory module */ class MOD_mkMemory : public Module { /* Clock handles */ private: tClock __clk_handle_0; /* Clock gate handles */ public: tUInt8 *clk_gate[0]; /* Instantiation parameters */ public: /* Module state */ public: MOD_Reg<tUInt8> INST_dMemCnt; MOD_Reg<tUWide> INST_dMemReqQ_data_0; MOD_Reg<tUWide> INST_dMemReqQ_data_1; MOD_Reg<tUInt8> INST_dMemReqQ_deqEn_dummy2_0; MOD_Reg<tUInt8> INST_dMemReqQ_deqEn_dummy2_1; MOD_Reg<tUInt8> INST_dMemReqQ_deqEn_dummy2_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_0_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_0_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_0_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_1_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_1_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_1_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_2_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_2_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_dummy_2_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_lat_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_lat_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqEn_lat_2; MOD_Reg<tUInt8> INST_dMemReqQ_deqEn_rl; MOD_Reg<tUInt8> INST_dMemReqQ_deqP_dummy2_0; MOD_Reg<tUInt8> INST_dMemReqQ_deqP_dummy2_1; MOD_Reg<tUInt8> INST_dMemReqQ_deqP_dummy2_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_0_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_0_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_0_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_1_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_1_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_1_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_2_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_2_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_dummy_2_2; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_lat_0; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_lat_1; MOD_Wire<tUInt8> INST_dMemReqQ_deqP_lat_2; MOD_Reg<tUInt8> INST_dMemReqQ_deqP_rl; MOD_Reg<tUInt8> INST_dMemReqQ_enqEn_dummy2_0; MOD_Reg<tUInt8> INST_dMemReqQ_enqEn_dummy2_1; MOD_Reg<tUInt8> INST_dMemReqQ_enqEn_dummy2_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_0_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_0_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_0_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_1_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_1_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_1_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_2_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_2_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_dummy_2_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_lat_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_lat_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqEn_lat_2; MOD_Reg<tUInt8> INST_dMemReqQ_enqEn_rl; MOD_Reg<tUInt8> INST_dMemReqQ_enqP_dummy2_0; MOD_Reg<tUInt8> INST_dMemReqQ_enqP_dummy2_1; MOD_Reg<tUInt8> INST_dMemReqQ_enqP_dummy2_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_0_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_0_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_0_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_1_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_1_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_1_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_2_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_2_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_dummy_2_2; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_lat_0; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_lat_1; MOD_Wire<tUInt8> INST_dMemReqQ_enqP_lat_2; MOD_Reg<tUInt8> INST_dMemReqQ_enqP_rl; MOD_Reg<tUInt8> INST_dMemReqQ_tempData_dummy2_0; MOD_Reg<tUInt8> INST_dMemReqQ_tempData_dummy2_1; MOD_Wire<tUWide> INST_dMemReqQ_tempData_dummy_0_0; MOD_Wire<tUWide> INST_dMemReqQ_tempData_dummy_0_1; MOD_Wire<tUWide> INST_dMemReqQ_tempData_dummy_1_0; MOD_Wire<tUWide> INST_dMemReqQ_tempData_dummy_1_1; MOD_Wire<tUWide> INST_dMemReqQ_tempData_lat_0; MOD_Wire<tUWide> INST_dMemReqQ_tempData_lat_1; MOD_Reg<tUWide> INST_dMemReqQ_tempData_rl; MOD_Reg<tUInt8> INST_dMemReqQ_tempEnqP_dummy2_0; MOD_Reg<tUInt8> INST_dMemReqQ_tempEnqP_dummy2_1; MOD_Wire<tUInt8> INST_dMemReqQ_tempEnqP_dummy_0_0; MOD_Wire<tUInt8> INST_dMemReqQ_tempEnqP_dummy_0_1; MOD_Wire<tUInt8> INST_dMemReqQ_tempEnqP_dummy_1_0; MOD_Wire<tUInt8> INST_dMemReqQ_tempEnqP_dummy_1_1; MOD_Wire<tUInt8> INST_dMemReqQ_tempEnqP_lat_0; MOD_Wire<tUInt8> INST_dMemReqQ_tempEnqP_lat_1; MOD_Reg<tUInt8> INST_dMemReqQ_tempEnqP_rl; MOD_Reg<tUInt64> INST_dMemRespQ_data_0; MOD_Reg<tUInt64> INST_dMemRespQ_data_1; MOD_Reg<tUInt8> INST_dMemRespQ_deqEn_dummy2_0; MOD_Reg<tUInt8> INST_dMemRespQ_deqEn_dummy2_1; MOD_Reg<tUInt8> INST_dMemRespQ_deqEn_dummy2_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_0_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_0_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_0_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_1_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_1_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_1_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_2_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_2_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_dummy_2_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_lat_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_lat_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqEn_lat_2; MOD_Reg<tUInt8> INST_dMemRespQ_deqEn_rl; MOD_Reg<tUInt8> INST_dMemRespQ_deqP_dummy2_0; MOD_Reg<tUInt8> INST_dMemRespQ_deqP_dummy2_1; MOD_Reg<tUInt8> INST_dMemRespQ_deqP_dummy2_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_0_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_0_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_0_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_1_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_1_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_1_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_2_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_2_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_dummy_2_2; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_lat_0; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_lat_1; MOD_Wire<tUInt8> INST_dMemRespQ_deqP_lat_2; MOD_Reg<tUInt8> INST_dMemRespQ_deqP_rl; MOD_Reg<tUInt8> INST_dMemRespQ_enqEn_dummy2_0; MOD_Reg<tUInt8> INST_dMemRespQ_enqEn_dummy2_1; MOD_Reg<tUInt8> INST_dMemRespQ_enqEn_dummy2_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_0_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_0_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_0_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_1_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_1_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_1_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_2_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_2_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_dummy_2_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_lat_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_lat_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqEn_lat_2; MOD_Reg<tUInt8> INST_dMemRespQ_enqEn_rl; MOD_Reg<tUInt8> INST_dMemRespQ_enqP_dummy2_0; MOD_Reg<tUInt8> INST_dMemRespQ_enqP_dummy2_1; MOD_Reg<tUInt8> INST_dMemRespQ_enqP_dummy2_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_0_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_0_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_0_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_1_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_1_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_1_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_2_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_2_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_dummy_2_2; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_lat_0; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_lat_1; MOD_Wire<tUInt8> INST_dMemRespQ_enqP_lat_2; MOD_Reg<tUInt8> INST_dMemRespQ_enqP_rl; MOD_Reg<tUInt8> INST_dMemRespQ_tempData_dummy2_0; MOD_Reg<tUInt8> INST_dMemRespQ_tempData_dummy2_1; MOD_Wire<tUWide> INST_dMemRespQ_tempData_dummy_0_0; MOD_Wire<tUWide> INST_dMemRespQ_tempData_dummy_0_1; MOD_Wire<tUWide> INST_dMemRespQ_tempData_dummy_1_0; MOD_Wire<tUWide> INST_dMemRespQ_tempData_dummy_1_1; MOD_Wire<tUInt64> INST_dMemRespQ_tempData_lat_0; MOD_Wire<tUInt64> INST_dMemRespQ_tempData_lat_1; MOD_Reg<tUInt64> INST_dMemRespQ_tempData_rl; MOD_Reg<tUInt8> INST_dMemRespQ_tempEnqP_dummy2_0; MOD_Reg<tUInt8> INST_dMemRespQ_tempEnqP_dummy2_1; MOD_Wire<tUInt8> INST_dMemRespQ_tempEnqP_dummy_0_0; MOD_Wire<tUInt8> INST_dMemRespQ_tempEnqP_dummy_0_1; MOD_Wire<tUInt8> INST_dMemRespQ_tempEnqP_dummy_1_0; MOD_Wire<tUInt8> INST_dMemRespQ_tempEnqP_dummy_1_1; MOD_Wire<tUInt8> INST_dMemRespQ_tempEnqP_lat_0; MOD_Wire<tUInt8> INST_dMemRespQ_tempEnqP_lat_1; MOD_Reg<tUInt8> INST_dMemRespQ_tempEnqP_rl; MOD_Reg<tUInt8> INST_dMemStatus; MOD_Reg<tUInt64> INST_dMemTempData; MOD_Reg<tUInt8> INST_iMemCnt; MOD_Reg<tUWide> INST_iMemReqQ_data_0; MOD_Reg<tUWide> INST_iMemReqQ_data_1; MOD_Reg<tUInt8> INST_iMemReqQ_deqEn_dummy2_0; MOD_Reg<tUInt8> INST_iMemReqQ_deqEn_dummy2_1; MOD_Reg<tUInt8> INST_iMemReqQ_deqEn_dummy2_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_0_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_0_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_0_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_1_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_1_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_1_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_2_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_2_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_dummy_2_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_lat_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_lat_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqEn_lat_2; MOD_Reg<tUInt8> INST_iMemReqQ_deqEn_rl; MOD_Reg<tUInt8> INST_iMemReqQ_deqP_dummy2_0; MOD_Reg<tUInt8> INST_iMemReqQ_deqP_dummy2_1; MOD_Reg<tUInt8> INST_iMemReqQ_deqP_dummy2_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_0_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_0_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_0_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_1_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_1_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_1_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_2_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_2_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_dummy_2_2; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_lat_0; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_lat_1; MOD_Wire<tUInt8> INST_iMemReqQ_deqP_lat_2; MOD_Reg<tUInt8> INST_iMemReqQ_deqP_rl; MOD_Reg<tUInt8> INST_iMemReqQ_enqEn_dummy2_0; MOD_Reg<tUInt8> INST_iMemReqQ_enqEn_dummy2_1; MOD_Reg<tUInt8> INST_iMemReqQ_enqEn_dummy2_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_0_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_0_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_0_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_1_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_1_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_1_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_2_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_2_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_dummy_2_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_lat_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_lat_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqEn_lat_2; MOD_Reg<tUInt8> INST_iMemReqQ_enqEn_rl; MOD_Reg<tUInt8> INST_iMemReqQ_enqP_dummy2_0; MOD_Reg<tUInt8> INST_iMemReqQ_enqP_dummy2_1; MOD_Reg<tUInt8> INST_iMemReqQ_enqP_dummy2_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_0_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_0_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_0_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_1_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_1_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_1_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_2_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_2_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_dummy_2_2; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_lat_0; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_lat_1; MOD_Wire<tUInt8> INST_iMemReqQ_enqP_lat_2; MOD_Reg<tUInt8> INST_iMemReqQ_enqP_rl; MOD_Reg<tUInt8> INST_iMemReqQ_tempData_dummy2_0; MOD_Reg<tUInt8> INST_iMemReqQ_tempData_dummy2_1; MOD_Wire<tUWide> INST_iMemReqQ_tempData_dummy_0_0; MOD_Wire<tUWide> INST_iMemReqQ_tempData_dummy_0_1; MOD_Wire<tUWide> INST_iMemReqQ_tempData_dummy_1_0; MOD_Wire<tUWide> INST_iMemReqQ_tempData_dummy_1_1; MOD_Wire<tUWide> INST_iMemReqQ_tempData_lat_0; MOD_Wire<tUWide> INST_iMemReqQ_tempData_lat_1; MOD_Reg<tUWide> INST_iMemReqQ_tempData_rl; MOD_Reg<tUInt8> INST_iMemReqQ_tempEnqP_dummy2_0; MOD_Reg<tUInt8> INST_iMemReqQ_tempEnqP_dummy2_1; MOD_Wire<tUInt8> INST_iMemReqQ_tempEnqP_dummy_0_0; MOD_Wire<tUInt8> INST_iMemReqQ_tempEnqP_dummy_0_1; MOD_Wire<tUInt8> INST_iMemReqQ_tempEnqP_dummy_1_0; MOD_Wire<tUInt8> INST_iMemReqQ_tempEnqP_dummy_1_1; MOD_Wire<tUInt8> INST_iMemReqQ_tempEnqP_lat_0; MOD_Wire<tUInt8> INST_iMemReqQ_tempEnqP_lat_1; MOD_Reg<tUInt8> INST_iMemReqQ_tempEnqP_rl; MOD_Reg<tUInt64> INST_iMemRespQ_data_0; MOD_Reg<tUInt64> INST_iMemRespQ_data_1; MOD_Reg<tUInt8> INST_iMemRespQ_deqEn_dummy2_0; MOD_Reg<tUInt8> INST_iMemRespQ_deqEn_dummy2_1; MOD_Reg<tUInt8> INST_iMemRespQ_deqEn_dummy2_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_0_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_0_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_0_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_1_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_1_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_1_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_2_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_2_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_dummy_2_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_lat_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_lat_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqEn_lat_2; MOD_Reg<tUInt8> INST_iMemRespQ_deqEn_rl; MOD_Reg<tUInt8> INST_iMemRespQ_deqP_dummy2_0; MOD_Reg<tUInt8> INST_iMemRespQ_deqP_dummy2_1; MOD_Reg<tUInt8> INST_iMemRespQ_deqP_dummy2_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_0_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_0_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_0_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_1_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_1_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_1_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_2_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_2_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_dummy_2_2; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_lat_0; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_lat_1; MOD_Wire<tUInt8> INST_iMemRespQ_deqP_lat_2; MOD_Reg<tUInt8> INST_iMemRespQ_deqP_rl; MOD_Reg<tUInt8> INST_iMemRespQ_enqEn_dummy2_0; MOD_Reg<tUInt8> INST_iMemRespQ_enqEn_dummy2_1; MOD_Reg<tUInt8> INST_iMemRespQ_enqEn_dummy2_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_0_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_0_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_0_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_1_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_1_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_1_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_2_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_2_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_dummy_2_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_lat_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_lat_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqEn_lat_2; MOD_Reg<tUInt8> INST_iMemRespQ_enqEn_rl; MOD_Reg<tUInt8> INST_iMemRespQ_enqP_dummy2_0; MOD_Reg<tUInt8> INST_iMemRespQ_enqP_dummy2_1; MOD_Reg<tUInt8> INST_iMemRespQ_enqP_dummy2_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_0_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_0_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_0_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_1_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_1_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_1_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_2_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_2_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_dummy_2_2; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_lat_0; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_lat_1; MOD_Wire<tUInt8> INST_iMemRespQ_enqP_lat_2; MOD_Reg<tUInt8> INST_iMemRespQ_enqP_rl; MOD_Reg<tUInt8> INST_iMemRespQ_tempData_dummy2_0; MOD_Reg<tUInt8> INST_iMemRespQ_tempData_dummy2_1; MOD_Wire<tUWide> INST_iMemRespQ_tempData_dummy_0_0; MOD_Wire<tUWide> INST_iMemRespQ_tempData_dummy_0_1; MOD_Wire<tUWide> INST_iMemRespQ_tempData_dummy_1_0; MOD_Wire<tUWide> INST_iMemRespQ_tempData_dummy_1_1; MOD_Wire<tUInt64> INST_iMemRespQ_tempData_lat_0; MOD_Wire<tUInt64> INST_iMemRespQ_tempData_lat_1; MOD_Reg<tUInt64> INST_iMemRespQ_tempData_rl; MOD_Reg<tUInt8> INST_iMemRespQ_tempEnqP_dummy2_0; MOD_Reg<tUInt8> INST_iMemRespQ_tempEnqP_dummy2_1; MOD_Wire<tUInt8> INST_iMemRespQ_tempEnqP_dummy_0_0; MOD_Wire<tUInt8> INST_iMemRespQ_tempEnqP_dummy_0_1; MOD_Wire<tUInt8> INST_iMemRespQ_tempEnqP_dummy_1_0; MOD_Wire<tUInt8> INST_iMemRespQ_tempEnqP_dummy_1_1; MOD_Wire<tUInt8> INST_iMemRespQ_tempEnqP_lat_0; MOD_Wire<tUInt8> INST_iMemRespQ_tempEnqP_lat_1; MOD_Reg<tUInt8> INST_iMemRespQ_tempEnqP_rl; MOD_Reg<tUInt8> INST_iMemStatus; MOD_Reg<tUInt64> INST_iMemTempData; MOD_RegFile<tUInt32,tUInt64> INST_mem; MOD_Reg<tUInt64> INST_penaltyCnt; /* Constructor */ public: MOD_mkMemory(tSimStateHdl simHdl, char const *name, Module *parent); /* Symbol init methods */ private: void init_symbols_0(); /* Reset signal definitions */ private: tUInt8 PORT_RST_N; /* Port definitions */ public: tUWide PORT_dReq_r; tUWide PORT_iReq_r; /* Publicly accessible definitions */ public: tUInt8 DEF_dMemRespQ_deqEn_rl__h46287; tUInt8 DEF_iMemRespQ_deqEn_rl__h20064; tUInt8 DEF_iMemCnt_00_EQ_SEL_ARR_iMemReqQ_data_0_01_BIT_0_ETC___d614; tUInt8 DEF_x__h56854; tUInt8 DEF_dMemCnt_15_EQ_SEL_ARR_dMemReqQ_data_0_16_BIT_0_ETC___d529; tUInt8 DEF_x__h55157; tUInt8 DEF_SEL_ARR_dMemReqQ_data_0_16_BIT_129_34_dMemReqQ_ETC___d537; tUInt8 DEF_NOT_dMemCnt_15_EQ_SEL_ARR_dMemReqQ_data_0_16_B_ETC___d530; tUInt8 DEF_x__h53200; tUInt64 DEF__read__h52843; tUInt8 DEF_dMemRespQ_deqEn_dummy2_2__h50796; tUInt8 DEF_dMemRespQ_enqEn_dummy2_2__h49302; tUInt8 DEF_dMemReqQ_deqEn_dummy2_2__h37717; tUInt8 DEF_dMemReqQ_enqEn_dummy2_2__h36223; tUInt8 DEF_iMemRespQ_deqEn_dummy2_2__h24579; tUInt8 DEF_iMemRespQ_enqEn_dummy2_2__h23085; tUInt8 DEF_iMemReqQ_deqEn_dummy2_2__h11494; tUInt8 DEF_iMemReqQ_enqEn_dummy2_2__h10000; tUWide DEF_dMemReqQ_data_1___d518; tUWide DEF_dMemReqQ_data_0___d516; tUWide DEF_iMemReqQ_data_1___d603; tUWide DEF_iMemReqQ_data_0___d601; tUInt8 DEF_upd__h53217; tUInt8 DEF_upd__h55301; tUInt8 DEF_dMemStatus__h53090; tUInt8 DEF_iMemStatus__h55176; tUInt8 DEF_dMemRespQ_enqEn_rl__h44662; tUInt8 DEF_dMemReqQ_deqEn_rl__h33111; tUInt8 DEF_dMemReqQ_enqEn_rl__h31486; tUInt8 DEF_dMemReqQ_deqP_dummy2_2__h36803; tUInt8 DEF_dMemReqQ_deqP_dummy2_1__h53272; tUInt8 DEF_dMemReqQ_deqP_dummy2_0__h53260; tUInt8 DEF_iMemRespQ_enqEn_rl__h18439; tUInt8 DEF_iMemReqQ_deqEn_rl__h6888; tUInt8 DEF_iMemReqQ_enqEn_rl__h5263; tUInt8 DEF_iMemReqQ_deqP_dummy2_2__h10580; tUInt8 DEF_iMemReqQ_deqP_dummy2_1__h55356; tUInt8 DEF_iMemReqQ_deqP_dummy2_0__h55344; tUInt8 DEF__read_burstLength__h55402; tUInt8 DEF__read_burstLength__h55394; tUInt8 DEF__read_burstLength__h53310; tUInt8 DEF__read_burstLength__h53318; tUInt8 DEF_x__h55803; tUInt8 DEF_x__h54074; tUInt8 DEF_x__h55284; tUInt8 DEF_y__h55184; tUInt8 DEF_y__h53100; tUInt8 DEF_penaltyCnt_31_EQ_100___d532; tUInt8 DEF_NOT_iMemCnt_00_EQ_SEL_ARR_iMemReqQ_data_0_01_B_ETC___d615; /* Local definitions */ private: tUInt8 DEF__0_CONCAT_DONTCARE___d123; tUInt8 DEF_IF_dMemRespQ_tempEnqP_lat_0_whas__33_THEN_dMem_ETC___d438; tUInt8 DEF_IF_dMemRespQ_tempEnqP_lat_0_whas__33_THEN_NOT__ETC___d443; tUInt8 DEF_dMemRespQ_deqEn_lat_1_whas____d415; tUInt8 DEF_dMemRespQ_enqEn_lat_1_whas____d405; tUInt8 DEF_IF_dMemReqQ_tempEnqP_lat_0_whas__06_THEN_dMemR_ETC___d311; tUInt8 DEF_IF_dMemReqQ_tempEnqP_lat_0_whas__06_THEN_NOT_d_ETC___d316; tUInt8 DEF_dMemReqQ_deqEn_lat_1_whas____d288; tUInt8 DEF_dMemReqQ_enqEn_lat_1_whas____d278; tUInt8 DEF_IF_iMemRespQ_tempEnqP_lat_0_whas__79_THEN_iMem_ETC___d184; tUInt8 DEF_IF_iMemRespQ_tempEnqP_lat_0_whas__79_THEN_NOT__ETC___d189; tUInt8 DEF_iMemRespQ_deqEn_lat_1_whas____d161; tUInt8 DEF_iMemRespQ_enqEn_lat_1_whas____d151; tUInt8 DEF_IF_iMemReqQ_tempEnqP_lat_0_whas__1_THEN_iMemRe_ETC___d56; tUInt8 DEF_IF_iMemReqQ_tempEnqP_lat_0_whas__1_THEN_NOT_iM_ETC___d61; tUInt8 DEF_iMemReqQ_deqEn_lat_1_whas____d33; tUInt8 DEF_iMemReqQ_enqEn_lat_1_whas____d23; tUWide DEF_dMemReqQ_tempData_rl___d300; tUWide DEF_dMemReqQ_tempData_lat_1_wget____d297; tUWide DEF_dMemReqQ_tempData_lat_0_wget____d299; tUWide DEF_iMemReqQ_tempData_rl___d45; tUWide DEF_iMemReqQ_tempData_lat_1_wget____d42; tUWide DEF_iMemReqQ_tempData_lat_0_wget____d44; tUInt8 DEF_dMemRespQ_tempEnqP_rl___d436; tUInt8 DEF_dMemRespQ_tempEnqP_lat_0_wget____d434; tUInt8 DEF_dMemReqQ_tempEnqP_rl___d309; tUInt8 DEF_dMemReqQ_tempEnqP_lat_0_wget____d307; tUInt8 DEF_iMemRespQ_tempEnqP_rl___d182; tUInt8 DEF_iMemRespQ_tempEnqP_lat_0_wget____d180; tUInt8 DEF_iMemReqQ_tempEnqP_rl___d54; tUInt8 DEF_iMemReqQ_tempEnqP_lat_0_wget____d52; tUInt8 DEF_upd__h59956; tUInt8 DEF_upd__h49921; tUInt8 DEF_upd__h49954; tUInt8 DEF_upd__h54716; tUInt8 DEF_upd__h49638; tUInt8 DEF_upd__h49671; tUInt8 DEF_upd__h36842; tUInt8 DEF_upd__h36875; tUInt8 DEF_upd__h59187; tUInt8 DEF_upd__h36559; tUInt8 DEF_upd__h36592; tUInt8 DEF_upd__h58207; tUInt8 DEF_upd__h23704; tUInt8 DEF_upd__h23737; tUInt8 DEF_upd__h56430; tUInt8 DEF_upd__h23421; tUInt8 DEF_upd__h23454; tUInt8 DEF_upd__h10619; tUInt8 DEF_upd__h10652; tUInt8 DEF_upd__h57438; tUInt8 DEF_upd__h10336; tUInt8 DEF_upd__h10369; tUInt8 DEF_dMemRespQ_tempEnqP_lat_0_whas____d433; tUInt8 DEF_dMemRespQ_deqEn_lat_1_wget____d416; tUInt8 DEF_dMemRespQ_deqEn_lat_0_whas____d417; tUInt8 DEF_dMemRespQ_deqEn_lat_0_wget____d418; tUInt8 DEF_dMemRespQ_enqEn_lat_1_wget____d406; tUInt8 DEF_dMemRespQ_enqEn_lat_0_whas____d407; tUInt8 DEF_dMemRespQ_enqEn_lat_0_wget____d408; tUInt8 DEF_dMemRespQ_deqP_dummy2_2__h49882; tUInt8 DEF_dMemRespQ_enqP_dummy2_2__h49599; tUInt8 DEF_dMemReqQ_tempEnqP_lat_0_whas____d306; tUInt8 DEF_dMemReqQ_deqEn_lat_1_wget____d289; tUInt8 DEF_dMemReqQ_deqEn_lat_0_whas____d290; tUInt8 DEF_dMemReqQ_deqEn_lat_0_wget____d291; tUInt8 DEF_dMemReqQ_enqEn_lat_1_wget____d279; tUInt8 DEF_dMemReqQ_enqEn_lat_0_whas____d280; tUInt8 DEF_dMemReqQ_enqEn_lat_0_wget____d281; tUInt8 DEF_dMemReqQ_enqP_dummy2_2__h36520; tUInt8 DEF_iMemRespQ_tempEnqP_lat_0_whas____d179; tUInt8 DEF_iMemRespQ_deqEn_lat_1_wget____d162; tUInt8 DEF_iMemRespQ_deqEn_lat_0_whas____d163; tUInt8 DEF_iMemRespQ_deqEn_lat_0_wget____d164; tUInt8 DEF_iMemRespQ_enqEn_lat_1_wget____d152; tUInt8 DEF_iMemRespQ_enqEn_lat_0_whas____d153; tUInt8 DEF_iMemRespQ_enqEn_lat_0_wget____d154; tUInt8 DEF_iMemRespQ_deqP_dummy2_2__h23665; tUInt8 DEF_iMemRespQ_enqP_dummy2_2__h23382; tUInt8 DEF_iMemReqQ_tempEnqP_lat_0_whas____d51; tUInt8 DEF_iMemReqQ_deqEn_lat_1_wget____d34; tUInt8 DEF_iMemReqQ_deqEn_lat_0_whas____d35; tUInt8 DEF_iMemReqQ_deqEn_lat_0_wget____d36; tUInt8 DEF_iMemReqQ_enqEn_lat_1_wget____d24; tUInt8 DEF_iMemReqQ_enqEn_lat_0_whas____d25; tUInt8 DEF_iMemReqQ_enqEn_lat_0_wget____d26; tUInt8 DEF_iMemReqQ_enqP_dummy2_2__h10297; tUInt8 DEF_x__h49034; tUInt8 DEF_x__h49033; tUInt8 DEF_x__h35955; tUInt8 DEF_x__h35954; tUInt8 DEF_x__h22817; tUInt8 DEF_x__h22816; tUInt8 DEF_x__h9732; tUInt8 DEF_x__h9731; tUInt8 DEF_dMemRespQ_tempEnqP_rl_36_BIT_3___d437; tUInt8 DEF_dMemRespQ_tempEnqP_lat_0_wget__34_BIT_3___d435; tUInt8 DEF_dMemReqQ_tempEnqP_rl_09_BIT_3___d310; tUInt8 DEF_dMemReqQ_tempEnqP_lat_0_wget__07_BIT_3___d308; tUInt8 DEF_iMemRespQ_tempEnqP_rl_82_BIT_3___d183; tUInt8 DEF_iMemRespQ_tempEnqP_lat_0_wget__80_BIT_3___d181; tUInt8 DEF_iMemReqQ_tempEnqP_rl_4_BIT_3___d55; tUInt8 DEF_iMemReqQ_tempEnqP_lat_0_wget__2_BIT_3___d53; tUWide DEF_IF_dMemReqQ_tempData_dummy2_1_74_THEN_IF_dMemR_ETC___d375; tUWide DEF_IF_dMemReqQ_tempData_lat_0_whas__98_THEN_dMemR_ETC___d301; tUWide DEF_IF_dMemReqQ_tempData_lat_1_whas__96_THEN_dMemR_ETC___d302; tUWide DEF_IF_iMemReqQ_tempData_dummy2_1_19_THEN_IF_iMemR_ETC___d120; tUWide DEF_IF_iMemReqQ_tempData_lat_0_whas__3_THEN_iMemRe_ETC___d46; tUWide DEF_IF_iMemReqQ_tempData_lat_1_whas__1_THEN_iMemRe_ETC___d47; tUInt64 DEF_IF_dMemRespQ_tempData_lat_0_whas__25_THEN_dMem_ETC___d428; tUInt64 DEF_IF_iMemRespQ_tempData_lat_0_whas__71_THEN_iMem_ETC___d174; tUInt8 DEF_IF_dMemRespQ_tempEnqP_lat_0_whas__33_THEN_dMem_ETC___d448; tUInt8 DEF_IF_dMemRespQ_deqP_lat_1_whas__95_THEN_dMemResp_ETC___d401; tUInt8 DEF_IF_dMemRespQ_enqP_lat_1_whas__85_THEN_dMemResp_ETC___d391; tUInt8 DEF_IF_dMemReqQ_tempEnqP_lat_0_whas__06_THEN_dMemR_ETC___d321; tUInt8 DEF_IF_dMemReqQ_deqP_lat_1_whas__68_THEN_dMemReqQ__ETC___d274; tUInt8 DEF_IF_dMemReqQ_enqP_lat_1_whas__58_THEN_dMemReqQ__ETC___d264; tUInt8 DEF_IF_iMemRespQ_tempEnqP_lat_0_whas__79_THEN_iMem_ETC___d194; tUInt8 DEF_IF_iMemRespQ_deqP_lat_1_whas__41_THEN_iMemResp_ETC___d147; tUInt8 DEF_IF_iMemRespQ_enqP_lat_1_whas__31_THEN_iMemResp_ETC___d137; tUInt8 DEF_IF_iMemReqQ_tempEnqP_lat_0_whas__1_THEN_iMemRe_ETC___d66; tUInt8 DEF_IF_iMemReqQ_deqP_lat_1_whas__3_THEN_iMemReqQ_d_ETC___d19; tUInt8 DEF_IF_iMemReqQ_enqP_lat_1_whas_THEN_iMemReqQ_enqP_ETC___d9; /* Rules */ public: void RL_iMemReqQ_enqP_canon(); void RL_iMemReqQ_deqP_canon(); void RL_iMemReqQ_enqEn_canon(); void RL_iMemReqQ_deqEn_canon(); void RL_iMemReqQ_tempData_canon(); void RL_iMemReqQ_tempEnqP_canon(); void RL_iMemReqQ_canonicalize(); void RL_iMemRespQ_enqP_canon(); void RL_iMemRespQ_deqP_canon(); void RL_iMemRespQ_enqEn_canon(); void RL_iMemRespQ_deqEn_canon(); void RL_iMemRespQ_tempData_canon(); void RL_iMemRespQ_tempEnqP_canon(); void RL_iMemRespQ_canonicalize(); void RL_dMemReqQ_enqP_canon(); void RL_dMemReqQ_deqP_canon(); void RL_dMemReqQ_enqEn_canon(); void RL_dMemReqQ_deqEn_canon(); void RL_dMemReqQ_tempData_canon(); void RL_dMemReqQ_tempEnqP_canon(); void RL_dMemReqQ_canonicalize(); void RL_dMemRespQ_enqP_canon(); void RL_dMemRespQ_deqP_canon(); void RL_dMemRespQ_enqEn_canon(); void RL_dMemRespQ_deqEn_canon(); void RL_dMemRespQ_tempData_canon(); void RL_dMemRespQ_tempEnqP_canon(); void RL_dMemRespQ_canonicalize(); void RL_getDResp(); void RL_getIResp(); /* Methods */ public: void METH_iReq(tUWide ARG_iReq_r); tUInt8 METH_RDY_iReq(); tUInt64 METH_iResp(); tUInt8 METH_RDY_iResp(); void METH_dReq(tUWide ARG_dReq_r); tUInt8 METH_RDY_dReq(); tUInt64 METH_dResp(); tUInt8 METH_RDY_dResp(); /* Reset routines */ public: void reset_RST_N(tUInt8 ARG_rst_in); /* Static handles to reset routines */ public: /* Pointers to reset fns in parent module for asserting output resets */ private: /* Functions for the parent module to register its reset fns */ public: /* Functions to set the elaborated clock id */ public: void set_clk_0(char const *s); /* State dumping routine */ public: void dump_state(unsigned int indent); /* VCD dumping routines */ public: unsigned int dump_VCD_defs(unsigned int levels); void dump_VCD(tVCDDumpType dt, unsigned int levels, MOD_mkMemory &backing); void vcd_defs(tVCDDumpType dt, MOD_mkMemory &backing); void vcd_prims(tVCDDumpType dt, MOD_mkMemory &backing); }; #endif /* ifndef __mkMemory_h__ */
[ "hoihoilee@naver.com" ]
hoihoilee@naver.com
37f5da6e72edb016b599c311c918580428ebc1c7
be04d41cc516caec667467787a238e1463b815eb
/src/py/wrapper_7d10a38ead5950acb903ebd8bb882a64.cpp
393d2e5c7924d80ea50ccfe2387898dbf3f7533a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nikhilkalige/ClangLite
9f0db6088dee83f89996d4c01da9979c39b3862c
dcb6d7385cca25c0a888bb56ae3ec1eb951cd752
refs/heads/master
2020-04-21T23:48:28.409657
2019-02-20T08:14:21
2019-02-20T08:14:21
169,958,200
0
0
Apache-2.0
2019-02-10T08:37:14
2019-02-10T08:37:14
null
UTF-8
C++
false
false
1,776
cpp
#include "_clanglite.h" class ::clang::QualType (::clang::DependentSizedExtVectorType::*method_pointer_f91f23f0fd375062ae158b25dcad6834)()const= &::clang::DependentSizedExtVectorType::getElementType; class ::clang::SourceLocation (::clang::DependentSizedExtVectorType::*method_pointer_f8a4f7dead185ec2b8e098f7bd4d6172)()const= &::clang::DependentSizedExtVectorType::getAttributeLoc; bool (::clang::DependentSizedExtVectorType::*method_pointer_137a2faf33fe59a59d5bc6fa22773297)()const= &::clang::DependentSizedExtVectorType::isSugared; class ::clang::QualType (::clang::DependentSizedExtVectorType::*method_pointer_ed6b22c67de15c75bc0fede3c2eb5ac2)()const= &::clang::DependentSizedExtVectorType::desugar; bool (*method_pointer_739102925faa5693a39e5e597c74456a)(class ::clang::Type const *)= ::clang::DependentSizedExtVectorType::classof; namespace autowig { } void wrapper_7d10a38ead5950acb903ebd8bb882a64(pybind11::module& module) { pybind11::class_<class ::clang::DependentSizedExtVectorType, autowig::HolderType< class ::clang::DependentSizedExtVectorType >::Type, class ::clang::Type > class_7d10a38ead5950acb903ebd8bb882a64(module, "DependentSizedExtVectorType", ""); class_7d10a38ead5950acb903ebd8bb882a64.def("get_element_type", method_pointer_f91f23f0fd375062ae158b25dcad6834, ""); class_7d10a38ead5950acb903ebd8bb882a64.def("get_attribute_loc", method_pointer_f8a4f7dead185ec2b8e098f7bd4d6172, ""); class_7d10a38ead5950acb903ebd8bb882a64.def("is_sugared", method_pointer_137a2faf33fe59a59d5bc6fa22773297, ""); class_7d10a38ead5950acb903ebd8bb882a64.def("desugar", method_pointer_ed6b22c67de15c75bc0fede3c2eb5ac2, ""); class_7d10a38ead5950acb903ebd8bb882a64.def_static("classof", method_pointer_739102925faa5693a39e5e597c74456a, ""); }
[ "pfernique@gmail.com" ]
pfernique@gmail.com
1b277710658b01221cd3ecf96a21e56c26a77dba
cde72953df2205c2322aac3debf058bb31d4f5b9
/win10.19042/System32/networkitemfactory.dll.cpp
e4ccfdd425dc7343180d95506f5df14329efdc1c
[]
no_license
v4nyl/dll-exports
928355082725fbb6fcff47cd3ad83b7390c60c5a
4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf
refs/heads/main
2023-03-30T13:49:47.617341
2021-04-10T20:01:34
2021-04-10T20:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
#print comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\System32\\networkitemfactory.dll\"") #print comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\System32\\networkitemfactory.dll\"")
[ "magnus@stubman.eu" ]
magnus@stubman.eu
691f26cb5d698b9e8c4d14232e009e667ed0aef5
54ca8f4a5630c134c688ffee37931ef04d413cc7
/Code/VFDTest_Count/StopWatch.h
024265e5fd5b921caeacba045e9d692c3e16bfb4
[]
no_license
minori24/VFDClock_LD8035
eb860a1322d271fda3a82d910b50847575ff9ba0
81d6d815bb470bf80ccb1897f159497ea6f2800b
refs/heads/master
2022-04-30T11:08:59.053725
2022-04-08T07:39:50
2022-04-08T07:39:50
128,710,756
1
0
null
null
null
null
UTF-8
C++
false
false
951
h
// StopWatch.h // (c) 2018 FabLab Kannai // #ifndef STOP_WATCH_H #define STOP_WATCH_H #include <Arduino.h> #include "VFD.h" typedef uint8_t stat_t; typedef uint8_t mode_t; //====================================================== class StopWatch { public: static const stat_t STAT_STOP = 0x01; static const stat_t STAT_RUNNING = 0x02; static const mode_t MODE_TIME = 0x01; static const mode_t MODE_LAP = 0x02; StopWatch() {}; void init(VFD *vfd); void loop(unsigned long cur_msec); mode_t mode(); void set_mode(mode_t mode); stat_t stat(); void set_stat(stat_t stat); unsigned long time_val(); unsigned long lap_val(); void start(); void stop(); void reset(); void lap(); void setVfd(unsigned long msec, boolean blink); void display(); private: VFD *_vfd; stat_t _stat; mode_t _mode; unsigned long _start_msec; unsigned long _cur_msec; unsigned long _lap_msec; }; #endif
[ "minoritk@outlook.com" ]
minoritk@outlook.com
2c0bb79274e7f043e3ec361bfa11966e51be8cb4
b915b1940cb3f9a4f8b2db231ea73a75ae283513
/Graph/Edge.h
00462b32093cbc7685d83f5d08cda93469e5cb85
[]
no_license
hblee12294/algorithm-prc
bc3259106ec7f4fe30289146d0fa126c038502ef
8ceaa7ac00b619f3be23e2c1dd6d90aa848c0e58
refs/heads/master
2021-06-08T21:12:27.516054
2016-12-03T14:00:02
2016-12-03T14:00:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
285
h
typedef enum { UNDETERMINED, TREE, CROSS, FORWARD, BACKWARD } Estatus; template <typename Tr> struct Edge { Te data; // 数据 int weight; // 权重 Estaus status; // 以上五种状态 Edge(Te const &d, int w) : data(d), weight(w), status(UNDETERMINED) {} }
[ "hblee12294@gmail.com" ]
hblee12294@gmail.com
f4333c809e5013c8de0d65d0c8326e66ea4927a3
4bc239619d4511d4551909d0e4353e71f0b2f439
/Практическое занятие 5/Exercise_4_sln/Exercise_4/Exercise_4.cpp
972a581be6926df2a2d2f42436bf5abb71bb5813
[]
no_license
87053334313/c-
d8f2987a33f014b5ae05938963ea98e5d1303e09
be9dbe9ede40340a60b0336a5913a372c9d3be0c
refs/heads/main
2023-07-03T10:19:13.109791
2021-07-30T15:48:29
2021-07-30T15:48:29
383,513,247
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
 #include <iostream> #include <string> #include <iterator> using namespace std; void MyMass(int mas[], const int size) { int k; cout << "Введи значение в 0 индекс массива"; cin >> k; mas[0] = k; } int main() { system("chcp 1251"); int n; cout << "Введи количество эллементов в массиве"; cin >> n; int* myArray = new int[n]; if (n >= 3) { myArray[0] = 0; myArray[1] = 1; myArray[2] = 2; } MyMass(myArray,n); cout << "\nвесь массив:" << endl;; for (int i = 0; i < n; i++) { cout << myArray[i] << " "; } delete myArray; }
[ "87053334313@mail.ru" ]
87053334313@mail.ru
3c1aec17181fc73649707f035c573bf7a1949131
f55f34c95fc3d28b818565bf8f20f5ee99ebf97f
/main.cpp
bdf91eb89b7774247e7d282e9ef2228d783a348a
[]
no_license
gtier/VoxwellEngine
2ac5c8d54f332d16e8780e89f5749a05f1f66c6f
551de7b04cbd35fa29cecdb632a7d46c93c0157e
refs/heads/master
2023-08-22T11:51:53.341222
2021-09-09T19:22:06
2021-09-09T19:22:06
404,835,601
0
0
null
null
null
null
UTF-8
C++
false
false
2,214
cpp
#include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "VoxwellEngine/VoxwellEngine.h" #include "VoxwellEngine/Shapes/3D/cube.hpp" #include "VoxwellEngine/Voxel.h" #include "VoxwellEngine/Chunk.h" #include "VoxwellEngine/DiscWorld.h" #include "VoxwellEngine/Biome.h" #include "PerlinNoise/PerlinNoise.hpp" #include "VoxwellEngine/Biomes/Overhang.h" #include "VoxwellEngine/Biomes/Mountains.h" #include "VoxwellEngine/Biomes/Desert.h" #include "VoxwellEngine/Biomes/Tunnels.h" int main() { Shader vertex_shader("/Users/griffin/Stanford/LOA/winter/CS 248/final project/VoxwellEngine/shaders/shader.vert"); Shader fragment_shader("/Users/griffin/Stanford/LOA/winter/CS 248/final project/VoxwellEngine/shaders/shader.frag"); VoxwellEngine engine(1280, 720, vertex_shader, fragment_shader); // Voxel v(glm::ivec3(0, 0, 0)); // v.set_visibility(true); // v.render(engine); // Chunk c(glm::ivec3(0, 0, -40), 32, 32, 32); // c.populate(); // c.render(engine); // DiscWorld disc_world(glm::ivec3(0, 0, 0), glm::ivec3(0, 1, 0), 10); // scene 1 start and scene 2 rgb // Overhang overhang(glm::ivec3(0, 0, 0), glm::ivec3(16, 32, 16), glm::ivec2(32, 32)); // overhang.render(engine); // Desert desert1(glm::ivec3((32 * 16), 0, 0), glm::ivec3(16, 64, 16), glm::ivec2(32, 32)); // desert1.render(engine); // Desert desert(glm::ivec3(0, 0, -(32 * 16)), glm::ivec3(16, 64, 16), glm::ivec2(32, 32)); // desert.render(engine); // Tunnels tunnels(glm::ivec3(0, 0, 320), glm::ivec3(256, 256, 256), glm::ivec2(1, 1)); // tunnels.render(engine); //scene 1 end // scene 2 start // Mountains mountains(glm::ivec3(0, 0, 0), glm::ivec3(512, 128, 512), glm::ivec2(1, 1)); // mountains.render(engine); // scene 2 end // Desert desert(glm::ivec3(0, 0, 0), glm::ivec3(16, 64, 16), glm::ivec2(64, 64)); // desert.render(engine); // scene 3 start Tunnels tunnels(glm::ivec3(0, 0, 0), glm::ivec3(256, 256, 256), glm::ivec2(1, 1)); tunnels.render(engine); // scene 3 end engine.start_render_loop(); return 0; }
[ "30325272+gtier@users.noreply.github.com" ]
30325272+gtier@users.noreply.github.com
baeb51b824e10c70876bd3e5aa6b73c7ca5bb119
4b944449775eaf8d9aca1a14aa6ea2de839e3892
/RM2/SRC/EUOPRES.HPP
3e2c1eaca5cd0d17b858c844a75a505baf03be40
[]
no_license
LaurentinoMX/ecfg_br_exe
61446cbb0e4602d722af45265ed8384a34df3ec4
e5237d64894b9f12bfbc8c91881f58e68b482388
refs/heads/master
2020-05-24T21:00:14.784853
2017-03-13T22:33:31
2017-03-13T22:33:31
84,880,574
0
0
null
null
null
null
UTF-8
C++
false
false
3,757
hpp
#ifndef _AB_EUOPRES_HPP_ #define _AB_EUOPRES_HPP_ /*--------------------------------------------------------------------------*\ | File Name : EUOPRES.HPP | | | | Description: | | This file contains the declaration(s) of the following | | class implementation(s): | | | | EUOPResolve - allowing for the retention of the system name | | to be Reconciled by the application with | | methods to | | Open | | Resolve | | Save | | Write | | the System class on which it is based. | | | | The ResMessage class (in EUOUTIL.HPP) allows for the | | formatting of Message File Strings | | | \*--------------------------------------------------------------------------*/ #include <isrtset.h> // ISorted Set edw07/01/1998 #include "system.hpp" // RMSystem class #pragma pack(4) #ifndef UNITTEST class XWindow; class EUOPResolve : public RMSystem ,public ResMessage { XWindow * pW; IString CurrentSystem; protected: Boolean convert(XWindow *, const char * szFile,Boolean fMRDB, IString & strConvertedFile,int version); public: EUOPResolve(XWindow * p) : RMSystem(), pW(p){} ~EUOPResolve(){} Boolean resolveX( const char * AASFile ,const char * MRDBFile ,const char * MRDBDescFile ,const char * MsgStringsFile ,ISortedSet<IString>* pNoCompTable //edw07/01/1998 ,ISortedSet<IString>* pQuickFixTable //49222-MAMT-06/27/2000 ,ISortedSet<IString>* pFeature54Table //53915-MAMT-08/31/2000 ,ISortedSet<IString>* pISeriesSWTable //F72273 -HECC-06/28/2002 ,char * szCompiledFeatFile = 0 ,Boolean fForcePKRead = 0 ,Boolean bS90 = 0 //edw07/01/1998 ,Boolean bAS4 = 0 ); //Include bAS4 flag to reconcile iSeries SW. HECC 72273 06/27/2002 Boolean resolve(const char * AASFile,const char * MRDBFile, const char * MRDBDescFile, const char * MsgStringsFile); Boolean reBuild( const char * szFileName); Boolean writeReport(const char * szFileName,Boolean fAppendRPOs = false,Boolean bSetLockingFlag = false); Boolean save(const char * szFileName); const IString & currentSystem() { return CurrentSystem;} }; #else class EUOPResolve : public RMSystem { public: EUOPResolve() : RMSystem(){} ~EUOPResolve(){} Boolean resolve(const char * AASFile,const char * MRDBFile, const char * MRDBDescFile, const char * MsgStringsFile); Boolean reBuild( const char * szFileName); Boolean writeReport(const char * szFileName); Boolean save(const char * szFileName); }; #endif #pragma pack() #endif
[ "Rickhunter08@gmail.com" ]
Rickhunter08@gmail.com
bca8c3fdb7d15c8e1055f10821264eda7f0cd38e
5ed7bfde1d44b0b400e4771855835ae5d08c7779
/algorithm/55.cpp
59b4b61410575a320fb8c14163f7511427861ab0
[]
no_license
LouYu2015/leetcode
f968ddabef6ce495af70053db2431db4c8248793
89267cb4966299047537ef4056a5ccc78d3e03fa
refs/heads/master
2022-04-09T14:53:21.624401
2020-03-23T05:09:41
2020-03-23T05:11:23
197,881,839
1
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
class Solution { public: bool canJump(vector<int>& nums) { int n = nums.size(); // Edge case: array is empty if (n == 0) { return true; } int min_possible = n - 1; // invariant: min_possible is the first position in nums[i..n-1] that is possible to jump to last position for (int i = n - 2; i >= 0; i--) { if (i + nums[i] >= min_possible) { min_possible = i; } } return min_possible == 0; } };
[ "louyu27@cs.washington.edu" ]
louyu27@cs.washington.edu
6a48a9e63f935715463c69f03cfee34596695180
598ff1c229fe40cae7615bb2929c800bd88ca028
/d01/ex05/Brain.cpp
90c24bdef1da784607c9538a99978189c5c1e27f
[]
no_license
Nick0JIau/CppPool
7bc9d5b527792b06c2751ae94de30e110c97c73c
34cf4d7ce90f9e6c3a4f68ee1a98b6383309619f
refs/heads/master
2020-12-09T06:41:17.147356
2020-01-11T12:11:15
2020-01-11T12:11:15
233,225,673
0
0
null
null
null
null
UTF-8
C++
false
false
1,082
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Brain.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ntrusevi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/30 18:30:13 by ntrusevi #+# #+# */ /* Updated: 2019/09/30 18:30:14 by ntrusevi ### ########.fr */ /* */ /* ************************************************************************** */ #include "Brain.hpp" Brain::Brain() { } Brain::~Brain() { } std::string Brain::identify(void) { std::stringstream str; str << this; return str.str(); }
[ "ntrusevi@e1r5p13.unit.ua" ]
ntrusevi@e1r5p13.unit.ua
69a51ba3dd37189ace3a8453c7926e71436697b9
b8f152f489f4d7baaeaeec80865680ba1fb32ba6
/DataFile/LocalDataFileReader.cpp
256481a7c4e437292e24419565e45f01b19d10ea
[]
no_license
zaqc/host_app
70f8c2d2b666d649fda0a00c13ae01062b5c9a15
4b7ee9fbaa358e8449ac24ccf79300ed47d65802
refs/heads/master
2021-01-24T02:46:17.021313
2017-06-21T16:44:27
2017-06-21T16:44:27
68,363,376
0
0
null
null
null
null
UTF-8
C++
false
false
20,868
cpp
#include "LocalDataFileReader.h" //#include "..\SS_Log\SS_Log.h" #include <iostream> #include <cassert> #include <fcntl.h> #include <sys/stat.h> using namespace DataFile; using std::wstring; using namespace std::placeholders; //#define ROUND_UP_SIZE(Value,Pow2) ((SIZE_T) ((((ULONG)(Value)) + (Pow2) - 1) & (~(((LONG)(Pow2)) - 1)))) //#define ROUND_UP_PTR(Ptr,Pow2) ((void *) ((((ULONG_PTR)(Ptr)) + (Pow2) - 1) & (~(((LONG_PTR)(Pow2)) - 1)))) LocalDataFileReader::LocalDataFileReader(const std::string& aFileName, bool aAutoFix , DataBlocksProc aNewDataBlockProc) : BaseLocalDataFileReader(aFileName, std::bind(&LocalDataFileReader::ProcessNewDataBlock, std::ref(*this), _1)) , m_pfnNewDataBlockProc(aNewDataBlockProc) , m_BrokenBlockListSize(0) { DATAFILEPOS pos{0}; SetFilePos(pos); m_pHeader = new DataFileHeader(false); unsigned long br{0}; ssize_t res = read(m_hFile, m_pHeader, sizeof(DataFileHeader)); if(0 >= res) std::cerr << "Failed to read file header" << std::endl; // ReadFile(m_hFile, m_pHeader, sizeof(DataFileHeader), &br, NULL); if(0 != strncmp(reinterpret_cast<const char*>(m_pHeader->m_Signature), STD_SIGNATURE, strlen(STD_SIGNATURE))) { std::cerr << "Invalid file signature" << std::endl; throw L"Invalid file signature"; } sscanf_s(reinterpret_cast<const char*>(m_pHeader->m_Version), "%d.%d", &m_verMajor, &m_verMinor); if(m_verMajor * 10 + m_verMinor > CUR_VERSION_MAJOR * 10 + CUR_VERSION_MINOR) { std::cout << "Invalid file version. Max supported version 02.00" << std::endl; throw L"Invalid file version. Max supported version 02.00"; } //обработать файл версии 01.00, в заголовке которого отсутствует поле FSpecificData и m_Guid if(1 == m_verMajor && 0 == m_verMinor) { m_pHeader->m_SpecificData = 0; m_pHeader->m_Guid = GUID_NULL; pos = sizeof(DataFileHeader) - sizeof (m_pHeader->m_SpecificData) - sizeof (m_pHeader->m_Guid); SetFilePos(pos); } else if(1 == m_verMajor && 1 == m_verMinor) { m_pHeader->m_SpecificData = 0; m_pHeader->m_Guid = GUID_NULL; pos = sizeof(DataFileHeader) - sizeof (m_pHeader->m_Guid); SetFilePos(pos); } else if(m_verMajor * 10 + m_verMinor < 22) //для версий ниже 2.01 нет TripGuid { m_pHeader->m_TripGuid = GUID_NULL; pos = sizeof(DataFileHeader) - sizeof (m_pHeader->m_TripGuid); SetFilePos(pos); } //для версий ниже 2.0 попытаться прочитать GUID в конце файла if(m_verMajor * 10 + m_verMinor < 20) { const size_t size{4}; char sigGuid[] = {"GUID"}; SetFilePos(GetFileSize() - strlen(sigGuid) - sizeof(GUID)); ssize_t res = read(m_hFile, sigGuid, size); if(size == res && 0 == strncmp(sigGuid, "GUID", size)) { res = read(m_hFile, &m_pHeader->m_Guid, sizeof(GUID)); if(sizeof(GUID) != res) m_pHeader->m_Guid = GUID_NULL; } SetFilePos(pos); } if(GetFileSize() == GetFilePos()) //после заголовка файл заканчивается, значит он пуст return; m_DataType = DataTypeConverter::ToDataType(reinterpret_cast<const char*>(m_pHeader->m_strDataType)); m_BrokenBlockListSize = -1; bool block_list_ok{true}; if(INVALID_DATAFILEPOS != m_pHeader->m_BlockListPos && 0 != m_pHeader->m_BlockListPos/*oldschool*/) { SetFilePos(m_pHeader->m_BlockListPos); if(nullptr != m_pfnNewDataBlockProc) { //std::unique_ptr<DataFileBlockList> dbl = std::make_unique<DataFileBlockList>(); DataFileBlockList *dbl = new DataFileBlockList(); dbl->Read(m_hFile); size_t count = dbl->GetBlockCount(); EnterCriticalSection(&m_lockDataBlockQueue); for(size_t i = 0; i < count; i++) { DataFileBlock* db = dbl->GetBlock(i); m_queDataBlocks.push(new DataFileBlock(*db)); } LeaveCriticalSection(&m_lockDataBlockQueue); if(0 != count) SetEvent(m_hNewDataBlockEvent); delete dbl; } else { LOCK(m_pBlockList); m_pBlockList->Read(m_hFile); DATAFILEPOS oeBlockList = GetFilePos(); DataFileBlock *block = m_pBlockList->GetBlock(m_pBlockList->GetBlockCount() - 1); if(not block) block_list_ok = false; else { //между последним блоком данных и таблице индекса есть пространство, поискать в нем еще блоки if(block->m_FilePosition + sizeof(DataFileBlock) + block->m_ZippedSize < m_pHeader->m_BlockListPos) { DATAFILEPOS eobPos = block->m_FilePosition + sizeof(DataFileBlock) + block->m_ZippedSize; SetFilePos(eobPos); DATAFILEPOS tmp_pos = INVALID_DATAFILEPOS; ssize_t res1 = read(m_hFile, &tmp_pos, sizeof(DATAFILEPOS)); if(tmp_pos == eobPos) //следующее прочитанное число совпадает с тек позицией => это очередной блок { DataFileBlock db; while(tmp_pos == eobPos) { SetFilePos(tmp_pos); ssize_t res2 = read(m_hFile, &db, sizeof(DataFileBlock)); if(block->m_FromFrame + block->m_FrameCount == db.m_FromFrame && db.m_ZippedSize > 0 && db.m_FrameCount > 0) { m_pBlockList->Add(&db); block = m_pBlockList->GetBlock(m_pBlockList->GetBlockCount() - 1); eobPos = block->m_FilePosition + sizeof(DataFileBlock) + block->m_ZippedSize; //попытаемся прочитать после структуры DataFileBlock DATAFILEPOS и если он будет равен предполагаемой позиции начала следующего блока данных //значит дальше идет очередная структура DataFileBlock, иначе двигаемся дальше по данным и вытаскивает DataFileBlock's ssize_t res3 = read(m_hFile, &tmp_pos, sizeof(DATAFILEPOS)); if(0 >= res3 || tmp_pos != eobPos) { SetFilePos(eobPos); ssize_t res4 = read(m_hFile, &db, sizeof(DataFileBlock)); if(0 < res4 && db.m_FilePosition == eobPos) { tmp_pos = eobPos; SetFilePos(eobPos); } } } else { break; } } } else SetFilePos(eobPos); } if(m_pBlockList->FromMF() > m_pBlockList->ToMF() || m_pBlockList->ToMF() > block->m_ToMF) block_list_ok = false; //позиция последнего блока + размер блока + размер структуры блока + размер прочитанного списка блока (с длиной) должна быть равна размеру файла //if(block->m_FilePosition + block->m_ZippedSize + sizeof(DataFileBlock) + sizeof(int) + sizeof(DataFileBlock) * m_pBlockList->GetBlockCount() < GetFileSize()) if(oeBlockList < GetFileSize()) { block_list_ok = false; m_BrokenBlockListSize= m_pBlockList->GetBlockCount(); std::cout << "Файл " << m_FileName << " поврежден, количество блоков " << m_BrokenBlockListSize << ". Проиндексированный размер " << block->m_FilePosition + block->m_ZippedSize << " байт из " << GetFileSize() << " байт. Попытка восстановить..." << std::endl; } //if(block->m_FilePosition + sizeof(DataFileBlock) + block->m_ZippedSize > m_pHeader->m_BlockListPos) // block_list_ok = false; } } } else { block_list_ok = false; } if(!block_list_ok) m_bNeedFix = true; if(m_pHeader->m_MarkerListPos != INVALID_DATAFILEPOS && m_pHeader->m_MarkerListPos != 0 /*oldschool*/) { SetFilePos(m_pHeader->m_MarkerListPos); } if(!block_list_ok && aAutoFix == true) { try { Fix(); } catch(const wchar_t* aError) { std::cerr << "Cannot fix local file. Error " << aError << std::endl; } } } LocalDataFileReader::~LocalDataFileReader() { } bool LocalDataFileReader::Fix() { //assert(0); std::cout << "Run Fix" << std::endl; m_hFile = open(m_FileName.c_str(), O_RDWR | O_LARGEFILE, S_IRWXO); // if(m_hFile == INVALID_HANDLE_VALUE|| !m_pHeader || (strncmp(m_pHeader->m_Signature, STD_SIGNATURE, strlen(STD_SIGNATURE)) != 0)) // throw L"Невозможно вызвать Fix. Файл не открыт или имеет неверный формат"; // // SAFE_CLOSE_HANDLE(m_hFile); // // m_hFile = CreateFileW(m_FileName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); // if(m_hFile == INVALID_HANDLE_VALUE) // { // m_hFile = CreateFileW(m_FileName.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); // if(m_hFile == INVALID_HANDLE_VALUE) // { // wchar_t sError[256] = {}; // wsprintf(sError, L"Не удалось восстановить хендл файла. Ошибка %d", GetLastError()); // throw sError; // } // // wchar_t sError[256] = {}; // wsprintf(sError, L"Не удалось открыть файл в монопольное пользование. Ошибка %d", GetLastError()); // throw sError; // } // LOCK(m_pBlockList); m_pBlockList->Clear(); DATAFILEPOS pos = sizeof(DataFileHeader); // //поддержка старой версии // if(m_verMajor == 1 && m_verMinor == 0) // { // pos -= sizeof(m_pHeader->m_SpecificData); // } // else if(m_verMajor * 10 + m_verMinor < 22) //для версий ниже 2.01 нет TripGuid // { // m_pHeader->m_TripGuid = GUID_NULL; // pos = sizeof(DataFileHeader) - sizeof (m_pHeader->m_TripGuid); // SetFilePos(pos); // } SetFilePos(pos); int from_frame = 0; while(true) { DataFileBlock db; ssize_t res = read(m_hFile, &db, sizeof(DataFileBlock)); if(db.m_FromFrame != from_frame) break; if(!res || res != sizeof(DataFileBlock)) break; pos = db.m_ZippedSize; MoveFilePos(pos); if(nullptr != m_pfnNewDataBlockProc) { EnterCriticalSection(&m_lockDataBlockQueue); m_queDataBlocks.push(new DataFileBlock(db)); SetEvent(m_hNewDataBlockEvent); LeaveCriticalSection(&m_lockDataBlockQueue); } if(db.m_FromMF > db.m_ToMF) //если что-то сглючило при записи, скорректировать мастерфрейм в блоке, пусть блок пропадет,но следующие спасутся db.m_FromMF = db.m_ToMF; m_pBlockList->Add(db); from_frame += db.m_FrameCount; // if(m_pBlockList->GetBlockCount() == static_cast<size_t>(m_BrokenBlockListSize)) // { // Log(L"Успешно прочитано %d блоков. Поиск дополнительного списка блоков", m_BrokenBlockListSize); // DATAFILEPOS save_pos = GetFilePos(); // int count; // ReadFile(m_hFile, &count, sizeof(int), &br, NULL); // if(count > 0 && count < 1000000 /* разумное количество блоков на файл*/) // { // DataFileBlock db; // ReadFile(m_hFile, &db, sizeof(DataFileBlock), &br, NULL); // if(*(m_pBlockList->GetBlock(0)) == db) // { // DataFileBlockList block_list; // SetFilePos(save_pos); // block_list.Read(m_hFile); // if(block_list.GetBlockCount() == static_cast<size_t>(count)) // { // Log(L"Успешно прочитан список из %d блоков. Продолжаем восстановление файла", count); // } // else // { // Log(L"Ошибка чтения списка блоков. Восстановление файла прервано."); // break; // } // } // else // { // Log(L"Найденная последовательноть не явлвяется корректным списком блоков. Восстановление файла прервано."); // break; // } // } // else // { // Log(L"Не найден список блоков в данных. Восстановление файла прервано."); // break; // } // } } // pos = 0; if(m_pBlockList->GetBlockCount() > 0) { //перейти в конец файла и запомнить позицию конца в соответствущем поле заголовка m_pHeader->m_BlockListPos = GetFilePos(); //записать в конец файл таблицу блоков m_pBlockList->Write(m_hFile); SetFilePos(0); unsigned long bw; if(m_verMajor == 1 && m_verMinor == 0) write(m_hFile, m_pHeader, sizeof(DataFileHeader) - sizeof(m_pHeader->m_SpecificData) - sizeof(m_pHeader->m_Guid)); else if(m_verMajor == 1 && m_verMinor == 1) write(m_hFile, m_pHeader, sizeof(DataFileHeader) - sizeof(m_pHeader->m_SpecificData)); else if(m_verMajor * 10 + m_verMinor < 22) //для версий ниже 2.01 нет TripGuid write(m_hFile, m_pHeader, sizeof(DataFileHeader) - sizeof(m_pHeader->m_TripGuid)); else write(m_hFile, m_pHeader, sizeof(DataFileHeader)); m_bNeedFix = false; } close(m_hFile); // // m_hFile = CreateFileW(m_FileName.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); // if(m_hFile == INVALID_HANDLE_VALUE) // { // wchar_t sError[256] = {}; // wsprintf(sError, L"Не удалось восстановить хендл файла. Ошибка %d", GetLastError()); // throw sError; // } // return !m_bNeedFix; } BaseDataFileReader* LocalDataFileReader::MakeNewInstance(void) { return new LocalDataFileReader(m_FileName); } bool LocalDataFileReader::NeedFix() const { return m_bNeedFix; } bool LocalDataFileReader::TestFileUnbuffered(const std::string& aFileName, int* pTripID, DataType* pDT, int64_t* pFileSize) { assert(0); return false; // STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR AlignmentDescriptor; // std::wstring drive = HelperFunctions::String::Format(L"\\\\.\\%s", HelperFunctions::File::GetDriveLetter(aFileName).c_str()); // if (HelperFunctions::File::DetectSectorSize(const_cast<WCHAR*>(drive.c_str()), &AlignmentDescriptor) != NO_ERROR) // return false; // HANDLE hFile = CreateFileW(aFileName.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, // OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, 0); // if (INVALID_HANDLE_VALUE == hFile) // return false; // // size_t Size = ROUND_UP_SIZE(sizeof(DataFileHeader), AlignmentDescriptor.BytesPerPhysicalSector); // size_t SizeNeeded = AlignmentDescriptor.BytesPerPhysicalSector + Size; // char* pBuffer = new char[SizeNeeded]; // // Actual alignment happens here. // void *pBufferAligned = ROUND_UP_PTR(pBuffer, AlignmentDescriptor.BytesPerPhysicalSector); // LARGE_INTEGER pos; // GetFileSizeEx(hFile, &pos); // if (pFileSize) // *pFileSize = pos.QuadPart; // //если файл не содержит данных кроме заголовка, считаем его невалидным // bool bValidSize = (pos.QuadPart > sizeof(DataFile::DataFileHeader)); // pos.QuadPart = 0; // SetFilePointerEx(hFile, pos, NULL, FILE_BEGIN); // unsigned long br; // ReadFile(hFile, pBufferAligned, Size, &br, NULL); // DataFileHeader* pHeader = reinterpret_cast<DataFileHeader*>(pBufferAligned); // // if (strncmp(pHeader->m_Signature, STD_SIGNATURE, strlen(STD_SIGNATURE)) != 0) // { // SAFE_CLOSE_HANDLE(hFile); // SAFE_ARRAY_DELETE(pBuffer); // return false; // } // int major = 0, minor = 0; // char strVer[HDR_VERSION_SIZE + 1]; //Access violation can occur in sscanf_s(pHeader->m_Version, "%d.%d", &major, &minor); // memset(strVer, 0, HDR_VERSION_SIZE + 1); // strncpy(strVer, pHeader->m_Version, HDR_VERSION_SIZE); // sscanf_s(strVer, "%d.%d", &major, &minor); // // //Неподдерживаемая версия // if (major * 10 + minor > CUR_VERSION_MAJOR * 10 + CUR_VERSION_MINOR) // { // SAFE_CLOSE_HANDLE(hFile); // SAFE_ARRAY_DELETE(pBuffer); // return false; // } // if (pDT) // *pDT = DataTypeConverter::ToDataType(pHeader->m_strDataType); // if (pTripID) // *pTripID = pHeader->m_TripID; // SAFE_CLOSE_HANDLE(hFile); // SAFE_ARRAY_DELETE(pBuffer); // return bValidSize; } bool LocalDataFileReader::TestFile(const std::string& aFileName, int* pTripID, DataType* pDT, MASTERFRAME* pFromMF, MASTERFRAME* pToMF, int64_t* pFileSize, GUID* pGuid) { assert(0); return true; // // if(pFromMF) // *pFromMF = INVALID_MASTERFRAME; // if(pToMF) // *pToMF = INVALID_MASTERFRAME; // if(pDT) // *pDT = dtNONE; // if(pTripID) // *pTripID = -1; // if(pFileSize) // *pFileSize = -1; // if(pGuid) // *pGuid = GUID_NULL; // if (!pFromMF && !pToMF && !pGuid) // return TestFileUnbuffered(aFileName, pTripID, pDT, pFileSize); // HANDLE hFile = CreateFileW(aFileName.c_str(), GENERIC_READ /*| GENERIC_WRITE*/, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, // OPEN_EXISTING, 0, 0); // if(INVALID_HANDLE_VALUE == hFile) // { // return false; // } // LARGE_INTEGER pos; // GetFileSizeEx(hFile, &pos); // if(pFileSize) // *pFileSize = pos.QuadPart; // //если файл не содержит данных кроме заголовка, считаем его невалидным // bool bValidSize = (pos.QuadPart > sizeof(DataFile::DataFileHeader)); // pos.QuadPart = 0; // SetFilePointerEx(hFile, pos, NULL, FILE_BEGIN); // DataFileHeader fh(false); // unsigned long br; // ReadFile(hFile, &fh, sizeof(DataFileHeader), &br, NULL); // if(strncmp(fh.m_Signature, STD_SIGNATURE, strlen(STD_SIGNATURE)) != 0) // { // SAFE_CLOSE_HANDLE(hFile); // return false; // } // int major = 0, minor = 0; // char strVer[HDR_VERSION_SIZE + 1]; //Access violation can occur in sscanf_s(pHeader->m_Version, "%d.%d", &major, &minor); // memset(strVer, 0, HDR_VERSION_SIZE + 1); // strncpy(strVer, fh.m_Version, HDR_VERSION_SIZE); // sscanf_s(strVer, "%d.%d", &major, &minor); // // //Неподдерживаемая версия // if(major * 10 + minor > CUR_VERSION_MAJOR * 10 + CUR_VERSION_MINOR ) // { // SAFE_CLOSE_HANDLE(hFile); // return false; // } // // //обработать файл версии 01.00, в заголовке которого отсутствует поле FSpecificData и m_Guid // if(major == 1 && minor == 0) // { // fh.m_SpecificData = 0; // fh.m_Guid = GUID_NULL; // pos.QuadPart = sizeof(DataFileHeader) - sizeof (fh.m_SpecificData) - sizeof (fh.m_Guid); // SetFilePointerEx(hFile, pos, NULL, FILE_BEGIN); // } // //обработать файл версии 01.01, в заголовке которого отсутствует поле m_Guid // if(major == 1 && minor == 1) // { // fh.m_Guid = GUID_NULL; // pos.QuadPart = sizeof(DataFileHeader) - sizeof (fh.m_Guid); // SetFilePointerEx(hFile, pos, NULL, FILE_BEGIN); // } // //для версий ниже 2.0 попытаться прочитать GUID в конце файла // if(major * 10 + minor < 20) // { // char sigGuid [] = "GUID"; // LARGE_INTEGER newpos; // newpos.QuadPart = HelperFunctions::File::GetFileSize(aFileName) - strlen(sigGuid) - sizeof(GUID); // SetFilePointerEx(hFile, newpos, NULL, FILE_BEGIN); // DWORD br; // ReadFile(hFile, sigGuid, 4, &br, NULL); // if(br == 4 && strncmp(sigGuid, "GUID", 4) == 0) // { // ReadFile(hFile, &fh.m_Guid, sizeof(GUID), &br, NULL); // if(br != sizeof(GUID)) // fh.m_Guid = GUID_NULL; // } // SetFilePointerEx(hFile, pos, NULL, FILE_BEGIN); // } // // if(pDT) // *pDT = DataTypeConverter::ToDataType(fh.m_strDataType); // if(pTripID) // *pTripID = fh.m_TripID; // if(pGuid) // *pGuid = fh.m_Guid; // bool block_list_ok = true; // if((fh.m_BlockListPos != INVALID_DATAFILEPOS && fh.m_BlockListPos != 0/*oldschool*/) && (pFromMF || pToMF)) //если ни pToMF, pFromMF не указаны, то не читаем блоки // { // pos.QuadPart = fh.m_BlockListPos; // SetFilePointerEx(hFile, pos, NULL, FILE_BEGIN); // DataFileBlockList bl; // bl.Read(hFile); // if(pFromMF) // *pFromMF = bl.FromMF(); // if(pToMF) // *pToMF = bl.ToMF(); // } // SAFE_CLOSE_HANDLE(hFile); // return bValidSize; } void LocalDataFileReader::ProcessNewDataBlock(DataFileBlock* aDataBlock) { std::vector<DataFileBlock*> datablocks; datablocks.push_back(aDataBlock); EnterCriticalSection(&m_lockDataBlockQueue); while(!m_queDataBlocks.empty()) { datablocks.push_back(m_queDataBlocks.front()); m_queDataBlocks.pop(); } LeaveCriticalSection(&m_lockDataBlockQueue); if(nullptr != m_pfnNewDataBlockProc) m_pfnNewDataBlockProc(datablocks); }
[ "melan81@gmail.com" ]
melan81@gmail.com
e46bccf55dd3c85574d85cf5318be6b88aadc0be
ebf7d1450fe2f230631e031662e0fd5edb57a7a8
/TrbModelConverter/XUI.h
24d0e1ca4dde560423fec473cb917c527338dbb8
[]
no_license
AdventureT/TrbModelConverter
c8bdf3af6261d85e9ff94c18e53d8d28884c15dc
a8db67fa582e2bc903424bd0567e202b1e14216f
refs/heads/master
2022-06-14T20:31:41.447123
2020-05-11T12:02:04
2020-05-11T12:02:04
254,840,718
2
1
null
null
null
null
UTF-8
C++
false
false
158
h
#pragma once #include <cstdint> #include <string> struct XUI { uint32_t zero; union FileName { uint32_t fileNameOffset; std::string fileName; }; };
[ "le@nepelius.at" ]
le@nepelius.at
5302543318347cba86e0bbf7654685422902a243
e985dc956df5965b2ba2230a4f06489ac7cf2937
/include/GL/glui.h
9939c0c7df8d24b69181f7140aa413730cfb9fcf
[]
no_license
olawlor/directcompression
883cca902bf0e6f5310612c3789ee145273f83cd
97ba4e71115130e017b803bbf217e4d1208848e8
refs/heads/master
2020-03-26T07:28:27.711206
2018-08-10T22:06:40
2018-08-10T22:06:40
144,656,234
0
0
null
null
null
null
UTF-8
C++
false
false
96,039
h
/**************************************************************************** GLUI User Interface Toolkit (LGPL) ---------------------------------- glui.h - Main (and only) external header for GLUI User Interface Toolkit -------------------------------------------------- Copyright (c) 1998 Paul Rademacher WWW: http://sourceforge.net/projects/glui/ Forums: http://sourceforge.net/forum/?group_id=92496 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *****************************************************************************/ #ifndef GLUI_GLUI_H #define GLUI_GLUI_H #define GLUI_NO_LIB_PRAGMA /* static linking on Windows */ #if defined(GLUI_FREEGLUT) // FreeGLUT does not yet work perfectly with GLUI // - use at your own risk. #include <GL/freeglut.h> #elif defined(GLUI_OPENGLUT) // OpenGLUT does not yet work properly with GLUI // - use at your own risk. #include <GL/openglut.h> #else #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #endif #include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <vector> #define GLUI_VERSION 2.3f /********** Current version **********/ #if defined(_WIN32) #if !defined(GLUI_NO_LIB_PRAGMA) #pragma comment(lib, "glui32.lib") // Link automatically with GLUI library #endif #endif /********** Do some basic defines *******/ typedef unsigned char Byte; #ifndef _RGBC_ class RGBc { public: Byte r, g, b; void set(Byte r,Byte g,Byte b) {this->r=r;this->g=g;this->b=b;} RGBc( void ) {} RGBc( Byte r, Byte g, Byte b ) { set( r, g, b ); } }; #define _RGBC_ #endif /********** List of GLUT callbacks ********/ enum GLUI_Glut_CB_Types { GLUI_GLUT_RESHAPE, GLUI_GLUT_KEYBOARD, GLUI_GLUT_DISPLAY, GLUI_GLUT_MOUSE, GLUI_GLUT_MOTION, GLUI_GLUT_SPECIAL, GLUI_GLUT_PASSIVE_MOTION, GLUI_GLUT_ENTRY, GLUI_GLUT_VISIBILITY }; /********* Constants for window placement **********/ #define GLUI_XOFF 6 #define GLUI_YOFF 6 #define GLUI_ITEMSPACING 3 #define GLUI_CHECKBOX_SIZE 13 #define GLUI_RADIOBUTTON_SIZE 13 #define GLUI_BUTTON_SIZE 20 #define GLUI_STATICTEXT_SIZE 13 #define GLUI_SEPARATOR_HEIGHT 8 #define GLUI_DEFAULT_CONTROL_WIDTH 100 #define GLUI_DEFAULT_CONTROL_HEIGHT 13 #define GLUI_EDITTEXT_BOXINNERMARGINX 3 #define GLUI_EDITTEXT_HEIGHT 20 #define GLUI_EDITTEXT_WIDTH 130 #define GLUI_EDITTEXT_MIN_INT_WIDTH 35 #define GLUI_EDITTEXT_MIN_TEXT_WIDTH 50 #define GLUI_PANEL_NAME_DROP 8 #define GLUI_PANEL_EMBOSS_TOP 4 /* #define GLUI_ROTATION_WIDTH 60 */ /* #define GLUI_ROTATION_HEIGHT 78 */ #define GLUI_ROTATION_WIDTH 50 #define GLUI_ROTATION_HEIGHT (GLUI_ROTATION_WIDTH+18) #define GLUI_MOUSE_INTERACTION_WIDTH 50 #define GLUI_MOUSE_INTERACTION_HEIGHT (GLUI_MOUSE_INTERACTION_WIDTH)+18 /** Different panel control types **/ #define GLUI_PANEL_NONE 0 #define GLUI_PANEL_EMBOSSED 1 #define GLUI_PANEL_RAISED 2 /** Max # of els in control's float_array **/ #define GLUI_DEF_MAX_ARRAY 30 /********* The control's 'active' behavior *********/ #define GLUI_CONTROL_ACTIVE_MOUSEDOWN 1 #define GLUI_CONTROL_ACTIVE_PERMANENT 2 /********* Control alignment types **********/ #define GLUI_ALIGN_CENTER 1 #define GLUI_ALIGN_RIGHT 2 #define GLUI_ALIGN_LEFT 3 /********** Limit types - how to limit spinner values *********/ #define GLUI_LIMIT_NONE 0 #define GLUI_LIMIT_CLAMP 1 #define GLUI_LIMIT_WRAP 2 /********** Translation control types ********************/ #define GLUI_TRANSLATION_XY 0 #define GLUI_TRANSLATION_Z 1 #define GLUI_TRANSLATION_X 2 #define GLUI_TRANSLATION_Y 3 #define GLUI_TRANSLATION_LOCK_NONE 0 #define GLUI_TRANSLATION_LOCK_X 1 #define GLUI_TRANSLATION_LOCK_Y 2 /********** How was a control activated? *****************/ #define GLUI_ACTIVATE_MOUSE 1 #define GLUI_ACTIVATE_TAB 2 /********** What type of live variable does a control have? **********/ #define GLUI_LIVE_NONE 0 #define GLUI_LIVE_INT 1 #define GLUI_LIVE_FLOAT 2 #define GLUI_LIVE_TEXT 3 #define GLUI_LIVE_STRING 6 #define GLUI_LIVE_DOUBLE 4 #define GLUI_LIVE_FLOAT_ARRAY 5 /************* Textbox and List Defaults - JVK ******************/ #define GLUI_TEXTBOX_HEIGHT 130 #define GLUI_TEXTBOX_WIDTH 130 #define GLUI_LIST_HEIGHT 130 #define GLUI_LIST_WIDTH 130 #define GLUI_DOUBLE_CLICK 1 #define GLUI_SINGLE_CLICK 0 #define GLUI_TAB_WIDTH 50 /* In pixels */ #define GLUI_TEXTBOX_BOXINNERMARGINX 3 #define GLUI_TEXTBOX_MIN_TEXT_WIDTH 50 #define GLUI_LIST_BOXINNERMARGINX 3 #define GLUI_LIST_MIN_TEXT_WIDTH 50 /*********************** TreePanel Defaults - JVK *****************************/ #define GLUI_TREEPANEL_DEFAULTS 0 // bar, standard bar color #define GLUI_TREEPANEL_ALTERNATE_COLOR 1 // Alternate between 8 different bar colors #define GLUI_TREEPANEL_ENABLE_BAR 2 // enable the bar #define GLUI_TREEPANEL_DISABLE_BAR 4 // disable the bar #define GLUI_TREEPANEL_DISABLE_DEEPEST_BAR 8 // disable only the deepest bar #define GLUI_TREEPANEL_CONNECT_CHILDREN_ONLY 16 // disable only the bar of the last child of each root #define GLUI_TREEPANEL_DISPLAY_HIERARCHY 32 // display some sort of hierachy in the tree node title #define GLUI_TREEPANEL_HIERARCHY_NUMERICDOT 64 // display hierarchy in 1.3.2 (etc... ) format #define GLUI_TREEPANEL_HIERARCHY_LEVEL_ONLY 128 // display hierarchy as only the level depth /******************* GLUI Scrollbar Defaults - JVK ***************************/ #define GLUI_SCROLL_ARROW_WIDTH 16 #define GLUI_SCROLL_ARROW_HEIGHT 16 #define GLUI_SCROLL_BOX_MIN_HEIGHT 5 #define GLUI_SCROLL_BOX_STD_HEIGHT 16 #define GLUI_SCROLL_STATE_NONE 0 #define GLUI_SCROLL_STATE_UP 1 #define GLUI_SCROLL_STATE_DOWN 2 #define GLUI_SCROLL_STATE_BOTH 3 #define GLUI_SCROLL_STATE_SCROLL 4 #define GLUI_SCROLL_DEFAULT_GROWTH_EXP 1.05f #define GLUI_SCROLL_VERTICAL 0 #define GLUI_SCROLL_HORIZONTAL 1 /** Size of the character width hash table for faster lookups. Make sure to keep this a power of two to avoid the slow divide. This is also a speed/memory tradeoff; 128 is enough for low ASCII. */ #define CHAR_WIDTH_HASH_SIZE 128 /********** Translation codes **********/ enum TranslationCodes { GLUI_TRANSLATION_MOUSE_NONE = 0, GLUI_TRANSLATION_MOUSE_UP, GLUI_TRANSLATION_MOUSE_DOWN, GLUI_TRANSLATION_MOUSE_LEFT, GLUI_TRANSLATION_MOUSE_RIGHT, GLUI_TRANSLATION_MOUSE_UP_LEFT, GLUI_TRANSLATION_MOUSE_UP_RIGHT, GLUI_TRANSLATION_MOUSE_DOWN_LEFT, GLUI_TRANSLATION_MOUSE_DOWN_RIGHT }; /************ A string type for us to use **********/ typedef std::string GLUI_String; GLUI_String& glui_format_str(GLUI_String &str, const char* fmt, ...); /********* Pre-declare classes as needed *********/ class GLUI; class GLUI_Control; class GLUI_Listbox; class GLUI_StaticText; class GLUI_EditText; class GLUI_Panel; class GLUI_Spinner; class GLUI_RadioButton; class GLUI_RadioGroup; class GLUI_Glut_Window; class GLUI_TreePanel; class GLUI_Scrollbar; class GLUI_List; class Arcball; /*** Flags for GLUI class constructor ***/ #define GLUI_SUBWINDOW ((long)(1<<1)) #define GLUI_SUBWINDOW_TOP ((long)(1<<2)) #define GLUI_SUBWINDOW_BOTTOM ((long)(1<<3)) #define GLUI_SUBWINDOW_LEFT ((long)(1<<4)) #define GLUI_SUBWINDOW_RIGHT ((long)(1<<5)) /*** Codes for different type of edittext boxes and spinners ***/ #define GLUI_EDITTEXT_TEXT 1 #define GLUI_EDITTEXT_INT 2 #define GLUI_EDITTEXT_FLOAT 3 #define GLUI_SPINNER_INT GLUI_EDITTEXT_INT #define GLUI_SPINNER_FLOAT GLUI_EDITTEXT_FLOAT #define GLUI_SCROLL_INT GLUI_EDITTEXT_INT #define GLUI_SCROLL_FLOAT GLUI_EDITTEXT_FLOAT // This is only for deprecated interface #define GLUI_EDITTEXT_STRING 4 /*** Definition of callbacks ***/ typedef void (*GLUI_Update_CB) (int id); typedef void (*GLUI_Control_CB)(GLUI_Control *); typedef void (*Int1_CB) (int); typedef void (*Int2_CB) (int, int); typedef void (*Int3_CB) (int, int, int); typedef void (*Int4_CB) (int, int, int, int); /************************************************************/ /** Callback Adapter Class Allows us to support different types of callbacks; like a GLUI_Update_CB function pointer--which takes an int; and a GLUI_Control_CB function pointer--which takes a GUI_Control object. */ class GLUI_CB { public: GLUI_CB() : idCB(0),objCB(0) {} GLUI_CB(GLUI_Update_CB cb) : idCB(cb),objCB(0) {} GLUI_CB(GLUI_Control_CB cb) : idCB(0),objCB(cb) {} // (Compiler generated copy constructor) /** This control just activated. Fire our callback.*/ void operator()(GLUI_Control *ctrl) const; bool operator!() const { return !idCB && !objCB; } operator bool() const { return !(!(*this)); } private: GLUI_Update_CB idCB; GLUI_Control_CB objCB; }; /************************************************************/ /* */ /* Base class, for hierarchical relationships */ /* */ /************************************************************/ class GLUI_Control; /** GLUI_Node is a node in a sort of tree of GLUI controls. Each GLUI_Node has a list of siblings (in a circular list) and a linked list of children. Everything onscreen is a GLUI_Node--windows, buttons, etc. The nodes are traversed for event processing, sizing, redraws, etc. */ class GLUI_Node { friend class GLUI_Tree; /* JVK */ friend class GLUI_Rollout; friend class GLUI_Main; public: GLUI_Node(); virtual ~GLUI_Node() {} GLUI_Node *first_sibling(); GLUI_Node *last_sibling(); GLUI_Node *prev(); GLUI_Node *next(); GLUI_Node *first_child() { return child_head; } GLUI_Node *last_child() { return child_tail; } GLUI_Node *parent() { return parent_node; } /** Link in a new child control */ virtual int add_control( GLUI_Control *control ); void link_this_to_parent_last (GLUI_Node *parent ); void link_this_to_parent_first(GLUI_Node *parent ); void link_this_to_sibling_next(GLUI_Node *sibling ); void link_this_to_sibling_prev(GLUI_Node *sibling ); void unlink(); void dump( FILE *out, const char *name ); protected: static void add_child_to_control(GLUI_Node *parent,GLUI_Control *child); GLUI_Node *parent_node; GLUI_Node *child_head; GLUI_Node *child_tail; GLUI_Node *next_sibling; GLUI_Node *prev_sibling; }; /************************************************************/ /* */ /* Standard Bitmap stuff */ /* */ /************************************************************/ enum GLUI_StdBitmaps_Codes { GLUI_STDBITMAP_CHECKBOX_OFF = 0, GLUI_STDBITMAP_CHECKBOX_ON, GLUI_STDBITMAP_RADIOBUTTON_OFF, GLUI_STDBITMAP_RADIOBUTTON_ON, GLUI_STDBITMAP_UP_ARROW, GLUI_STDBITMAP_DOWN_ARROW, GLUI_STDBITMAP_LEFT_ARROW, GLUI_STDBITMAP_RIGHT_ARROW, GLUI_STDBITMAP_SPINNER_UP_OFF, GLUI_STDBITMAP_SPINNER_UP_ON, GLUI_STDBITMAP_SPINNER_DOWN_OFF, GLUI_STDBITMAP_SPINNER_DOWN_ON, GLUI_STDBITMAP_CHECKBOX_OFF_DIS, /*** Disactivated control bitmaps ***/ GLUI_STDBITMAP_CHECKBOX_ON_DIS, GLUI_STDBITMAP_RADIOBUTTON_OFF_DIS, GLUI_STDBITMAP_RADIOBUTTON_ON_DIS, GLUI_STDBITMAP_SPINNER_UP_DIS, GLUI_STDBITMAP_SPINNER_DOWN_DIS, GLUI_STDBITMAP_LISTBOX_UP, GLUI_STDBITMAP_LISTBOX_DOWN, GLUI_STDBITMAP_LISTBOX_UP_DIS, GLUI_STDBITMAP_NUM_ITEMS }; /************************************************************/ /* */ /* Class GLUI_Bitmap */ /* */ /************************************************************/ /** GLUI_Bitmap is a simple 2D texture map. It's used to represent small textures like checkboxes, arrows, etc. via the GLUI_StdBitmaps class. */ class GLUI_Bitmap { friend class GLUI_StdBitmaps; public: GLUI_Bitmap(); ~GLUI_Bitmap(); /** Create bitmap from greyscale byte image */ void init_grey(unsigned char *array); /** Create bitmap from color int image */ void init(int *array); private: /** RGB pixel data */ unsigned char *pixels; int w, h; }; /************************************************************/ /* */ /* Class GLUI_StdBitmap */ /* */ /************************************************************/ /** Keeps an array of GLUI_Bitmap objects to represent all the images used in the UI: checkboxes, arrows, etc. */ class GLUI_StdBitmaps { public: GLUI_StdBitmaps(); ~GLUI_StdBitmaps(); /** Return the width (in pixels) of the n'th standard bitmap. */ int width (int n) const; /** Return the height (in pixels) of the n'th standard bitmap. */ int height(int n) const; /** Draw the n'th standard bitmap (one of the enums listed in GLUI_StdBitmaps_Codes) at pixel corner (x,y). */ void draw(int n, int x, int y) const; private: GLUI_Bitmap bitmaps[GLUI_STDBITMAP_NUM_ITEMS]; }; /************************************************************/ /* */ /* Master GLUI Class */ /* */ /************************************************************/ /** The master manages our interaction with GLUT. There's only one GLUI_Master_Object. */ class GLUI_Master_Object { friend void glui_idle_func(); public: GLUI_Master_Object(); ~GLUI_Master_Object(); GLUI_Node gluis; GLUI_Control *active_control, *curr_left_button_glut_menu; GLUI *active_control_glui; int glui_id_counter; GLUI_Glut_Window *find_glut_window( int window_id ); void set_glutIdleFunc(void (*f)(void)); /************** void (*glut_keyboard_CB)(unsigned char, int, int); void (*glut_reshape_CB)(int, int); void (*glut_special_CB)(int, int, int); void (*glut_mouse_CB)(int,int,int,int); void (*glut_passive_motion_CB)(int,int); void (*glut_visibility_CB)(int); void (*glut_motion_CB)(int,int); void (*glut_display_CB)(void); void (*glut_entry_CB)(int); **********/ void set_left_button_glut_menu_control( GLUI_Control *control ); /********** GLUT callthroughs **********/ /* These are the glut callbacks that we do not handle */ void set_glutReshapeFunc (void (*f)(int width, int height)); void set_glutKeyboardFunc(void (*f)(unsigned char key, int x, int y)); void set_glutSpecialFunc (void (*f)(int key, int x, int y)); void set_glutMouseFunc (void (*f)(int, int, int, int )); void set_glutDisplayFunc(void (*f)(void)) {glutDisplayFunc(f);} void set_glutTimerFunc(unsigned int millis, void (*f)(int value), int value) { ::glutTimerFunc(millis,f,value);} void set_glutOverlayDisplayFunc(void(*f)(void)){glutOverlayDisplayFunc(f);} void set_glutSpaceballMotionFunc(Int3_CB f) {glutSpaceballMotionFunc(f);} void set_glutSpaceballRotateFunc(Int3_CB f) {glutSpaceballRotateFunc(f);} void set_glutSpaceballButtonFunc(Int2_CB f) {glutSpaceballButtonFunc(f);} void set_glutTabletMotionFunc(Int2_CB f) {glutTabletMotionFunc(f);} void set_glutTabletButtonFunc(Int4_CB f) {glutTabletButtonFunc(f);} /* void set_glutWindowStatusFunc(Int1_CB f) {glutWindowStatusFunc(f);} */ void set_glutMenuStatusFunc(Int3_CB f) {glutMenuStatusFunc(f);} void set_glutMenuStateFunc(Int1_CB f) {glutMenuStateFunc(f);} void set_glutButtonBoxFunc(Int2_CB f) {glutButtonBoxFunc(f);} void set_glutDialsFunc(Int2_CB f) {glutDialsFunc(f);} GLUI *create_glui( const char *name, long flags=0, int x=-1, int y=-1 ); GLUI *create_glui_subwindow( int parent_window, long flags=0 ); GLUI *find_glui_by_window_id( int window_id ); void get_viewport_area( int *x, int *y, int *w, int *h ); void auto_set_viewport(); void close_all(); void sync_live_all(); void reshape(); float get_version() { return GLUI_VERSION; } void glui_setIdleFuncIfNecessary(void); private: GLUI_Node glut_windows; void (*glut_idle_CB)(void); void add_cb_to_glut_window(int window,int cb_type,void *cb); }; /** This is the only GLUI_Master_Object in existence. */ extern GLUI_Master_Object GLUI_Master; /************************************************************/ /* */ /* Class for managing a GLUT window */ /* */ /************************************************************/ /** A top-level window. The GLUI_Master GLUT callback can route events to the callbacks in this class, for arbitrary use by external users. (see GLUI_Master_Object::set_glutKeyboardFunc). This entire approach seems to be superceded by the "subwindow" flavor of GLUI. */ class GLUI_Glut_Window : public GLUI_Node { public: GLUI_Glut_Window(); int glut_window_id; /*********** Pointers to GLUT callthrough functions *****/ void (*glut_keyboard_CB)(unsigned char, int, int); void (*glut_special_CB)(int, int, int); void (*glut_reshape_CB)(int, int); void (*glut_passive_motion_CB)(int,int); void (*glut_mouse_CB)(int,int,int,int); void (*glut_visibility_CB)(int); void (*glut_motion_CB)(int,int); void (*glut_display_CB)(void); void (*glut_entry_CB)(int); }; /************************************************************/ /* */ /* Main Window GLUI class (not user-level) */ /* */ /************************************************************/ /** A GLUI_Main handles GLUT events for one window, routing them to the appropriate controls. The central user-visible "GLUI" class inherits from this class; users should not allocate GLUT_Main objects. There's a separate GLUI_Main object for: - Each top-level window with GUI stuff in it. - Each "subwindow" of another top-level window. All the GLUI_Main objects are listed in GLUI_Master.gluis. A better name for this class might be "GLUI_Environment"; this class provides the window-level context for every control. */ class GLUI_Main : public GLUI_Node { /********** Friend classes *************/ friend class GLUI_Control; friend class GLUI_Rotation; friend class GLUI_Translation; friend class GLUI; friend class GLUI_Master_Object; /*********** Friend functions **********/ friend void glui_mouse_func(int button, int state, int x, int y); friend void glui_keyboard_func(unsigned char key, int x, int y); friend void glui_special_func(int key, int x, int y); friend void glui_passive_motion_func(int x, int y); friend void glui_reshape_func( int w, int h ); friend void glui_visibility_func(int state); friend void glui_motion_func(int x, int y); friend void glui_entry_func(int state); friend void glui_display_func( void ); friend void glui_idle_func(void); friend void glui_parent_window_reshape_func( int w, int h ); friend void glui_parent_window_keyboard_func( unsigned char, int, int ); friend void glui_parent_window_special_func( int, int, int ); friend void glui_parent_window_mouse_func( int, int, int, int ); protected: /*** Variables ***/ int main_gfx_window_id; int mouse_button_down; int glut_window_id; int top_level_glut_window_id; GLUI_Control *active_control; GLUI_Control *mouse_over_control; GLUI_Panel *main_panel; enum buffer_mode_t { buffer_front=1, ///< Draw updated controls directly to screen. buffer_back=2 ///< Double buffering: postpone updates until next redraw. }; buffer_mode_t buffer_mode; ///< Current drawing mode int curr_cursor; int w, h; long flags; bool closing; int parent_window; int glui_id; /********** Misc functions *************/ public: GLUI_Control *find_control( int x, int y ); protected: GLUI_Control *find_next_control( GLUI_Control *control ); GLUI_Control *find_next_control_rec( GLUI_Control *control ); GLUI_Control *find_next_control_( GLUI_Control *control ); GLUI_Control *find_prev_control( GLUI_Control *control ); void create_standalone_window( const char *name, int x=-1, int y=-1 ); void create_subwindow( int parent,int window_alignment ); void setup_default_glut_callbacks( void ); void mouse(int button, int state, int x, int y); void keyboard(unsigned char key, int x, int y); void special(int key, int x, int y); void passive_motion(int x, int y); void reshape( int w, int h ); void visibility(int state); void motion(int x, int y); void entry(int state); void display( void ); void idle(void); int needs_idle(void); void (*glut_mouse_CB)(int, int, int, int); void (*glut_keyboard_CB)(unsigned char, int, int); void (*glut_special_CB)(int, int, int); void (*glut_reshape_CB)(int, int); /*********** Controls ************/ virtual int add_control( GLUI_Node *parent, GLUI_Control *control ); /********** Constructors and Destructors ***********/ GLUI_Main( void ); public: GLUI_StdBitmaps std_bitmaps; GLUI_String window_name; RGBc bkgd_color; float bkgd_color_f[3]; void *font; int curr_modifiers; void adjust_glut_xy( int &x, int &y ) { y = h-y; } void activate_control( GLUI_Control *control, int how ); void align_controls( GLUI_Control *control ); void deactivate_current_control( void ); /** Draw a 3D-look pushed-out box around this rectangle */ void draw_raised_box( int x, int y, int w, int h ); /** Draw a 3D-look pushed-in box around this rectangle */ void draw_lowered_box( int x, int y, int w, int h ); /** Return true if this control should redraw itself immediately (front buffer); Or queue up a redraw and return false if it shouldn't (back buffer). */ bool should_redraw_now(GLUI_Control *ctl); /** Switch to the appropriate draw buffer now. Returns the old draw buffer. This routine should probably only be called from inside the GLUI_DrawingSentinal, in glui_internal_control.h */ int set_current_draw_buffer(); /** Go back to using this draw buffer. Undoes set_current_draw_buffer. */ void restore_draw_buffer( int buffer_state ); /** Pack, resize the window, and redraw all the controls. */ void refresh(); /** Redraw the main graphics window */ void post_update_main_gfx(); /** Recompute the sizes and positions of all controls */ void pack_controls(); void close_internal(); void check_subwindow_position(); void set_ortho_projection(); void set_viewport(); int get_glut_window_id( void ) { return glut_window_id; } /* JVK */ int get_top_level_glut_window_id( void ) { return top_level_glut_window_id; } /* JVK */ }; /************************************************************/ /* */ /* GLUI_Control: base class for all controls */ /* */ /************************************************************/ /** All the GUI objects inherit from GLUI_Control: buttons, checkboxes, labels, edit boxes, scrollbars, etc. Most of the work of this class is in routing events, like keystrokes, mouseclicks, redraws, and sizing events. Yes, this is a huge and hideous class. It needs to be split up into simpler subobjects. None of the data members should be directly accessed by users (they should be protected, not public); only subclasses. */ class GLUI_Control : public GLUI_Node { public: /** Onscreen coordinates */ int w, h; /* dimensions of control */ int x_abs, y_abs; /* GLUT subwindow absolute coordinates */ int x_off, y_off_top, y_off_bot; /* INNER margins, by which child controls are indented */ int contain_x, contain_y; int contain_w, contain_h; /* if this is a container control (e.g., radiogroup or panel) this indicated dimensions of inner area in which controls reside */ /** "activation" for tabbing between controls. */ int active_type; ///< "GLUI_CONTROL_ACTIVE_..." bool active; ///< If true, we've got the focus bool can_activate; ///< If false, remove from tab order. bool spacebar_mouse_click; ///< Spacebar simulates click. /** Callbacks */ long user_id; ///< Integer to pass to callback function. GLUI_CB callback; ///< User callback function, or NULL. /** Variable value storage */ float float_val; /**< Our float value */ int int_val; /**< Our integer value */ float float_array_val[GLUI_DEF_MAX_ARRAY]; int float_array_size; GLUI_String text; /**< The text inside this control */ /** "Live variable" updating */ void *ptr_val; /**< A pointer to the user's live variable value */ int live_type; bool live_inited; /* These variables store the last value that live variable was known to have. */ int last_live_int; float last_live_float; GLUI_String last_live_text; float last_live_float_array[GLUI_DEF_MAX_ARRAY]; /** Properties of our control */ GLUI *glui; /**< Our containing event handler (NEVER NULL during event processing!) */ bool is_container; /**< Is this a container class (e.g., panel) */ int alignment; bool enabled; /**< Is this control grayed out? */ GLUI_String name; /**< The name of this control */ void *font; /**< Our glutbitmap font */ bool collapsible, is_open; GLUI_Node collapsed_node; bool hidden; /* Collapsed controls (and children) are hidden */ int char_widths[CHAR_WIDTH_HASH_SIZE][2]; /* Character width hash table */ public: /*** Get/Set values ***/ virtual void set_name( const char *string ); virtual void set_int_val( int new_int ) { int_val = new_int; output_live(true); } virtual void set_float_val( float new_float ) { float_val = new_float; output_live(true); } virtual void set_ptr_val( void *new_ptr ) { ptr_val = new_ptr; output_live(true); } virtual void set_float_array_val( float *array_ptr ); virtual float get_float_val( void ) { return float_val; } virtual int get_int_val( void ) { return int_val; } virtual void get_float_array_val( float *array_ptr ); virtual int get_id( void ) const { return user_id; } virtual void set_id( int id ) { user_id=id; } virtual int mouse_down_handler( int local_x, int local_y ) { return false; } virtual int mouse_up_handler( int local_x, int local_y, bool inside ) { return false; } virtual int mouse_held_down_handler( int local_x, int local_y, bool inside) { return false; } virtual int key_handler( unsigned char key, int modifiers ) { return false; } virtual int special_handler( int key,int modifiers ) { return false; } virtual void update_size( void ) { } virtual void idle( void ) { } virtual int mouse_over( int state, int x, int y ) { return false; } virtual void enable( void ); virtual void disable( void ); virtual void activate( int how ) { active = true; } virtual void deactivate( void ) { active = false; } /** Hide (shrink into a rollout) and unhide (expose from a rollout) */ void hide_internal( int recurse ); void unhide_internal( int recurse ); /** Return true if it currently makes sense to draw this class. */ int can_draw( void ) { return (glui != NULL && hidden == false); } /** Redraw this control. In single-buffering mode (drawing to GL_FRONT), this is just a call to translate_and_draw_front (after a can_draw() check). In double-buffering mode (drawing to GL_BACK), this queues up a redraw and returns false, since you shouldn't draw yet. */ void redraw(void); /** Redraw everybody in our window. */ void redraw_window(void); virtual void align( void ); void pack( int x, int y ); /* Recalculate positions and offsets */ void pack_old( int x, int y ); /** Draw this control to the screen. The OpenGL coordinate system has already been translated to pixel (x,y) onscreen. This routine must be overridden by each GLUI_Control subclass. */ virtual void draw( int x, int y )=0; /** Draw us, then draw all our children (according to GLUI_Node) */ void draw_recursive( int x, int y ); /** Shift the OpenGL coordinate system, and call draw */ void translate_and_draw_front( void ); /** Shift the OpenGL coordinate system from panel coords to our control's coords. */ void translate_to_origin( void ) {glTranslatef((float)x_abs+.5,(float)y_abs+.5,0.0);} int set_to_glut_window( void ); void restore_window( int orig ); void set_font( void *new_font ); void *get_font( void ); int string_width( const char *text ); int string_width( const GLUI_String &str ) { return string_width(str.c_str()); } int char_width( char c ); /* Utility routines to help you draw controls: */ /** Draw our name string, greyed out if we're not enabled. */ void draw_name( int x, int y ); void draw_box_inwards_outline( int x_min, int x_max, int y_min, int y_max ); void draw_box( int x_min, int x_max, int y_min, int y_max, float r, float g, float b ); void draw_bkgd_box( int x_min, int x_max, int y_min, int y_max ); void draw_emboss_box( int x_min, int x_max,int y_min,int y_max); void draw_string( const char *text ); void draw_string( const GLUI_String &s ) { draw_string(s.c_str()); } void draw_char( char c ); void draw_active_box( int x_min, int x_max, int y_min, int y_max ); void set_to_bkgd_color( void ); /** Set our width to this value */ void set_w( int new_w ); void set_h( int new_w ); void set_alignment( int new_align ); void sync_live( int recurse, int draw ); /* Reads live variable */ void init_live( void ); void output_live( int update_main_gfx ); /** Writes live variable **/ virtual void set_text( const char *t ) {} void execute_callback( void ); void get_this_column_dims( int *col_x, int *col_y, int *col_w, int *col_h, int *col_x_off, int *col_y_off ); virtual bool needs_idle( void ) const; virtual bool wants_tabs() const { return false; } GLUI_Control(void) { x_off = GLUI_XOFF; y_off_top = GLUI_YOFF; y_off_bot = GLUI_YOFF; x_abs = GLUI_XOFF; y_abs = GLUI_YOFF; active = false; enabled = true; int_val = 0; last_live_int = 0; float_array_size = 0; glui_format_str(name, "Control: %p", this); float_val = 0.0; last_live_float = 0.0; ptr_val = NULL; glui = NULL; w = GLUI_DEFAULT_CONTROL_WIDTH; h = GLUI_DEFAULT_CONTROL_HEIGHT; font = NULL; active_type = GLUI_CONTROL_ACTIVE_MOUSEDOWN; alignment = GLUI_ALIGN_LEFT; is_container = false; can_activate = true; /* By default, you can activate a control */ spacebar_mouse_click = true; /* Does spacebar simulate a mouse click? */ live_type = GLUI_LIVE_NONE; text = ""; last_live_text == ""; live_inited = false; collapsible = false; is_open = true; hidden = false; memset(char_widths, -1, sizeof(char_widths)); /* JVK */ int i; for( i=0; i<GLUI_DEF_MAX_ARRAY; i++ ) float_array_val[i] = last_live_float_array[i] = 0.0; } virtual ~GLUI_Control(); }; /************************************************************/ /* */ /* Button class (container) */ /* */ /************************************************************/ /** An onscreen, clickable button--an outlined label that can be clicked. When clicked, a button calls its GLUI_CB callback with its ID. */ class GLUI_Button : public GLUI_Control { public: bool currently_inside; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); void draw( int x, int y ); void draw_pressed( void ); void draw_text( int sunken ); void update_size( void ); /** Create a new button. @param parent The panel our object is inside; or the main GLUI object. @param name The text inside the button. @param id Optional ID number, to pass to the optional callback function. @param callback Optional callback function, taking either the int ID or control. */ GLUI_Button( GLUI_Node *parent, const char *name, int id=-1, GLUI_CB cb=GLUI_CB() ); GLUI_Button( void ) { common_init(); }; protected: void common_init(void) { glui_format_str(name, "Button: %p", this ); h = GLUI_BUTTON_SIZE; w = 100; alignment = GLUI_ALIGN_CENTER; can_activate = true; } }; /************************************************************/ /* */ /* Checkbox class (container) */ /* */ /************************************************************/ /** A checkbox, which can be checked on or off. Can be linked to an int value, which gets 1 for on and 0 for off. */ class GLUI_Checkbox : public GLUI_Control { public: int orig_value; bool currently_inside; int text_x_offset; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); void update_size( void ); void draw( int x, int y ); void draw_active_area( void ); void draw_empty_box( void ); void set_int_val( int new_val ); /** Create a new checkbox object. @param parent The panel our object is inside; or the main GLUI object. @param name Label next to our checkbox. @param value_ptr Optional integer value to attach to this checkbox. When the checkbox is checked or unchecked, *value_ptr will also be changed. ("Live Vars"). @param id Optional ID number, to pass to the optional callback function. @param callback Optional callback function, taking either the int ID or control. */ GLUI_Checkbox(GLUI_Node *parent, const char *name, int *value_ptr=NULL, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Checkbox( void ) { common_init(); } protected: void common_init(void) { glui_format_str( name, "Checkbox: %p", this ); w = 100; h = GLUI_CHECKBOX_SIZE; orig_value = -1; text_x_offset = 18; can_activate = true; live_type = GLUI_LIVE_INT; /* This control has an 'int' live var */ } }; /************************************************************/ /* */ /* Column class */ /* */ /************************************************************/ /** A GLUI_Column object separates all previous controls from subsequent controls with a vertical bar. */ class GLUI_Column : public GLUI_Control { public: void draw( int x, int y ); /** Create a new column, which separates the previous controls from subsequent controls. @param parent The panel our object is inside; or the main GLUI object. @param draw_bar If true, draw a visible bar between new and old controls. */ GLUI_Column( GLUI_Node *parent, int draw_bar = true ); GLUI_Column( void ) { common_init(); } protected: void common_init() { w = 0; h = 0; int_val = 0; can_activate = false; } }; /************************************************************/ /* */ /* Panel class (container) */ /* */ /************************************************************/ /** A GLUI_Panel contains a group of related controls. */ class GLUI_Panel : public GLUI_Control { public: /** Create a new panel. A panel groups together a set of related controls. @param parent The outer panel our panel is inside; or the main GLUI object. @param name The string name at the top of our panel. @param type Optional style to display the panel with--GLUI_PANEL_EMBOSSED by default. GLUI_PANEL_RAISED causes the panel to appear higher than the surroundings. GLUI_PANEL_NONE causes the panel's outline to be invisible. */ GLUI_Panel( GLUI_Node *parent, const char *name, int type=GLUI_PANEL_EMBOSSED ); GLUI_Panel() { common_init(); } void draw( int x, int y ); void set_name( const char *text ); void set_type( int new_type ); void update_size( void ); protected: void common_init( void ) { w = 300; h = GLUI_DEFAULT_CONTROL_HEIGHT + 7; int_val = GLUI_PANEL_EMBOSSED; alignment = GLUI_ALIGN_CENTER; is_container = true; can_activate = false; name=""; }; }; /************************************************************/ /* */ /* File Browser class (container) */ /* JVK */ /************************************************************/ /** A list of files the user can select from. */ class GLUI_FileBrowser : public GLUI_Panel { public: /** Create a new list of files the user can select from. @param parent The panel our object is inside; or the main GLUI object. @param name Prompt to give to the user at the top of the file browser. @param frame_type Optional style to display the panel with--GLUI_PANEL_EMBOSSED by default. GLUI_PANEL_RAISED causes the panel to appear higher than the surroundings. GLUI_PANEL_NONE causes the panel's outline to be invisible. @param id Optional ID number, to pass to the optional callback function. @param callback Optional callback function, taking either the int ID or control. */ GLUI_FileBrowser( GLUI_Node *parent, const char *name, int frame_type = GLUI_PANEL_EMBOSSED, int user_id = -1, GLUI_CB callback = GLUI_CB()); GLUI_List *list; GLUI_String current_dir; void fbreaddir(const char *); static void dir_list_callback(GLUI_Control*); void set_w(int w); void set_h(int h); const char* get_file() { return file.c_str(); } void set_allow_change_dir(int c) { allow_change_dir = c; } protected: void common_init() { w = GLUI_DEFAULT_CONTROL_WIDTH; h = GLUI_DEFAULT_CONTROL_HEIGHT; int_val = GLUI_PANEL_EMBOSSED; alignment = GLUI_ALIGN_CENTER; is_container = true; can_activate = false; allow_change_dir = true; last_item = -1; user_id = -1; name = ""; current_dir = "."; file = ""; }; private: int last_item; GLUI_String file; int allow_change_dir; }; /************************************************************/ /* */ /* Rollout class (container) */ /* */ /************************************************************/ /** A rollout contains a set of controls, like a panel, but can be collapsed to just the name. */ class GLUI_Rollout : public GLUI_Panel { public: /** Create a new rollout. A rollout contains a set of controls, like a panel, but can be collapsed to just the name. @param parent The panel our object is inside; or the main GLUI object. @param name String to show at the top of the rollout. @param open Optional boolean. If true (the default), the rollout's controls are displayed. If false, the rollout is closed to display only the name. @param type Optional style to display the panel with--GLUI_PANEL_EMBOSSED by default. GLUI_PANEL_RAISED causes the panel to appear higher than the surroundings. GLUI_PANEL_NONE causes the panel's outline to be invisible. */ GLUI_Rollout( GLUI_Node *parent, const char *name, int open=true, int type=GLUI_PANEL_EMBOSSED ); GLUI_Rollout( void ) { common_init(); } bool currently_inside, initially_inside; GLUI_Button button; void draw( int x, int y ); void draw_pressed( void ); int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); void open( void ); void close( void ); void update_size( void ); protected: void common_init() { currently_inside = false; initially_inside = false; can_activate = true; is_container = true; h = GLUI_DEFAULT_CONTROL_HEIGHT + 7; w = GLUI_DEFAULT_CONTROL_WIDTH; y_off_top = 21; collapsible = true; name = ""; } }; /************************************************************/ /* */ /* Tree Panel class (container) */ /* JVK */ /************************************************************/ /** One collapsible entry in a GLUI_TreePanel. */ class GLUI_Tree : public GLUI_Panel { public: GLUI_Tree(GLUI_Node *parent, const char *name, int open=false, int inset=0); private: int level; // how deep is this node float red; //Color coding of column line float green; float blue; float lred; //Color coding of level name float lgreen; float lblue; int id; GLUI_Column *column; int is_current; // Whether this tree is the // current root in a treePanel int child_number; int format; public: bool currently_inside, initially_inside; GLUI_Button button; GLUI_String level_name; // level name, eg: 1.1.2, III, or 3 GLUI_TreePanel *panel; void draw( int x, int y ); void draw_pressed( void ); int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); void set_column(GLUI_Column *c) { column = c; } void open( void ); void close( void ); /* void set_name( const char *text ) { panel.set_name( text ); }; */ void update_size( void ); void set_id(int i) { id = i; } void set_level(int l) { level = l; } void set_format(int f) { format = f; } void set_current(int c) { is_current = c; } int get_id() { return id; } int get_level() { return level; } int get_child_number() { return child_number; } void enable_bar() { if (column) { column->int_val = 1; set_color(red, green, blue); } } void disable_bar() { if (column) { column->int_val = 0; } } void set_child_number(int c) { child_number = c; } void set_level_color(float r, float g, float b) { lred = r; lgreen = g; lblue = b; } void set_color(float r, float g, float b) { red = r; green = g; blue = b; } protected: void common_init() { currently_inside = false; initially_inside = false; can_activate = true; is_container = true; h = GLUI_DEFAULT_CONTROL_HEIGHT + 7; w = GLUI_DEFAULT_CONTROL_WIDTH; y_off_top = 21; collapsible = true; red = .5; green = .5; blue = .5; lred = 0; lgreen = 0; lblue = 0; column = NULL; is_current = 0; child_number = 0; format = 0; panel = NULL; name = ""; level_name = ""; level = 0; }; }; /************************************************************/ /* */ /* TreePanel class (container) JVK */ /* */ /************************************************************/ /** Manages, maintains, and formats a tree of GLUI_Tree objects. These are shown in a heirarchical, collapsible display. FIXME: There's an infinite loop in the traversal code (OSL 2006/06) */ class GLUI_TreePanel : public GLUI_Panel { public: GLUI_TreePanel(GLUI_Node *parent, const char *name, bool open=false, int inset=0); int max_levels; int next_id; int format; float red; float green; float blue; float lred; float lgreen; float lblue; int root_children; /* These variables allow the tree panel to traverse the tree using only two function calls. (Well, four, if you count going in reverse */ GLUI_Tree *curr_branch; /* Current Branch */ GLUI_Panel *curr_root; /* Current Root */ public: void set_color(float r, float g, float b); void set_level_color(float r, float g, float b); void set_format(int f) { format = f; } /* Adds branch to curr_root */ GLUI_Tree * ab(const char *name, GLUI_Tree *root = NULL); /* Goes up one level, resets curr_root and curr_branch to parents*/ void fb(GLUI_Tree *branch= NULL); /* Deletes the curr_branch, goes up one level using fb */ void db(GLUI_Tree *branch = NULL); /* Finds the very last branch of curr_root, resets vars */ void descendBranch(GLUI_Panel *root = NULL); /* Resets curr_root and curr branch to TreePanel and lastChild */ void resetToRoot(GLUI_Panel *new_root = NULL); void next( void ); void refresh( void ); void expand_all( void ); void collapse_all( void ); void update_all( void ); void initNode(GLUI_Tree *temp); void formatNode(GLUI_Tree *temp); protected: int uniqueID( void ) { next_id++; return next_id - 1; } void common_init() { GLUI_Panel(); next_id = 0; curr_root = this; curr_branch = NULL; red = .5; green = .5; blue = .5; root_children = 0; } }; /************************************************************/ /* */ /* User-Level GLUI class */ /* */ /************************************************************/ class GLUI_Rotation; class GLUI_Translation; /** The main user-visible interface object to GLUI. */ class GLUI : public GLUI_Main { public: /** DEPRECATED interface for creating new GLUI objects */ int add_control( GLUI_Control *control ) { return main_panel->add_control(control); } void add_column( int draw_bar = true ); void add_column_to_panel( GLUI_Panel *panel, int draw_bar = true ); void add_separator( void ); void add_separator_to_panel( GLUI_Panel *panel ); GLUI_RadioGroup *add_radiogroup( int *live_var=NULL, int user_id=-1,GLUI_CB callback=GLUI_CB()); GLUI_RadioGroup *add_radiogroup_to_panel( GLUI_Panel *panel, int *live_var=NULL, int user_id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_RadioButton *add_radiobutton_to_group( GLUI_RadioGroup *group, const char *name ); GLUI_Listbox *add_listbox( const char *name, int *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Listbox *add_listbox_to_panel( GLUI_Panel *panel, const char *name, int *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Rotation *add_rotation( const char *name, float *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Rotation *add_rotation_to_panel( GLUI_Panel *panel, const char *name, float *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Translation *add_translation( const char *name, int trans_type, float *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Translation *add_translation_to_panel( GLUI_Panel *panel, const char *name, int trans_type, float *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Checkbox *add_checkbox( const char *name, int *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Checkbox *add_checkbox_to_panel( GLUI_Panel *panel, const char *name, int *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Button *add_button( const char *name, int id=-1, GLUI_CB callback=GLUI_CB()); GLUI_Button *add_button_to_panel( GLUI_Panel *panel, const char *name, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_StaticText *add_statictext( const char *name ); GLUI_StaticText *add_statictext_to_panel( GLUI_Panel *panel, const char *name ); GLUI_EditText *add_edittext( const char *name, int data_type=GLUI_EDITTEXT_TEXT, void*live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_EditText *add_edittext_to_panel( GLUI_Panel *panel, const char *name, int data_type=GLUI_EDITTEXT_TEXT, void *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_EditText *add_edittext( const char *name, GLUI_String& live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_EditText *add_edittext_to_panel( GLUI_Panel *panel, const char *name, GLUI_String& live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Spinner *add_spinner( const char *name, int data_type=GLUI_SPINNER_INT, void *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Spinner *add_spinner_to_panel( GLUI_Panel *panel, const char *name, int data_type=GLUI_SPINNER_INT, void *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Panel *add_panel( const char *name, int type=GLUI_PANEL_EMBOSSED ); GLUI_Panel *add_panel_to_panel( GLUI_Panel *panel, const char *name, int type=GLUI_PANEL_EMBOSSED ); GLUI_Rollout *add_rollout( const char *name, int open=true, int type=GLUI_PANEL_EMBOSSED); GLUI_Rollout *add_rollout_to_panel( GLUI_Panel *panel, const char *name, int open=true, int type=GLUI_PANEL_EMBOSSED); /** Set the window where our widgets should be displayed. */ void set_main_gfx_window( int window_id ); int get_glut_window_id( void ) { return glut_window_id; } void enable( void ) { main_panel->enable(); } void disable( void ); void sync_live( void ); void close( void ); void show( void ); void hide( void ); /***** GLUT callback setup functions *****/ /* void set_glutDisplayFunc(void (*f)(void)); void set_glutReshapeFunc(void (*f)(int width, int height)); void set_glutKeyboardFunc(void (*f)(unsigned char key, int x, int y)); void set_glutSpecialFunc(void (*f)(int key, int x, int y)); void set_glutMouseFunc(void (*f)(int button, int state, int x, int y)); void set_glutMotionFunc(void (*f)(int x, int y)); void set_glutPassiveMotionFunc(void (*f)(int x, int y)); void set_glutEntryFunc(void (*f)(int state)); void set_glutVisibilityFunc(void (*f)(int state)); void set_glutInit( int *argcp, const char **argv ); void set_glutInitWindowSize(int width, int height); void set_glutInitWindowPosition(int x, int y); void set_glutInitDisplayMode(unsigned int mode); int set_glutCreateWindow(const char *name); */ /***** Constructors and desctructors *****/ int init( const char *name, long flags, int x, int y, int parent_window ); protected: virtual int add_control( GLUI_Node *parent, GLUI_Control *control ) { return GLUI_Main::add_control( parent, control ); } }; /************************************************************/ /* */ /* EditText class */ /* */ /************************************************************/ /** An EditText is a single-line text box. It's used by Spinner, CommandLine, and several other places. For multi-line text, see GLUI_TextBox below. */ class GLUI_EditText : public GLUI_Control { public: int has_limits; int data_type; GLUI_String orig_text; int insertion_pt; int title_x_offset; int text_x_offset; int substring_start; /*substring that gets displayed in box*/ int substring_end; int sel_start, sel_end; /* current selection */ int num_periods; int last_insertion_pt; float float_low, float_high; int int_low, int_high; GLUI_Spinner *spinner; int debug; int draw_text_only; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); int special_handler( int key, int modifiers ); void activate( int how ); void deactivate( void ); void draw( int x, int y ); int mouse_over( int state, int x, int y ); int find_word_break( int start, int direction ); int substring_width( int start, int end ); void clear_substring( int start, int end ); int find_insertion_pt( int x, int y ); int update_substring_bounds( void ); void update_and_draw_text( void ); void draw_text( int x, int y ); void draw_insertion_pt( void ); void set_numeric_text( void ); void update_x_offsets( void ); void update_size( void ); void set_float_limits( float low,float high,int limit_type=GLUI_LIMIT_CLAMP); void set_int_limits( int low, int high, int limit_type=GLUI_LIMIT_CLAMP ); void set_float_val( float new_val ); void set_int_val( int new_val ); void set_text( const char *text ); void set_text( const GLUI_String &s) { set_text(s.c_str()); } const char *get_text() { return text.c_str(); } void dump( FILE *out, const char *text ); // Constructor, no live variable GLUI_EditText( GLUI_Node *parent, const char *name, int text_type=GLUI_EDITTEXT_TEXT, int id=-1, GLUI_CB callback=GLUI_CB() ); // Constructor, int live variable GLUI_EditText( GLUI_Node *parent, const char *name, int *live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Constructor, float live variable GLUI_EditText( GLUI_Node *parent, const char *name, float *live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Constructor, char* live variable GLUI_EditText( GLUI_Node *parent, const char *name, char *live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Constructor, std::string live variable GLUI_EditText( GLUI_Node *parent, const char *name, std::string &live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Deprecated constructor, only called internally GLUI_EditText( GLUI_Node *parent, const char *name, int text_type, void *live_var, int id, GLUI_CB callback ); // Deprecated constructor, only called internally GLUI_EditText( void ) { common_init(); } protected: void common_init( void ) { h = GLUI_EDITTEXT_HEIGHT; w = GLUI_EDITTEXT_WIDTH; title_x_offset = 0; text_x_offset = 55; insertion_pt = -1; last_insertion_pt = -1; name = ""; substring_start = 0; data_type = GLUI_EDITTEXT_TEXT; substring_end = 2; num_periods = 0; has_limits = GLUI_LIMIT_NONE; sel_start = 0; sel_end = 0; active_type = GLUI_CONTROL_ACTIVE_PERMANENT; can_activate = true; spacebar_mouse_click = false; spinner = NULL; debug = false; draw_text_only = false; } void common_construct( GLUI_Node *parent, const char *name, int data_type, int live_type, void *live_var, int id, GLUI_CB callback ); }; /************************************************************/ /* */ /* CommandLine class */ /* */ /************************************************************/ class GLUI_CommandLine : public GLUI_EditText { public: typedef GLUI_EditText Super; enum { HIST_SIZE = 100 }; std::vector<GLUI_String> hist_list; int curr_hist; int oldest_hist; int newest_hist; bool commit_flag; public: int key_handler( unsigned char key,int modifiers ); int special_handler( int key,int modifiers ); void deactivate( void ); virtual const char *get_history( int command_number ) const { return hist_list[command_number - oldest_hist].c_str(); } virtual GLUI_String& get_history_str( int command_number ) { return hist_list[command_number - oldest_hist]; } virtual const GLUI_String& get_history_str( int command_number ) const { return hist_list[command_number - oldest_hist]; } virtual void recall_history( int history_number ); virtual void scroll_history( int direction ); virtual void add_to_history( const char *text ); virtual void reset_history( void ); void dump( FILE *out, const char *text ); GLUI_CommandLine( GLUI_Node *parent, const char *name, void *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_CommandLine( void ) { common_init(); } protected: void common_init() { hist_list.resize(HIST_SIZE); curr_hist = 0; oldest_hist = 0; newest_hist = 0; commit_flag = false; } }; /************************************************************/ /* */ /* RadioGroup class (container) */ /* */ /************************************************************/ /** A RadioGroup contains a set of RadioButton objects, only one of which can be selected at once. This class provides the interface to get and set the currently selected button index. You use it by creating a RadioGroup, and then adding a set of RadioButtons to it. */ class GLUI_RadioGroup : public GLUI_Control { public: int num_buttons; void draw( int x, int y ); void set_name( const char *text ); void set_int_val( int int_val ); void set_selected( int int_val ); void draw_group( int translate ); GLUI_RadioGroup( GLUI_Node *parent, int *live_var=NULL, int user_id=-1,GLUI_CB callback=GLUI_CB() ); GLUI_RadioGroup( void ) { common_init(); } protected: void common_init( void ) { x_off = 0; y_off_top = 0; y_off_bot = 0; is_container = true; w = 300; h = 300; num_buttons = 0; name = ""; can_activate = false; live_type = GLUI_LIVE_INT; } }; /************************************************************/ /* */ /* RadioButton class (container) */ /* */ /************************************************************/ /** A RadioButton is like a checkbox, but only one button in the RadioGroup can be selected at once. */ class GLUI_RadioButton : public GLUI_Control { public: int orig_value; bool currently_inside; int text_x_offset; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); void draw( int x, int y ); void update_size( void ); void draw_active_area( void ); void draw_checked( void ); void draw_unchecked( void ); void draw_O( void ); GLUI_RadioButton( GLUI_RadioGroup *group, const char *name ); GLUI_RadioGroup *group; protected: void common_init() { glui_format_str( name, "RadioButton: %p", (void *) this ); h = GLUI_RADIOBUTTON_SIZE; group = NULL; orig_value = -1; text_x_offset = 18; can_activate = true; } }; /************************************************************/ /* */ /* Separator class (container) */ /* */ /************************************************************/ /** A Separator is just used to provide space between components. It doesn't do anything other than take up space onscreen. */ class GLUI_Separator : public GLUI_Control { public: void draw( int x, int y ); GLUI_Separator( GLUI_Node *parent ); GLUI_Separator( void ) { common_init(); } protected: void common_init() { w = 100; h = GLUI_SEPARATOR_HEIGHT; can_activate = false; } }; #define GLUI_SPINNER_ARROW_WIDTH 12 #define GLUI_SPINNER_ARROW_HEIGHT 8 #define GLUI_SPINNER_ARROW_Y 2 #define GLUI_SPINNER_STATE_NONE 0 #define GLUI_SPINNER_STATE_UP 1 #define GLUI_SPINNER_STATE_DOWN 2 #define GLUI_SPINNER_STATE_BOTH 3 #define GLUI_SPINNER_DEFAULT_GROWTH_EXP 1.05f /************************************************************/ /* */ /* Spinner class (container) */ /* */ /************************************************************/ /** A spinner provides an EditText box and a set of arrows. You can flip through a set of integer or float values with the arrows, or enter a new value in the tex box. */ class GLUI_Spinner : public GLUI_Control { public: // Constructor, no live var GLUI_Spinner( GLUI_Node* parent, const char *name, int data_type=GLUI_SPINNER_INT, int id=-1, GLUI_CB callback=GLUI_CB() ); // Constructor, int live var GLUI_Spinner( GLUI_Node* parent, const char *name, int *live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Constructor, float live var GLUI_Spinner( GLUI_Node* parent, const char *name, float *live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Deprecated constructor GLUI_Spinner( GLUI_Node* parent, const char *name, int data_type, void *live_var, int id=-1, GLUI_CB callback=GLUI_CB() ); // Deprecated constructor GLUI_Spinner( void ) { common_init(); } bool currently_inside; int state; float growth, growth_exp; int last_x, last_y; int data_type; int callback_count; int last_int_val; float last_float_val; int first_callback; float user_speed; GLUI_EditText *edittext; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); int special_handler( int key,int modifiers ); void draw( int x, int y ); void draw_pressed( void ); void draw_unpressed( void ); void draw_text( int sunken ); void update_size( void ); void set_float_limits( float low,float high,int limit_type=GLUI_LIMIT_CLAMP); void set_int_limits( int low, int high,int limit_type=GLUI_LIMIT_CLAMP); int find_arrow( int local_x, int local_y ); void do_drag( int x, int y ); void do_callbacks( void ); void do_click( void ); void idle( void ); bool needs_idle( void ) const; const char *get_text( void ); void set_float_val( float new_val ); void set_int_val( int new_val ); float get_float_val( void ); int get_int_val( void ); void increase_growth( void ); void reset_growth( void ); void set_speed( float speed ) { user_speed = speed; } protected: void common_init() { glui_format_str( name, "Spinner: %p", this ); h = GLUI_EDITTEXT_HEIGHT; w = GLUI_EDITTEXT_WIDTH; x_off = 0; y_off_top = 0; y_off_bot = 0; can_activate = true; state = GLUI_SPINNER_STATE_NONE; edittext = NULL; growth_exp = GLUI_SPINNER_DEFAULT_GROWTH_EXP; callback_count = 0; first_callback = true; user_speed = 1.0; } void common_construct( GLUI_Node* parent, const char *name, int data_type, void *live_var, int id, GLUI_CB callback ); }; /************************************************************/ /* */ /* StaticText class */ /* */ /************************************************************/ /** StaticText is a one-line visible non-editable text class. In Java, this is a "Label" object. */ class GLUI_StaticText : public GLUI_Control { public: void set_text( const char *text ); void draw( int x, int y ); void draw_text( void ); void update_size( void ); void erase_text( void ); GLUI_StaticText(GLUI_Node *parent, const char *name); GLUI_StaticText( void ) { common_init(); } protected: void common_init() { h = GLUI_STATICTEXT_SIZE; name = ""; can_activate = false; } }; /************************************************************/ /* */ /* TextBox class - JVK */ /* */ /************************************************************/ /** A TextBox is a multi-line editable text area. */ class GLUI_TextBox : public GLUI_Control { public: /* GLUI Textbox - JVK */ GLUI_TextBox(GLUI_Node *parent, GLUI_String &live_var, bool scroll = false, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_TextBox( GLUI_Node *parent, bool scroll = false, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_String orig_text; int insertion_pt; int substring_start; /*substring that gets displayed in box*/ int substring_end; int sel_start, sel_end; /* current selection */ int last_insertion_pt; int debug; int draw_text_only; int tab_width; int start_line; int num_lines; int curr_line; int visible_lines; int insert_x; /* Similar to "insertion_pt", these variables keep */ int insert_y; /* track of where the ptr is, but in pixels */ int keygoal_x; /* where up down keys would like to put insertion pt*/ GLUI_Scrollbar *scrollbar; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); int special_handler( int key,int modifiers ); void activate( int how ); void deactivate( void ); void enable( void ); void disable( void ); void draw( int x, int y ); int mouse_over( int state, int x, int y ); int get_box_width(); int find_word_break( int start, int direction ); int substring_width( int start, int end, int initial_width=0 ); void clear_substring( int start, int end ); int find_insertion_pt( int x, int y ); int update_substring_bounds( void ); void update_and_draw_text( void ); void draw_text( int x, int y ); void draw_insertion_pt( void ); void update_x_offsets( void ); void update_size( void ); void set_text( const char *text ); const char *get_text( void ) { return text.c_str(); } void dump( FILE *out, const char *text ); void set_tab_w(int w) { tab_width = w; } void set_start_line(int l) { start_line = l; } static void scrollbar_callback(GLUI_Control*); bool wants_tabs( void ) const { return true; } protected: void common_init() { h = GLUI_TEXTBOX_HEIGHT; w = GLUI_TEXTBOX_WIDTH; tab_width = GLUI_TAB_WIDTH; num_lines = 0; visible_lines = 0; start_line = 0; curr_line = 0; insert_y = -1; insert_x = -1; insertion_pt = -1; last_insertion_pt = -1; name[0] = '\0'; substring_start = 0; substring_end = 2; sel_start = 0; sel_end = 0; active_type = GLUI_CONTROL_ACTIVE_PERMANENT; can_activate = true; spacebar_mouse_click = false; scrollbar = NULL; debug = false; draw_text_only = false; } void common_construct( GLUI_Node *parent, GLUI_String *live_var, bool scroll, int id, GLUI_CB callback); }; /************************************************************/ /* */ /* List class - JVK */ /* */ /************************************************************/ class GLUI_List_Item : public GLUI_Node { public: GLUI_String text; int id; }; /************************************************************/ /* */ /* List class - JVK */ /* */ /************************************************************/ /** A List provides a vertically arranged set of selectable items. */ class GLUI_List : public GLUI_Control { public: /* GLUI List - JVK */ GLUI_List( GLUI_Node *parent, bool scroll = false, int id=-1, GLUI_CB callback=GLUI_CB() ); /*, GLUI_Control *object = NULL ,GLUI_InterObject_CB obj_cb = NULL);*/ GLUI_List( GLUI_Node *parent, GLUI_String& live_var, bool scroll = false, int id=-1, GLUI_CB callback=GLUI_CB() /*,GLUI_Control *object = NULL */ /*,GLUI_InterObject_CB obj_cb = NULL*/); GLUI_String orig_text; int debug; int draw_text_only; int start_line; int num_lines; int curr_line; int visible_lines; GLUI_Scrollbar *scrollbar; GLUI_List_Item items_list; GLUI_Control *associated_object; GLUI_CB obj_cb; int cb_click_type; int last_line; int last_click_time; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); int special_handler( int key,int modifiers ); void activate( int how ); void deactivate( void ); void draw( int x, int y ); int mouse_over( int state, int x, int y ); int get_box_width(); int find_word_break( int start, int direction ); int substring_width( const char *t, int start, int end ); int find_line( int x, int y ); void update_and_draw_text( void ); void draw_text( const char *t, int selected, int x, int y ); void update_size( void ); int add_item( int id, const char *text ); int delete_item( const char *text ); int delete_item( int id ); int delete_all(); GLUI_List_Item *get_item_ptr( const char *text ); GLUI_List_Item *get_item_ptr( int id ); void dump( FILE *out, const char *text ); void set_start_line(int l) { start_line = l; } static void scrollbar_callback(GLUI_Control*); int get_current_item() { return curr_line; } void set_click_type(int d) { cb_click_type = d; } void set_object_callback(GLUI_CB cb=GLUI_CB(), GLUI_Control*obj=NULL) { obj_cb=cb; associated_object=obj; } protected: void common_init() { h = GLUI_LIST_HEIGHT; w = GLUI_LIST_WIDTH; num_lines = 0; visible_lines = 0; start_line = 0; curr_line = 0; name[0] = '\0'; active_type = GLUI_CONTROL_ACTIVE_PERMANENT; can_activate = true; spacebar_mouse_click = false; scrollbar = NULL; debug = false; draw_text_only = false; cb_click_type = GLUI_SINGLE_CLICK; last_line = -1; last_click_time = 0; associated_object = NULL; }; void common_construct( GLUI_Node *parent, GLUI_String* live_var, bool scroll, int id, GLUI_CB callback /*,GLUI_Control *object*/ /*,GLUI_InterObject_CB obj_cb*/); }; /************************************************************/ /* */ /* Scrollbar class - JVK */ /* */ /************************************************************/ class GLUI_Scrollbar : public GLUI_Control { public: // Constructor, no live var GLUI_Scrollbar( GLUI_Node *parent, const char *name, int horz_vert=GLUI_SCROLL_HORIZONTAL, int data_type=GLUI_SCROLL_INT, int id=-1, GLUI_CB callback=GLUI_CB() /*,GLUI_Control *object = NULL*/ /*,GLUI_InterObject_CB obj_cb = NULL*/ ); // Constructor, int live var GLUI_Scrollbar( GLUI_Node *parent, const char *name, int horz_vert, int *live_var, int id=-1, GLUI_CB callback=GLUI_CB() /*,GLUI_Control *object = NULL*/ /*,GLUI_InterObject_CB obj_cb = NULL*/ ); // Constructor, float live var GLUI_Scrollbar( GLUI_Node *parent, const char *name, int horz_vert, float *live_var, int id=-1, GLUI_CB callback=GLUI_CB() /*,GLUI_Control *object = NULL*/ /*,GLUI_InterObject_CB obj_cb = NULL*/ ); bool currently_inside; int state; float growth, growth_exp; int last_x, last_y; int data_type; int callback_count; int last_int_val; ///< Used to prevent repeated callbacks. float last_float_val; int first_callback; float user_speed; float float_min, float_max; int int_min, int_max; int horizontal; double last_update_time; ///< GLUI_Time() we last advanced scrollbar. double velocity_limit; ///< Maximum distance to advance per second. int box_length; int box_start_position; int box_end_position; int track_length; /* Rather than directly access an Editbox or Textbox for changing variables, a pointer to some object is defined along with a static callback in the form func(void *, int) - the int is the new value, the void * must be cast to that particular object type before use. */ void * associated_object; /* Lets the Spinner manage it's own callbacks */ GLUI_CB object_cb; /* function pointer to object call_back */ int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); int special_handler( int key,int modifiers ); void draw( int x, int y ); void draw_pressed( void ); void draw_unpressed( void ); void draw_text( int sunken ); void update_size( void ); void set_int_limits( int low, int high,int limit_type=GLUI_LIMIT_CLAMP); void set_float_limits( float low,float high,int limit_type=GLUI_LIMIT_CLAMP); int find_arrow( int local_x, int local_y ); void do_drag( int x, int y ); void do_callbacks( void ); void draw_scroll( void ); void do_click( void ); void idle( void ); bool needs_idle( void ) const; void set_int_val( int new_val ); void set_float_val( float new_val ); void increase_growth( void ); void reset_growth( void ); void set_speed( float speed ) { user_speed = speed; }; void update_scroll_parameters(); void set_object_callback(GLUI_CB cb=GLUI_CB(), GLUI_Control*obj=NULL) { object_cb=cb; associated_object=obj; } protected: void common_init ( void ); void common_construct( GLUI_Node *parent, const char *name, int horz_vert, int data_type, void* live_var, int id, GLUI_CB callback /*,GLUI_Control *object ,GLUI_InterObject_CB obj_cb*/ ); virtual void draw_scroll_arrow(int arrowtype, int x, int y); virtual void draw_scroll_box(int x, int y, int w, int h); }; /************************************************************/ /* */ /* Listbox class */ /* */ /************************************************************/ class GLUI_Listbox_Item : public GLUI_Node { public: GLUI_String text; int id; }; /** A Listbox provides a pop-up menu displaying a set of Listbox_Items. Unlike a GLUI_List, only the currently selected item is shown onscreen unless the user is selecting a new item. You use a Listbox by creating it, then calling add_item to add various strings and IDs for the options. */ class GLUI_Listbox : public GLUI_Control { public: GLUI_String curr_text; GLUI_Listbox_Item items_list; int depressed; int orig_value; bool currently_inside; int text_x_offset, title_x_offset; int glut_menu_id; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int key_handler( unsigned char key,int modifiers ); int special_handler( int key,int modifiers ); void update_size( void ); void draw( int x, int y ); int mouse_over( int state, int x, int y ); void set_int_val( int new_val ); void dump( FILE *output ); int add_item( int id, const char *text ); int delete_item( const char *text ); int delete_item( int id ); int sort_items( void ); int do_selection( int item ); GLUI_Listbox_Item *get_item_ptr( const char *text ); GLUI_Listbox_Item *get_item_ptr( int id ); GLUI_Listbox( GLUI_Node *parent, const char *name, int *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Listbox( void ) { common_init(); } protected: /** Change w and return true if we need to be widened to fit the current item. */ bool recalculate_item_width( void ); void common_init() { glui_format_str( name, "Listbox: %p", this ); w = GLUI_EDITTEXT_WIDTH; h = GLUI_EDITTEXT_HEIGHT; orig_value = -1; title_x_offset = 0; text_x_offset = 55; can_activate = true; curr_text = ""; live_type = GLUI_LIVE_INT; /* This has an integer live var */ depressed = false; glut_menu_id = -1; } ~GLUI_Listbox(); }; /************************************************************/ /* */ /* Mouse_Interaction class */ /* */ /************************************************************/ /** This is the superclass of translation and rotation widgets. */ class GLUI_Mouse_Interaction : public GLUI_Control { public: /*int get_main_area_size( void ) { return MIN( h-18, */ int draw_active_area_only; int mouse_down_handler( int local_x, int local_y ); int mouse_up_handler( int local_x, int local_y, bool inside ); int mouse_held_down_handler( int local_x, int local_y, bool inside ); int special_handler( int key, int modifiers ); void update_size( void ); void draw( int x, int y ); void draw_active_area( void ); /*** The following methods (starting with "iaction_") need to be overloaded ***/ virtual int iaction_mouse_down_handler( int local_x, int local_y ) = 0; virtual int iaction_mouse_up_handler( int local_x, int local_y, bool inside )=0; virtual int iaction_mouse_held_down_handler( int local_x, int local_y, bool inside )=0; virtual int iaction_special_handler( int key, int modifiers )=0; virtual void iaction_draw_active_area_persp( void )=0; virtual void iaction_draw_active_area_ortho( void )=0; virtual void iaction_dump( FILE *output )=0; virtual void iaction_init( void ) = 0; GLUI_Mouse_Interaction( void ) { glui_format_str( name, "Mouse_Interaction: %p", this ); w = GLUI_MOUSE_INTERACTION_WIDTH; h = GLUI_MOUSE_INTERACTION_HEIGHT; can_activate = true; live_type = GLUI_LIVE_NONE; alignment = GLUI_ALIGN_CENTER; draw_active_area_only = false; } }; /************************************************************/ /* */ /* Rotation class */ /* */ /************************************************************/ /** An onscreen rotation controller--allows the user to interact with a 3D rotation via a spaceball-like interface. The live_var output of this rotation is a 4x4 rotation matrix, stored as 16 floats in a */ class GLUI_Rotation : public GLUI_Mouse_Interaction { public: Arcball *ball; GLUquadricObj *quadObj; bool can_spin, spinning; float damping; int iaction_mouse_down_handler( int local_x, int local_y ); int iaction_mouse_up_handler( int local_x, int local_y, bool inside ); int iaction_mouse_held_down_handler( int local_x, int local_y, bool inside ); int iaction_special_handler( int key, int modifiers ); void iaction_init( void ) { init_ball(); } void iaction_draw_active_area_persp( void ); void iaction_draw_active_area_ortho( void ); void iaction_dump( FILE *output ); /* void update_size( void ); */ /* void draw( int x, int y ); */ /* int mouse_over( int state, int x, int y ); */ void setup_texture( void ); void setup_lights( void ); void draw_ball( float radius ); void init_ball( void ); void reset( void ); bool needs_idle( void ) const; void idle( void ); void copy_float_array_to_ball( void ); void copy_ball_to_float_array( void ); void set_spin( float damp_factor ); GLUI_Rotation( GLUI_Node *parent, const char *name, float *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Rotation(void) { common_init(); } protected: void common_init(); }; /************************************************************/ /* */ /* Translation class */ /* */ /************************************************************/ /** An onscreen translation controller--allows the user to interact with a 3D translation. */ class GLUI_Translation : public GLUI_Mouse_Interaction { public: int trans_type; /* Is this an XY or a Z controller? */ int down_x, down_y; float scale_factor; GLUquadricObj *quadObj; int trans_mouse_code; float orig_x, orig_y, orig_z; int locked; int iaction_mouse_down_handler( int local_x, int local_y ); int iaction_mouse_up_handler( int local_x, int local_y, bool inside ); int iaction_mouse_held_down_handler( int local_x, int local_y, bool inside ); int iaction_special_handler( int key, int modifiers ); void iaction_init( void ) { } void iaction_draw_active_area_persp( void ); void iaction_draw_active_area_ortho( void ); void iaction_dump( FILE *output ); void set_speed( float s ) { scale_factor = s; } void setup_texture( void ); void setup_lights( void ); void draw_2d_arrow( int radius, int filled, int orientation ); void draw_2d_x_arrows( int radius ); void draw_2d_y_arrows( int radius ); void draw_2d_z_arrows( int radius ); void draw_2d_xy_arrows( int radius ); int get_mouse_code( int x, int y ); /* Float array is either a single float (for single-axis controls), or two floats for X and Y (if an XY controller) */ float get_z( void ) { return float_array_val[0]; } float get_x( void ) { return float_array_val[0]; } float get_y( void ) { if ( trans_type == GLUI_TRANSLATION_XY ) return float_array_val[1]; else return float_array_val[0]; } void set_z( float val ); void set_x( float val ); void set_y( float val ); void set_one_val( float val, int index ); GLUI_Translation( GLUI_Node *parent, const char *name, int trans_type, float *live_var=NULL, int id=-1, GLUI_CB callback=GLUI_CB() ); GLUI_Translation( void ) { common_init(); } protected: void common_init() { locked = GLUI_TRANSLATION_LOCK_NONE; glui_format_str( name, "Translation: %p", this ); w = GLUI_MOUSE_INTERACTION_WIDTH; h = GLUI_MOUSE_INTERACTION_HEIGHT; can_activate = true; live_type = GLUI_LIVE_FLOAT_ARRAY; float_array_size = 0; alignment = GLUI_ALIGN_CENTER; trans_type = GLUI_TRANSLATION_XY; scale_factor = 1.0; quadObj = NULL; trans_mouse_code = GLUI_TRANSLATION_MOUSE_NONE; } }; /********** Misc functions *********************/ int _glutBitmapWidthString( void *font, const char *s ); void _glutBitmapString( void *font, const char *s ); /********** Our own callbacks for glut *********/ /* These are the callbacks that we pass to glut. They take some action if necessary, then (possibly) call the user-level glut callbacks. */ void glui_display_func( void ); void glui_reshape_func( int w, int h ); void glui_keyboard_func(unsigned char key, int x, int y); void glui_special_func(int key, int x, int y); void glui_mouse_func(int button, int state, int x, int y); void glui_motion_func(int x, int y); void glui_passive_motion_func(int x, int y); void glui_entry_func(int state); void glui_visibility_func(int state); void glui_idle_func(void); void glui_parent_window_reshape_func( int w, int h ); void glui_parent_window_keyboard_func(unsigned char key, int x, int y); void glui_parent_window_mouse_func(int, int, int, int ); void glui_parent_window_special_func(int key, int x, int y); #endif
[ "lawlor@alaska.edu" ]
lawlor@alaska.edu
7dc7c67699fe9d96f6842a9310f75168665254f8
bf5bbd1248cf94942cbb622c6e9383a0ceca3921
/BulletSwift/bullet-2.87/BulletCollision/CollisionShapes/btTetrahedronShape.cpp
ca992198cc8e337305631ba2716b949b5bb6930d
[]
no_license
yohei-yoshihara/BulletSwift
0ea3bcee10f988f312ea0b6a3f25cd2e2ae255c8
eb6f0a91068769f32959319509fe8f1c5dbace86
refs/heads/master
2021-07-02T09:23:19.798915
2020-09-12T08:07:11
2020-09-12T08:07:11
150,093,949
4
0
null
null
null
null
UTF-8
C++
false
false
4,812
cpp
#pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wcomma" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wunused-variable" #pragma clang diagnostic ignored "-Wunreachable-code" #pragma clang diagnostic ignored "-Wconditional-uninitialized" /* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btTetrahedronShape.h" #include "LinearMath/btMatrix3x3.h" btBU_Simplex1to4::btBU_Simplex1to4() : btPolyhedralConvexAabbCachingShape (), m_numVertices(0) { m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE; } btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0) : btPolyhedralConvexAabbCachingShape (), m_numVertices(0) { m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE; addVertex(pt0); } btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1) : btPolyhedralConvexAabbCachingShape (), m_numVertices(0) { m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE; addVertex(pt0); addVertex(pt1); } btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1,const btVector3& pt2) : btPolyhedralConvexAabbCachingShape (), m_numVertices(0) { m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE; addVertex(pt0); addVertex(pt1); addVertex(pt2); } btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1,const btVector3& pt2,const btVector3& pt3) : btPolyhedralConvexAabbCachingShape (), m_numVertices(0) { m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE; addVertex(pt0); addVertex(pt1); addVertex(pt2); addVertex(pt3); } void btBU_Simplex1to4::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { #if 1 btPolyhedralConvexAabbCachingShape::getAabb(t,aabbMin,aabbMax); #else aabbMin.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT); aabbMax.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT); //just transform the vertices in worldspace, and take their AABB for (int i=0;i<m_numVertices;i++) { btVector3 worldVertex = t(m_vertices[i]); aabbMin.setMin(worldVertex); aabbMax.setMax(worldVertex); } #endif } void btBU_Simplex1to4::addVertex(const btVector3& pt) { m_vertices[m_numVertices++] = pt; recalcLocalAabb(); } int btBU_Simplex1to4::getNumVertices() const { return m_numVertices; } int btBU_Simplex1to4::getNumEdges() const { //euler formula, F-E+V = 2, so E = F+V-2 switch (m_numVertices) { case 0: return 0; case 1: return 0; case 2: return 1; case 3: return 3; case 4: return 6; } return 0; } void btBU_Simplex1to4::getEdge(int i,btVector3& pa,btVector3& pb) const { switch (m_numVertices) { case 2: pa = m_vertices[0]; pb = m_vertices[1]; break; case 3: switch (i) { case 0: pa = m_vertices[0]; pb = m_vertices[1]; break; case 1: pa = m_vertices[1]; pb = m_vertices[2]; break; case 2: pa = m_vertices[2]; pb = m_vertices[0]; break; } break; case 4: switch (i) { case 0: pa = m_vertices[0]; pb = m_vertices[1]; break; case 1: pa = m_vertices[1]; pb = m_vertices[2]; break; case 2: pa = m_vertices[2]; pb = m_vertices[0]; break; case 3: pa = m_vertices[0]; pb = m_vertices[3]; break; case 4: pa = m_vertices[1]; pb = m_vertices[3]; break; case 5: pa = m_vertices[2]; pb = m_vertices[3]; break; } } } void btBU_Simplex1to4::getVertex(int i,btVector3& vtx) const { vtx = m_vertices[i]; } int btBU_Simplex1to4::getNumPlanes() const { switch (m_numVertices) { case 0: return 0; case 1: return 0; case 2: return 0; case 3: return 2; case 4: return 4; default: { } } return 0; } void btBU_Simplex1to4::getPlane(btVector3&, btVector3& ,int ) const { } int btBU_Simplex1to4::getIndex(int ) const { return 0; } bool btBU_Simplex1to4::isInside(const btVector3& ,btScalar ) const { return false; } #pragma clang diagnostic pop
[ "yohei_yoshihara@cx5software.com" ]
yohei_yoshihara@cx5software.com
b5249756ec5dd5d7bf0281ca47b3e5f5b8cb1ed1
d1b03d4b061305018084b4dc21a4bdba35335c05
/Plugins/SocketIOClient/Source/ThirdParty/asio/asio/src/examples/cpp03/porthopper/protocol.hpp
6adb306ddc7a94b825a2850cd126f4aa62362b47
[ "Apache-2.0", "BSL-1.0", "MIT" ]
permissive
uetopia/ExampleGame
004b9f1a6f93c725750a82b51cac8d8516c3b769
008ab5d3e817ef763fa42ed551715208682a7ecf
refs/heads/master
2023-03-08T07:56:55.819372
2023-02-26T14:59:42
2023-02-26T14:59:42
205,035,752
36
16
Apache-2.0
2020-05-23T22:14:35
2019-08-28T22:42:22
C++
UTF-8
C++
false
false
4,270
hpp
// // protocol.hpp // ~~~~~~~~~~~~ // // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef PORTHOPPER_PROTOCOL_HPP #define PORTHOPPER_PROTOCOL_HPP #include <boost/array.hpp> #include <asio.hpp> #include <cstring> #include <iomanip> #include <string> #include <strstream> // This request is sent by the client to the server over a TCP connection. // The client uses it to perform three functions: // - To request that data start being sent to a given port. // - To request that data is no longer sent to a given port. // - To change the target port to another. class control_request { public: // Construct an empty request. Used when receiving. control_request() { } // Create a request to start sending data to a given port. static const control_request start(unsigned short port) { return control_request(0, port); } // Create a request to stop sending data to a given port. static const control_request stop(unsigned short port) { return control_request(port, 0); } // Create a request to change the port that data is sent to. static const control_request change( unsigned short old_port, unsigned short new_port) { return control_request(old_port, new_port); } // Get the old port. Returns 0 for start requests. unsigned short old_port() const { std::istrstream is(data_, encoded_port_size); unsigned short port = 0; is >> std::setw(encoded_port_size) >> std::hex >> port; return port; } // Get the new port. Returns 0 for stop requests. unsigned short new_port() const { std::istrstream is(data_ + encoded_port_size, encoded_port_size); unsigned short port = 0; is >> std::setw(encoded_port_size) >> std::hex >> port; return port; } // Obtain buffers for reading from or writing to a socket. boost::array<asio::mutable_buffer, 1> to_buffers() { boost::array<asio::mutable_buffer, 1> buffers = { { asio::buffer(data_) } }; return buffers; } private: // Construct with specified old and new ports. control_request(unsigned short old_port_number, unsigned short new_port_number) { std::ostrstream os(data_, control_request_size); os << std::setw(encoded_port_size) << std::hex << old_port_number; os << std::setw(encoded_port_size) << std::hex << new_port_number; } // The length in bytes of a control_request and its components. enum { encoded_port_size = 4, // 16-bit port in hex. control_request_size = encoded_port_size * 2 }; // The encoded request data. char data_[control_request_size]; }; // This frame is sent from the server to subscribed clients over UDP. class frame { public: // The maximum allowable length of the payload. enum { payload_size = 32 }; // Construct an empty frame. Used when receiving. frame() { } // Construct a frame with specified frame number and payload. frame(unsigned long frame_number, const std::string& payload_data) { std::ostrstream os(data_, frame_size); os << std::setw(encoded_number_size) << std::hex << frame_number; os << std::setw(payload_size) << std::setfill(' ') << payload_data.substr(0, payload_size); } // Get the frame number. unsigned long number() const { std::istrstream is(data_, encoded_number_size); unsigned long frame_number = 0; is >> std::setw(encoded_number_size) >> std::hex >> frame_number; return frame_number; } // Get the payload data. const std::string payload() const { return std::string(data_ + encoded_number_size, payload_size); } // Obtain buffers for reading from or writing to a socket. boost::array<asio::mutable_buffer, 1> to_buffers() { boost::array<asio::mutable_buffer, 1> buffers = { { asio::buffer(data_) } }; return buffers; } private: // The length in bytes of a frame and its components. enum { encoded_number_size = 8, // Frame number in hex. frame_size = encoded_number_size + payload_size }; // The encoded frame data. char data_[frame_size]; }; #endif // PORTHOPPER_PROTOCOL_HPP
[ "ed@uetopia.com" ]
ed@uetopia.com
96df67c35d4f5c281f1430af34ff9b392319e33a
3505dc59e38763af442aeda7cef6307d0b2cc06e
/Lab_5/Exercise_B/circle.h
c38405d2ee666ddc032054acc118e557c152a61d
[]
no_license
ENSF-619/Lab_5
37c48b0edfbf236eec7b505633ecb2d0dcb039ce
9aa7248fe12f8cc2d9aed1878183a6394c71b305
refs/heads/master
2022-12-31T02:42:58.099688
2020-10-23T21:05:51
2020-10-23T21:05:51
305,926,762
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
h
/* *File Name: Exercise_B,circle.h * Lab_5 * Completed by Ziad Chemali * Submission: 23,10,2020 */ #include"shape.h" # ifndef PI #define PI 3.14159265358979323846 #endif #ifndef circle_h #define circle_h class Circle :public virtual Shape { public: /* * PROMISES: constructor for Circle that invokes Shape constructor */ Circle(double x, double y, double r, const char* name); /* * Overriding pure virtual area function in Shape class, * PROMISES: returns the area of circle */ double area() const override; /* * PROMISES: return radius */ double get_radius() const; /* * PROMISES: sets radius */ void set_radius(double num); /* * Overriding pure virtual area function in Shape class, * PROMISES: returns the perimeter of circle */ double perimeter() const override; /* * Overriding pure virtual area function in Shape class, * PROMISES: displays name, coordinates,radius, area, and perimeter of Circle */ void display() override; /* * PROMISES: copy constructor of Circle */ Circle (const Circle& r); /* * PROMISES: Overloads assignment operator of Circle */ Circle& operator=(Circle& rhs); private: double radius; }; #endif // !circle_h
[ "zchemali@ucalgary.ca" ]
zchemali@ucalgary.ca
a6d949fc7fb8f1ed55413a31cec855f55624d953
1cae4ca61d28c697330d64c579aba09553239f70
/includes/utilities.h
5428e3115d438d764a7ab950c3da3b03d54c6bcc
[]
no_license
wikoj1021/file_client
b756b86c0e0729a1b50dd787990d23b73fad3e04
20522817f4ad32e14ed16445602dd95a57a0f29b
refs/heads/master
2020-04-06T07:33:27.275605
2019-01-20T15:33:00
2019-01-20T15:33:00
157,276,881
0
0
null
null
null
null
UTF-8
C++
false
false
2,137
h
// // Created by wikoj on 13.11.2018. // #ifndef FILE_CLIENT_UTILITIES_H #define FILE_CLIENT_UTILITIES_H #include <string> #include <unordered_map> #include <iostream> #include <vector> namespace util{ static void toUpperCase(std::string &str){ for(char &c : str){ c = toupper(c); } } static void toLowerCase(std::string &str){ for(char &c : str){ c = tolower(c); } } static std::unordered_map<std::string, std::string> parseArgs(int argc, char **args){ std::unordered_map<std::string, std::string> mappedArgs; std::locale loc; for(int i = 1; i < argc; i++){ std::string arg(args[i]); if(arg.substr(0,2) == "--" && arg.erase(0,2) != ""){ util::toUpperCase(arg); std::string argVal(args[i+1]); if(i+1 >= argc || argVal.substr(0,2) == "--"){ mappedArgs.insert({arg, "1"}); continue; } util::toUpperCase(argVal); mappedArgs.insert({arg, argVal}); i++; } } #ifdef DEBUG for(std::pair<std::string, std::string> arg : mappedArgs){ std::cout << arg.first << " :: " << arg.second << std::endl; } #endif return mappedArgs; } static std::vector<std::string> parseCommandLine(std::string commandLine){ std::vector<std::string> commandArgs; std::size_t lastPos = 0; std::size_t aktPos = 0; do{ aktPos = commandLine.find(' ', lastPos+1); commandArgs.push_back(commandLine.substr(lastPos, aktPos-lastPos)); lastPos = aktPos+1; }while (aktPos != std::string::npos); util::toUpperCase(commandArgs[0]); #ifdef DEBUG std::cout << "command args: " << std::endl; for(std::string s : commandArgs){ std::cout << s << std::endl; } std::cout << "end of command args" << std::endl; #endif return commandArgs; } } #endif //FILE_CLIENT_UTILITIES_H
[ "wikoj1021@gmail.com" ]
wikoj1021@gmail.com
8bdea790ab914ea58c972c2d0b06c38d1b49cea0
98d693b8f1da98fd26be578bec53d20fdecd6346
/src/Cape.h
f4bfb95c9b7e68db2d724fab901e092c92700853
[]
no_license
NetjerDjehuty/INFOMGP
3b0a4bd5045d5af953f6a269fbeb6136d06a5fb3
1db56d158dd9b2bab6dab8580317be9920458615
refs/heads/master
2016-09-05T10:24:36.234695
2014-06-27T14:56:09
2014-06-27T14:56:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
h
#ifndef CAPE_H #define CAPE_H #include "BulletSoftBody/btSoftRigidDynamicsWorld.h" #include "Environment.h" // Cape class Cape { public: Cape (btSoftRigidDynamicsWorld* ownerWorld, Environment *environment, const btVector3& offset); // Constructor virtual ~Cape(); // Destructor void bindRigidBody(btRigidBody *body); // Bind the corners of the cape to some rigidbody void update(); // Taking new environment forces into account protected: btSoftRigidDynamicsWorld * m_ownerWorld; // The physics world of the simulation Environment * m_environment; // Calculating the wind force const btVector3& m_offset; // Inital offset of the cape btSoftBody * m_softBody; // Soft body representing the cape }; #endif
[ "jarno.leconte@me.com" ]
jarno.leconte@me.com
7cc4e5e80be84b538931736f2aa8952c629f2dc2
f0923ceb7f73de7d9d01e0a28140629f7d38764d
/src/client/Interface/Command/UICommand.cpp
9807817b8df470f4d9a79eb872c474b1f58f4efd
[]
no_license
uvbs/rose-137
95b1ca3ecf5ff4dc80a4a371c35c4090df8fde5a
78d886fc63b095e962727b35e6b31774ce16c576
refs/heads/master
2020-03-18T09:45:22.464847
2018-04-02T22:20:48
2018-04-02T22:20:48
134,579,008
1
0
null
2018-05-23T14:07:39
2018-05-23T14:07:39
null
UHC
C++
false
false
29,082
cpp
#include "stdafx.h" #include "uicommand.h" #include "CTCmdNumberInput.h" #include "Interface/CToolTipMgr.h" #include "interface/it_mgr.h" #include "Object.h" #include "System/CGame.h" #include "../Dlgs/CSeparateDlg.h" #include "../DLGs/COptionDlg.h" #include "../DLGs/AvatarInfoDlg.h" #include "../Dlgs/CNumberInputDlg.h" #include "../Dlgs/QuickToolBAR.h" #include "../Dlgs/CUpgradeDlg.h" #include "../Dlgs/DeliveryStoreDlg.h" #include "../DLGs/CSkillDLG.h" #include "../DLGs/CItemDlg.h" #include "Interface/Icon/CIconItem.h" #include "Interface/Icon/CIconDialog.h" #include "Common/CItem.h" #include "Common/IO_Pat.h" #include "GameData/CManufacture.h" #include "GameData/CSeparate.h" #include "GameData/cprivatestore.h" #include "GameCommon/Item.h" #include "System/CGame.h" #include "Network//CNetwork.h" #include "../Dlgs/CCommDlg.h" #include "../ClanMarkTransfer.h" #include "JCommandState.h" #include "../dlgs/subclass/CSlot.h" #include "interface/icon/ciconskill.h" #include "GameCommon/Skill.h" bool CTCmdTakeInItem2MakeDlg::Exec( CTObject* pObj ) { if( pObj == NULL ) { assert( pObj && "CTCmdTakeInItem2MakeDlg::Exec" ); return true; } if( strcmp( pObj->toString(),"CIcon" ) == 0 ) CManufacture::GetInstance().SetMaterialItem( ((CIconItem*)pObj)->GetCItem() ); else if( strcmp( pObj->toString(), "CItem" ) == 0 ) CManufacture::GetInstance().SetMaterialItem( (CItem*)pObj ); else assert( 0 && "Invalid TObject Type @CTCmdTakeInItem2makedlg" ); return true; } bool CTCmdTakeOutItemFromMakeDlg::Exec( CTObject* pObj ) { if( pObj == NULL ) { assert( pObj && "CTCmdTakeOutItemFromMakeDlg::Exec" ); return true; } if( strcmp( pObj->toString(),"CIcon" ) == 0 ) CManufacture::GetInstance().RemoveMaterialItem( ((CIconItem*)pObj)->GetCItem() ); else if( strcmp( pObj->toString(), "CItem" ) == 0 ) CManufacture::GetInstance().RemoveMaterialItem( (CItem*)pObj ); else assert( 0 && "Invalid TObject Type @CTCmdTakeOutItemFrommakedlg" ); return true; } bool CTCmdTakeOutItemFromSeparateDlg::Exec( CTObject* pObj ) { if( pObj == NULL ) { assert( pObj ); return true; } if( strcmp( pObj->toString(),"CIcon" ) == 0 ) CSeparate::GetInstance().RemoveItem(); else assert( 0 && "Invalid TObject Type @CTCmdTakeOutItemFromSeparateDlg" ); return true; } ///*----------------------------------------------------------------------------------------- //CTCmdAssembleRideItem::CTCmdAssembleRideItem( short nPartIdx, short nInvenIdx , short nEquipedBodyPartItemNo ) //{ // m_nPartIdx = nPartIdx; // m_nInvenIdx = nInvenIdx; // m_nEquipedBodyPartItemNo = nEquipedBodyPartItemNo; //} bool CTCmdAssembleRideItem::Exec( CTObject* pObj ) { if( g_pAVATAR->GetPetMode() >= 0 ) { if( ( g_pAVATAR->GetPetState() != CS_STOP ) ) { g_itMGR.AppendChatMsg( STR_ACTION_COMMAND_STOP_STATE_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); return false; } } #ifdef _GBC // 홍근 : 2인승 카트 // 카트 보조석에 게스트가 타고 있을때, // 카트 보조석에 타고 있을때 // 아이템 교환 금지. if( g_pAVATAR->GetRideUserIndex() || g_pAVATAR->IsRideUser() ) { g_itMGR.AppendChatMsg( STR_BOARDING_CANT_USE, IT_MGR::CHAT_TYPE_SYSTEM ); return false; } #endif if( pObj == NULL ) { assert( pObj && "pObj is NULL @CTCmdAssembleRideItem::Exec" ); return true; } short nInvenIdx = 0; short nItemNo = 0; if( strcmp(pObj->toString(), "CIcon" ) == 0 ) { CIconItem* pItemIcon = (CIconItem*)pObj; nItemNo = pItemIcon->GetItemNo(); nInvenIdx = pItemIcon->GetIndex(); } else if( strcmp( pObj->toString(), "CItem" ) == 0 ) { CItem* pItem = (CItem*)pObj; nItemNo = pItem->GetItemNo(); nInvenIdx = pItem->GetIndex(); } else { assert( 0 && "Invalid TObject Type @CTCmdAssembleRideItem::Exec" ); return true; } short nPartIdx = PAT_ITEM_PART_IDX( nItemNo ); CItemSlot* pItemSlot = g_pAVATAR->GetItemSlot(); CItem* pBodyItem = pItemSlot->GetItem( INVENTORY_RIDE_ITEM0 );///장착되어있는 아이템 CItem* pItem = pItemSlot->GetItem( nInvenIdx );///장착하려는 아이템 if( pItem == NULL ) { assert( pItem ); return true; } if( !g_pAVATAR->Check_PatEquipCondition ( pItem->GetItem() ) ) { g_itMGR.AppendChatMsg( STR_NOTIFY_06, IT_MGR::CHAT_TYPE_SYSTEM ); return false; } #if defined(_GBC) ///직업 제한 if( !g_pAVATAR->Check_JobCollection(PAT_ITEM_EQUIP_REQUIRE_CLASS( nItemNo )) ) { g_itMGR.AppendChatMsg( STR_NOT_ENOUGH_CONDITION, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } #endif if( nPartIdx != RIDE_PART_BODY ) { if( pBodyItem ) { if( PAT_ITEM_PART_TYPE( pBodyItem->GetItemNo() ) != PAT_ITEM_PART_TYPE( nItemNo ) ) { g_itMGR.AppendChatMsg(STR_PAT_ERROR_NOT_EQUAL_CLASS, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } if( PAT_ITEM_PART_VER( pBodyItem->GetItemNo() ) < PAT_ITEM_PART_VER( nItemNo ) ) { g_itMGR.AppendChatMsg(STR_PAT_ERROR_NOT_VERSION, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } } else { g_itMGR.AppendChatMsg(STR_PAT_ERROR_NOT_EQUIP_BODY, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } } else///바디 부품일경우 { if( g_pAVATAR->GetPetMode() >= 0 )///드라이브 스킬 사용중이라면 { ///같은 타입만 장착할수 있다. if( pBodyItem && PAT_ITEM_PART_TYPE( pBodyItem->GetItemNo() ) != PAT_ITEM_PART_TYPE( pItem->GetItemNo() ) ) { g_itMGR.AppendChatMsg(STR_PAT_ERROR_NOT_EQUAL_CLASS, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } CItem* pPartItem = NULL; for( int i = 1; i < MAX_RIDING_PART; ++i ) { pPartItem = pItemSlot->GetItem( INVENTORY_RIDE_ITEM0 + i); if( pPartItem ) { if( PAT_ITEM_PART_TYPE( pItem->GetItemNo() ) != PAT_ITEM_PART_TYPE( pPartItem->GetItemNo() )) { g_itMGR.AppendChatMsg(STR_PAT_ERROR_NOT_EQUAL_CLASS, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } if( PAT_ITEM_PART_VER( pItem->GetItemNo() ) < PAT_ITEM_PART_VER( pPartItem->GetItemNo() ) ) { g_itMGR.AppendChatMsg(STR_ERROR_EQUIP_PAT_BODY_VER, IT_MGR::CHAT_TYPE_SYSTEM ); return true; } } } } else///드라이브 스킬 사용중이 아니라면 { /// 새로 장착하는 Body와 다른 Parts가 장착되어 있다면 다 떨군다. /// 새로 장착하는 Body의 버젼보다 낮은 부품이 있다면 다 떨군다. CItem* pPartItem = NULL; //06. 12. 11 - 김주현 : 기존 코드는 부품을 해제하다가 공간이 부족하면 취소를 해서 아이템이 이상하게 장착되던 문제가 있었다. //그래서 미리 필요한 공간을 계산해서 모자랄 경우에 메세지를 찍고 false를 리턴하게 수정. int iCountPartItem = 0; for( int i = 1; i < MAX_RIDING_PART; ++i ) { pPartItem = pItemSlot->GetItem( INVENTORY_RIDE_ITEM0 + i); if(pPartItem) { if( PAT_ITEM_PART_TYPE( pItem->GetItemNo() ) != PAT_ITEM_PART_TYPE( pPartItem->GetItemNo() ) ) { iCountPartItem++; } else if( PAT_ITEM_PART_VER( pItem->GetItemNo() ) < PAT_ITEM_PART_VER( pPartItem->GetItemNo() ) ) { iCountPartItem++; } } } tagITEM sItem = pItem->GetItem(); t_InvTYPE Type = g_pAVATAR->m_Inventory.GetInvPageTYPE( sItem ); if( g_pAVATAR->m_Inventory.GetEmptyInvenSlotCount( Type ) < iCountPartItem ) { g_itMGR.AppendChatMsg(STR_NOT_ENOUGH_INVENTORY_SPACE, IT_MGR::CHAT_TYPE_SYSTEM ); return false; } for( int i = 1; i < MAX_RIDING_PART; ++i ) { pPartItem = pItemSlot->GetItem( INVENTORY_RIDE_ITEM0 + i); if( pPartItem ) { if( PAT_ITEM_PART_TYPE( pItem->GetItemNo() ) != PAT_ITEM_PART_TYPE( pPartItem->GetItemNo() ) ) { g_pNet->Send_cli_ASSEMBLE_RIDE_ITEM( i, 0 ); } else if( PAT_ITEM_PART_VER( pItem->GetItemNo() ) < PAT_ITEM_PART_VER( pPartItem->GetItemNo() ) ) { g_pNet->Send_cli_ASSEMBLE_RIDE_ITEM( i, 0 ); } } } } } g_pNet->Send_cli_ASSEMBLE_RIDE_ITEM( nPartIdx, nInvenIdx ); return true; } bool CTCmdDisAssembleRideItem::Exec( CTObject* pObj ) { if( pObj == NULL ) { assert( pObj && "pObj is NULL @CTCmdDisAssembleRideItem::Exec" ); return true; } short nPartIdx; if( strcmp(pObj->toString(), "CIcon" ) == 0 ) { CIconItem* pItemIcon = (CIconItem*)pObj; nPartIdx = pItemIcon->GetIndex() - INVENTORY_RIDE_ITEM0; g_pNet->Send_cli_ASSEMBLE_RIDE_ITEM( nPartIdx, 0 ); } else if( strcmp( pObj->toString(), "CItem" ) == 0 ) { CItem* pItem = (CItem*)pObj; nPartIdx = pItem->GetIndex() - INVENTORY_RIDE_ITEM0; g_pNet->Send_cli_ASSEMBLE_RIDE_ITEM( nPartIdx, 0 ); } else { assert( 0 && "Invalid TObject Type @CTCmdDisAssembleRideItem::Exec" ); } return true; } ///*----------------------------------------------------------------------------------------- ///*----------------------------------------------------------------------------------------- CTCmdOpenNumberInputDlg::CTCmdOpenNumberInputDlg(void) { m_pCmd = NULL; m_i64Maximum = 0; m_iType = CNumberInputDlg::TYPE_USE_MAX_HIDE; } bool CTCmdOpenNumberInputDlg::Exec( CTObject* pObj ) { CTDialog* pDlg = NULL; pDlg = g_itMGR.FindDlg( DLG_TYPE_N_INPUT ); if( pDlg ) { CNumberInputDlg* pNInputDlg = (CNumberInputDlg*)pDlg; __int64 iMaxNumber = 0; CTObject* pCmdParam = NULL; if( pObj == NULL )///돈일경우 { iMaxNumber = (int)m_i64Maximum; LogString( LOG_NORMAL,"maximum money is 0" ); if( iMaxNumber == 0 ) return true; } else if( strcmp( pObj->toString(), "CIcon" ) == 0 )///드래그앤드랍에서 실행되었을 경우 { tagITEM& Item = ((CIconItem*)pObj)->GetItem(); pCmdParam = ((CIconItem*)pObj)->GetCItem(); if( Item.IsEnableDupCNT() ) { if( m_i64Maximum ) iMaxNumber = m_i64Maximum; else iMaxNumber = Item.GetQuantity(); } else iMaxNumber = 1; } else if( strcmp( pObj->toString(), "CItem" ) == 0 ) { tagITEM& Item = ((CItem*)pObj)->GetItem(); pCmdParam = pObj; if( Item.IsEnableDupCNT() ) { if( m_i64Maximum ) iMaxNumber = m_i64Maximum; else iMaxNumber = Item.GetQuantity(); } else iMaxNumber = 1; } else { assert( 0 && "알수 없는 CTobject Type @CTCmdOpenNumberInputDlg::Exec" ); return true; } if( iMaxNumber > 1 ) { pNInputDlg->SetMaxNumber( iMaxNumber ); pNInputDlg->SetNumberInputType(m_iType); pNInputDlg->SetCommand( m_pCmd, pCmdParam ); g_itMGR.OpenDialog( DLG_TYPE_N_INPUT ); } else if( iMaxNumber == 1 ) { m_pCmd->SetNumber( 1 ); m_pCmd->Exec( pCmdParam ); } else { assert( 0 && "Maximum 값이 0보다 작거나 같다"); } } return true; } void CTCmdOpenNumberInputDlg::SetCommand( CTCmdNumberInput* pCmd ) { m_pCmd = pCmd; } void CTCmdOpenNumberInputDlg::SetMaximum( __int64 i64Maximum ) { m_i64Maximum = i64Maximum; } void CTCmdOpenNumberInputDlg::SetNumberInputType(int iType) { m_iType = iType; } //*--------------------------------------------------------------------- #include "../dlgs/CAvatarStoreDlg.h" bool CTCmdDragItem2AvatarStoreDlg::Exec( CTObject* pObj ) { if( pObj == NULL || strcmp( pObj->toString(), "CIcon" ) ) { assert( 0 && "pObj is NULL or Invalid Type" ); return true; } CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_AVATARSTORE ); if( pDlg ) { CAvatarStoreDlg* pStoreDlg = ( CAvatarStoreDlg*) pDlg; CIconItem* pItemIcon = (CIconItem*)pObj; int iCount = pStoreDlg->IsBuyItem( pItemIcon->GetItem() ); if( iCount > 0 ) { m_i64Maximum = iCount; CTCmdOpenNumberInputDlg::Exec(pItemIcon->GetCItem()); } } return true; } CTCmdAcceptAddFriend::CTCmdAcceptAddFriend( WORD wUserIdx, BYTE btStatus, const char* pszName ) { m_wUserIdx = wUserIdx; m_btStatus = btStatus; assert( pszName ); if( pszName ) m_strName = pszName; } bool CTCmdAcceptAddFriend::Exec(CTObject* pObj ) { g_pAVATAR->SetAddFriendWnd(false); g_pNet->Send_cli_MCMD_APPEND_REPLY( MSGR_CMD_APPEND_ACCEPT, m_wUserIdx , (char*)m_strName.c_str() ); return true; } CTCmdRejectAddFriend::CTCmdRejectAddFriend( WORD wUserIdx , const char* pszName ) { m_wUserIdx = wUserIdx; m_strName = pszName; } bool CTCmdRejectAddFriend::Exec( CTObject* pObj ) { g_pAVATAR->SetAddFriendWnd(false); g_pNet->Send_cli_MCMD_APPEND_REPLY( MSGR_CMD_APPEND_REJECT, m_wUserIdx , (char*)m_strName.c_str() ); return true; } CTCmdRemoveFriend::CTCmdRemoveFriend( DWORD dwUserTag ) { m_dwUserTag = dwUserTag; } bool CTCmdRemoveFriend::Exec( CTObject* pObj ) { g_pNet->Send_cli_MCMD_TAG( MSGR_CMD_DELETE, m_dwUserTag ); CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_COMMUNITY ); assert( pDlg ); if( pDlg ) { CCommDlg* pCommDlg = ( CCommDlg* )pDlg; pCommDlg->RemoveFriend( m_dwUserTag ); } return true; } CTCmdAbandonQuest::CTCmdAbandonQuest( int iQuestSlotIdx,int iQuestID ) { m_iQuestSlotIdx = iQuestSlotIdx; m_iQuestID = iQuestID; } bool CTCmdAbandonQuest::Exec( CTObject* pObj ) { g_pNet->Send_cli_QUEST_REQ (TYPE_QUEST_REQ_DEL, m_iQuestSlotIdx, m_iQuestID ); return true; } CTCmdSendPacketDropItem::CTCmdSendPacketDropItem( short nInvenIdx, int iQuantity ) { m_nInvenIdx = nInvenIdx; m_iQuantity = iQuantity;; } bool CTCmdSendPacketDropItem::Exec( CTObject* pObj ) { LogString( LOG_NORMAL,CStr::Printf( "Send_cli_Drop_item %d %d" , m_nInvenIdx, m_iQuantity ) ); g_pNet->Send_cli_DROP_ITEM( m_nInvenIdx, m_iQuantity ); return true; } bool CTCmdMoveDialogIcon2Ground::Exec( CTObject* pObj ) { assert( pObj ); if( pObj == NULL ) return true; CIconDialog* pIcon = (CIconDialog*)pObj; POINT ptMouse; CGame::GetInstance().Get_MousePos( ptMouse ); ptMouse.x -= pIcon->GetWidth() / 2; ptMouse.y -= pIcon->GetHeight() / 2; g_itMGR.SetDialogIconPosition( pIcon->GetDialogType(), ptMouse ); return true; } bool CTCmdMoveDialogIcon2GroundFromMenu::Exec( CTObject* pObj ) { assert( pObj ); if( pObj == NULL ) return true; CIconDialog* pIcon = (CIconDialog*)pObj; POINT ptMouse; CGame::GetInstance().Get_MousePos( ptMouse ); ptMouse.x -= pIcon->GetWidth() / 2; ptMouse.y -= pIcon->GetHeight() / 2; g_itMGR.SetDialogIconPosition( pIcon->GetDialogType(), ptMouse ); g_itMGR.AddDialogIcon( pIcon->GetDialogType() ); return true; } CTCmdRemoveDialogIcon::CTCmdRemoveDialogIcon( int iDialogType ) { m_iDialogType = iDialogType; } bool CTCmdRemoveDialogIcon::Exec( CTObject* pObj ) { g_itMGR.DelDialogIcon( m_iDialogType ); return true; } bool CTCmdRegistDialogIcon2QuickBar::Exec( CTObject* pObj ) { if( pObj == NULL ) { assert( 0 && "Invalid Param @CTCmdDragInven2QuickBar::Exec" ); return true; } CIconDialog* pIcon = (CIconDialog*)pObj; POINT ptMouse; CGame::GetInstance().Get_MousePos( ptMouse ); CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_QUICKBAR ); if( pDlg == NULL ) { assert( 0 && "Not Found QuickBar Dialog @CTCmdDragInven2QuickBar::Exec" ); return true; } CQuickBAR* pQuickBar = (CQuickBAR*)pDlg; short nQuickSlotIdx = pQuickBar->GetMouseClickSlot( ptMouse ); if( nQuickSlotIdx == -1 )///해당 위치에 슬롯이 없다. return true; tagHotICON hotICON; hotICON.m_cType = DIALOG_ICON; hotICON.m_nSlotNo = pIcon->GetDialogType(); if( hotICON.m_nSlotNo < 0 || hotICON.m_nSlotNo >= DLG_TYPE_MAX ) { assert( 0 && "Invalid Dialog Type @CTCmdRegistDialogIcon2QuickBar::Exec" ); return true; } g_pNet->Send_cli_SET_HOTICON( (BYTE)nQuickSlotIdx, hotICON ); return true; } CTCmdAddItem2WishList::CTCmdAddItem2WishList( tagITEM& Item ) { m_Item = Item; } bool CTCmdAddItem2WishList::Exec( CTObject* pObj ) { CPrivateStore::GetInstance().AddItemWishList( m_Item, true ); return true; } CTCmdChangeStateUpgradeDlg::CTCmdChangeStateUpgradeDlg( int iState ) { m_iState = iState; } bool CTCmdChangeStateUpgradeDlg::Exec( CTObject* pObj ) { if( CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_UPGRADE ) ) { CUpgradeDlg* pUpgradeDlg = (CUpgradeDlg*)pDlg; pUpgradeDlg->ChangeState( m_iState ); } return true; } bool CTCmdEndRepair::Exec( CTObject* pObj ) { CGame::GetInstance().EndRepair(); return true; } bool CTCmdEndAppraisal::Exec( CTObject* pObj ) { CGame::GetInstance().EndAppraisal(); return true; } bool CTCmdEndMakeSocket::Exec( CTObject* pObj ) { CGame::GetInstance().EndMakeSocket(); return true; } CTCmdSendAppraisalReq::CTCmdSendAppraisalReq( int iIndex ) { m_iIndex = iIndex; } bool CTCmdSendAppraisalReq::Exec( CTObject* pObj ) { g_pNet->Send_cli_APPRAISAL_REQ( m_iIndex ); return true; } CTCmdQuerySellItem2PrivateStore::CTCmdQuerySellItem2PrivateStore( WORD wSellerSvrIdx, int iItemCount, tagSELL_ITEM& Item ) { m_wSellerSvrIdx = wSellerSvrIdx; m_iItemCount = iItemCount; m_SellItem = Item; } bool CTCmdQuerySellItem2PrivateStore::Exec( CTObject* pObj ) { g_pNet->Send_cli_P_STORE_SELL_REQ( m_wSellerSvrIdx, m_iItemCount, &m_SellItem ); return true; } CTCmdQueryBuyItemFromPrivateStore::CTCmdQueryBuyItemFromPrivateStore( WORD wSellerSvrIdx, int iItemCount, tagPS_SLOT_ITEM& Item ) { m_wSellerSvrIdx = wSellerSvrIdx; m_iItemCount = iItemCount;; m_BuyItem = Item; } bool CTCmdQueryBuyItemFromPrivateStore::Exec( CTObject* pObj ) { g_pNet->Send_cli_P_STORE_BUY_REQ( m_wSellerSvrIdx, m_iItemCount, &m_BuyItem ); return true; } CTCmdAcceptReqJoinClan::CTCmdAcceptReqJoinClan( const char* pszMasterName ) { assert( pszMasterName ); if( pszMasterName ) m_strMasterName = pszMasterName; } bool CTCmdAcceptReqJoinClan::Exec( CTObject* pObj ) { assert( m_strMasterName.c_str() ); if( m_strMasterName.c_str() ) g_pNet->Send_cli_CLAN_COMMAND( GCMD_INVITE_REPLY_YES , (char*)m_strMasterName.c_str() ); return true; } CTCmdRejectReqJoinClan::CTCmdRejectReqJoinClan( const char* pszMasterName ) { assert( pszMasterName ); if( pszMasterName ) m_strMasterName = pszMasterName; } bool CTCmdRejectReqJoinClan::Exec( CTObject* pObj ) { assert( m_strMasterName.c_str() ); if( m_strMasterName.c_str() ) g_pNet->Send_cli_CLAN_COMMAND( GCMD_INVITE_REPLY_NO , (char*)m_strMasterName.c_str() ); return true; } CTCmdClanCommand::CTCmdClanCommand( BYTE btCmd, const char* pszMsg ) { m_btCmd = btCmd; if( pszMsg ) m_strMsg = pszMsg; else m_strMsg.clear(); } bool CTCmdClanCommand::Exec( CTObject* pObj ) { if( m_strMsg.empty() ) { g_pNet->Send_cli_CLAN_COMMAND( m_btCmd, NULL ); // 클랜 해체 및 클랜 탈퇴시 //if ( m_btCmd == GCMD_DISBAND ) // || m_btCmd == GCMD_QUIT ) //{ // g_pNet->Send_cli_CLANWAR_INFO( 3 ); //} } else { g_pNet->Send_cli_CLAN_COMMAND( m_btCmd, (char*)m_strMsg.c_str() ); // 클랜장이 클랜원 강제 탈퇴시 //if ( m_btCmd == GCMD_REMOVE ) //{ // g_pNet->Send_cli_CLANWAR_INFO( 4 ); //} } return true; } bool CTCmdCancelWaitDisconnect::Exec( CTObject* pObj ) { g_pNet->Send_cli_LOGOUT_CANCEL(); g_itMGR.ChangeState( IT_MGR::STATE_NORMAL ); return true; } /*--------------------------------------------------------------------------------------------------------------*/ void CTCmdInputName::SetName( const char* pszName ) { assert( pszName && strlen( pszName ) > 0); if( pszName && strlen( pszName ) > 0 ) m_name = pszName; } bool CTCmdInputName::Exec( CTObject* pObj ) { return true; } /*--------------------------------------------------------------------------------------------------------------*/ bool CTCmdInputNameGiftReceiver::Exec( CTObject* pObj ) { if( m_name.empty() ) return true; if( CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_DELIVERYSTORE ) ) { CDeliveryStoreDlg* p = (CDeliveryStoreDlg*)pDlg; p->save_receiver_name( m_name.c_str() ); } g_pNet->Send_cli_MAIL_ITEM_FIND_CHAR( (char*)m_name.c_str() ); return true; } CTCmdGiftMallItem::CTCmdGiftMallItem( BYTE slotindex, const char* name ) { assert( name ); if( name ) { m_slotindex = slotindex; m_name = name; } } bool CTCmdGiftMallItem::Exec( CTObject* pObj ) { if( !m_name.empty() ) g_pNet->Send_cli_MALL_ITEM_GIVE( m_slotindex, (char*)m_name.c_str() ); return true; } CTCmdRegisterClanMark::CTCmdRegisterClanMark( int clan_id, const char* filename ) { m_clan_id = clan_id; assert( filename ); if( filename ) m_filename = filename; } bool CTCmdRegisterClanMark::Exec( CTObject* pObj ) { if( m_filename.empty() ) return true; CClanMarkTransfer::GetSingleton().RegisterMarkToServer( m_clan_id, m_filename.c_str() ); return true; } CTCmdChangeStateInterface::CTCmdChangeStateInterface( int state ) { m_state = state; } bool CTCmdChangeStateInterface::Exec( CTObject* pObj ) { g_itMGR.ChangeState( m_state ); return true; } CTCmdSetOption::CTCmdSetOption(const char * pszOption, const char * pszStatus) { m_pszOption = pszOption; m_pszStatus = pszStatus; } bool CTCmdSetOption::Exec(CTObject* pObj) { CTDialog * pDialog = NULL; CWinCtrl * pCtrl = NULL; if( strcmp( m_pszOption, "CTRL")==0 || strcmp( m_pszOption, "CHAT")==0 || strcmp( m_pszOption, "SOUND")==0) { pDialog = g_itMGR.FindDlg( DLG_TYPE_INFO ); assert( pDialog ); ((CAvatarInfoDlg*)pDialog)->SetOptionStatus(m_pszOption, m_pszStatus); pDialog = g_itMGR.FindDlg( DLG_TYPE_OPTION ); assert( pDialog ); ((COptionDlg*)pDialog)->SetOptionStatus(m_pszOption, m_pszStatus); } else if( strcmp( m_pszOption, "TIP")==0 ) { if( strcmp( m_pszStatus, "SHOW" )==0 ) { CToolTipMgr::GetInstance().Show(); } else { CToolTipMgr::GetInstance().Show(false); } } return true; } CTCmdChangeStateSeparateDlg::CTCmdChangeStateSeparateDlg( int iState ) { m_iState = iState; } bool CTCmdChangeStateSeparateDlg::Exec( CTObject* pObj ) { if( CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_SEPARATE ) ) { CSeparateDlg* pSeparateDlg = (CSeparateDlg*)pDlg; pSeparateDlg->ChangeState( m_iState ); } return true; } CTCmdItemUpgradeOk::CTCmdItemUpgradeOk(BYTE btType, short nSkillSLOTorNpcIDX, BYTE btTargetInvIDX, BYTE btUseItemINV[ UPGRADE_ITEM_STEP ]) { m_btType = btType; m_nSkillSLOTorNpcIDX = nSkillSLOTorNpcIDX; m_btTargetInvIDX = btTargetInvIDX; for( int i = 0 ; i < UPGRADE_ITEM_STEP; ++i ) m_btUseItemINV[i] = btUseItemINV[i]; } bool CTCmdItemUpgradeOk::Exec( CTObject* pObj ) { g_pNet->Send_cli_CRAFT_UPGRADE_REQ( m_btType, m_nSkillSLOTorNpcIDX, m_btTargetInvIDX, m_btUseItemINV ); return true; } #include "GameData/CUpgrade.h" CTCmdItemUpgradeCancel::CTCmdItemUpgradeCancel() { } bool CTCmdItemUpgradeCancel::Exec( CTObject* pObj ) { CUpgrade::GetInstance().RemoveTargetItem(); if( CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_UPGRADE ) ) { CUpgradeDlg* pUpgradeDlg = (CUpgradeDlg*)pDlg; pUpgradeDlg->ChangeState( 0 ); // 0 = NORMAL_ } return true; } CTCmdSetSkillDlg::CTCmdSetSkillDlg( int iJobIndex ) { m_iJobIndex = iJobIndex; } bool CTCmdSetSkillDlg::Exec( CTObject* pObj ) { if( CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_SKILL ) ) { CSkillDLG * pSkillDlg = (CSkillDLG*)pDlg; pSkillDlg->Set_Skill4Job( m_iJobIndex ); } return true; } CTCmdLearnSkill::CTCmdLearnSkill(CIconSkill * pSkillIcon) { m_pSkillIcon = pSkillIcon; } bool CTCmdLearnSkill::Exec( CTObject* pObj ) { if( m_pSkillIcon ) { int iSkillBookIndex = SKILL_NEED_SKILLBOOK( m_pSkillIcon->GetSkill()->GetClanSkillSlot() ); if( CTDialog* pDlg = g_itMGR.FindDlg( DLG_TYPE_ITEM ) ) { CSlot * pSlot = ((CItemDlg*)pDlg)->SearchItem_Inventory( iSkillBookIndex ); if( pSlot ) { if( pSlot->GetIcon() ) { pSlot->GetIcon()->ExecuteCommand(); } else if( pSlot->GetCommand() ) { pSlot->GetCommand()->Exec( NULL ); } return true; } } } //문자열 추가. //스킬북이 없습니다. g_itMGR.OpenMsgBox( LIST_STRING(912) ); return false; } CTCmdUpdateLearnAbleSkill::CTCmdUpdateLearnAbleSkill() { } bool CTCmdUpdateLearnAbleSkill::Exec(CTObject * pObj) { CTDialog * pDlg = g_itMGR.FindDlg( DLG_TYPE_SKILL ); if( pDlg && pDlg->IsVision() ) { ((CSkillDLG*)pDlg)->Update_LearnSkill(); } return false; } //홍근: 아이템 사용. CTCmdUseItem::CTCmdUseItem(CItem * pItem) { m_pItem = pItem; m_bTargetSkill = false; } bool CTCmdUseItem::Exec( CTObject* pObj ) { if(USEITEM_TYPE( m_pItem->GetItem().GetItemNO() )==USE_ITEM_SKILL_LEARN) { BYTE btT = g_pAVATAR->Skill_LearnCondition( USEITEM_SCROLL_LEARN_SKILL( m_pItem->GetItem().GetItemNO() ) ); if( btT != RESULT_SKILL_LEARN_SUCCESS ) { switch( btT ) { case RESULT_SKILL_LEARN_FAILED : // 배우기 실패. g_itMGR.AppendChatMsg( STR_LEARN_SKILL_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); break; case RESULT_SKILL_LEARN_NEED_JOB : // 직업이 일치하지 않는다. g_itMGR.AppendChatMsg( STR_LEARN_SKILL_JOB_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); break; case RESULT_SKILL_LEARN_NEED_SKILL : // 보유할 스킬이 필요한다. g_itMGR.AppendChatMsg( STR_LEARN_SKILL_NEED_PRESKILL_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); break; case RESULT_SKILL_LEARN_NEED_ABILITY : // 능력치가 부족하다 g_itMGR.AppendChatMsg( STR_LEARN_SKILL_NEED_ABILITY_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); break; case RESULT_SKILL_LEARN_OUTOFSLOT : // 더이상 스킬을 배울수 없다. g_itMGR.AppendChatMsg( STR_LEARN_SKILL_SLOT_FULL_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); break; case RESULT_SKILL_LEARN_INVALID_SKILL : // 잘못된 스킬번호 입니다. g_itMGR.AppendChatMsg( STR_LEARN_SKILL_INVALID_SKILL_FAILED, IT_MGR::CHAT_TYPE_SYSTEM ); break; case RESULT_SKILL_LEARN_OUTOFPOINT :// 0x07 // 스킬 포인트 부족 g_itMGR.AppendChatMsg( STR_NOT_ENOUGH_SKILLPOINT, IT_MGR::CHAT_TYPE_SYSTEM ); break; default: break; } return true; } } if ( g_pNet->Send_cli_USE_ITEM( m_pItem->GetIndex(), m_bTargetSkill, g_UserInputSystem.GetCurrentTarget() ) ) { g_pSoundLIST->IDX_PlaySound( USEITEM_USE_SOUND( m_pItem->GetItem().m_nItemNo_1) ); } return false; } //======================================================================================= // // 클랜전과련 UI Callback // //======================================================================================= #ifdef __CLAN_WAR_SET #include "System/SystemProcScript.h" // 클래스 정적 변수 초기화 bool CTCmdClanWarJoinAck::isPresent = false; int CTCmdClanWarJoinAck::err = 0; DWORD CTCmdClanWarJoinAck::time = 120000; //--------------------------------------------------------------------------------------- // Name : EnterTheClanField() // Desc : Helper inline for below function // Author: Antonio - 2006-07-26 오후 4:55:32 //--------------------------------------------------------------------------------------- inline void EnterTheClanField( gsv_cli_CLAN_WAR_OK *p, bool isCancel ) { char psz[_MAX_PATH] = { '\0' }; if ( CTCmdClanWarJoinAck::err == 1 ) { sprintf( psz, STR_CLANWAR_ABSTENTION ); g_itMGR.OpenMsgBox( psz ); CTCmdClanWarJoinAck::err = 0; isCancel = true; } else if ( CTCmdClanWarJoinAck::err == 2 ) { sprintf( psz, STR_CLANWAR_QUEST_LIST_FULL ); g_itMGR.OpenMsgBox( psz ); CTCmdClanWarJoinAck::err = 0; isCancel = true; } if ( p->m_Sub_Type == 1 ) // 클랜장인 경우 { if ( isCancel ) // 클랜전 포기시 NPC 변수 초기화 { CSystemProcScript::GetSingleton().CallLuaFunction( "RejectJoinClanWar", ZZ_PARAM_END ); } else // 클랜전 승인시 클랜전 퀘스트 등록 { CSystemProcScript::GetSingleton().CallLuaFunction( "RequestJoinClanWar", ZZ_PARAM_END ); } } if ( isCancel ) // 클랜전 포기 코드 설정 { p->m_Sub_Type = 100; //홍근 : 재입장 거부시 존번호 0으로 세팅. 20070509 if( p->m_Team_N == p->m_Zone_N ) { p->m_Zone_N = 0; } } g_pNet->Send_cli_CLANWAR_JOIN_ACK( p ); } //--------------------------------------------------------------------------------------- // Name : CTCmdJoinAckClanWar // Desc : "클랜전에 입장하겠냐?"는 응답 대화상자에 handler // Author: Antonio - 2006-07-24 오후 12:31:10 //--------------------------------------------------------------------------------------- bool CTCmdClanWarJoinAck::Exec( CTObject *pObj ) { bool isCancel = false; if ( isOK ) { if ( isRecured ) { isCancel = true; } EnterTheClanField( &p, isCancel ); } else { if ( !isRecured ) // 첫번째 대화상자 (입장하겠냐?) "Cancel"은 포기 확인 대화상자 출력 { char psz[_MAX_PATH]; CTCmdClanWarJoinAck *pCmdOk = new CTCmdClanWarJoinAck( &p, true, true ); CTCmdClanWarJoinAck *pCmdCancel = new CTCmdClanWarJoinAck( &p, false, true ); short btType = CMsgBox::BT_OK | CMsgBox::BT_CANCEL; if ( p.m_Sub_Type == 1 ) { sprintf( psz, STR_CLANWAR_JOIN_REQ_RECONFIRM_M ); } else { sprintf( psz, STR_CLANWAR_JOIN_REQ_RECONFIRM_S ); } g_itMGR.OpenMsgBox( psz, btType, false, 0, pCmdOk, pCmdCancel, CMsgBox::MSGTYPE_RECV_CLANWAR_JOIN_REQ_RECONFIRM, "MsgBox", true, CTCmdClanWarJoinAck::time, CMsgBox::CHECKCOMMAND_NONE ); } else // 두번째 대화상자 (포기하겠냐?) "Cancel"은 입장 { EnterTheClanField( &p, isCancel ); } } return true; } #endif
[ "ralphminderhoud@gmail.com" ]
ralphminderhoud@gmail.com
d4e862b6939c86f2659bb0c576d68ea44f2f3c03
1184517c3afb6ba9a291bc452c4ddc7467ce19ba
/extern/optix-7.3.0/SDK/lib/DemandLoading/include/DemandLoading/TileIndexing.h
395a9f9586bb5a668aa4198dddfd5e86333821fa
[]
no_license
DennisVanEe/cs259_proj
a5ec3658e9a76bb09dbbb3af02806dfd528f2bc5
d68c5f2874d4090b9b71ec080af9e07bcb15142e
refs/heads/main
2023-04-27T07:57:46.131081
2021-05-18T21:05:47
2021-05-18T21:05:47
368,666,273
0
0
null
null
null
null
UTF-8
C++
false
false
7,323
h
// // Copyright (c) 2021 NVIDIA Corporation. All rights reserved. // // NVIDIA Corporation and its licensors retain all intellectual property and proprietary // rights in and to this software, related documentation and any modifications thereto. // Any use, reproduction, disclosure or distribution of this software and related // documentation without an express license agreement from NVIDIA Corporation is strictly // prohibited. // // TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* // AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, // INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY // SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT // LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF // BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR // INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGES // #pragma once #include <DemandLoading/TextureSampler.h> #ifndef __CUDACC_RTC__ #include <cuda.h> #include <texture_types.h> #else enum CUaddress_mode { CU_TR_ADDRESS_MODE_WRAP = 0, CU_TR_ADDRESS_MODE_CLAMP = 1, CU_TR_ADDRESS_MODE_MIRROR = 2, CU_TR_ADDRESS_MODE_BORDER = 3 }; #endif #ifndef __CUDACC__ #include <algorithm> #include <cmath> #endif namespace demandLoading { const unsigned int DEMAND_TEXTURE_VIRTUAL_PAGE_ALIGNMENT = 32; // clang-format off #ifdef __CUDACC__ __host__ __device__ static __forceinline__ float maxf( float x, float y ) { return ::fmaxf( x, y ); } __host__ __device__ static __forceinline__ float minf( float x, float y ) { return ::fminf( x, y ); } __host__ __device__ static __forceinline__ unsigned int uimax( unsigned int a, unsigned int b ) { return ( a > b ) ? a : b; } #else __host__ __device__ static __forceinline__ float maxf( float x, float y ) { return std::max( x, y ); } __host__ __device__ static __forceinline__ float minf( float x, float y ) { return std::min( x, y ); } __host__ __device__ static __forceinline__ unsigned int uimax( unsigned int a, unsigned int b ) { return std::max( a, b ); } #endif __host__ __device__ static __forceinline__ float clampf( float f, float a, float b ) { return maxf( a, minf( f, b ) ); } // clang-format on __host__ __device__ static __forceinline__ unsigned int calculateLevelDim( unsigned int mipLevel, unsigned int textureDim ) { return uimax( textureDim >> mipLevel, 1U ); } __host__ __device__ static __forceinline__ unsigned int getLevelDimInTiles( unsigned int textureDim, unsigned int mipLevel, unsigned int tileDim ) { return ( calculateLevelDim( mipLevel, textureDim ) + tileDim - 1 ) / tileDim; } __host__ __device__ static __forceinline__ unsigned int calculateNumTilesInLevel( unsigned int levelWidthInTiles, unsigned int levelHeightInTiles ) { // Round up width and height to multiples of 8 to be consistent with hardware footprint alignment. levelWidthInTiles = ( levelWidthInTiles + 7 ) & 0xfffffff8; levelHeightInTiles = ( levelHeightInTiles + 7 ) & 0xfffffff8; return levelWidthInTiles * levelHeightInTiles; } __host__ __device__ static __forceinline__ void getTileCoordsFromPageOffset( int pageOffsetInLevel, int levelWidthInTiles, unsigned int& tileX, unsigned int& tileY ) { int levelWidthInBlocks = ( levelWidthInTiles + 7 ) / 8; int blockNum = pageOffsetInLevel / 64; int xblock = blockNum % levelWidthInBlocks; int yblock = blockNum / levelWidthInBlocks; int blockOffset = pageOffsetInLevel % 64; int xoffset = blockOffset % 8; int yoffset = blockOffset / 8; tileX = xblock * 8 + xoffset; tileY = yblock * 8 + yoffset; } __host__ __device__ static __forceinline__ float wrapTexCoord( float x, CUaddress_mode addressMode ) { const float firstFloatLessThanOne = 0.999999940395355224609375f; return ( addressMode == CU_TR_ADDRESS_MODE_WRAP ) ? x - floorf( x ) : clampf( x, 0.0f, firstFloatLessThanOne ); } __host__ __device__ static __forceinline__ int getPageOffsetFromTileCoords( int x, int y, int levelWidthInTiles ) { // Tiles are layed out in 8x8 blocks to match the output of the texture footprint instruction int levelWidthInBlocks = ( levelWidthInTiles + 7 ) / 8; return 64 * ( levelWidthInBlocks * ( y / 8 ) ) + // Offset for full rows of blocks 64 * ( x / 8 ) + // Offset for full blocks on last row 8 * ( y % 8 ) + ( x % 8 ); // Partial offset in last block } // Return the mip level and pixel coordinates of the corner of the tile associated with tileIndex __host__ __device__ static __forceinline__ void unpackTileIndex( const TextureSampler& sampler, unsigned int tileIndex, unsigned int& outMipLevel, unsigned int& outTileX, unsigned int& outTileY ) { const demandLoading::TextureSampler::MipLevelSizes* mls = sampler.mipLevelSizes; for( int mipLevel = sampler.mipTailFirstLevel; mipLevel >= 0; --mipLevel ) { unsigned int nextMipLevelStart = ( mipLevel > 0 ) ? mls[mipLevel - 1].mipLevelStart : sampler.numPages; if( tileIndex < nextMipLevelStart ) { const unsigned int levelWidthInTiles = sampler.mipLevelSizes[mipLevel].levelWidthInTiles; const unsigned int indexInLevel = tileIndex - sampler.mipLevelSizes[mipLevel].mipLevelStart; outMipLevel = mipLevel; getTileCoordsFromPageOffset( indexInLevel, levelWidthInTiles, outTileX, outTileY ); return; } } outMipLevel = 0; outTileX = 0; outTileY = 0; } __host__ __device__ static __forceinline__ bool isMipTailIndex( unsigned int pageIndex ) { // Page 0 always contains the mip tail. return pageIndex == 0; } // Wrap the tile coordinate x based on the toroidal addressing scheme of the footprint instruction __host__ __device__ static __forceinline__ int wrapFootprintTileCoord( int x, unsigned int dx, unsigned int tileX, unsigned int levelWidthInTiles ) { // Toroidal rotation if( x + dx >= 8 ) x -= 8; // Fix spillover that happens on small levels sometimes if( x > (int)levelWidthInTiles ) x = 0; // Add base tile contribution x += 8 * tileX; // Wrap the tile coord if( x < 0 ) x += levelWidthInTiles; if( x >= static_cast<int>( levelWidthInTiles ) ) x -= levelWidthInTiles; return x; } } // namespace demandLoading
[ "dvanee@tetracosa.cs.ucla.edu" ]
dvanee@tetracosa.cs.ucla.edu
bdc1dadc43c499ad2d4cd212c164902e0dc7c999
f933b3960ba73367d95b510c196a5e13d9e77ab9
/trx/WallsMap/ScaleWnd.h
c8307ccb3fe7c1e9f30682db8545ffa78a61e805
[]
no_license
victorursu/walls
7ba50033c1ad28f66e8a97bcf37248e527c878a1
fab6c82714d837acdc5ecb95c7cb36a5d0cbc903
refs/heads/master
2021-01-21T14:17:21.934574
2017-02-19T23:58:52
2017-02-19T23:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
868
h
#pragma once #ifndef _DIBWRAPPER_H #include "DIBWrapper.h" #endif // CScaleWnd enum {BAR_MARGIN=10,BAR_HEIGHT=24,BAR_WIDTH=320}; #define BAR_MAXWIDTH (BAR_WIDTH-2*BAR_MARGIN) class CScaleWnd : public CStatic { DECLARE_DYNAMIC(CScaleWnd) public: CScaleWnd(); virtual ~CScaleWnd(); int m_bottom,m_width; virtual BOOL Create(CWnd *pWnd); void Draw(double mPerPx,bool bFeet); //static int CScaleWnd::DrawScaleBar(HBITMAP hbm,HFONT hFont,double mPerPx,bool bFeet); static int cro_DrawScaleBar(CDC *pDC,double mPerPx,long barlen,bool bFeet); static void CopyScaleBar(CDIBWrapper &dib,double mPerPx,double fRatio,bool bFeet); private: HFONT m_hFont; bool m_bFeet; protected: DECLARE_MESSAGE_MAP() public: afx_msg BOOL OnEraseBkgnd(CDC* pDC); //afx_msg void OnContextMenu(CWnd* /*pWnd*/, CPoint /*point*/); };
[ "jedwards@fastmail.com" ]
jedwards@fastmail.com
0c8e374b3ac36a3dc0be2a5791f3d1ecc281612c
ae7691ad42c4ac27a7ee0368a512e890b4510267
/main_window.h
73c6bae1221b1ded030bcf828964c52e91d81ae6
[]
no_license
LiangliangNan/ImageDiff
fef9b4c2d80fd9fc741c9252160ba337508239b3
30650634cd05e85634cc96dc515f75a4d750b77c
refs/heads/main
2023-05-15T06:54:32.341835
2023-05-08T09:45:54
2023-05-08T09:45:54
342,295,611
5
1
null
null
null
null
UTF-8
C++
false
false
394
h
#ifndef MAIN_WINDOW_H #define MAIN_WINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); protected slots: void onImageChanged(); private slots: void on_actionExit_triggered(); private: Ui::MainWindow *ui; }; #endif // MAIN_WINDOW_H
[ "liangliang.nan@gmail.com" ]
liangliang.nan@gmail.com
22bbb481c57342732244005286e0d11e7937d25e
16c3d340e2112ee82d8f6ee97fa8ec105dbdab44
/Faculdade/2008-2_-_IV/Computacao_Grafica/projeto/N1_01_-_06_SextoPrograma/Principal.cpp
1ce9eb9a9443ee12e27091464add07163e6f82df
[ "Apache-2.0" ]
permissive
mtulio/kb
14be0875649a03adfa62a2e8a21ea12eeda3ebb8
1bc355d1750664cfea10dbb5a3f60549a1668971
refs/heads/master
2021-11-19T05:01:47.184128
2021-08-15T23:27:49
2021-08-15T23:27:49
39,852,791
3
0
Apache-2.0
2019-01-31T15:03:34
2015-07-28T19:08:00
C++
ISO-8859-1
C++
false
false
6,819
cpp
#include <GL/glut.h> #include <GL/glu.h> #include <stdio.h> #include<math.h> void Desenha(void) // funcoa que tem como objetivo desenhar uma tela em branco { glClearColor(1,1,1,0); glClear(GL_COLOR_BUFFER_BIT); glFlush(); } void DesenhaTriangulo(void) // funcao que tem como objetivo desenhar um triangulo na tela { glClearColor(1,1,1,0); // define como cor branca da janela de fundo glClear(GL_COLOR_BUFFER_BIT); // Desenhando os triangulos // desenhando o primeiro triangulo glBegin(GL_TRIANGLES); //dando cores para cada vertice: glColor3f(0,1,0); //verde glVertex2f(-0.4,-0.5); glColor3f(1,1,0); //amarelo glVertex2f(0,0.5); glColor3f(0,0,1); //verde glVertex2f(0.4,-0.5); glEnd(); // fim do triangulo 1 glFlush(); }// fim desenha Triangulo void DesenhaTrianguloRetangulo(void){ glClearColor(1,1,1,0); // define como cor branca do fundo da janela glClear(GL_COLOR_BUFFER_BIT); //Desenhando o retangulo glBegin(GL_QUADS); glColor3f(0,0,0); //Define a cor preta glVertex2f(-0.8,0.5); glColor3f(1,0,0); glVertex2f(0.8,0.5); glColor3f(0,0,0); glVertex2f(0.8,-0.5); glColor3f(1,0,0); glVertex2f(-0.8,-0.5); glEnd(); // end do retangulo // Desenhando os triangulos // desenhando o primeiro triangulo glBegin(GL_TRIANGLES); glColor3f(1,1,0); //amarelo glVertex2f(-0.4,0.5); glColor3f(0,1,0); //verde glVertex2f(0,-0.5); glColor3f(0,1,0); //verde glVertex2f(-0.8,-0.5); glEnd(); // fim do triangulo 1 //desenhando o segundo triangulo glBegin(GL_TRIANGLES); glColor3f(0,1,0); // amarelo glVertex2f(0.4,0.5); glColor3f(1,1,0); // amarelo glVertex2f(0.8,-0.5); glColor3f(1,1,0); // amarelo glVertex2f(0,-0.5); glEnd(); // fim do 2 triangulo //comando que define o fim dos comandos da OPenGL glFlush(); }//fim da função para desenhar um triangulo retangulo void DesenhaCasa(void) //inicio do metodo desenha casa { glClearColor(1,1,1,0); // define como cor branca do fundo da janela glClear(GL_COLOR_BUFFER_BIT); //Desenhando o retangulo glBegin(GL_QUADS); glColor3f(1,1,0); //Define a cor preta glVertex2f(-0.9,0.4); // glColor3f(1,0,0); glVertex2f(0.9,0.4); // glColor3f(0,0,0); glVertex2f(0.9,-0.9); //glColor3f(1,0,0); glVertex2f(-0.9,-0.9); glEnd(); // end do retangulo //******************************** //telhado //desenhando o triangulo glBegin(GL_TRIANGLES); glColor3f(1,0,0); //amarelo glVertex2f(-0.9,0.4); // glColor3f(0,1,0); //verde glVertex2f(0,0.9); // glColor3f(0,1,0); //verde glVertex2f(0.9,0.4); glEnd(); // fim do triangulo 1 //******************************** //JANELA esquerda glBegin(GL_QUADS); glColor3f(1,0,0); //Define a cor preta glVertex2f(-0.7,-0.2); // glColor3f(1,0,0); glVertex2f(-0.4,-0.2); // glColor3f(0,0,0); glVertex2f(-0.4,-0.6); //glColor3f(1,0,0); glVertex2f(-0.7,-0.6); glEnd(); glBegin(GL_TRIANGLES); glColor3f(0,0,0); glVertex2f(-0.4,-0.6); glVertex2f(-0.55,-0.2); glVertex2f(-0.7,-0.6); glEnd(); //******************************** //Porta glBegin(GL_QUADS); glColor3f(0,0,0); glVertex2f(-0.15,0); glVertex2f(0.15,0); glVertex2f(0.15,-0.9); glVertex2f(-0.15,-0.9); glEnd(); //************************ //2a janela glBegin(GL_QUADS); glColor3f(1,0,0); //Define a cor preta glVertex2f(0.7,-0.2); // glColor3f(1,0,0); glVertex2f(0.4,-0.2); // glColor3f(0,0,0); glVertex2f(0.4,-0.6); //glColor3f(1,0,0); glVertex2f(0.7,-0.6); glEnd(); glBegin(GL_TRIANGLES); glColor3f(0,0,0); glVertex2f(0.4,-0.6); glVertex2f(0.55,-0.2); glVertex2f(0.7,-0.6); glEnd(); //*********************************** //desenhando um circulo com uma propria função // tentando desenhar uma circunferencia // DESISTO DE DESENHAR UM CIRCULO float PI = 3.1415, angle; GLfloat circle_points = 100; glBegin(GL_LINE_LOOP); for( int i=0; i<circle_points; i++) {//inicio for glColor3f(0,0,0); angle = 2*PI*1/circle_points; glVertex2f(cos(angle), sin(angle)); }//fim for glEnd(); /* int i, num_linhas=2000; GLfloat angulo, raio; angulo = 2 * M_PI / num_linhas; glBegin(GL_LINE_LOOP); for(i = 1; i <= num_linhas; i++) { glVertex2f(cos(i * angulo) * raio, sin(i * angulo) * raio); } glEnd(); */ glFlush(); }// fim do metodo desenha casa void Teclado(unsigned char key, int x, int y) { if (key==27) // pressionando a tecla esc saira do programa exit(0); if (key == 97) // pressinando a tecla "a" ajustara pra tela inteira glutFullScreen(); if (key == 65) // pressionando a tecla "A" ajustara a tela como definida abaixo { glutReshapeWindow(500,400); glutPositionWindow(100,100); } }// fim da funcao teclado void Inicializa(void) { glMatrixMode(GL_PROJECTION); gluOrtho2D(-1.0,1.0,-1.0,1.0); glMatrixMode(GL_MODELVIEW); } void MenuWin(int op) { printf(" Menu Windows: "); switch(op) { case 1:{ printf("Opçao Triangulo"); glutDisplayFunc(DesenhaTriangulo); break; }//fim case 0 case 2:{ printf("Opçao Retangulo com Triangulos"); glutDisplayFunc(DesenhaTrianguloRetangulo); break; }// fim case 1 case 3: { printf("Desenha Casa"); glutDisplayFunc(DesenhaCasa); break; }// fim case 2 case 0: { printf("Limpa"); glutDisplayFunc(Desenha); break; }// fim case 2 }// fim switch printf("\n"); glutPostRedisplay(); }//fim da funcao MenuWin void CriaMenu() { int menu,submenu1; submenu1 = glutCreateMenu(MenuWin); glutAddMenuEntry("Triangulo",1); glutAddMenuEntry("Retangulo com Triangulos",2); glutAddMenuEntry("Desenha Casa",3); glutAddMenuEntry("Limpa",0); menu = glutCreateMenu(MenuWin); glutAddSubMenu("Escolha a opção",submenu1); glutAttachMenu(GLUT_RIGHT_BUTTON); }// fim da funcao CriaMenu int main(int argc,char ** argv){ glutInit(&argc,argv); glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB ); glutInitWindowSize( 700,500 ); glutCreateWindow("Sexto Trabalho"); glutDisplayFunc(Desenha); //desenha a tela glutKeyboardFunc(Teclado); Inicializa(); CriaMenu(); glutMainLoop(); return 0; }// fim do programa principal
[ "marco.braga@chaordicsystems.com" ]
marco.braga@chaordicsystems.com
243a1cae4c8521743870ea95d024d4125ac1a458
b8c77d795b77253fb560942294f5068f139b8eaf
/diffusion1dp.cpp
6adbc65dae8833f78b2149c08a5a6cf95368508e
[]
no_license
IvanAssing/IMC_Diffusion1Dp
85d9b906afe088354aae0dd8466cc81ee2b53879
8ea89a6bea6699d8828e1225438a982e55f5f97c
refs/heads/master
2021-01-19T22:29:48.955884
2013-07-27T01:09:24
2013-07-27T01:09:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,684
cpp
#include "diffusion1dp.h" Diffusion1Dp::Diffusion1Dp(DiffusionProblem _problemType, tInteger _nodes, Boundary1D _left, Boundary1D _right, DiffusionData _data) { problemType = _problemType; boundaryLeft = _left; boundaryRight = _right; data = _data; n = _nodes; // Calcula L e h l = boundaryRight.x - boundaryLeft.x; h = l/(n - 1); if(boundaryLeft.type != Dirichlet && boundaryRight.type != Dirichlet){ std::cout<<"Problema inconsistente, solução indeterminada!"; return; } } void Diffusion1Dp::solver(void) { // Configura o número de equações do solver TDMA equationsSystem.setMaxEquations(n); // DISCRETIZAÇÃO PARA O PROBLEMA DE DIFUSÃO DE CALOR EM PAREDA PLANA if(problemType == ParedePlana){ // Aplica a condição de contorno esquerdo if(boundaryLeft.type == Dirichlet) equationsSystem(1.0q, 0.0q, 0.0q, boundaryLeft.bcValue); // Se Dirichlet else equationsSystem(1.0q, 0.0q, 1.0q, boundaryLeft.bcValue*h); // Se Neumann // Aplica discretização de d2T/dx2 = S(x), com CDS-2 for(tInteger i=1; i<n-1; i++){ tFloat xp = boundaryLeft.x+i*h; equationsSystem(2.0q, 1.0q, 1.0q, -h*h*data.heatSource->operator ()(xp)); } // Aplica a condição de contorno direito if(boundaryRight.type == Dirichlet) equationsSystem(1.0q, 0.0q, 0.0q, boundaryRight.bcValue); // Se Dirichlet else equationsSystem(1.0q, 1.0q, 0.0q, -boundaryRight.bcValue*h); // Se Neumann } // DISCRETIZAÇÃO PARA O PROBLEMA DE DIFUSÃO DE CALOR ALETA if(problemType == Aleta){ // Aplica a condição de contorno esquerdo if(boundaryLeft.type == Dirichlet) equationsSystem(1.0q, 0.0q, 0.0q, data.Tb); // Se Dirichlet else equationsSystem(data.k-data.H*h, 0.0q, data.k, -h*data.H*data.Tinf); // Se Robin tFloat m2_h2 = (data.H*data.P*h*h)/(data.k*data.Ab); tFloat ap = 2.0q+m2_h2; tFloat bp = m2_h2*data.Tinf; // Aplica discretização de d2T/dx2 = S(T), com CDS-2 for(tInteger i=1; i<n-1; i++) equationsSystem(ap, 1.0q, 1.0q, bp); // Aplica a condição de contorno direito if(boundaryRight.type == Dirichlet) equationsSystem(1.0q, 0.0q, 0.0q, data.Tb); // Se Dirichlet else equationsSystem(data.k+data.H*h, data.k, 0.0q, h*data.H*data.Tinf); // Se Robin } // DISCRETIZAÇÃO PARA O PROBLEMA DE DIFUSÃO DE QUANTIDADE DE MOVIMENTO LINEAR if(problemType == QML){ // Aplica a condição de contorno esquerdo equationsSystem(1.0q, 0.0q, 0.0q, 0.0q); // Dirichlet tFloat bp = -data.C*h*h/data.mi; // Aplica discretização de mi.d2u/dy2 = C, com CDS-2 for(tInteger i=1; i<n-1; i++) equationsSystem(2.0q, 1.0q, 1.0q, bp); // Aplica a condição de contorno direito equationsSystem(1.0q, 0.0q, 0.0q, 0.0q); // Dirichlet } // Resolve o sistema de equações lineares equationsSystem.solver(); // Calcula a temperatura média averageValue = 0.0q; for(tInteger i=1; i<n; i++) averageValue += (equationsSystem.getT(i-1)+equationsSystem.getT(i)); averageValue *= 0.5q*h/l; // Calcula o fluxo de calor //heatFlowLeft = -data.k/h*(equationsSystem.getT(1)-equationsSystem.getT(0)); heatFlowLeft = -0.5q*data.k/h*(4.0q*equationsSystem.getT(1)-3.0q*equationsSystem.getT(0)-equationsSystem.getT(2)); //heatFlowRight = -data.k/h*(equationsSystem.getT(n-1)-equationsSystem.getT(n-2)); heatFlowRight = -0.5q*data.k/h*(3.0q*equationsSystem.getT(n-1)-4.0q*equationsSystem.getT(n-2)+equationsSystem.getT(n-3)); if(problemType == Aleta) heatFlowLeft *= data.Ab; // Calcula Valor máximo maxValue = equationsSystem.getT(0); for(tInteger i=1; i<n; i++) maxValue = equationsSystem.getT(i)>maxValue ? equationsSystem.getT(i):maxValue; } void Diffusion1Dp::plotSolution(Functor1D &analyticalSolution) { const std::string cmd_filename = "plotconfig.gnu"; const std::string pic_filename = "image.png"; const std::string dat1_filename = "data1.txt"; const std::string dat2_filename = "data2.txt"; // Solução numérica std::ofstream file1(dat1_filename.c_str()); for(tInteger i=0; i<n; i++) file1<<static_cast<double>(boundaryLeft.x+i*h)<<"\t"<< static_cast<double>(equationsSystem.getT(i))<<std::endl; file1.close(); // Solução Analítica std::ofstream file2(dat2_filename.c_str()); tFloat h_10 = l/(10*n-1); // Aumenta o número de pontos em 10X for(tInteger i=0; i<10*n; i++){ tFloat xp = boundaryLeft.x+i*h_10; file2<<static_cast<double>(xp)<<"\t"<<static_cast<double>(analyticalSolution(xp))<<std::endl; } file2.close(); std::ofstream file3(cmd_filename.c_str()); file3 << "set terminal pngcairo enhanced font \"arial,12\" size 1600, 1000 \n" "set output '" << pic_filename <<"'\n" "set key inside right top vertical Right noreverse enhanced autotitles box linetype -1 linewidth 1.000\n" "set grid\n"; if(problemType == ParedePlana) file3 << "set title \""<<STR_PAREDE_PLANA<<"\\nResolução com MDF / Aproximação com CDS-2\"\n" "set xlabel 'x'\n" "set ylabel 'Temperatura'\n"; else if(problemType == Aleta) file3 << "set title \""<<STR_ALETA<<"\\nResolução com MDF / Aproximação com CDS-2\"\n" "set xlabel 'x'\n" "set ylabel 'Temperatura'\n"; else file3 << "set title \""<<STR_QML<<"\\nResolução com MDF / Aproximação com CDS-2\"\n" "set xlabel 'y'\n" "set ylabel 'Velocidade'\n"; file3 << "plot '" <<dat2_filename<<"' t\"Solução Analítica\" with lines lt 2 lc 2 lw 2, " "'" <<dat1_filename<<"' t\"Solução Numérica\" with points lt 2 lc 1 pt 13 lw 5"; file3.close(); const std::string cmd1 = "gnuplot " + cmd_filename; // Gráfico com GNUPLOT const std::string cmd2 = "eog " + pic_filename; // Visualizador de imagem std::system(cmd1.c_str()); std::system(cmd2.c_str()); } // Imprime a solução do problema void Diffusion1Dp::printSolution(Functor1D &analyticalSolution) { std::cout<<std::endl; if(problemType == ParedePlana) std::cout<<STR_PAREDE_PLANA; else if(problemType == Aleta) std::cout<<STR_ALETA; else std::cout<<STR_QML; std::cout<<std::endl; std::cout<<std::endl<<std::setfill('-')<<std::setw(5+4*OUT_FLOAT_WIDTH)<<""<<std::setfill(' '); std::cout<<std::endl<<std::setw(5)<<std::right<<"p"; std::cout<<std::setw(OUT_FLOAT_WIDTH)<<std::right<<"Xp"; std::cout<<std::setw(OUT_FLOAT_WIDTH+1)<<std::right<<"Yp (Numérica)"; std::cout<<std::setw(OUT_FLOAT_WIDTH+1)<<std::right<<"Yp (Analítica)"; std::cout<<std::setw(OUT_FLOAT_WIDTH)<<std::right<<"Erro"; std::cout<<std::endl<<std::setfill('-')<<std::setw(5+4*OUT_FLOAT_WIDTH)<<""<<std::setfill(' '); std::cout.precision(OUT_FLOAT_PRECISION); std::cout<<std::scientific; #ifdef QUAD_PRECISION char str[1000]; for(tInteger i=0;i<n;i++){ tFloat xp = boundaryLeft.x+i*h; std::cout<<std::endl; std::cout<<std::setw(5)<<i; quadmath_snprintf(str, 1000, Q_FORMAT,xp); std::cout<<std::setw(OUT_FLOAT_WIDTH)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,equationsSystem.getT(i)); std::cout<<std::setw(OUT_FLOAT_WIDTH)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,analyticalSolution(xp)); std::cout<<std::setw(OUT_FLOAT_WIDTH)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,analyticalSolution(xp)-equationsSystem.getT(i)); std::cout<<std::setw(OUT_FLOAT_WIDTH)<<str; } std::cout<<std::endl<<std::setfill('-')<<std::setw(5+4*OUT_FLOAT_WIDTH)<<""<<std::setfill(' '); #else for(tInteger i=0;i<n;i++){ tFloat xp = boundaryLeft.x+i*h; std::cout<<std::endl; std::cout<<std::setw(5)<<i; std::cout<<std::setw(OUT_FLOAT_WIDTH)<<xp; std::cout<<std::setw(OUT_FLOAT_WIDTH)<<equationsSystem.getT(i); std::cout<<std::setw(OUT_FLOAT_WIDTH)<<analyticalSolution(xp); std::cout<<std::setw(OUT_FLOAT_WIDTH)<<analyticalSolution(xp)-equationsSystem.getT(i); } std::cout<<std::endl<<std::setfill('-')<<std::setw(5+4*OUT_FLOAT_WIDTH)<<""<<std::setfill(' '); #endif } // Imprime os resultados das variáveis secundárias void Diffusion1Dp::printSecondaryResults(tFloat AS_average, tFloat AS_left, tFloat AS_right, tFloat AS_left_1, tFloat AS_right_1) { std::cout<<std::endl; std::cout<<std::endl<<std::setfill('-')<<std::setw(30+3*(OUT_FLOAT_WIDTH+5))<<""<<std::setfill(' '); std::cout<<std::endl<<std::setw(30)<<""; std::cout<<std::setw(OUT_FLOAT_WIDTH+5+3)<<"Solução Numérica"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5+3)<<"Solução Analítica"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<"Erro"; std::cout<<std::endl<<std::setfill('-')<<std::setw(30+3*(OUT_FLOAT_WIDTH+5))<<""<<std::setfill(' '); #ifdef QUAD_PRECISION char str[1000]; if(problemType == ParedePlana){ std::cout<<std::endl<<std::setw(30+1)<<"Temperatura Média"; quadmath_snprintf(str, 1000, Q_FORMAT,averageValue); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_average); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_average - averageValue); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; std::cout<<std::endl<<std::setw(30)<<"Temperatura em X = X0"; quadmath_snprintf(str, 1000, Q_FORMAT,equationsSystem.getT(0)); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left_1); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left_1 - equationsSystem.getT(0)); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; std::cout<<std::endl<<std::setw(30)<<"Temperatura em X = XL"; quadmath_snprintf(str, 1000, Q_FORMAT,equationsSystem.getT(n-1)); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_right_1); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_right_1 - equationsSystem.getT(n-1)); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; std::cout<<std::endl<<std::setw(30)<<"Fluxo de Calor em X = X0"; quadmath_snprintf(str, 1000, Q_FORMAT,heatFlowLeft); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left - heatFlowLeft); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; std::cout<<std::endl<<std::setw(30)<<"Fluxo de Calor em X = XL"; quadmath_snprintf(str, 1000, Q_FORMAT,heatFlowRight); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_right); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_right - heatFlowRight); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; } else if(problemType == Aleta){ std::cout<<std::endl<<std::setw(30)<<"Fluxo de Calor"; quadmath_snprintf(str, 1000, Q_FORMAT,heatFlowLeft); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left - heatFlowLeft); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; } else{ std::cout<<std::endl<<std::setw(30+1)<<"Velocidade Média"; quadmath_snprintf(str, 1000, Q_FORMAT,averageValue); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_average); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_average - averageValue); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; std::cout<<std::endl<<std::setw(30)<<"Velocidade Máxima"; quadmath_snprintf(str, 1000, Q_FORMAT,maxValue); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; quadmath_snprintf(str, 1000, Q_FORMAT,AS_left - maxValue); std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<str; } #else if(problemType == ParedePlana){ std::cout<<std::endl<<std::setw(30+1)<<"Temperatura Média"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<averageValue; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_average; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_average - averageValue; std::cout<<std::endl<<std::setw(30)<<"Fluxo de Calor em X = X0"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<heatFlowLeft; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_left; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_left - heatFlowLeft; std::cout<<std::endl<<std::setw(30)<<"Fluxo de Calor em X = XL"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<heatFlowRight; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_right; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_right - heatFlowRight; } else if(problemType == Aleta){ std::cout<<std::endl<<std::setw(30)<<"Fluxo de Calor"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<heatFlowLeft; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_left; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_left - heatFlowLeft; } else{ std::cout<<std::endl<<std::setw(30+1)<<"Velocidade Média"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<averageValue; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_average; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_average - averageValue; std::cout<<std::endl<<std::setw(30)<<"Velocidade Máxima"; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<maxValue; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_left; std::cout<<std::setw(OUT_FLOAT_WIDTH+5)<<AS_left - maxValue; } #endif std::cout<<std::endl<<std::setfill('-')<<std::setw(30+3*(OUT_FLOAT_WIDTH+5))<<""<<std::setfill(' '); }
[ "ivanassing@gmail.com" ]
ivanassing@gmail.com
453b290b1ea9c1c93d28b7b8b70e32f6321229df
947ff7b1800df3a87827757d474673e435979b26
/src/nbt/prettyprinter.hpp
60ced2fad9fd62664fa569a5a066dd0392b53421
[ "MIT" ]
permissive
xTachyon/RedstoneInside
852e3888a988693fbdb5f6b4561b088035c6acab
6fabed21c0ed92c4bc605ab4a968f6e8d9f7275d
refs/heads/master
2021-01-19T20:46:22.155402
2018-12-10T06:36:16
2018-12-10T06:36:16
73,366,979
9
3
null
null
null
null
UTF-8
C++
false
false
1,649
hpp
#pragma once #include <string> #include <boost/format.hpp> #include "type.hpp" #include "visitor.hpp" namespace redi::nbt { struct pretty_print_options { nbt_int indent_size; nbt_string indent_character; explicit pretty_print_options(nbt_int indent_size = 2, nbt_string indent_character = " "); }; class pretty_printer : public const_nbt_visitor { public: std::string string; explicit pretty_printer(nbt_int indent = 2); explicit pretty_printer(pretty_print_options options); void visit(const tag_byte& x) override; void visit(const tag_short& x) override; void visit(const tag_int& x) override; void visit(const tag_long& x) override; void visit(const tag_float& x) override; void visit(const tag_double& x) override; void visit(const tag_byte_array& x) override; void visit(const tag_string& x) override; void visit(const tag_list& x) override; void visit(const tag_compound& x) override; void visit(const root_tag& x) override; void visit(const tag_int_array& x) override; void visit(const tag_long_array& x) override; pretty_print_options options; std::string indent_string; void writeType(tag_type t); void writeType(tag_type t, nbt_string_view str); void writeIndent(nbt_int update = 0); void writeNewLine(); void writeEntry(std::size_t size); void writeOne(const tag& tag); void writeArrayNumbers(nbt_string_view name, std::size_t size); void append(nbt_string_view str); void append(const boost::format& format); template <typename T> void writeNumber(T x); }; std::ostream& operator<<(std::ostream& stream, const pretty_printer& printer); } // namespace redi::nbt
[ "andreidaamian@gmail.com" ]
andreidaamian@gmail.com
0104adfcc8a65f74ed329fd6ed76e2cc0149ca3d
90047daeb462598a924d76ddf4288e832e86417c
/third_party/WebKit/Source/platform/wtf/HashTable.h
8c653aa4e7b05b02e524022aa8226b5eadfedd13
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
73,023
h
/* * Copyright (C) 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights * reserved. * Copyright (C) 2008 David Levin <levin@chromium.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library * General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef WTF_HashTable_h #define WTF_HashTable_h #include "platform/wtf/Alignment.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/Assertions.h" #include "platform/wtf/ConditionalDestructor.h" #include "platform/wtf/HashTraits.h" #include "platform/wtf/PtrUtil.h" #include "platform/wtf/allocator/PartitionAllocator.h" #include <memory> #define DUMP_HASHTABLE_STATS 0 #define DUMP_HASHTABLE_STATS_PER_TABLE 0 #if DUMP_HASHTABLE_STATS #include "platform/wtf/Atomics.h" #include "platform/wtf/Threading.h" #endif #if DUMP_HASHTABLE_STATS_PER_TABLE #include "platform/wtf/DataLog.h" #include <type_traits> #endif #if DUMP_HASHTABLE_STATS #if DUMP_HASHTABLE_STATS_PER_TABLE #define UPDATE_PROBE_COUNTS() \ ++probeCount; \ HashTableStats::instance().recordCollisionAtCount(probeCount); \ ++perTableProbeCount; \ stats_->recordCollisionAtCount(perTableProbeCount) #define UPDATE_ACCESS_COUNTS() \ atomicIncrement(&HashTableStats::instance().numAccesses); \ int probeCount = 0; \ ++stats_->numAccesses; \ int perTableProbeCount = 0 #else #define UPDATE_PROBE_COUNTS() \ ++probeCount; \ HashTableStats::instance().recordCollisionAtCount(probeCount) #define UPDATE_ACCESS_COUNTS() \ atomicIncrement(&HashTableStats::instance().numAccesses); \ int probeCount = 0 #endif #else #if DUMP_HASHTABLE_STATS_PER_TABLE #define UPDATE_PROBE_COUNTS() \ ++perTableProbeCount; \ stats_->recordCollisionAtCount(perTableProbeCount) #define UPDATE_ACCESS_COUNTS() \ ++stats_->numAccesses; \ int perTableProbeCount = 0 #else #define UPDATE_PROBE_COUNTS() \ do { \ } while (0) #define UPDATE_ACCESS_COUNTS() \ do { \ } while (0) #endif #endif namespace WTF { // This is for tracing inside collections that have special support for weak // pointers. The trait has a trace method which returns true if there are weak // pointers to things that have not (yet) been marked live. Returning true // indicates that the entry in the collection may yet be removed by weak // handling. Default implementation for non-weak types is to use the regular // non-weak TraceTrait. Default implementation for types with weakness is to // call traceInCollection on the type's trait. template <WeakHandlingFlag weakHandlingFlag, ShouldWeakPointersBeMarkedStrongly strongify, typename T, typename Traits> struct TraceInCollectionTrait; #if DUMP_HASHTABLE_STATS struct WTF_EXPORT HashTableStats { HashTableStats() : numAccesses(0), numRehashes(0), numRemoves(0), numReinserts(0), maxCollisions(0), numCollisions(0), collisionGraph() {} // The following variables are all atomically incremented when modified. int numAccesses; int numRehashes; int numRemoves; int numReinserts; // The following variables are only modified in the recordCollisionAtCount // method within a mutex. int maxCollisions; int numCollisions; int collisionGraph[4096]; void copy(const HashTableStats* other); void recordCollisionAtCount(int count); void dumpStats(); static HashTableStats& instance(); template <typename VisitorDispatcher> void trace(VisitorDispatcher) {} }; #if DUMP_HASHTABLE_STATS_PER_TABLE template <typename Allocator, bool isGCType = Allocator::isGarbageCollected> class HashTableStatsPtr; template <typename Allocator> class HashTableStatsPtr<Allocator, false> final { STATIC_ONLY(HashTableStatsPtr); public: static std::unique_ptr<HashTableStats> create() { return WTF::wrapUnique(new HashTableStats); } static std::unique_ptr<HashTableStats> copy( const std::unique_ptr<HashTableStats>& other) { if (!other) return nullptr; return WTF::wrapUnique(new HashTableStats(*other)); } static void swap(std::unique_ptr<HashTableStats>& stats, std::unique_ptr<HashTableStats>& other) { stats.swap(other); } }; template <typename Allocator> class HashTableStatsPtr<Allocator, true> final { STATIC_ONLY(HashTableStatsPtr); public: static HashTableStats* create() { // Resort to manually allocating this POD on the vector // backing heap, as blink::GarbageCollected<> isn't in scope // in WTF. void* storage = reinterpret_cast<void*>( Allocator::template allocateVectorBacking<unsigned char>( sizeof(HashTableStats))); return new (storage) HashTableStats; } static HashTableStats* copy(const HashTableStats* other) { if (!other) return nullptr; HashTableStats* obj = create(); obj->copy(other); return obj; } static void swap(HashTableStats*& stats, HashTableStats*& other) { std::swap(stats, other); } }; #endif #endif template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> class HashTable; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> class HashTableIterator; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> class HashTableConstIterator; template <typename Value, typename HashFunctions, typename HashTraits, typename Allocator> class LinkedHashSet; template <WeakHandlingFlag x, typename T, typename U, typename V, typename W, typename X, typename Y, typename Z> struct WeakProcessingHashTableHelper; typedef enum { kHashItemKnownGood } HashItemKnownGoodTag; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> class HashTableConstIterator final { DISALLOW_NEW(); private: typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> HashTableType; typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> iterator; typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> const_iterator; typedef Value ValueType; using value_type = ValueType; typedef typename Traits::IteratorConstGetType GetType; typedef const ValueType* PointerType; friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>; friend class HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>; void SkipEmptyBuckets() { while (position_ != end_position_ && HashTableType::IsEmptyOrDeletedBucket(*position_)) ++position_; } HashTableConstIterator(PointerType position, PointerType end_position, const HashTableType* container) : position_(position), end_position_(end_position) #if DCHECK_IS_ON() , container_(container), container_modifications_(container->Modifications()) #endif { SkipEmptyBuckets(); } HashTableConstIterator(PointerType position, PointerType end_position, const HashTableType* container, HashItemKnownGoodTag) : position_(position), end_position_(end_position) #if DCHECK_IS_ON() , container_(container), container_modifications_(container->Modifications()) #endif { #if DCHECK_IS_ON() DCHECK_EQ(container_modifications_, container_->Modifications()); #endif } void CheckModifications() const { #if DCHECK_IS_ON() // HashTable and collections that build on it do not support // modifications while there is an iterator in use. The exception is // ListHashSet, which has its own iterators that tolerate modification // of the underlying set. DCHECK_EQ(container_modifications_, container_->Modifications()); DCHECK(!container_->AccessForbidden()); #endif } public: HashTableConstIterator() {} GetType Get() const { CheckModifications(); return position_; } typename Traits::IteratorConstReferenceType operator*() const { return Traits::GetToReferenceConstConversion(Get()); } GetType operator->() const { return Get(); } const_iterator& operator++() { DCHECK_NE(position_, end_position_); CheckModifications(); ++position_; SkipEmptyBuckets(); return *this; } // postfix ++ intentionally omitted // Comparison. bool operator==(const const_iterator& other) const { return position_ == other.position_; } bool operator!=(const const_iterator& other) const { return position_ != other.position_; } bool operator==(const iterator& other) const { return *this == static_cast<const_iterator>(other); } bool operator!=(const iterator& other) const { return *this != static_cast<const_iterator>(other); } std::ostream& PrintTo(std::ostream& stream) const { if (position_ == end_position_) return stream << "iterator representing <end>"; // TODO(tkent): Change |position_| to |*position_| to show the // pointed object. It requires a lot of new stream printer functions. return stream << "iterator pointing to " << position_; } private: PointerType position_; PointerType end_position_; #if DCHECK_IS_ON() const HashTableType* container_; int64_t container_modifications_; #endif }; template <typename Key, typename Value, typename Extractor, typename Hash, typename Traits, typename KeyTraits, typename Allocator> std::ostream& operator<<(std::ostream& stream, const HashTableConstIterator<Key, Value, Extractor, Hash, Traits, KeyTraits, Allocator>& iterator) { return iterator.PrintTo(stream); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> class HashTableIterator final { DISALLOW_NEW(); private: typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> HashTableType; typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> iterator; typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> const_iterator; typedef Value ValueType; typedef typename Traits::IteratorGetType GetType; typedef ValueType* PointerType; friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>; HashTableIterator(PointerType pos, PointerType end, const HashTableType* container) : iterator_(pos, end, container) {} HashTableIterator(PointerType pos, PointerType end, const HashTableType* container, HashItemKnownGoodTag tag) : iterator_(pos, end, container, tag) {} public: HashTableIterator() {} // default copy, assignment and destructor are OK GetType Get() const { return const_cast<GetType>(iterator_.Get()); } typename Traits::IteratorReferenceType operator*() const { return Traits::GetToReferenceConversion(Get()); } GetType operator->() const { return Get(); } iterator& operator++() { ++iterator_; return *this; } // postfix ++ intentionally omitted // Comparison. bool operator==(const iterator& other) const { return iterator_ == other.iterator_; } bool operator!=(const iterator& other) const { return iterator_ != other.iterator_; } bool operator==(const const_iterator& other) const { return iterator_ == other; } bool operator!=(const const_iterator& other) const { return iterator_ != other; } operator const_iterator() const { return iterator_; } std::ostream& PrintTo(std::ostream& stream) const { return iterator_.PrintTo(stream); } private: const_iterator iterator_; }; template <typename Key, typename Value, typename Extractor, typename Hash, typename Traits, typename KeyTraits, typename Allocator> std::ostream& operator<<(std::ostream& stream, const HashTableIterator<Key, Value, Extractor, Hash, Traits, KeyTraits, Allocator>& iterator) { return iterator.PrintTo(stream); } using std::swap; template <typename T, typename Allocator, bool enterGCForbiddenScope> struct Mover { STATIC_ONLY(Mover); static void Move(T&& from, T& to) { to.~T(); new (NotNull, &to) T(std::move(from)); } }; template <typename T, typename Allocator> struct Mover<T, Allocator, true> { STATIC_ONLY(Mover); static void Move(T&& from, T& to) { to.~T(); Allocator::EnterGCForbiddenScope(); new (NotNull, &to) T(std::move(from)); Allocator::LeaveGCForbiddenScope(); } }; template <typename HashFunctions> class IdentityHashTranslator { STATIC_ONLY(IdentityHashTranslator); public: template <typename T> static unsigned GetHash(const T& key) { return HashFunctions::GetHash(key); } template <typename T, typename U> static bool Equal(const T& a, const U& b) { return HashFunctions::Equal(a, b); } template <typename T, typename U, typename V> static void Translate(T& location, U&&, V&& value) { location = std::forward<V>(value); } }; template <typename HashTableType, typename ValueType> struct HashTableAddResult final { STACK_ALLOCATED(); HashTableAddResult(const HashTableType* container, ValueType* stored_value, bool is_new_entry) : stored_value(stored_value), is_new_entry(is_new_entry) #if ENABLE(SECURITY_ASSERT) , container_(container), container_modifications_(container->Modifications()) #endif { ALLOW_UNUSED_LOCAL(container); DCHECK(container); } ValueType* stored_value; bool is_new_entry; #if ENABLE(SECURITY_ASSERT) ~HashTableAddResult() { // If rehash happened before accessing storedValue, it's // use-after-free. Any modification may cause a rehash, so we check for // modifications here. // Rehash after accessing storedValue is harmless but will assert if the // AddResult destructor takes place after a modification. You may need // to limit the scope of the AddResult. SECURITY_DCHECK(container_modifications_ == container_->Modifications()); } private: const HashTableType* container_; const int64_t container_modifications_; #endif }; template <typename Value, typename Extractor, typename KeyTraits> struct HashTableHelper { STATIC_ONLY(HashTableHelper); static bool IsEmptyBucket(const Value& value) { return IsHashTraitsEmptyValue<KeyTraits>(Extractor::Extract(value)); } static bool IsDeletedBucket(const Value& value) { return KeyTraits::IsDeletedValue(Extractor::Extract(value)); } static bool IsEmptyOrDeletedBucket(const Value& value) { return IsEmptyBucket(value) || IsDeletedBucket(value); } }; template <typename HashTranslator, typename KeyTraits, bool safeToCompareToEmptyOrDeleted> struct HashTableKeyChecker { STATIC_ONLY(HashTableKeyChecker); // There's no simple generic way to make this check if // safeToCompareToEmptyOrDeleted is false, so the check always passes. template <typename T> static bool CheckKey(const T&) { return true; } }; template <typename HashTranslator, typename KeyTraits> struct HashTableKeyChecker<HashTranslator, KeyTraits, true> { STATIC_ONLY(HashTableKeyChecker); template <typename T> static bool CheckKey(const T& key) { // FIXME : Check also equality to the deleted value. return !HashTranslator::Equal(KeyTraits::EmptyValue(), key); } }; // Note: empty or deleted key values are not allowed, using them may lead to // undefined behavior. For pointer keys this means that null pointers are not // allowed unless you supply custom key traits. template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> class HashTable final : public ConditionalDestructor<HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>, Allocator::kIsGarbageCollected> { DISALLOW_NEW(); public: typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> iterator; typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> const_iterator; typedef Traits ValueTraits; typedef Key KeyType; typedef typename KeyTraits::PeekInType KeyPeekInType; typedef Value ValueType; typedef Extractor ExtractorType; typedef KeyTraits KeyTraitsType; typedef IdentityHashTranslator<HashFunctions> IdentityTranslatorType; typedef HashTableAddResult<HashTable, ValueType> AddResult; HashTable(); void Finalize() { DCHECK(!Allocator::kIsGarbageCollected); if (LIKELY(!table_)) return; EnterAccessForbiddenScope(); DeleteAllBucketsAndDeallocate(table_, table_size_); LeaveAccessForbiddenScope(); table_ = nullptr; } HashTable(const HashTable&); HashTable(HashTable&&); void swap(HashTable&); HashTable& operator=(const HashTable&); HashTable& operator=(HashTable&&); // When the hash table is empty, just return the same iterator for end as // for begin. This is more efficient because we don't have to skip all the // empty and deleted buckets, and iterating an empty table is a common case // that's worth optimizing. iterator begin() { return IsEmpty() ? end() : MakeIterator(table_); } iterator end() { return MakeKnownGoodIterator(table_ + table_size_); } const_iterator begin() const { return IsEmpty() ? end() : MakeConstIterator(table_); } const_iterator end() const { return MakeKnownGoodConstIterator(table_ + table_size_); } unsigned size() const { DCHECK(!AccessForbidden()); return key_count_; } unsigned Capacity() const { DCHECK(!AccessForbidden()); return table_size_; } bool IsEmpty() const { DCHECK(!AccessForbidden()); return !key_count_; } void ReserveCapacityForSize(unsigned size); template <typename IncomingValueType> AddResult insert(IncomingValueType&& value) { return insert<IdentityTranslatorType>( Extractor::Extract(value), std::forward<IncomingValueType>(value)); } // A special version of insert() that finds the object by hashing and // comparing with some other type, to avoid the cost of type conversion if the // object is already in the table. template <typename HashTranslator, typename T, typename Extra> AddResult insert(T&& key, Extra&&); template <typename HashTranslator, typename T, typename Extra> AddResult InsertPassingHashCode(T&& key, Extra&&); iterator find(KeyPeekInType key) { return Find<IdentityTranslatorType>(key); } const_iterator find(KeyPeekInType key) const { return Find<IdentityTranslatorType>(key); } bool Contains(KeyPeekInType key) const { return Contains<IdentityTranslatorType>(key); } template <typename HashTranslator, typename T> iterator Find(const T&); template <typename HashTranslator, typename T> const_iterator Find(const T&) const; template <typename HashTranslator, typename T> bool Contains(const T&) const; void erase(KeyPeekInType); void erase(iterator); void erase(const_iterator); void clear(); static bool IsEmptyBucket(const ValueType& value) { return IsHashTraitsEmptyValue<KeyTraits>(Extractor::Extract(value)); } static bool IsDeletedBucket(const ValueType& value) { return KeyTraits::IsDeletedValue(Extractor::Extract(value)); } static bool IsEmptyOrDeletedBucket(const ValueType& value) { return HashTableHelper<ValueType, Extractor, KeyTraits>::IsEmptyOrDeletedBucket(value); } ValueType* Lookup(KeyPeekInType key) { return Lookup<IdentityTranslatorType, KeyPeekInType>(key); } template <typename HashTranslator, typename T> ValueType* Lookup(const T&); template <typename HashTranslator, typename T> const ValueType* Lookup(const T&) const; template <typename VisitorDispatcher> void Trace(VisitorDispatcher); #if DCHECK_IS_ON() void EnterAccessForbiddenScope() { DCHECK(!access_forbidden_); access_forbidden_ = true; } void LeaveAccessForbiddenScope() { access_forbidden_ = false; } bool AccessForbidden() const { return access_forbidden_; } int64_t Modifications() const { return modifications_; } void RegisterModification() { modifications_++; } // HashTable and collections that build on it do not support modifications // while there is an iterator in use. The exception is ListHashSet, which // has its own iterators that tolerate modification of the underlying set. void CheckModifications(int64_t mods) const { DCHECK_EQ(mods, modifications_); } #else ALWAYS_INLINE void EnterAccessForbiddenScope() {} ALWAYS_INLINE void LeaveAccessForbiddenScope() {} ALWAYS_INLINE bool AccessForbidden() const { return false; } ALWAYS_INLINE int64_t Modifications() const { return 0; } ALWAYS_INLINE void RegisterModification() {} ALWAYS_INLINE void CheckModifications(int64_t mods) const {} #endif private: static ValueType* AllocateTable(unsigned size); static void DeleteAllBucketsAndDeallocate(ValueType* table, unsigned size); typedef std::pair<ValueType*, bool> LookupType; typedef std::pair<LookupType, unsigned> FullLookupType; LookupType LookupForWriting(const Key& key) { return LookupForWriting<IdentityTranslatorType>(key); } template <typename HashTranslator, typename T> FullLookupType FullLookupForWriting(const T&); template <typename HashTranslator, typename T> LookupType LookupForWriting(const T&); void erase(ValueType*); bool ShouldExpand() const { return (key_count_ + deleted_count_) * kMaxLoad >= table_size_; } bool MustRehashInPlace() const { return key_count_ * kMinLoad < table_size_ * 2; } bool ShouldShrink() const { // isAllocationAllowed check should be at the last because it's // expensive. return key_count_ * kMinLoad < table_size_ && table_size_ > KeyTraits::kMinimumTableSize && !Allocator::IsObjectResurrectionForbidden() && Allocator::IsAllocationAllowed(); } ValueType* Expand(ValueType* entry = 0); void Shrink() { Rehash(table_size_ / 2, 0); } ValueType* ExpandBuffer(unsigned new_table_size, ValueType* entry, bool&); ValueType* RehashTo(ValueType* new_table, unsigned new_table_size, ValueType* entry); ValueType* Rehash(unsigned new_table_size, ValueType* entry); ValueType* Reinsert(ValueType&&); static void InitializeBucket(ValueType& bucket); static void DeleteBucket(ValueType& bucket) { bucket.~ValueType(); Traits::ConstructDeletedValue(bucket, Allocator::kIsGarbageCollected); } FullLookupType MakeLookupResult(ValueType* position, bool found, unsigned hash) { return FullLookupType(LookupType(position, found), hash); } iterator MakeIterator(ValueType* pos) { return iterator(pos, table_ + table_size_, this); } const_iterator MakeConstIterator(ValueType* pos) const { return const_iterator(pos, table_ + table_size_, this); } iterator MakeKnownGoodIterator(ValueType* pos) { return iterator(pos, table_ + table_size_, this, kHashItemKnownGood); } const_iterator MakeKnownGoodConstIterator(ValueType* pos) const { return const_iterator(pos, table_ + table_size_, this, kHashItemKnownGood); } static const unsigned kMaxLoad = 2; static const unsigned kMinLoad = 6; unsigned TableSizeMask() const { size_t mask = table_size_ - 1; DCHECK_EQ((mask & table_size_), 0u); return mask; } void SetEnqueued() { queue_flag_ = true; } void ClearEnqueued() { queue_flag_ = false; } bool Enqueued() { return queue_flag_; } ValueType* table_; unsigned table_size_; unsigned key_count_; #if DCHECK_IS_ON() unsigned deleted_count_ : 30; unsigned queue_flag_ : 1; unsigned access_forbidden_ : 1; unsigned modifications_; #else unsigned deleted_count_ : 31; unsigned queue_flag_ : 1; #endif #if DUMP_HASHTABLE_STATS_PER_TABLE public: mutable typename std::conditional<Allocator::isGarbageCollected, HashTableStats*, std::unique_ptr<HashTableStats>>::type stats_; #endif template <WeakHandlingFlag x, typename T, typename U, typename V, typename W, typename X, typename Y, typename Z> friend struct WeakProcessingHashTableHelper; template <typename T, typename U, typename V, typename W> friend class LinkedHashSet; }; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> inline HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::HashTable() : table_(nullptr), table_size_(0), key_count_(0), deleted_count_(0), queue_flag_(false) #if DCHECK_IS_ON() , access_forbidden_(false), modifications_(0) #endif #if DUMP_HASHTABLE_STATS_PER_TABLE , stats_(nullptr) #endif { static_assert(Allocator::kIsGarbageCollected || (!IsPointerToGarbageCollectedType<Key>::value && !IsPointerToGarbageCollectedType<Value>::value), "Cannot put raw pointers to garbage-collected classes into an " "off-heap collection."); } inline unsigned DoubleHash(unsigned key) { key = ~key + (key >> 23); key ^= (key << 12); key ^= (key >> 7); key ^= (key << 2); key ^= (key >> 20); return key; } inline unsigned CalculateCapacity(unsigned size) { for (unsigned mask = size; mask; mask >>= 1) size |= mask; // 00110101010 -> 00111111111 return (size + 1) * 2; // 00111111111 -> 10000000000 } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::ReserveCapacityForSize(unsigned new_size) { unsigned new_capacity = CalculateCapacity(new_size); if (new_capacity < KeyTraits::kMinimumTableSize) new_capacity = KeyTraits::kMinimumTableSize; if (new_capacity > Capacity()) { CHECK(!static_cast<int>( new_capacity >> 31)); // HashTable capacity should not overflow 32bit int. Rehash(new_capacity, 0); } } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> inline Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Lookup(const T& key) { return const_cast<Value*>( const_cast<const HashTable*>(this)->Lookup<HashTranslator>(key)); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> inline const Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Lookup(const T& key) const { DCHECK(!AccessForbidden()); DCHECK((HashTableKeyChecker< HashTranslator, KeyTraits, HashFunctions::safe_to_compare_to_empty_or_deleted>::CheckKey(key))); const ValueType* table = table_; if (!table) return nullptr; size_t k = 0; size_t size_mask = TableSizeMask(); unsigned h = HashTranslator::GetHash(key); size_t i = h & size_mask; UPDATE_ACCESS_COUNTS(); while (1) { const ValueType* entry = table + i; if (HashFunctions::safe_to_compare_to_empty_or_deleted) { if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return entry; if (IsEmptyBucket(*entry)) return nullptr; } else { if (IsEmptyBucket(*entry)) return nullptr; if (!IsDeletedBucket(*entry) && HashTranslator::Equal(Extractor::Extract(*entry), key)) return entry; } UPDATE_PROBE_COUNTS(); if (!k) k = 1 | DoubleHash(h); i = (i + k) & size_mask; } } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::LookupType HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: LookupForWriting(const T& key) { DCHECK(!AccessForbidden()); DCHECK(table_); RegisterModification(); ValueType* table = table_; size_t k = 0; size_t size_mask = TableSizeMask(); unsigned h = HashTranslator::GetHash(key); size_t i = h & size_mask; UPDATE_ACCESS_COUNTS(); ValueType* deleted_entry = nullptr; while (1) { ValueType* entry = table + i; if (IsEmptyBucket(*entry)) return LookupType(deleted_entry ? deleted_entry : entry, false); if (HashFunctions::safe_to_compare_to_empty_or_deleted) { if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return LookupType(entry, true); if (IsDeletedBucket(*entry)) deleted_entry = entry; } else { if (IsDeletedBucket(*entry)) deleted_entry = entry; else if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return LookupType(entry, true); } UPDATE_PROBE_COUNTS(); if (!k) k = 1 | DoubleHash(h); i = (i + k) & size_mask; } } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::FullLookupType HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: FullLookupForWriting(const T& key) { DCHECK(!AccessForbidden()); DCHECK(table_); RegisterModification(); ValueType* table = table_; size_t k = 0; size_t size_mask = TableSizeMask(); unsigned h = HashTranslator::GetHash(key); size_t i = h & size_mask; UPDATE_ACCESS_COUNTS(); ValueType* deleted_entry = nullptr; while (1) { ValueType* entry = table + i; if (IsEmptyBucket(*entry)) return MakeLookupResult(deleted_entry ? deleted_entry : entry, false, h); if (HashFunctions::safe_to_compare_to_empty_or_deleted) { if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return MakeLookupResult(entry, true, h); if (IsDeletedBucket(*entry)) deleted_entry = entry; } else { if (IsDeletedBucket(*entry)) deleted_entry = entry; else if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return MakeLookupResult(entry, true, h); } UPDATE_PROBE_COUNTS(); if (!k) k = 1 | DoubleHash(h); i = (i + k) & size_mask; } } template <bool emptyValueIsZero> struct HashTableBucketInitializer; template <> struct HashTableBucketInitializer<false> { STATIC_ONLY(HashTableBucketInitializer); template <typename Traits, typename Value> static void Initialize(Value& bucket) { new (NotNull, &bucket) Value(Traits::EmptyValue()); } }; template <> struct HashTableBucketInitializer<true> { STATIC_ONLY(HashTableBucketInitializer); template <typename Traits, typename Value> static void Initialize(Value& bucket) { // This initializes the bucket without copying the empty value. That // makes it possible to use this with types that don't support copying. // The memset to 0 looks like a slow operation but is optimized by the // compilers. memset(&bucket, 0, sizeof(bucket)); } }; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: InitializeBucket(ValueType& bucket) { HashTableBucketInitializer<Traits::kEmptyValueIsZero>::template Initialize< Traits>(bucket); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T, typename Extra> typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::AddResult HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: insert(T&& key, Extra&& extra) { DCHECK(!AccessForbidden()); DCHECK(Allocator::IsAllocationAllowed()); if (!table_) Expand(); DCHECK(table_); ValueType* table = table_; size_t k = 0; size_t size_mask = TableSizeMask(); unsigned h = HashTranslator::GetHash(key); size_t i = h & size_mask; UPDATE_ACCESS_COUNTS(); ValueType* deleted_entry = nullptr; ValueType* entry; while (1) { entry = table + i; if (IsEmptyBucket(*entry)) break; if (HashFunctions::safe_to_compare_to_empty_or_deleted) { if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return AddResult(this, entry, false); if (IsDeletedBucket(*entry)) deleted_entry = entry; } else { if (IsDeletedBucket(*entry)) deleted_entry = entry; else if (HashTranslator::Equal(Extractor::Extract(*entry), key)) return AddResult(this, entry, false); } UPDATE_PROBE_COUNTS(); if (!k) k = 1 | DoubleHash(h); i = (i + k) & size_mask; } RegisterModification(); if (deleted_entry) { // Overwrite any data left over from last use, using placement new or // memset. InitializeBucket(*deleted_entry); entry = deleted_entry; --deleted_count_; } HashTranslator::Translate(*entry, std::forward<T>(key), std::forward<Extra>(extra)); DCHECK(!IsEmptyOrDeletedBucket(*entry)); ++key_count_; if (ShouldExpand()) { entry = Expand(entry); } else if (Traits::kWeakHandlingFlag == kWeakHandlingInCollections && ShouldShrink()) { // When weak hash tables are processed by the garbage collector, // elements with no other strong references to them will have their // table entries cleared. But no shrinking of the backing store is // allowed at that time, as allocations are prohibited during that // GC phase. // // With that weak processing taking care of removals, explicit // erase()s of elements is rarely done. Which implies that the // weak hash table will never be checked if it can be shrunk. // // To prevent weak hash tables with very low load factors from // developing, we perform it when adding elements instead. entry = Rehash(table_size_ / 2, entry); } return AddResult(this, entry, true); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T, typename Extra> typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::AddResult HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: InsertPassingHashCode(T&& key, Extra&& extra) { DCHECK(!AccessForbidden()); DCHECK(Allocator::IsAllocationAllowed()); if (!table_) Expand(); FullLookupType lookup_result = FullLookupForWriting<HashTranslator>(key); ValueType* entry = lookup_result.first.first; bool found = lookup_result.first.second; unsigned h = lookup_result.second; if (found) return AddResult(this, entry, false); RegisterModification(); if (IsDeletedBucket(*entry)) { InitializeBucket(*entry); --deleted_count_; } HashTranslator::Translate(*entry, std::forward<T>(key), std::forward<Extra>(extra), h); DCHECK(!IsEmptyOrDeletedBucket(*entry)); ++key_count_; if (ShouldExpand()) entry = Expand(entry); return AddResult(this, entry, true); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Reinsert(ValueType&& entry) { DCHECK(table_); RegisterModification(); DCHECK(!LookupForWriting(Extractor::Extract(entry)).second); DCHECK( !IsDeletedBucket(*(LookupForWriting(Extractor::Extract(entry)).first))); #if DUMP_HASHTABLE_STATS atomicIncrement(&HashTableStats::instance().numReinserts); #endif #if DUMP_HASHTABLE_STATS_PER_TABLE ++stats_->numReinserts; #endif Value* new_entry = LookupForWriting(Extractor::Extract(entry)).first; Mover<ValueType, Allocator, Traits::template NeedsToForbidGCOnMove<>::value>::Move(std::move(entry), *new_entry); return new_entry; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::iterator HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Find(const T& key) { ValueType* entry = Lookup<HashTranslator>(key); if (!entry) return end(); return MakeKnownGoodIterator(entry); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::const_iterator HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Find(const T& key) const { ValueType* entry = const_cast<HashTable*>(this)->Lookup<HashTranslator>(key); if (!entry) return end(); return MakeKnownGoodConstIterator(entry); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> bool HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::Contains(const T& key) const { return const_cast<HashTable*>(this)->Lookup<HashTranslator>(key); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::erase(ValueType* pos) { RegisterModification(); #if DUMP_HASHTABLE_STATS atomicIncrement(&HashTableStats::instance().numRemoves); #endif #if DUMP_HASHTABLE_STATS_PER_TABLE ++stats_->numRemoves; #endif EnterAccessForbiddenScope(); DeleteBucket(*pos); LeaveAccessForbiddenScope(); ++deleted_count_; --key_count_; if (ShouldShrink()) Shrink(); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: erase(iterator it) { if (it == end()) return; erase(const_cast<ValueType*>(it.iterator_.position_)); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: erase(const_iterator it) { if (it == end()) return; erase(const_cast<ValueType*>(it.position_)); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: erase(KeyPeekInType key) { erase(find(key)); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: AllocateTable(unsigned size) { size_t alloc_size = size * sizeof(ValueType); ValueType* result; // Assert that we will not use memset on things with a vtable entry. The // compiler will also check this on some platforms. We would like to check // this on the whole value (key-value pair), but std::is_polymorphic will // return false for a pair of two types, even if one of the components is // polymorphic. static_assert( !Traits::kEmptyValueIsZero || !std::is_polymorphic<KeyType>::value, "empty value cannot be zero for things with a vtable"); static_assert(Allocator::kIsGarbageCollected || ((!AllowsOnlyPlacementNew<KeyType>::value || !IsTraceable<KeyType>::value) && (!AllowsOnlyPlacementNew<ValueType>::value || !IsTraceable<ValueType>::value)), "Cannot put DISALLOW_NEW_EXCEPT_PLACEMENT_NEW objects that " "have trace methods into an off-heap HashTable"); if (Traits::kEmptyValueIsZero) { result = Allocator::template AllocateZeroedHashTableBacking<ValueType, HashTable>( alloc_size); } else { result = Allocator::template AllocateHashTableBacking<ValueType, HashTable>( alloc_size); for (unsigned i = 0; i < size; i++) InitializeBucket(result[i]); } return result; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::DeleteAllBucketsAndDeallocate(ValueType* table, unsigned size) { if (!IsTriviallyDestructible<ValueType>::value) { for (unsigned i = 0; i < size; ++i) { // This code is called when the hash table is cleared or resized. We // have allocated a new backing store and we need to run the // destructors on the old backing store, as it is being freed. If we // are GCing we need to both call the destructor and mark the bucket // as deleted, otherwise the destructor gets called again when the // GC finds the backing store. With the default allocator it's // enough to call the destructor, since we will free the memory // explicitly and we won't see the memory with the bucket again. if (Allocator::kIsGarbageCollected) { if (!IsEmptyOrDeletedBucket(table[i])) DeleteBucket(table[i]); } else { if (!IsDeletedBucket(table[i])) table[i].~ValueType(); } } } Allocator::FreeHashTableBacking(table); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Expand(Value* entry) { unsigned new_size; if (!table_size_) { new_size = KeyTraits::kMinimumTableSize; } else if (MustRehashInPlace()) { new_size = table_size_; } else { new_size = table_size_ * 2; CHECK_GT(new_size, table_size_); } return Rehash(new_size, entry); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: ExpandBuffer(unsigned new_table_size, Value* entry, bool& success) { success = false; DCHECK_LT(table_size_, new_table_size); CHECK(!Allocator::IsObjectResurrectionForbidden()); if (!Allocator::ExpandHashTableBacking(table_, new_table_size * sizeof(ValueType))) return nullptr; success = true; Value* new_entry = nullptr; unsigned old_table_size = table_size_; ValueType* original_table = table_; ValueType* temporary_table = AllocateTable(old_table_size); for (unsigned i = 0; i < old_table_size; i++) { if (&table_[i] == entry) new_entry = &temporary_table[i]; if (IsEmptyOrDeletedBucket(table_[i])) { DCHECK_NE(&table_[i], entry); if (Traits::kEmptyValueIsZero) { memset(&temporary_table[i], 0, sizeof(ValueType)); } else { InitializeBucket(temporary_table[i]); } } else { Mover<ValueType, Allocator, Traits::template NeedsToForbidGCOnMove<>::value>:: Move(std::move(table_[i]), temporary_table[i]); table_[i].~ValueType(); } } table_ = temporary_table; if (Traits::kEmptyValueIsZero) { memset(original_table, 0, new_table_size * sizeof(ValueType)); } else { for (unsigned i = 0; i < new_table_size; i++) InitializeBucket(original_table[i]); } new_entry = RehashTo(original_table, new_table_size, new_entry); EnterAccessForbiddenScope(); DeleteAllBucketsAndDeallocate(temporary_table, old_table_size); LeaveAccessForbiddenScope(); return new_entry; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: RehashTo(ValueType* new_table, unsigned new_table_size, Value* entry) { unsigned old_table_size = table_size_; ValueType* old_table = table_; #if DUMP_HASHTABLE_STATS if (oldTableSize != 0) atomicIncrement(&HashTableStats::instance().numRehashes); #endif #if DUMP_HASHTABLE_STATS_PER_TABLE if (oldTableSize != 0) ++stats_->numRehashes; #endif table_ = new_table; table_size_ = new_table_size; Value* new_entry = nullptr; for (unsigned i = 0; i != old_table_size; ++i) { if (IsEmptyOrDeletedBucket(old_table[i])) { DCHECK_NE(&old_table[i], entry); continue; } Value* reinserted_entry = Reinsert(std::move(old_table[i])); if (&old_table[i] == entry) { DCHECK(!new_entry); new_entry = reinserted_entry; } } deleted_count_ = 0; #if DUMP_HASHTABLE_STATS_PER_TABLE if (!stats_) stats_ = HashTableStatsPtr<Allocator>::create(); #endif return new_entry; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: Rehash(unsigned new_table_size, Value* entry) { unsigned old_table_size = table_size_; ValueType* old_table = table_; #if DUMP_HASHTABLE_STATS if (oldTableSize != 0) atomicIncrement(&HashTableStats::instance().numRehashes); #endif #if DUMP_HASHTABLE_STATS_PER_TABLE if (oldTableSize != 0) ++stats_->numRehashes; #endif // The Allocator::isGarbageCollected check is not needed. The check is just // a static hint for a compiler to indicate that Base::expandBuffer returns // false if Allocator is a PartitionAllocator. if (Allocator::kIsGarbageCollected && new_table_size > old_table_size) { bool success; Value* new_entry = ExpandBuffer(new_table_size, entry, success); if (success) return new_entry; } ValueType* new_table = AllocateTable(new_table_size); Value* new_entry = RehashTo(new_table, new_table_size, entry); EnterAccessForbiddenScope(); DeleteAllBucketsAndDeallocate(old_table, old_table_size); LeaveAccessForbiddenScope(); return new_entry; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::clear() { RegisterModification(); if (!table_) return; EnterAccessForbiddenScope(); DeleteAllBucketsAndDeallocate(table_, table_size_); LeaveAccessForbiddenScope(); table_ = nullptr; table_size_ = 0; key_count_ = 0; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: HashTable(const HashTable& other) : table_(nullptr), table_size_(0), key_count_(0), deleted_count_(0), queue_flag_(false) #if DCHECK_IS_ON() , access_forbidden_(false), modifications_(0) #endif #if DUMP_HASHTABLE_STATS_PER_TABLE , stats_(HashTableStatsPtr<Allocator>::copy(other.stats_)) #endif { if (other.size()) ReserveCapacityForSize(other.size()); // Copy the hash table the dumb way, by adding each element to the new // table. It might be more efficient to copy the table slots, but it's not // clear that efficiency is needed. for (const auto& element : other) insert(element); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: HashTable(HashTable&& other) : table_(nullptr), table_size_(0), key_count_(0), deleted_count_(0), queue_flag_(false) #if DCHECK_IS_ON() , access_forbidden_(false), modifications_(0) #endif #if DUMP_HASHTABLE_STATS_PER_TABLE , stats_(HashTableStatsPtr<Allocator>::copy(other.stats_)) #endif { swap(other); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::swap(HashTable& other) { DCHECK(!AccessForbidden()); std::swap(table_, other.table_); std::swap(table_size_, other.table_size_); std::swap(key_count_, other.key_count_); // std::swap does not work for bit fields. unsigned deleted = deleted_count_; deleted_count_ = other.deleted_count_; other.deleted_count_ = deleted; DCHECK(!queue_flag_); DCHECK(!other.queue_flag_); #if DCHECK_IS_ON() std::swap(modifications_, other.modifications_); #endif #if DUMP_HASHTABLE_STATS_PER_TABLE HashTableStatsPtr<Allocator>::swap(stats_, other.stats_); #endif } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>& HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: operator=(const HashTable& other) { HashTable tmp(other); swap(tmp); return *this; } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>& HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>:: operator=(HashTable&& other) { swap(other); return *this; } template <WeakHandlingFlag weakHandlingFlag, typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> struct WeakProcessingHashTableHelper; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> struct WeakProcessingHashTableHelper<kNoWeakHandlingInCollections, Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> { STATIC_ONLY(WeakProcessingHashTableHelper); static void Process(typename Allocator::Visitor* visitor, void* closure) {} static void EphemeronIteration(typename Allocator::Visitor* visitor, void* closure) {} static void EphemeronIterationDone(typename Allocator::Visitor* visitor, void* closure) {} }; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> struct WeakProcessingHashTableHelper<kWeakHandlingInCollections, Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator> { STATIC_ONLY(WeakProcessingHashTableHelper); using HashTableType = HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>; using ValueType = typename HashTableType::ValueType; // Used for purely weak and for weak-and-strong tables (ephemerons). static void Process(typename Allocator::Visitor* visitor, void* closure) { HashTableType* table = reinterpret_cast<HashTableType*>(closure); if (!table->table_) return; // Now perform weak processing (this is a no-op if the backing was // accessible through an iterator and was already marked strongly). for (ValueType* element = table->table_ + table->table_size_ - 1; element >= table->table_; element--) { if (!HashTableType::IsEmptyOrDeletedBucket(*element)) { // At this stage calling trace can make no difference // (everything is already traced), but we use the return value // to remove things from the collection. // FIXME: This should be rewritten so that this can check if the // element is dead without calling trace, which is semantically // not correct to be called in weak processing stage. if (TraceInCollectionTrait<kWeakHandlingInCollections, kWeakPointersActWeak, ValueType, Traits>::Trace(visitor, *element)) { table->RegisterModification(); HashTableType::DeleteBucket(*element); // Also calls the destructor. table->deleted_count_++; table->key_count_--; // We don't rehash the backing until the next add or delete, // because that would cause allocation during GC. } } } } // Called repeatedly for tables that have both weak and strong pointers. static void EphemeronIteration(typename Allocator::Visitor* visitor, void* closure) { HashTableType* table = reinterpret_cast<HashTableType*>(closure); DCHECK(table->table_); // Check the hash table for elements that we now know will not be // removed by weak processing. Those elements need to have their strong // pointers traced. for (ValueType* element = table->table_ + table->table_size_ - 1; element >= table->table_; element--) { if (!HashTableType::IsEmptyOrDeletedBucket(*element)) TraceInCollectionTrait<kWeakHandlingInCollections, kWeakPointersActWeak, ValueType, Traits>::Trace(visitor, *element); } } // Called when the ephemeron iteration is done and before running the per // thread weak processing. It is guaranteed to be called before any thread // is resumed. static void EphemeronIterationDone(typename Allocator::Visitor* visitor, void* closure) { HashTableType* table = reinterpret_cast<HashTableType*>(closure); #if DCHECK_IS_ON() DCHECK(Allocator::WeakTableRegistered(visitor, table)); #endif table->ClearEnqueued(); } }; template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename VisitorDispatcher> void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::Trace(VisitorDispatcher visitor) { #if DUMP_HASHTABLE_STATS_PER_TABLE Allocator::markNoTracing(visitor, stats_); #endif // If someone else already marked the backing and queued up the trace and/or // weak callback then we are done. This optimization does not happen for // ListHashSet since its iterator does not point at the backing. if (!table_ || Allocator::IsHeapObjectAlive(table_)) return; // Normally, we mark the backing store without performing trace. This means // it is marked live, but the pointers inside it are not marked. Instead we // will mark the pointers below. However, for backing stores that contain // weak pointers the handling is rather different. We don't mark the // backing store here, so the marking GC will leave the backing unmarked. If // the backing is found in any other way than through its HashTable (ie from // an iterator) then the mark bit will be set and the pointers will be // marked strongly, avoiding problems with iterating over things that // disappear due to weak processing while we are iterating over them. We // register the backing store pointer for delayed marking which will take // place after we know if the backing is reachable from elsewhere. We also // register a weakProcessing callback which will perform weak processing if // needed. if (Traits::kWeakHandlingFlag == kNoWeakHandlingInCollections) { Allocator::MarkNoTracing(visitor, table_); } else { Allocator::RegisterDelayedMarkNoTracing(visitor, table_); // Since we're delaying marking this HashTable, it is possible that the // registerWeakMembers is called multiple times (in rare // cases). However, it shouldn't cause any issue. Allocator::RegisterWeakMembers( visitor, this, WeakProcessingHashTableHelper<Traits::kWeakHandlingFlag, Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::Process); } // If the backing store will be moved by sweep compaction, register the // table reference pointing to the backing store object, so that the // reference is updated upon object relocation. A no-op if not enabled // by the visitor. Allocator::RegisterBackingStoreReference(visitor, &table_); if (!IsTraceableInCollectionTrait<Traits>::value) return; if (Traits::kWeakHandlingFlag == kWeakHandlingInCollections) { // If we have both strong and weak pointers in the collection then // we queue up the collection for fixed point iteration a la // Ephemerons: // http://dl.acm.org/citation.cfm?doid=263698.263733 - see also // http://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak #if DCHECK_IS_ON() DCHECK(!Enqueued() || Allocator::WeakTableRegistered(visitor, this)); #endif if (!Enqueued()) { Allocator::RegisterWeakTable( visitor, this, WeakProcessingHashTableHelper< Traits::kWeakHandlingFlag, Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::EphemeronIteration, WeakProcessingHashTableHelper< Traits::kWeakHandlingFlag, Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::EphemeronIterationDone); SetEnqueued(); } // We don't need to trace the elements here, since registering as a // weak table above will cause them to be traced (perhaps several // times). It's better to wait until everything else is traced // before tracing the elements for the first time; this may reduce // (by one) the number of iterations needed to get to a fixed point. return; } for (ValueType* element = table_ + table_size_ - 1; element >= table_; element--) { if (!IsEmptyOrDeletedBucket(*element)) Allocator::template Trace<VisitorDispatcher, ValueType, Traits>(visitor, *element); } } // iterator adapters template <typename HashTableType, typename Traits> struct HashTableConstIteratorAdapter { STACK_ALLOCATED(); HashTableConstIteratorAdapter() {} HashTableConstIteratorAdapter( const typename HashTableType::const_iterator& impl) : impl_(impl) {} typedef typename Traits::IteratorConstGetType GetType; typedef typename HashTableType::ValueTraits::IteratorConstGetType SourceGetType; GetType Get() const { return const_cast<GetType>(SourceGetType(impl_.Get())); } typename Traits::IteratorConstReferenceType operator*() const { return Traits::GetToReferenceConstConversion(Get()); } GetType operator->() const { return Get(); } HashTableConstIteratorAdapter& operator++() { ++impl_; return *this; } // postfix ++ intentionally omitted typename HashTableType::const_iterator impl_; }; template <typename HashTable, typename Traits> std::ostream& operator<<( std::ostream& stream, const HashTableConstIteratorAdapter<HashTable, Traits>& iterator) { return stream << iterator.impl_; } template <typename HashTableType, typename Traits> struct HashTableIteratorAdapter { STACK_ALLOCATED(); typedef typename Traits::IteratorGetType GetType; typedef typename HashTableType::ValueTraits::IteratorGetType SourceGetType; HashTableIteratorAdapter() {} HashTableIteratorAdapter(const typename HashTableType::iterator& impl) : impl_(impl) {} GetType Get() const { return const_cast<GetType>(SourceGetType(impl_.get())); } typename Traits::IteratorReferenceType operator*() const { return Traits::GetToReferenceConversion(Get()); } GetType operator->() const { return Get(); } HashTableIteratorAdapter& operator++() { ++impl_; return *this; } // postfix ++ intentionally omitted operator HashTableConstIteratorAdapter<HashTableType, Traits>() { typename HashTableType::const_iterator i = impl_; return i; } typename HashTableType::iterator impl_; }; template <typename HashTable, typename Traits> std::ostream& operator<<( std::ostream& stream, const HashTableIteratorAdapter<HashTable, Traits>& iterator) { return stream << iterator.impl_; } template <typename T, typename U> inline bool operator==(const HashTableConstIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b) { return a.impl_ == b.impl_; } template <typename T, typename U> inline bool operator!=(const HashTableConstIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b) { return a.impl_ != b.impl_; } template <typename T, typename U> inline bool operator==(const HashTableIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b) { return a.impl_ == b.impl_; } template <typename T, typename U> inline bool operator!=(const HashTableIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b) { return a.impl_ != b.impl_; } // All 4 combinations of ==, != and Const,non const. template <typename T, typename U> inline bool operator==(const HashTableConstIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b) { return a.impl_ == b.impl_; } template <typename T, typename U> inline bool operator!=(const HashTableConstIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b) { return a.impl_ != b.impl_; } template <typename T, typename U> inline bool operator==(const HashTableIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b) { return a.impl_ == b.impl_; } template <typename T, typename U> inline bool operator!=(const HashTableIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b) { return a.impl_ != b.impl_; } template <typename Collection1, typename Collection2> inline void RemoveAll(Collection1& collection, const Collection2& to_be_removed) { if (collection.IsEmpty() || to_be_removed.IsEmpty()) return; typedef typename Collection2::const_iterator CollectionIterator; CollectionIterator end(to_be_removed.end()); for (CollectionIterator it(to_be_removed.begin()); it != end; ++it) collection.erase(*it); } } // namespace WTF #include "platform/wtf/HashIterators.h" #endif // WTF_HashTable_h
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
5c56ccef3d81f3f779552b273185456b2f5a3960
340f055a3fb5b70302690a026ba93e8bc8ff5896
/src/rpc/server.h
a197721a7273ddd1dc98aa66c5d08c06f65579a2
[ "MIT" ]
permissive
Supernode-SUNO/SUNO
9af127dc615abad83c0567420dc6f29c1df883f8
6b34a154671597b6e072eeecf336d2d3d38ee6bb
refs/heads/master
2023-02-13T21:17:05.024653
2021-01-05T10:52:37
2021-01-05T10:52:37
326,248,236
0
0
null
null
null
null
UTF-8
C++
false
false
11,803
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2020 The PIVX developers // Copyright (c) 2020 The Supernode Coin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RPCSERVER_H #define BITCOIN_RPCSERVER_H #include "amount.h" #include "rpc/protocol.h" #include "uint256.h" #include <list> #include <map> #include <stdint.h> #include <string> #include <univalue.h> class CRPCCommand; namespace RPCServer { void OnStarted(std::function<void ()> slot); void OnStopped(std::function<void ()> slot); void OnPreCommand(std::function<void (const CRPCCommand&)> slot); void OnPostCommand(std::function<void (const CRPCCommand&)> slot); } class CBlockIndex; class CNetAddr; class JSONRPCRequest { public: UniValue id; std::string strMethod; UniValue params; bool fHelp; std::string URI; std::string authUser; JSONRPCRequest() { id = NullUniValue; params = NullUniValue; fHelp = false; } void parse(const UniValue& valRequest); }; /** Query whether RPC is running */ bool IsRPCRunning(); /** * Set the RPC warmup status. When this is done, all RPC calls will error out * immediately with RPC_IN_WARMUP. */ void SetRPCWarmupStatus(const std::string& newStatus); /* Mark warmup as done. RPC calls will be processed from now on. */ void SetRPCWarmupFinished(); /* returns the current warmup state. */ bool RPCIsInWarmup(std::string* statusOut); /** * Type-check arguments; throws JSONRPCError if wrong type given. Does not check that * the right number of arguments are passed, just that any passed are the correct type. * Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); */ void RPCTypeCheck(const UniValue& params, const std::list<UniValue::VType>& typesExpected, bool fAllowNull=false); /** * Check for expected keys/value types in an Object. * Use like: RPCTypeCheckObj(object, boost::assign::map_list_of("name", str_type)("value", int_type)); */ void RPCTypeCheckObj(const UniValue& o, const std::map<std::string, UniValue::VType>& typesExpected, bool fAllowNull=false, bool fStrict=false); /** Opaque base class for timers returned by NewTimerFunc. * This provides no methods at the moment, but makes sure that delete * cleans up the whole state. */ class RPCTimerBase { public: virtual ~RPCTimerBase() {} }; /** * RPC timer "driver". */ class RPCTimerInterface { public: virtual ~RPCTimerInterface() {} /** Implementation name */ virtual const char *Name() = 0; /** Factory function for timers. * RPC will call the function to create a timer that will call func in *millis* milliseconds. * @note As the RPC mechanism is backend-neutral, it can use different implementations of timers. * This is needed to cope with the case in which there is no HTTP server, but * only GUI RPC console, and to break the dependency of pcserver on httprpc. */ virtual RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) = 0; }; /** Set factory function for timers */ void RPCSetTimerInterface(RPCTimerInterface *iface); /** Set factory function for timers, but only if unset */ void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface); /** Unset factory function for timers */ void RPCUnsetTimerInterface(RPCTimerInterface *iface); /** * Run func nSeconds from now. * Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_t nSeconds); typedef UniValue(*rpcfn_type)(const JSONRPCRequest& jsonRequest); class CRPCCommand { public: std::string category; std::string name; rpcfn_type actor; bool okSafeMode; }; /** * SupernodeCoin RPC command dispatcher. */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](const std::string& name) const; std::string help(std::string name) const; /** * Execute a method. * @param request The JSONRPCRequest to execute * @returns Result of the call. * @throws an exception (UniValue) when an error happens. */ UniValue execute(const JSONRPCRequest &request) const; /** * Returns a list of registered commands * @returns List of registered commands. */ std::vector<std::string> listCommands() const; /** * Appends a CRPCCommand to the dispatch table. * Returns false if RPC server is already running (dump concurrency protection). * Commands cannot be overwritten (returns false). */ bool appendCommand(const std::string& name, const CRPCCommand* pcmd); }; bool IsDeprecatedRPCEnabled(const std::string& method); extern CRPCTable tableRPC; /** * Utilities: convert hex-encoded Values * (throws error if not hex). */ extern uint256 ParseHashV(const UniValue& v, std::string strName); extern uint256 ParseHashO(const UniValue& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey); extern int ParseInt(const UniValue& o, std::string strKey); extern bool ParseBool(const UniValue& o, std::string strKey); extern int64_t nWalletUnlockTime; extern CAmount AmountFromValue(const UniValue& value); extern UniValue ValueFromAmount(const CAmount& amount); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern std::string HelpRequiringPassphrase(); extern std::string HelpExampleCli(std::string methodname, std::string args); extern std::string HelpExampleRpc(std::string methodname, std::string args); extern void EnsureWalletIsUnlocked(bool fAllowAnonOnly = false); // Ensure the wallet's existence. extern void EnsureWallet(); extern UniValue getconnectioncount(const JSONRPCRequest& request); // in rpc/net.cpp extern UniValue getpeerinfo(const JSONRPCRequest& request); extern UniValue ping(const JSONRPCRequest& request); extern UniValue addnode(const JSONRPCRequest& request); extern UniValue disconnectnode(const JSONRPCRequest& request); extern UniValue getaddednodeinfo(const JSONRPCRequest& request); extern UniValue getnettotals(const JSONRPCRequest& request); extern UniValue setban(const JSONRPCRequest& request); extern UniValue listbanned(const JSONRPCRequest& request); extern UniValue clearbanned(const JSONRPCRequest& request); extern UniValue bip38encrypt(const JSONRPCRequest& request); extern UniValue bip38decrypt(const JSONRPCRequest& request); extern UniValue getgenerate(const JSONRPCRequest& request); // in rpc/mining.cpp extern UniValue setgenerate(const JSONRPCRequest& request); extern UniValue generate(const JSONRPCRequest& request); extern UniValue getnetworkhashps(const JSONRPCRequest& request); extern UniValue gethashespersec(const JSONRPCRequest& request); extern UniValue getmininginfo(const JSONRPCRequest& request); extern UniValue prioritisetransaction(const JSONRPCRequest& request); extern UniValue getblocktemplate(const JSONRPCRequest& request); extern UniValue submitblock(const JSONRPCRequest& request); extern UniValue estimatefee(const JSONRPCRequest& request); extern UniValue estimatesmartfee(const JSONRPCRequest& request); extern UniValue getaddressinfo(const JSONRPCRequest& request); extern UniValue getblockchaininfo(const JSONRPCRequest& request); extern UniValue getnetworkinfo(const JSONRPCRequest& request); extern UniValue multisend(const JSONRPCRequest& request); extern UniValue getrawtransaction(const JSONRPCRequest& request); // in rpc/rawtransaction.cpp extern UniValue createrawtransaction(const JSONRPCRequest& request); extern UniValue decoderawtransaction(const JSONRPCRequest& request); extern UniValue decodescript(const JSONRPCRequest& request); extern UniValue fundrawtransaction(const JSONRPCRequest& request); extern UniValue signrawtransaction(const JSONRPCRequest& request); extern UniValue sendrawtransaction(const JSONRPCRequest& request); extern UniValue getblockcount(const JSONRPCRequest& request); extern UniValue getbestblockhash(const JSONRPCRequest& request); extern UniValue waitfornewblock(const JSONRPCRequest& request); extern UniValue waitforblock(const JSONRPCRequest& request); extern UniValue waitforblockheight(const JSONRPCRequest& request); extern UniValue getdifficulty(const JSONRPCRequest& request); extern UniValue getmempoolinfo(const JSONRPCRequest& request); extern UniValue getrawmempool(const JSONRPCRequest& request); extern UniValue getblockhash(const JSONRPCRequest& request); extern UniValue getblock(const JSONRPCRequest& request); extern UniValue getblockheader(const JSONRPCRequest& request); extern UniValue getfeeinfo(const JSONRPCRequest& request); extern UniValue gettxoutsetinfo(const JSONRPCRequest& request); extern UniValue gettxout(const JSONRPCRequest& request); extern UniValue verifychain(const JSONRPCRequest& request); extern UniValue getchaintips(const JSONRPCRequest& request); extern UniValue invalidateblock(const JSONRPCRequest& request); extern UniValue reconsiderblock(const JSONRPCRequest& request); extern UniValue getblockindexstats(const JSONRPCRequest& request); extern void validaterange(const UniValue& params, int& heightStart, int& heightEnd, int minHeightStart=1); // in rpc/masternode.cpp extern UniValue listmasternodes(const JSONRPCRequest& request); extern UniValue getmasternodecount(const JSONRPCRequest& request); extern UniValue createmasternodebroadcast(const JSONRPCRequest& request); extern UniValue decodemasternodebroadcast(const JSONRPCRequest& request); extern UniValue relaymasternodebroadcast(const JSONRPCRequest& request); extern UniValue masternodecurrent(const JSONRPCRequest& request); extern UniValue startmasternode(const JSONRPCRequest& request); extern UniValue createmasternodekey(const JSONRPCRequest& request); extern UniValue getmasternodeoutputs(const JSONRPCRequest& request); extern UniValue listmasternodeconf(const JSONRPCRequest& request); extern UniValue getmasternodestatus(const JSONRPCRequest& request); extern UniValue getmasternodewinners(const JSONRPCRequest& request); extern UniValue getmasternodescores(const JSONRPCRequest& request); extern UniValue preparebudget(const JSONRPCRequest& request); // in rpc/budget.cpp extern UniValue submitbudget(const JSONRPCRequest& request); extern UniValue mnbudgetvote(const JSONRPCRequest& request); extern UniValue getbudgetvotes(const JSONRPCRequest& request); extern UniValue getnextsuperblock(const JSONRPCRequest& request); extern UniValue getbudgetprojection(const JSONRPCRequest& request); extern UniValue getbudgetinfo(const JSONRPCRequest& request); extern UniValue mnbudgetrawvote(const JSONRPCRequest& request); extern UniValue mnfinalbudget(const JSONRPCRequest& request); extern UniValue checkbudgets(const JSONRPCRequest& request); extern UniValue getinfo(const JSONRPCRequest& request); // in rpc/misc.cpp extern UniValue logging(const JSONRPCRequest& request); extern UniValue mnsync(const JSONRPCRequest& request); extern UniValue spork(const JSONRPCRequest& request); extern UniValue validateaddress(const JSONRPCRequest& request); extern UniValue createmultisig(const JSONRPCRequest& request); extern UniValue verifymessage(const JSONRPCRequest& request); extern UniValue setmocktime(const JSONRPCRequest& request); extern UniValue getstakingstatus(const JSONRPCRequest& request); bool StartRPC(); void InterruptRPC(); void StopRPC(); std::string JSONRPCExecBatch(const UniValue& vReq); void RPCNotifyBlockChange(bool fInitialDownload, const CBlockIndex* pindex); #endif // BITCOIN_RPCSERVER_H
[ "76836543+Supernode-SUNO@users.noreply.github.com" ]
76836543+Supernode-SUNO@users.noreply.github.com
ffa9671239718623369aa25665b0f44816c8759d
11dfb8345e964f5f2c969a8da4f0c8911069123e
/cocos2d/cocos/2d/CCActionInstant.h
fa83260bb602d301f4db0bf1e6a8f61d90ed1d51
[]
no_license
FenneX/FenneXTestProject
9220b45cc70b7a90b021e2da4c809143ab5e2333
cd7d5db20b672d374d049f2d5f4c1e4eaf117419
refs/heads/master
2021-01-13T02:19:29.168857
2015-04-22T15:39:11
2015-04-22T15:39:11
24,424,401
2
1
null
null
null
null
UTF-8
C++
false
false
11,584
h
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2011 Zynga Inc. Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ #ifndef __CCINSTANT_ACTION_H__ #define __CCINSTANT_ACTION_H__ #include <functional> #include "2d/CCAction.h" NS_CC_BEGIN /** * @addtogroup actions * @{ */ /** @brief Instant actions are immediate actions. They don't have a duration like the IntervalAction actions. */ class CC_DLL ActionInstant : public FiniteTimeAction //<NSCopying> { public: // // Overrides // virtual ActionInstant* clone() const override { CC_ASSERT(0); return nullptr; } virtual ActionInstant * reverse() const override { CC_ASSERT(0); return nullptr; } virtual bool isDone() const override; virtual void step(float dt) override; virtual void update(float time) override; }; /** @brief Show the node */ class CC_DLL Show : public ActionInstant { public: /** Allocates and initializes the action */ static Show * create(); // // Overrides // virtual void update(float time) override; virtual ActionInstant* reverse() const override; virtual Show* clone() const override; CC_CONSTRUCTOR_ACCESS: Show(){} virtual ~Show(){} private: CC_DISALLOW_COPY_AND_ASSIGN(Show); }; /** @brief Hide the node */ class CC_DLL Hide : public ActionInstant { public: /** Allocates and initializes the action */ static Hide * create(); // // Overrides // virtual void update(float time) override; virtual ActionInstant* reverse() const override; virtual Hide* clone() const override; CC_CONSTRUCTOR_ACCESS: Hide(){} virtual ~Hide(){} private: CC_DISALLOW_COPY_AND_ASSIGN(Hide); }; /** @brief Toggles the visibility of a node */ class CC_DLL ToggleVisibility : public ActionInstant { public: /** Allocates and initializes the action */ static ToggleVisibility * create(); // // Overrides // virtual void update(float time) override; virtual ToggleVisibility* reverse() const override; virtual ToggleVisibility* clone() const override; CC_CONSTRUCTOR_ACCESS: ToggleVisibility(){} virtual ~ToggleVisibility(){} private: CC_DISALLOW_COPY_AND_ASSIGN(ToggleVisibility); }; /** @brief Remove the node */ class CC_DLL RemoveSelf : public ActionInstant { public: /** create the action */ static RemoveSelf * create(bool isNeedCleanUp = true); // // Override // virtual void update(float time) override; virtual RemoveSelf* clone() const override; virtual RemoveSelf* reverse() const override; CC_CONSTRUCTOR_ACCESS: RemoveSelf() : _isNeedCleanUp(true){} virtual ~RemoveSelf(){} /** init the action */ bool init(bool isNeedCleanUp); protected: bool _isNeedCleanUp; private: CC_DISALLOW_COPY_AND_ASSIGN(RemoveSelf); }; /** @brief Flips the sprite horizontally @since v0.99.0 */ class CC_DLL FlipX : public ActionInstant { public: /** create the action */ static FlipX * create(bool x); // // Overrides // virtual void update(float time) override; virtual FlipX* reverse() const override; virtual FlipX* clone() const override; CC_CONSTRUCTOR_ACCESS: FlipX() :_flipX(false) {} virtual ~FlipX() {} /** init the action */ bool initWithFlipX(bool x); protected: bool _flipX; private: CC_DISALLOW_COPY_AND_ASSIGN(FlipX); }; /** @brief Flips the sprite vertically @since v0.99.0 */ class CC_DLL FlipY : public ActionInstant { public: /** create the action */ static FlipY * create(bool y); // // Overrides // virtual void update(float time) override; virtual FlipY* reverse() const override; virtual FlipY* clone() const override; CC_CONSTRUCTOR_ACCESS: FlipY() :_flipY(false) {} virtual ~FlipY() {} /** init the action */ bool initWithFlipY(bool y); protected: bool _flipY; private: CC_DISALLOW_COPY_AND_ASSIGN(FlipY); }; /** @brief Places the node in a certain position */ class CC_DLL Place : public ActionInstant //<NSCopying> { public: /** creates a Place action with a position */ static Place * create(const Vec2& pos); // // Overrides // virtual void update(float time) override; virtual Place* reverse() const override; virtual Place* clone() const override; CC_CONSTRUCTOR_ACCESS: Place(){} virtual ~Place(){} /** Initializes a Place action with a position */ bool initWithPosition(const Vec2& pos); protected: Vec2 _position; private: CC_DISALLOW_COPY_AND_ASSIGN(Place); }; /** @brief Calls a 'callback' */ class CC_DLL CallFunc : public ActionInstant //<NSCopying> { public: /** creates the action with the callback of type std::function<void()>. This is the preferred way to create the callback. * When this funtion bound in js or lua ,the input param will be changed * In js: var create(var func, var this, var [data]) or var create(var func) * In lua:local create(local funcID) */ static CallFunc * create(const std::function<void()>& func); /** creates the action with the callback typedef void (Ref::*SEL_CallFunc)(); @deprecated Use the std::function API instead. * @js NA * @lua NA */ CC_DEPRECATED_ATTRIBUTE static CallFunc * create(Ref* target, SEL_CallFunc selector); public: /** executes the callback */ virtual void execute(); inline Ref* getTargetCallback() { return _selectorTarget; } inline void setTargetCallback(Ref* sel) { if (sel != _selectorTarget) { CC_SAFE_RETAIN(sel); CC_SAFE_RELEASE(_selectorTarget); _selectorTarget = sel; } } // // Overrides // virtual void update(float time) override; virtual CallFunc* reverse() const override; virtual CallFunc* clone() const override; CC_CONSTRUCTOR_ACCESS: CallFunc() : _selectorTarget(nullptr) , _callFunc(nullptr) , _function(nullptr) { } virtual ~CallFunc(); /** initializes the action with the callback typedef void (Ref::*SEL_CallFunc)(); @deprecated Use the std::function API instead. */ CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Ref* target); /** initializes the action with the std::function<void()> * @js NA * @lua NA */ bool initWithFunction(const std::function<void()>& func); protected: /** Target that will be called */ Ref* _selectorTarget; union { SEL_CallFunc _callFunc; SEL_CallFuncN _callFuncN; }; /** function that will be called */ std::function<void()> _function; private: CC_DISALLOW_COPY_AND_ASSIGN(CallFunc); }; /** @brief Calls a 'callback' with the node as the first argument N means Node */ class CC_DLL CallFuncN : public CallFunc { public: /** creates the action with the callback of type std::function<void()>. This is the preferred way to create the callback. */ static CallFuncN * create(const std::function<void(Node*)>& func); /** creates the action with the callback typedef void (Ref::*SEL_CallFuncN)(Node*); @deprecated Use the std::function API instead. */ CC_DEPRECATED_ATTRIBUTE static CallFuncN * create(Ref* target, SEL_CallFuncN selector); // // Overrides // virtual CallFuncN* clone() const override; virtual void execute() override; CC_CONSTRUCTOR_ACCESS: CallFuncN():_functionN(nullptr){} virtual ~CallFuncN(){} /** initializes the action with the std::function<void(Node*)> */ bool initWithFunction(const std::function<void(Node*)>& func); /** initializes the action with the callback typedef void (Ref::*SEL_CallFuncN)(Node*); @deprecated Use the std::function API instead. */ CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Ref* target, SEL_CallFuncN selector); protected: /** function that will be called with the "sender" as the 1st argument */ std::function<void(Node*)> _functionN; private: CC_DISALLOW_COPY_AND_ASSIGN(CallFuncN); }; /** @deprecated Please use CallFuncN instead. @brief Calls a 'callback' with the node as the first argument and the 2nd argument is data * ND means: Node and Data. Data is void *, so it could be anything. */ class CC_DLL __CCCallFuncND : public CallFunc { public: /** creates the action with the callback and the data to pass as an argument */ CC_DEPRECATED_ATTRIBUTE static __CCCallFuncND * create(Ref* target, SEL_CallFuncND selector, void* d); // // Overrides // virtual __CCCallFuncND* clone() const override; virtual void execute() override; CC_CONSTRUCTOR_ACCESS: __CCCallFuncND() {} virtual ~__CCCallFuncND() {} /** initializes the action with the callback and the data to pass as an argument */ bool initWithTarget(Ref* target, SEL_CallFuncND selector, void* d); protected: SEL_CallFuncND _callFuncND; void* _data; private: CC_DISALLOW_COPY_AND_ASSIGN(__CCCallFuncND); }; /** @deprecated Please use CallFuncN instead. @brief Calls a 'callback' with an object as the first argument. O means Object. @since v0.99.5 */ class CC_DLL __CCCallFuncO : public CallFunc { public: /** creates the action with the callback typedef void (Ref::*SEL_CallFuncO)(Ref*); */ CC_DEPRECATED_ATTRIBUTE static __CCCallFuncO * create(Ref* target, SEL_CallFuncO selector, Ref* object); // // Overrides // virtual __CCCallFuncO* clone() const override; virtual void execute() override; Ref* getObject() const; void setObject(Ref* obj); SEL_CallFuncO getSelectorTarget() const; CC_CONSTRUCTOR_ACCESS: __CCCallFuncO(); virtual ~__CCCallFuncO(); /** initializes the action with the callback typedef void (Ref::*SEL_CallFuncO)(Ref*); */ bool initWithTarget(Ref* target, SEL_CallFuncO selector, Ref* object); protected: /** object to be passed as argument */ Ref* _object; SEL_CallFuncO _callFuncO; private: CC_DISALLOW_COPY_AND_ASSIGN(__CCCallFuncO); }; // end of actions group /// @} NS_CC_END #endif //__CCINSTANT_ACTION_H__
[ "fradow@gmail.com" ]
fradow@gmail.com
68a1d1cc0fbefbe73e4727071202999399f0a22d
786de89be635eb21295070a6a3452f3a7fe6712c
/O2OTranslator/tags/V00-10-00/include/AcqirisTdcDataV1Cvt.h
91d916af3dac6a71e63f9e83902053662f829421
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,802
h
#ifndef O2OTRANSLATOR_ACQIRISTDCDATAV1CVT_H #define O2OTRANSLATOR_ACQIRISTDCDATAV1CVT_H //-------------------------------------------------------------------------- // File and Version Information: // $Id$ // // Description: // Class AcqirisTdcDataV1Cvt. // //------------------------------------------------------------------------ //----------------- // C/C++ Headers -- //----------------- //---------------------- // Base Class Headers -- //---------------------- #include "O2OTranslator/EvtDataTypeCvt.h" //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "H5DataTypes/AcqirisTdcDataV1.h" //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ #include "O2OTranslator/CvtDataContainer.h" #include "O2OTranslator/CvtDataContFactoryDef.h" // --------------------- // -- Class Interface -- // --------------------- namespace O2OTranslator { /** * Special converter class for Pds::Acqiris::TdcDataV1 * * This software was developed for the LUSI project. If you use all or * part of it, please give an appropriate acknowledgment. * * @see AdditionalClass * * @version $Id$ * * @author Andrei Salnikov */ class AcqirisTdcDataV1Cvt : public EvtDataTypeCvt<Pds::Acqiris::TdcDataV1> { public: typedef H5DataTypes::AcqirisTdcDataV1 H5Type ; typedef Pds::Acqiris::TdcDataV1 XtcType ; // constructor takes a location where the data will be stored AcqirisTdcDataV1Cvt (const std::string& typeGroupName, hsize_t chunk_size, int deflate) ; // Destructor virtual ~AcqirisTdcDataV1Cvt () ; protected: // typed conversion method virtual void typedConvertSubgroup ( hdf5pp::Group group, const XtcType& data, size_t size, const Pds::TypeId& typeId, const XtcInput::XtcSrcStack& src, const H5DataTypes::XtcClockTime& time ) ; /// method called when the driver closes a group in the file virtual void closeSubgroup( hdf5pp::Group group ) ; private: typedef CvtDataContainer<CvtDataContFactoryDef<H5DataTypes::XtcClockTime> > XtcClockTimeCont ; typedef CvtDataContainer<CvtDataContFactoryDef<H5Type> > DataCont ; // Data members hsize_t m_chunk_size ; int m_deflate ; DataCont* m_dataCont ; XtcClockTimeCont* m_timeCont ; // Copy constructor and assignment are disabled by default AcqirisTdcDataV1Cvt ( const AcqirisTdcDataV1Cvt& ) ; AcqirisTdcDataV1Cvt& operator = ( const AcqirisTdcDataV1Cvt& ) ; }; } // namespace O2OTranslator #endif // O2OTRANSLATOR_ACQIRISTDCDATAV1CVT_H
[ "salnikov@b967ad99-d558-0410-b138-e0f6c56caec7" ]
salnikov@b967ad99-d558-0410-b138-e0f6c56caec7
08f222fc251b7805924d3dadffb9706ccc536119
c88887a5855174dac1686b610b01fc417bcb8873
/Data_Structures/linked_list/linked list basic_implementation.cpp
74e3c53ffd0aec59e5f4be31fe2dbb5aecf57300
[]
no_license
gargaditya/Competitive-Programming
c2542f798dc5e604ccd09c5f63aa28acf9907220
f11aeec27bb5583bc2cb062f78b81a40f7a61a31
refs/heads/master
2021-04-28T10:26:48.931014
2015-06-25T00:50:41
2015-06-25T00:50:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,902
cpp
#include <cstdio> using namespace std; /************LINKED LIST IMPLEMENTATION*********** -Pointer to pointers will be used if we want to make change to pointer */ struct node { int value; node* next; }; void printAll(node *head){ node *p = head; while(p!=NULL){ printf("%d ",p->value); p = p->next; } printf("\n"); } void insert(node **head,int n){ node *temp,*p; temp = new node(); temp->value = n; temp->next = NULL; if(*head == NULL) /*When linked list is initially empty*/ *head = temp; else{ p = *head; while(p->next!=NULL) p = p->next; p->next = temp; } printAll(*head); } /*Two pointers will be used for deleting an node*/ void deleteNode(node **head,int n){ node *prev,*p; p = *head;prev = NULL; while(p!=NULL){ if(p->value == n){ if(prev == NULL) /*First node to be deleted*/ *head = p->next; else prev->next = p->next; delete p; /*Free the memory*/ printf("Successfully deleted\n"); printAll(*head); return; } prev = p; p = p->next; } printf("Not found\n"); printAll(*head); } void search(node *head,int n){ node *p=head; while(p!=NULL){ if(p->value == n){ printf("Yes node is presen\n"); return; } p = p->next; } printf("No node is not present\n"); } int main(){ int ch,n; bool Exit=false; node *head; while(!Exit){ printf("************************Menu**************************\n"); printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Search\n"); printf("4.Print\n"); printf("5.Exit\n");; scanf("%d",&ch); switch(ch){ case 1: printf("Insert Value: ");scanf("%d",&n); insert(&head,n); break; case 2: printf("Delete Value: ");scanf("%d",&n); deleteNode(&head,n); break; case 3: printf("Search Value: ");scanf("%d",&n); search(head,n); break; case 4: printAll(head); break; case 5: Exit = true; } } }
[ "shikharvashishth@gmail.com" ]
shikharvashishth@gmail.com
2f821a0d7a81d9777696e67b735bb4ae4fe3f803
872095f6ca1d7f252a1a3cb90ad73e84f01345a2
/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt8163/core/drv_FrmB/isp/isp_drv_FrmB.cpp
cd2119299262516b81a6e93f5d58bec15db28e0a
[]
no_license
colinovski/mt8163-vendor
724c49a47e1fa64540efe210d26e72c883ee591d
2006b5183be2fac6a82eff7d9ed09c2633acafcc
refs/heads/master
2020-07-04T12:39:09.679221
2018-01-20T09:11:52
2018-01-20T09:11:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
167,096
cpp
/******************************************************************************************** * LEGAL DISCLAIMER * * (Header of MediaTek Software/Firmware Release or Documentation) * * BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED * FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS * ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY * WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK * ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION * OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH * RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE * FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS * OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES. ************************************************************************************************/ #define LOG_TAG "IspDrv_FrmB" // #include <stdlib.h> // #include <utils/Errors.h> #include <utils/Mutex.h> // For android::Mutex. #include <cutils/log.h> #include <fcntl.h> #include <sys/mman.h> //#include <utils/threads.h> #include <cutils/atomic.h> //#include <cutils/pmem.h> #include "camera_isp_FrmB.h" //#include "mm_proprietary.h" #include <linux/mman-proprietary.h> #include <mtkcam/drv_common/isp_reg.h> #include "isp_drv_imp_FrmB.h" #include <cutils/properties.h> // For property_get(). #include <mtkcam/imageio/ispio_pipe_scenario.h> // For enum EDrvScenario. #undef DBG_LOG_TAG // Decide a Log TAG for current file. #define DBG_LOG_TAG "{IspDrv} " #include "drv_log.h" // Note: DBG_LOG_TAG/LEVEL will be used in header file, so header must be included after definition. DECLARE_DBG_LOG_VARIABLE(isp_drv); //EXTERN_DBG_LOG_VARIABLE(isp_drv); // Clear previous define, use our own define. #undef LOG_VRB #undef LOG_DBG #undef LOG_INF #undef LOG_WRN #undef LOG_ERR #undef LOG_AST #define LOG_VRB(fmt, arg...) do { if (isp_drv_DbgLogEnable_VERBOSE) { BASE_LOG_VRB(fmt, ##arg); } } while(0) #define LOG_DBG(fmt, arg...) do { if (isp_drv_DbgLogEnable_DEBUG ) { BASE_LOG_DBG(fmt, ##arg); } } while(0) #define LOG_INF(fmt, arg...) do { if (isp_drv_DbgLogEnable_INFO ) { BASE_LOG_INF(fmt, ##arg); } } while(0) #define LOG_WRN(fmt, arg...) do { if (isp_drv_DbgLogEnable_WARN ) { BASE_LOG_WRN(fmt, ##arg); } } while(0) #define LOG_ERR(fmt, arg...) do { if (isp_drv_DbgLogEnable_ERROR ) { BASE_LOG_ERR(fmt, ##arg); } } while(0) #define LOG_AST(cond, fmt, arg...) do { if (isp_drv_DbgLogEnable_ASSERT ) { BASE_LOG_AST(cond, fmt, ##arg); } } while(0) /////////////// using namespace NSIspDrv_FrmB; // for debug CQ virtual table static char CQDump_str[512]; #define LOG_CQ_VIRTUAL_TABLE(_pIspVirCqVa_,_idx_,_num_) \ { \ CQDump_str[0] = '\0';\ char* _ptr = CQDump_str;\ for(int j=0;j<_num_;j++){\ if(j > 20)\ break;\ else{\ sprintf(_ptr,"0x%08x-",_pIspVirCqVa_[(mIspCQModuleInfo[_idx_].addr_ofst >>2)+j]);\ while(*_ptr++ != '\0');\ _ptr -= 1;\ }\ }\ LOG_INF("%s\n",CQDump_str);\ CQDump_str[0] = '\0';\ } // for tuning queue #define GET_NEXT_TUNING_QUEUE_IDX(_idx_) ( ((((MINT32)_idx_)+1)>=ISP_TUNING_QUEUE_NUM )?(0):(((MINT32)_idx_)+1) ) #define GET_PREV_TUNING_QUEUE_IDX(_idx_) ( ((((MINT32)_idx_)-1)>=0 )?(((MINT32)_idx_)-1):(ISP_TUNING_QUEUE_NUM-1) ) // for checking the difference between tpipe and hw register #define CHECH_TPIPE_REG(_tpipePoint_ ,_tpipeField_, _regPoint_, _regElement1_, _regElement2) \ { \ if(_tpipePoint_->_tpipeField_ != (int)_regPoint_->_regElement1_.Bits._regElement2){ \ int oriVal, parseVal, i; \ int intSize = 32; \ /* backup the original value */ \ oriVal = _regPoint_->_regElement1_.Raw; \ /* start to parse union bits */ \ _regPoint_->_regElement1_.Raw = 0; \ _regPoint_->_regElement1_.Bits._regElement2 = 0xffffffff; \ parseVal = _regPoint_->_regElement1_.Raw; \ /*LOG_INF("parseVal(0x%x)",parseVal);*/ \ for(i=0;i<intSize;i++){ \ if(parseVal & 0x01<<i) \ break; \ } \ /* recover the original value */ \ _regPoint_->_regElement1_.Raw = oriVal; \ LOG_INF("[Diff][0x%x][Bit-%d]", \ (MUINTPTR)(&_regPoint_->_regElement1_)-(MUINTPTR)(&_regPoint_->rsv_0000[0]), i); \ } \ } /************************************************************************** * D E F I N E S / M A C R O S * **************************************************************************/ class IspDbgTimer { protected: char const*const mpszName; mutable MINT32 mIdx; MINT32 const mi4StartUs; mutable MINT32 mi4LastUs; public: IspDbgTimer(char const*const pszTitle) : mpszName(pszTitle) , mIdx(0) , mi4StartUs(getUs()) , mi4LastUs(getUs()) { } inline MINT32 getUs() const { struct timeval tv; ::gettimeofday(&tv, NULL); return tv.tv_sec * 1000000 + tv.tv_usec; } inline MBOOL ProfilingPrint(char const*const pszInfo = "") const { MINT32 const i4EndUs = getUs(); if (0==mIdx) { LOG_INF("[%s] %s:(%d-th) ===> [start-->now: %.06f ms]", mpszName, pszInfo, mIdx++, (float)(i4EndUs-mi4StartUs)/1000); } else { LOG_INF("[%s] %s:(%d-th) ===> [start-->now: %.06f ms] [last-->now: %.06f ms]", mpszName, pszInfo, mIdx++, (float)(i4EndUs-mi4StartUs)/1000, (float)(i4EndUs-mi4LastUs)/1000); } mi4LastUs = i4EndUs; //sleep(4); //wait 1 sec for AE stable return MTRUE; } }; #ifndef USING_MTK_LDVT // Not using LDVT. #if 0 // Use CameraProfile API static unsigned int G_emGlobalEventId = 0; // Used between different functions. static unsigned int G_emLocalEventId = 0; // Used within each function. #define GLOBAL_PROFILING_LOG_START(EVENT_ID); CPTLog(EVENT_ID, CPTFlagStart); G_emGlobalEventId = EVENT_ID; #define GLOBAL_PROFILING_LOG_END(); CPTLog(G_emGlobalEventId, CPTFlagEnd); #define GLOBAL_PROFILING_LOG_PRINT(LOG_STRING); CPTLogStr(G_emGlobalEventId, CPTFlagSeparator, LOG_STRING); #define LOCAL_PROFILING_LOG_AUTO_START(EVENT_ID); AutoCPTLog CPTlogLocalVariable(EVENT_ID); G_emLocalEventId = EVENT_ID; #define LOCAL_PROFILING_LOG_PRINT(LOG_STRING); CPTLogStr(G_emLocalEventId, CPTFlagSeparator, LOG_STRING); #elif 1 // Use debug print #define GLOBAL_PROFILING_LOG_START(EVENT_ID); #define GLOBAL_PROFILING_LOG_END(); #define GLOBAL_PROFILING_LOG_PRINT(LOG_STRING); #define LOCAL_PROFILING_LOG_AUTO_START(EVENT_ID); IspDbgTimer DbgTmr(#EVENT_ID); #define LOCAL_PROFILING_LOG_PRINT(LOG_STRING); DbgTmr.ProfilingPrint(LOG_STRING); #else // No profiling. #define GLOBAL_PROFILING_LOG_START(EVENT_ID); #define GLOBAL_PROFILING_LOG_END(); #define GLOBAL_PROFILING_LOG_PRINT(LOG_STRING); #define LOCAL_PROFILING_LOG_AUTO_START(EVENT_ID); #define LOCAL_PROFILING_LOG_PRINT(LOG_STRING); #endif // Diff Profile tool. #else // Using LDVT. #if 0 // Use debug print #define GLOBAL_PROFILING_LOG_START(EVENT_ID); #define GLOBAL_PROFILING_LOG_END(); #define GLOBAL_PROFILING_LOG_PRINT(LOG_STRING); #define LOCAL_PROFILING_LOG_AUTO_START(EVENT_ID); IspDbgTimer DbgTmr(#EVENT_ID); #define LOCAL_PROFILING_LOG_PRINT(LOG_STRING); DbgTmr.ProfilingPrint(LOG_STRING); #else // No profiling. #define GLOBAL_PROFILING_LOG_START(EVENT_ID); #define GLOBAL_PROFILING_LOG_END(); #define GLOBAL_PROFILING_LOG_PRINT(LOG_STRING); #define LOCAL_PROFILING_LOG_AUTO_START(EVENT_ID); #define LOCAL_PROFILING_LOG_PRINT(LOG_STRING); #endif // Diff Profile tool. #endif // USING_MTK_LDVT /************************************************************************** * E N U M / S T R U C T / T Y P E D E F D E C L A R A T I O N * **************************************************************************/ #define ISP_CQ_WRITE_INST 0x0 #define ISP_DRV_CQ_END_TOKEN 0xFC000000 #define ISP_DRV_CQ_DUMMY_WR_TOKEN 0x00004060 #define ISP_CQ_DUMMY_PA 0x88100000 #define ISP_INT_BIT_NUM 32 /************************************************************************** * E X T E R N A L R E F E R E N C E S * **************************************************************************/ /************************************************************************** * G L O B A L D A T A * **************************************************************************/ //----------------------------------------------------------------------------- /************************************************************************** * Member Variable Initilization **************************************************************************/ namespace NSIspDrv_FrmB { pthread_mutex_t IspTopRegMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t IspOtherRegMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t IspCQinfoMutex = PTHREAD_MUTEX_INITIALIZER; MUINT32* IspDrvImp::mpIspHwRegAddr = NULL; isp_reg_t* IspDrv::mpIspVirRegMap; MINT32 IspDrv::mIspVirRegFd; MUINT32* IspDrv::mpIspVirRegBufferBaseAddr; MUINT32 IspDrv::mIspVirRegSize; MUINT32** IspDrv::mpIspVirRegAddrVA=NULL; // CQ(VA) framework size MUINT32** IspDrv::mpIspVirRegAddrPA=NULL; // CQ(PA) framework size MUINT32 IspDrv::mIspVirRegAddrVAFd; MUINT32 IspDrv::mIspVirRegAddrPAFd; MINT32 IspDrv::mIspCQDescFd; MUINT32* IspDrv::mpIspCQDescBufferVirt = NULL; MUINT32 IspDrv::mIspCQDescSize; MUINT32* IspDrv::mpIspCQDescBufferPhy = NULL; // Fix build warning ISP_DRV_CQ_CMD_DESC_STRUCT **IspDrv::mpIspCQDescriptorVirt=NULL; MUINT32** IspDrv::mpIspCQDescriptorPhy=NULL; MINT32 IspDrv::mCurBurstQNum=1; // cq order: cq0, cq0b, cq0c, cq0_d, cq0b_d, cq0c_d, burstQ0_cq1_dup0,burstQ0_cq2_dup0,burstQ0_cq3_dup0,burstQ0_cq1_dup1,burstQ0_cq2_dup1,burstQ0_cq3_dup1, // burstQ1_cq1_dup0,burstQ1_cq2_dup0,burstQ1_cq3_dup0,burstQ1_cq1_dup1,burstQ1_cq2_dup1,burstQ1_cq3_dup1,...and so on MINT32 IspDrv::mTotalCQNum=ISP_DRV_BASIC_CQ_NUM; // for turning update stIspTuningQueInf IspDrv::mTuningQueInf[ISP_DRV_P2_CQ_NUM][ISP_TUNING_QUEUE_NUM]; stIspTuningQueIdx IspDrv::mTuningQueIdx[ISP_DRV_P2_CQ_NUM]; } ISP_DRV_CQ_CMD_DESC_INIT_STRUCT mIspCQDescInit[CAM_MODULE_MAX] #if 1 = {{ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_DUMMY_WR_TOKEN,(MUINT32)ISP_CQ_DUMMY_PA}, \ {ISP_DRV_CQ_END_TOKEN,(MUINT32)0}}; #endif ISP_DRV_CQ_MODULE_INFO_STRUCT mIspCQModuleInfo[CAM_MODULE_MAX] = { {CAM_TOP_CTL, 0x4050, 2 }, {CAM_TOP_CTL_01, 0x4080, 10 }, {CAM_TOP_CTL_02, 0x40C0, 8 }, {CAM_ISP_MDP_CROP, 0x4110, 2 }, {CAM_DMA_TDRI, 0x4204, 3 }, {CAM_DMA_IMGI, 0x4230, 7/*8*/ }, //0x4240/*0x4230*/, 3 /*8*/ },//0x4234/*0x4230*/, 6 /*8*/ }, //remove BASE/OFST/XS/YX/RSV from 4230 to 4244 just IMGI_CON.CON2 {CAM_DMA_IMGI, 0x4230, 8 }, //SL TEST_MDP {CAM_DMA_LSCI, 0x426C, 7 }, {CAM_DMA_IMGO_BASEADDR, 0x4300, 1 }, {CAM_DMA_IMGO, 0x4304, 7 }, {CAM_DMA_IMG2O_BASEADDR, 0x4320, 1 }, {CAM_DMA_IMG2O, 0x4324, 7 }, {CAM_DMA_EISO, 0x435C, 2 }, {CAM_DMA_AFO, 0x4364, 2 }, {CAM_DMA_ESFKO, 0x436C, 7 }, {CAM_DMA_AAO, 0x4388, 7 }, {CAM_RAW_TG1_TG2, 0x4410, 30 },// MT6582 only TG1 {CAM_ISP_BIN, 0x44F0, 2 }, {CAM_ISP_OBC, 0x4500, 8 }, {CAM_ISP_LSC, 0x4530, 8 }, {CAM_ISP_HRZ, 0x4580, 2 }, {CAM_ISP_AWB, 0x45B0, 36 }, {CAM_ISP_AE, 0x4650, 18 }, {CAM_ISP_SGG, 0x46A0, 2 }, {CAM_ISP_AF, 0x46B0, 23 }, {CAM_ISP_FLK, 0x4770, 4 }, {CAM_ISP_BNR, 0x4800, 18 }, {CAM_ISP_PGN, 0x4880, 6 }, {CAM_ISP_CFA, 0x48A0, 22},//22 }, {CAM_ISP_CCL, 0x4910, 3 }, {CAM_ISP_G2G, 0x4920, 7 }, {CAM_ISP_UNP, 0x4948, 1 }, {CAM_ISP_G2C, 0x4A00, 6 }, {CAM_ISP_C42, 0x4A1C, 1 }, {CAM_ISP_NBC, 0x4A20, 32 }, {CAM_ISP_SEEE, 0x4AA0, 24 }, {CAM_CDP_CDRZ, 0x4B00, 15 }, {CAM_ISP_EIS, 0x4DC0, 9 }, {CAM_CDP_SL2_FEATUREIO, 0x4F40, 7 }, {CAM_ISP_GGMRB, 0x5000, 144}, {CAM_ISP_GGMG, 0x5300, 144}, {CAM_ISP_GGM_CTL, 0x5600, 1 }, {CAM_ISP_PCA, 0x5800, 360}, {CAM_ISP_PCA_CON, 0x5E00, 2 }, {CAM_P1_MAGIC_NUM, 0x43DC, 1 }, {CAM_ISP_EIS_DB, 0x406C, 1 }, {CAM_ISP_EIS_DCM, 0x419C, 1 }, {CAM_DUMMY_, 0x4780, 1 }}; // dummy address 4780//0x4600, 1 }}; // dummy address ISP_TURNING_FUNC_BIT_MAPPING gIspTuningFuncBitMapp[eIspTuningMgrFuncBit_Num] ={{eIspTuningMgrFuncBit_Obc , eTuningCtlByte_P1, 3, -1, -1, CAM_ISP_OBC, CAM_DUMMY_}, {eIspTuningMgrFuncBit_Lsc , eTuningCtlByte_P1, 5, -1, 1, CAM_ISP_LSC, CAM_DMA_LSCI}, {eIspTuningMgrFuncBit_Bnr , eTuningCtlByte_P1, 7, -1, -1, CAM_ISP_BNR, CAM_DUMMY_}, {eIspTuningMgrFuncBit_Pgn , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_PGN, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Cfa , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_CFA, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Ccl , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_CCL, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_G2g , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_G2G, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_G2c , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_G2C, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Nbc , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_NBC, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Seee , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_SEEE, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Sl2 , eTuningCtlByte_P2, -1, -1, -1, CAM_CDP_SL2_FEATUREIO,CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Ggmrb , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_GGMRB, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Ggmg , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_GGMG, CAM_DUMMY_}, // not support this setting through tuningMgr {eIspTuningMgrFuncBit_Pca , eTuningCtlByte_P2, -1, -1, -1, CAM_ISP_PCA, CAM_DUMMY_}}; // not support this setting through tuningMgr ISP_DRV_CQ_BIT_3GP_MAPPING gIspTurnEn1Mapp[ISP_INT_BIT_NUM] = { {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 0 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 1 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 2 {CAM_ISP_OBC, CAM_DUMMY_, CAM_DUMMY_}, // bit 3 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 4 {CAM_ISP_LSC, CAM_DUMMY_, CAM_DUMMY_}, // bit 5 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 6 {CAM_ISP_BNR, CAM_DUMMY_, CAM_DUMMY_}, // bit 7 {CAM_CDP_SL2_FEATUREIO, CAM_DUMMY_, CAM_DUMMY_}, // bit 8 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 9 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 10 {CAM_ISP_PGN, CAM_DUMMY_, CAM_DUMMY_}, // bit 11 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 12 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 13 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 14 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 15 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 16 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 17 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 18 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 19 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 20 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 21 {CAM_ISP_CCL, CAM_DUMMY_, CAM_DUMMY_}, // bit 22 {CAM_ISP_G2G, CAM_DUMMY_, CAM_DUMMY_}, // bit 23 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 24 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 25 {CAM_ISP_GGMRB, CAM_ISP_GGMG, CAM_ISP_GGM_CTL}, // bit 26 (GGM controled by 0x5600) {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 27 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 28 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 29 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}, // bit 30 {CAM_DUMMY_, CAM_DUMMY_, CAM_DUMMY_}}; // bit 31 ISP_DRV_CQ_BIT_2GP_MAPPING gIspTurnEn2Mapp[ISP_INT_BIT_NUM] = { {CAM_ISP_G2C, CAM_DUMMY_}, // bit 0 {CAM_DUMMY_, CAM_DUMMY_}, // bit 1 {CAM_ISP_NBC, CAM_DUMMY_}, // bit 2 {CAM_ISP_PCA, CAM_ISP_PCA_CON}, // bit 3 {CAM_ISP_SEEE, CAM_DUMMY_}, // bit 4 {CAM_DUMMY_, CAM_DUMMY_}, // bit 5 {CAM_DUMMY_, CAM_DUMMY_}, // bit 6 {CAM_DUMMY_, CAM_DUMMY_}, // bit 7 {CAM_DUMMY_, CAM_DUMMY_}, // bit 8 {CAM_DUMMY_, CAM_DUMMY_}, // bit 9 {CAM_DUMMY_, CAM_DUMMY_}, // bit 10 {CAM_DUMMY_, CAM_DUMMY_}, // bit 11 {CAM_DUMMY_, CAM_DUMMY_}, // bit 12 {CAM_DUMMY_, CAM_DUMMY_}, // bit 13 {CAM_DUMMY_, CAM_DUMMY_}, // bit 14 {CAM_DUMMY_, CAM_DUMMY_}, // bit 15 {CAM_DUMMY_, CAM_DUMMY_}, // bit 16 {CAM_DUMMY_, CAM_DUMMY_}, // bit 17 {CAM_DUMMY_, CAM_DUMMY_}, // bit 18 {CAM_DUMMY_, CAM_DUMMY_}, // bit 19 {CAM_DUMMY_, CAM_DUMMY_}, // bit 20 {CAM_DUMMY_, CAM_DUMMY_}, // bit 21 {CAM_DUMMY_, CAM_DUMMY_}, // bit 22 {CAM_DUMMY_, CAM_DUMMY_}, // bit 23 {CAM_DUMMY_, CAM_DUMMY_}, // bit 24 {CAM_DUMMY_, CAM_DUMMY_}, // bit 25 {CAM_DUMMY_, CAM_DUMMY_}, // bit 26 {CAM_DUMMY_, CAM_DUMMY_}, // bit 27 {CAM_DUMMY_, CAM_DUMMY_}, // bit 28 {CAM_DUMMY_, CAM_DUMMY_}, // bit 29 {CAM_DUMMY_, CAM_DUMMY_}, // bit 30 {CAM_DUMMY_, CAM_DUMMY_}}; // bit 31 ISP_DRV_CQ_BIT_1GP_MAPPING gIspTurnDmaMapp[ISP_INT_BIT_NUM] = { {CAM_DUMMY_ }, // bit 0 {CAM_DMA_LSCI }, // bit 1 {CAM_DUMMY_ }, // bit 2 {CAM_DUMMY_ }, // bit 3 {CAM_DUMMY_ }, // bit 4 {CAM_DUMMY_ }, // bit 5 {CAM_DUMMY_ }, // bit 6 {CAM_DUMMY_ }, // bit 7 {CAM_DUMMY_ }, // bit 8 {CAM_DUMMY_ }, // bit 9 {CAM_DUMMY_ }, // bit 10 {CAM_DUMMY_ }, // bit 11 {CAM_DUMMY_ }, // bit 12 {CAM_DUMMY_ }, // bit 13 {CAM_DUMMY_ }, // bit 14 {CAM_DUMMY_ }, // bit 15 {CAM_DUMMY_ }, // bit 16 {CAM_DUMMY_ }, // bit 17 {CAM_DUMMY_ }, // bit 18 {CAM_DUMMY_ }, // bit 19 {CAM_DUMMY_ }, // bit 20 {CAM_DUMMY_ }, // bit 21 {CAM_DUMMY_ }, // bit 22 {CAM_DUMMY_ }, // bit 23 {CAM_DUMMY_ }, // bit 24 {CAM_DUMMY_ }, // bit 25 {CAM_DUMMY_ }, // bit 26 {CAM_DUMMY_ }, // bit 27 {CAM_DUMMY_ }, // bit 28 {CAM_DUMMY_ }, // bit 29 {CAM_DUMMY_ }, // bit 30 {CAM_DUMMY_ }}; // bit 31 //----------------------------------------------------------------------------- IspDrv* IspDrv::createInstance() { DBG_LOG_CONFIG(drv, isp_drv); return IspDrvImp::getInstance(); } //----------------------------------------------------------------------------- IspDrv* IspDrv::getCQInstance(MINT32 cq) { //LOG_DBG(""); return IspDrvVirImp::getInstance(cq,mpIspVirRegAddrVA[cq],mpIspVirRegMap); } //----------------------------------------------------------------------------- MINT32 IspDrv::getRealCQIndex(MINT32 cqBaseEnum,MINT32 burstQIdx,MINT32 dupCqIdx) { MINT32 realcqIdx=0; if(cqBaseEnum == 0xffff)//CAM_ISP_CQ_NONE return 0; if(cqBaseEnum>ISP_DRV_CQ03) { LOG_ERR("CQ crash error: enum sequence error, (%d/%d)\n",cqBaseEnum,ISP_DRV_CQ03); return -1; } else if(cqBaseEnum<=ISP_DRV_CQ0C) {//pass1 cq if(burstQIdx != 0){ burstQIdx = 0; LOG_ERR("p1 suppoort no burstQidx"); } realcqIdx=(burstQIdx*cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_P1DUPCQNUM) * ISP_DRV_P1_PER_CQ_SET_NUM)+(cqBaseEnum + dupCqIdx*ISP_DRV_P1_PER_CQ_SET_NUM); } else {//pass2 cq cqBaseEnum -= ISP_DRV_CQ01; realcqIdx=cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_CURBURSTQNUM)*ISP_DRV_P1_PER_CQ_SET_NUM*cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_P1DUPCQNUM) + \ (burstQIdx*cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_P2DUPCQNUM) * ISP_DRV_P2_PER_CQ_SET_NUM)+\ (cqBaseEnum+dupCqIdx*ISP_DRV_P2_PER_CQ_SET_NUM); } LOG_DBG("realcqIdx(%d),cqBaseEnum(%d),burstQIdx(%d),dupCqIdx(%d)",realcqIdx,cqBaseEnum,burstQIdx,dupCqIdx); return realcqIdx; } //----------------------------------------------------------------------------- int IspDrv::getCqModuleInfo(MINT32 cq,MINT32 burstQIdx,MINT32 dupCqIdx, CAM_MODULE_ENUM moduleId) { int cmd; int realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_DBG("- E. isp_cq[0x%x],[%d]",realCQIdx,moduleId); // Mutex::Autolock lock(cqVirDesLock); return mpIspCQDescriptorVirt[realCQIdx][moduleId].u.cmd; } MBOOL IspDrv::cqAddModule(MINT32 cq,MINT32 burstQIdx,MINT32 dupCqIdx, CAM_MODULE_ENUM moduleId) { int cmd; MUINTPTR dummyaddr; int realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_DBG("- E. isp_cq[0x%x],[%d]",realCQIdx,moduleId,burstQIdx,dupCqIdx); // Mutex::Autolock lock(cqVirDesLock); dummyaddr = (MUINTPTR)((MUINTPTR)mpIspVirRegAddrPA[realCQIdx] + mIspCQModuleInfo[moduleId].addr_ofst); //kk test cmd = (mIspCQModuleInfo[moduleId].addr_ofst&0xffff)|(((mIspCQModuleInfo[moduleId].reg_num-1)&0x3ff)<<16)|((ISP_CQ_WRITE_INST)<<26); mpIspCQDescriptorVirt[realCQIdx][moduleId].v_reg_addr = (MUINT32)dummyaddr & 0xFFFFFFFF;// >>2 for MUINT32* pointer mpIspCQDescriptorVirt[realCQIdx][moduleId].u.cmd = cmd; // LOG_DBG("- X."); return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrv::cqDelModule(MINT32 cq,MINT32 burstQIdx,MINT32 dupCqIdx, CAM_MODULE_ENUM moduleId) { LOG_DBG("cq(%d),burstQIdx(%d),dupCqIdx(%d),moduleId(%d)",cq,burstQIdx,dupCqIdx,moduleId); int realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_DBG("+,isp_cq[0x%x],[%d]",realCQIdx,moduleId); // Mutex::Autolock lock(cqVirDesLock); mpIspCQDescriptorVirt[realCQIdx][moduleId].u.cmd = ISP_DRV_CQ_DUMMY_WR_TOKEN; // LOG_DBG("-,"); return MTRUE; } //----------------------------------------------------------------------------- MUINT32* IspDrv::getCQDescBufPhyAddr(MINT32 cq,MINT32 burstQIdx,MINT32 dupCqIdx) { Mutex::Autolock lock(cqPhyDesLock); int realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_DBG("cq(%d),dupCqIdx(%d),realCQIdx(%d)",cq,dupCqIdx,realCQIdx); return (MUINT32*)mpIspCQDescriptorPhy[realCQIdx]; } //----------------------------------------------------------------------------- MUINT32* IspDrv::getCQDescBufVirAddr(MINT32 cq,MINT32 burstQIdx,MINT32 dupCqIdx) { Mutex::Autolock lock(cqVirDesLock); int realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_DBG("cq(%d),dupCqIdx(%d),realCQIdx(%d)",cq,dupCqIdx,realCQIdx); return (MUINT32*)mpIspCQDescriptorVirt[realCQIdx]; } //----------------------------------------------------------------------------- MUINT32* IspDrv::getCQVirBufVirAddr(MINT32 cq,MINT32 burstQIdx,MINT32 dupCqIdx) { Mutex::Autolock lock(cqVirDesLock); int realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_DBG("cq(%d),dupCqIdx(%d),realCQIdx(%d)",cq,dupCqIdx,realCQIdx); return (MUINT32*)mpIspVirRegAddrVA[realCQIdx]; } /******************************************************************************* * ********************************************************************************/ MBOOL IspDrv::setCQTriggerMode(ISP_DRV_CQ_ENUM cq, ISP_DRV_CQ_TRIGGER_MODE_ENUM mode, ISP_DRV_CQ_TRIGGER_SOURCE_ENUM trig_src) { //isp_reg_t *pIspReg = (isp_reg_t *)getRegAddr(); //no need in this function LOG_DBG("+,[%s],cq(%d),mode(%d),trig_src(%d)",__FUNCTION__, cq, mode, trig_src); switch(cq) { case ISP_DRV_CQ0: //trigger source is pass1_done if(CQ_SINGLE_IMMEDIATE_TRIGGER == mode) { //-Immediately trigger //-CQ0_MODE=1(reg_4018[17]), CQ0_CONT=0(reg_4018[2]) ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0_MODE, 1,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0_CONT, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0_MODE_SET, 1,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0_CONT_SET, 0,ISP_DRV_USER_ISPF); } else if(CQ_SINGLE_EVENT_TRIGGER == mode) { //-Trigger and wait trigger source //-CQ0_MODE=0, CQ0_CONT=0 ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0_MODE, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0_CONT, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0_MODE_SET, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0_CONT_SET, 0,ISP_DRV_USER_ISPF); } else if(CQ_CONTINUOUS_EVENT_TRIGGER == mode) { //-Continuous mode support(without trigger) //-CQ0_MODE=x, CQ0_CONT=1 ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0_MODE, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0_CONT, 1,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0_MODE_SET, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0_CONT_SET, 1,ISP_DRV_USER_ISPF); } break; case ISP_DRV_CQ0B: //-choose trigger source by CQ0B_SEL(0:img2o, 1:pass1_done)(reg_4018[11]) if(CQ_TRIG_BY_PASS1_DONE != trig_src && CQ_TRIG_BY_IMGO_DONE != trig_src) { LOG_ERR("[%s][ISP_DRV_CQ0B]:NOT Support trigger source",__FUNCTION__); } if(CQ_TRIG_BY_PASS1_DONE == trig_src) { ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_SEL, 1,ISP_DRV_USER_ISPF); } else { ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_SEL, 0,ISP_DRV_USER_ISPF); } if(CQ_SINGLE_IMMEDIATE_TRIGGER == mode) { //-Immediately trigger //-CQ0B_MODE=1 reg_4018[25], CQ0B_CONT=0 reg_4018[3] ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_MODE, 1,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_CONT, 0,ISP_DRV_USER_ISPF); } else if(CQ_SINGLE_EVENT_TRIGGER == mode) { //-Trigger and wait trigger source //-CQ0B_MODE=0, CQ0B_CONT=0 ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_MODE, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_CONT, 0,ISP_DRV_USER_ISPF); } else if(CQ_CONTINUOUS_EVENT_TRIGGER == mode) { //-Continuous mode support(without trigger) //-CQ0B_MODE=x, CQ0B_CONT=1 ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_MODE, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL, CQ0B_CONT, 1,ISP_DRV_USER_ISPF); } break; case ISP_DRV_CQ0C: //-cq0c // -trigger source is imgo_done (CQ0C_IMGO_SEL_SET=1,reg_40A0[7]) // OR img20_done(CQ0C_IMGO_SEL_SET=1,reg_40A0[22]). // -always continuous mode,NO cq0c_start. // If cq0c_en=1, it always load CQ when imgo_done||img2o_done occur if ( CQ_TRIG_BY_IMGO_DONE != trig_src && CQ_TRIG_BY_IMG2O_DONE != trig_src) { LOG_ERR("[%s][ISP_DRV_CQ0C]:NOT Support trigger source\n",__FUNCTION__); } if(CQ_TRIG_BY_IMGO_DONE == trig_src) { ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0C_IMGO_SEL_SET, 1,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_CLR, CQ0C_IMGO_SEL_CLR, 0,ISP_DRV_USER_ISPF); } else { ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0C_IMGO_SEL_SET, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_CLR, CQ0C_IMGO_SEL_CLR, 1,ISP_DRV_USER_ISPF); } if(CQ_TRIG_BY_IMG2O_DONE == trig_src) { ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0C_IMG2O_SEL_SET, 1,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_CLR, CQ0C_IMG2O_SEL_CLR, 0,ISP_DRV_USER_ISPF); } else { ISP_WRITE_BITS(this, CAM_CTL_SEL_SET, CQ0C_IMG2O_SEL_SET, 0,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_SEL_CLR, CQ0C_IMG2O_SEL_CLR, 1,ISP_DRV_USER_ISPF); } break; case ISP_DRV_CQ01: case ISP_DRV_CQ02: case ISP_DRV_CQ03: default: //-cq1/2/3 // -load one time. working time is at right after set pass2x_start=1 // -Immediately trigger ONLY break; } return MTRUE; } #define REMOVELATER_DUPIDX 0 //remove later //----------------------------------------------------------------------------- MBOOL IspDrv::checkTopReg(MUINT32 Addr) { #if 0 //fix it later switch(Addr) { case 0x00004000: return true; case 0x00004004: return true; case 0x00004008: return true; case 0x00004010: return true; case 0x00004014: return true; case 0x00004018: return true; case 0x0000401C: return true; case 0x00004020: return true; case 0x00004034: return true; case 0x00004038: return true; case 0x0000403C: return true; case 0x00004040: return true; default: return false; } #else return false; #endif } //----------------------------------------------------------------------------- IspDrvImp::IspDrvImp() { int i; GLOBAL_PROFILING_LOG_START(Event_IspDrv); // Profiling Start. LOG_VRB("getpid[0x%08x],gettid[0x%08x]", getpid() ,gettid()); mInitCount = 0; mFd = -1; m_pIMemDrv = NULL; m_pRTBufTbl = NULL; mpIspVirRegMap = NULL; mpTempIspHWRegValues = NULL; m_regRWMode=ISP_DRV_RWREG_MODE_RW; for(int i=0;i<((ISP_DRV_P2_CQ_DUPLICATION_NUM-1)*ISP_DRV_P2_PER_CQ_SET_NUM);i++) { ISP_DRV_CQ_MAPPING map; map.virtualAddrCq=ISP_DRV_BASIC_CQ_NUM+i; map.descriptorCq=ISP_DRV_DESCRIPTOR_BASIC_CQ_NUM+i; } } //----------------------------------------------------------------------------- IspDrvImp::~IspDrvImp() { LOG_INF(""); GLOBAL_PROFILING_LOG_END(); // Profiling End. } //----------------------------------------------------------------------------- static IspDrvImp singleton; IspDrv* IspDrvImp::getInstance() { LOG_DBG("singleton[0x%08x].", &singleton); return &singleton; } //----------------------------------------------------------------------------- void IspDrvImp::destroyInstance(void) { } //----------------------------------------------------------------------------- //#define __PMEM_ONLY__ MBOOL IspDrvImp::init(const char* userName) { MBOOL Result = MTRUE; IMEM_BUF_INFO m_ispTmpBufInfo; GLOBAL_PROFILING_LOG_PRINT(__func__); LOCAL_PROFILING_LOG_AUTO_START(Event_IspDrv_Init); // Mutex::Autolock lock(mLock); // LOG_INF(" - E. mInitCount(%d), curUser(%s).", mInitCount,userName); // if(strlen(userName)<1) { LOG_ERR("Plz add userName if you want to use isp driver\n"); return MFALSE; } #if 0 //todo, check debug m_userNameList.push_back(userName); #endif // if(mInitCount > 0) { android_atomic_inc(&mInitCount); LOCAL_PROFILING_LOG_PRINT("atomic_inc"); goto EXIT; } // mpIspVirRegMap = (isp_reg_t*)malloc(sizeof(isp_reg_t)); //always allocate this(be used to get register offset in macro) mpTempIspHWRegValues = (isp_reg_t*)malloc(sizeof(isp_reg_t)); //always allocate this(be used to get register offset in macro) LOCAL_PROFILING_LOG_PRINT("mpIspVirRegMap and mpTempIspHWRegValues malloc"); // Open isp driver mFd = open(ISP_DRV_DEV_NAME, O_RDWR); LOCAL_PROFILING_LOG_PRINT("1st open(ISP_DRV_DEV_NAME, O_RDWR)"); if (mFd < 0) // 1st time open failed. { LOG_WRN("ISP kernel open 1st attempt fail, errno(%d):%s.", errno, strerror(errno)); // Try again, using "Read Only". mFd = open(ISP_DRV_DEV_NAME, O_RDONLY); LOCAL_PROFILING_LOG_PRINT("2nd open(ISP_DRV_DEV_NAME, O_RDONLY)"); if (mFd < 0) // 2nd time open failed. { LOG_ERR("ISP kernel open 2nd attempt fail, errno(%d):%s.", errno, strerror(errno)); Result = MFALSE; goto EXIT; } m_regRWMode=ISP_DRV_RWREG_MODE_RO; LOCAL_PROFILING_LOG_PRINT("mpIspVirRegMap malloc()"); } else // 1st time open success. // Sometimes GDMA will go this path, too. e.g. File Manager -> Phone Storage -> Photo. { // mmap isp reg mpIspHwRegAddr = (MUINT32 *) mmap(0, ISP_BASE_RANGE, (PROT_READ | PROT_WRITE | PROT_NOCACHE), MAP_SHARED, mFd, ISP_BASE_HW); if(mpIspHwRegAddr == MAP_FAILED) { LOG_ERR("ISP mmap fail, errno(%d):%s", errno, strerror(errno)); Result = MFALSE; goto EXIT; } LOCAL_PROFILING_LOG_PRINT("mpIspHwRegAddr mmap()"); //pass1 buffer control shared mem. m_RTBufTblSize = RT_BUF_TBL_NPAGES * getpagesize(); m_pRTBufTbl = (MUINT32 *)mmap(0, m_RTBufTblSize, PROT_READ | PROT_WRITE | PROT_NOCACHE, MAP_SHARED| MAP_LOCKED, mFd, m_RTBufTblSize); LOG_DBG("m_RTBufTblSize(0x%x),m_pRTBufTbl(0x%x)",m_RTBufTblSize,m_pRTBufTbl); if (m_pRTBufTbl == MAP_FAILED) { LOG_ERR("m_pRTBufTbl mmap FAIL"); Result = MFALSE; goto EXIT; } m_regRWMode=ISP_DRV_RWREG_MODE_RW; LOCAL_PROFILING_LOG_PRINT("m_pRTBufTbl mmap()"); } // Increase ISP global reference count, and reset if 1st user. #if defined(_use_kernel_ref_cnt_) LOG_INF("use kernel ref. cnt.mFd(%d)",mFd); ISP_REF_CNT_CTRL_STRUCT_FRMB ref_cnt; MINT32 count; // For ISP global reference count. ref_cnt.ctrl = ISP_REF_CNT_GET_FRMB; ref_cnt.id = ISP_REF_CNT_ID_ISP_FUNC_FRMB; ref_cnt.data_ptr = &count; // if ( MTRUE == kRefCntCtrl(&ref_cnt) ) { // if (0==count) { LOG_DBG("DO ISP HW RESET"); reset(ISP_DRV_RST_CAM_P1); // Do IMGSYS SW RST. reset(ISP_DRV_RST_CAM_P2); } // ref_cnt.ctrl = ISP_REF_CNT_INC_FRMB; if ( MFALSE == kRefCntCtrl(&ref_cnt) ) { LOG_ERR("ISP_REF_CNT_INC fail, errno(%d):%s.", errno, strerror(errno)); } LOG_INF("ISP Global Count: %d.", count); } else { LOG_ERR("ISP_REF_CNT_GET fail, errno(%d):%s.", errno, strerror(errno)); } LOCAL_PROFILING_LOG_PRINT("kRefCntCtrl and ISP reset()"); #else LOG_DBG("DO ISP HW RESET"); reset(ISP_DRV_RST_CAM_P1); // Do IMGSYS SW RST, which will also enable CAM/SEN/JPGENC/JPGDEC clock. reset(ISP_DRV_RST_CAM_P2); #endif /*------------------------ Floria / Set Camera version: 0 means camera 1; 1 for camera 3 ------------------------*/ CAM_HAL_VER_IS3 = 1; if(ioctl(mFd,ISP_SET_CAM_VERSION,&CAM_HAL_VER_IS3) < 0){ LOG_ERR("SetCamVer error\n"); } /*============================================ imem driver =============================================*/ m_pIMemDrv = IMemDrv::createInstance(); LOG_DBG("[m_pIMemDrv]:0x%08x", m_pIMemDrv); //Vent@20121107: Fix build warning: format '%x' expects argument of type 'unsigned int', but argument 5 has type 'IMemDrv*' [-Wformat] if ( NULL == m_pIMemDrv ) { LOG_DBG("IMemDrv::createInstance fail"); return -1; } LOCAL_PROFILING_LOG_PRINT("IMemDrv::createInstance()"); m_pIMemDrv->init(); LOCAL_PROFILING_LOG_PRINT("m_pIMemDrv->init()"); // //virtual CQ //set default CQ desc for (int i=0; i<CAM_MODULE_MAX; i++ ) { mIspCQDescInit[i].cmd_set = ISP_DRV_CQ_DUMMY_WR_TOKEN; mIspCQDescInit[i].v_reg_addr = (MUINT32)ISP_CQ_DUMMY_PA; } mIspCQDescInit[CAM_MODULE_MAX-1].cmd_set = ISP_DRV_CQ_END_TOKEN; mIspCQDescInit[CAM_MODULE_MAX-1].v_reg_addr = (MUINT32)0; //inital total cq nun mCurBurstQNum=1; mTotalCQNum=(cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_P1DUPCQNUM) * ISP_DRV_P1_PER_CQ_SET_NUM)+\ (cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_CURBURSTQNUM) * cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_GET_P2DUPCQNUM) * ISP_DRV_P2_PER_CQ_SET_NUM); LOG_DBG("mTotalCQNum(%d)",mTotalCQNum); //initial cq related table(descriptor and virtual reg map) Result=cqTableControl(ISP_DRV_CQTABLE_CTRL_ALLOC,mCurBurstQNum); if(Result == MFALSE) { LOG_ERR("cqTableControl fail"); goto EXIT; } // #if defined(__PMEM_ONLY__) // For Tuning Queue LOG_INF("alloc tuning Queue"); for(int i=0;i<ISP_DRV_P2_CQ_NUM;i++){ for(int j=0;j<ISP_TUNING_QUEUE_NUM;j++){ mTuningQueInf[i][j].queSize = ISP_BASE_RANGE; mTuningQueInf[i][j].pTuningQue = (MUINT32*)pmem_alloc_sync(mTuningQueInf[i][j].queSize, &mTuningQueInf[i][j].queFd); memset((MUINT8*)mTuningQueInf[i][j].pTuningQue,0,mTuningQueInf[i][j].queSize); } // mTuningQueIdx[i].keepP1Que.pTuningQue.queSize = ISP_BASE_RANGE; mTuningQueIdx[i].keepP1Que.pTuningQue.pTuningQue = (MUINT32*)pmem_alloc_sync(mTuningQueIdx[i].keepP1Que.queSize, &mTuningQueIdx[i].keepP1Que.queFd); memset((MUINT8*)mTuningQueIdx[i].keepP1Que.pTuningQue,0,mTuningQueIdx[i].keepP1Que.queSize); // mTuningQueIdx[i].isApplyTuning = MFALSE; mTuningQueIdx[i].pCurReadP1TuningQue = NULL; mTuningQueIdx[i].pCurWriteTuningQue = NULL; mTuningQueIdx[i].eCurReadP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepReadP1CtlEn1 = 0; mTuningQueIdx[i].keepReadP1CtlEn2 = 0; mTuningQueIdx[i].keepReadP1CtlDmaEn = 0; // mTuningQueIdx[i].curWriteIdx = ISP_TUNING_INIT_IDX; mTuningQueIdx[i].curReadP1Idx = ISP_TUNING_INIT_IDX; //mTuningQueIdx[i].isInitP2 = MFALSE; mTuningQueIdx[i].isInitP1 = MFALSE; } #else // Not PMEM. // For Tuning Queue LOG_INF("alloc tuning Queue"); for(int i=0;i<ISP_DRV_P2_CQ_NUM;i++){ for(int j=0;j<ISP_TUNING_QUEUE_NUM;j++){ mTuningQueInf[i][j].queSize = ISP_BASE_RANGE; m_ispTmpBufInfo.size = mTuningQueInf[i][j].queSize; m_ispTmpBufInfo.useNoncache = 0; //alloc cacheable mem. if ( m_pIMemDrv->allocVirtBuf(&m_ispTmpBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->allocVirtBuf"); } mTuningQueInf[i][j].queFd = m_ispTmpBufInfo.memID; mTuningQueInf[i][j].pTuningQue = (MUINT32*)m_ispTmpBufInfo.virtAddr; memset((MUINT8*)mTuningQueInf[i][j].pTuningQue,0,mTuningQueInf[i][j].queSize); LOG_INF("p2cq(%d),que(%d):pTuningQue(0x%x)",i,j,mTuningQueInf[i][j].pTuningQue); } // mTuningQueIdx[i].keepP1Que.queSize = ISP_BASE_RANGE; m_ispTmpBufInfo.size = mTuningQueIdx[i].keepP1Que.queSize; m_ispTmpBufInfo.useNoncache = 0; //alloc cacheable mem. if ( m_pIMemDrv->allocVirtBuf(&m_ispTmpBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->allocVirtBuf"); } mTuningQueIdx[i].keepP1Que.queFd = m_ispTmpBufInfo.memID; mTuningQueIdx[i].keepP1Que.pTuningQue = (MUINT32*)m_ispTmpBufInfo.virtAddr; memset((MUINT8*)mTuningQueIdx[i].keepP1Que.pTuningQue,0,mTuningQueIdx[i].keepP1Que.queSize); LOG_INF("p2cq(%d),keepP1Que(0x%x)",i,mTuningQueIdx[i].keepP1Que.pTuningQue); // mTuningQueIdx[i].isApplyTuning = MFALSE; mTuningQueIdx[i].pCurReadP1TuningQue = NULL; mTuningQueIdx[i].pCurWriteTuningQue = NULL; mTuningQueIdx[i].eCurReadP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepReadP1CtlEn1 = 0; mTuningQueIdx[i].keepReadP1CtlEn2 = 0; mTuningQueIdx[i].keepReadP1CtlDmaEn = 0; // mTuningQueIdx[i].curWriteIdx = ISP_TUNING_INIT_IDX; mTuningQueIdx[i].curReadP1Idx = ISP_TUNING_INIT_IDX; //mTuningQueIdx[i].isInitP2 = MFALSE; mTuningQueIdx[i].isInitP1 = MFALSE; } LOCAL_PROFILING_LOG_PRINT("m_pIMemDrv->mapPhyAddr()"); // #endif // __PMEM_ONLY__ // loadInitSetting(); // load default setting // android_atomic_inc(&mInitCount); LOCAL_PROFILING_LOG_PRINT("atomic_inc"); // EXIT: if (!Result) // If some init step goes wrong. { if(mFd >= 0) { close(mFd); mFd = -1; LOCAL_PROFILING_LOG_PRINT("close isp mFd"); } } LOG_INF(" - X. ret: %d. mInitCount: %d.", Result, mInitCount); LOCAL_PROFILING_LOG_PRINT("Exit"); return Result; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::uninit(const char* userName) { MBOOL Result = MTRUE; IMEM_BUF_INFO m_ispTmpBufInfo; GLOBAL_PROFILING_LOG_PRINT(__func__); LOCAL_PROFILING_LOG_AUTO_START(Event_IspDrv_Uninit); // Mutex::Autolock lock(mLock); // LOG_INF(" - E. mInitCount(%d), curUser(%s)", mInitCount,userName); // if(strlen(userName)<1) { LOG_ERR("Plz add userName if you want to uninit isp driver\n"); return MFALSE; } // #if 0 //todo, check debug if(strlen(userName)==0) { } else { m_userNameList.remove(userName); list<const char*>::iterator iter; char* userlist=(char*)malloc(128*sizeof(char)); for (iter = m_userNameList.begin(); iter != m_userNameList.end(); ++iter) { strcat(userlist,*iter); strcat(userlist,","); } LOG_INF("ISPDrv RestUsers:%s\n",userlist); free(userlist); } #endif // if(mInitCount <= 0) { // No more users goto EXIT; } // More than one user android_atomic_dec(&mInitCount); LOCAL_PROFILING_LOG_PRINT("atomic_dec"); if(mInitCount > 0) // If there are still users, exit. { goto EXIT; } munmap(mpIspHwRegAddr, ISP_BASE_RANGE); mpIspHwRegAddr = NULL; LOCAL_PROFILING_LOG_PRINT("munmap(mpIspHwRegAddr)"); // munmap(m_pRTBufTbl, m_RTBufTblSize); m_pRTBufTbl = NULL; LOCAL_PROFILING_LOG_PRINT("munmap(m_pRTBufTbl)"); //free cq descriptor and virtual isp cqTableControl(ISP_DRV_CQTABLE_CTRL_DEALLOC,mCurBurstQNum); // Tuning Queue #if defined(__PMEM_ONLY__) LOG_DBG("Free Tuning Queue"); for(int i=0;i<ISP_DRV_P2_CQ_NUM;i++){ for(int j=0;j<ISP_TUNING_QUEUE_NUM;j++){ if((mTuningQueInf[i][j].queFd>=0) && (mTuningQueInf[i][j].pTuningQue!=0)){ pmem_free((MUINT8*)mTuningQueInf[i][j].pTuningQue,mTuningQueInf[i][j].queSize,mTuningQueInf[i][j].queFd); mTuningQueInf[i][j].queFd = -1; mTuningQueInf[i][j].pTuningQue = NULL; }else{ LOG_ERR("[Error]free TuningQue error i(%d),j(%d),fd(%d),va(0x%08x)",i,j,mTuningQueInf[i][j].queFd,mTuningQueInf[i][j].pTuningQue); } } // free keepP1Que if((mTuningQueIdx[i].keepP1Que.queFd>=0) && (mTuningQueIdx[i].keepP1Que.pTuningQue!=0)){ pmem_free((MUINT8*)mTuningQueIdx[i].keepP1Que.pTuningQue,mTuningQueIdx[i].keepP1Que.queSize,mTuningQueIdx[i].keepP1Que.queFd); mTuningQueIdx[i].keepP1Que.queFd = -1; mTuningQueIdx[i].keepP1Que.pTuningQue = NULL; }else{ LOG_ERR("[Error]free keepP1Que error i(%d),fd(%d),va(0x%08x)",i,mTuningQueIdx[i].keepP1Que.queFd,mTuningQueIdx[i].keepP1Que.pTuningQue); } mTuningQueIdx[i].isApplyTuning = MFALSE; mTuningQueIdx[i].pCurReadP1TuningQue = NULL; mTuningQueIdx[i].pCurWriteTuningQue = NULL; mTuningQueIdx[i].eCurReadP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepReadP1CtlEn1 = 0; mTuningQueIdx[i].keepReadP1CtlEn2 = 0; mTuningQueIdx[i].keepReadP1CtlDmaEn = 0; mTuningQueIdx[i].curWriteIdx = ISP_TUNING_INIT_IDX; mTuningQueIdx[i].curReadP1Idx = ISP_TUNING_INIT_IDX; //mTuningQueIdx[i].isInitP2 = MFALSE; mTuningQueIdx[i].isInitP1 = MFALSE; } #else LOG_DBG("Free Tuning Queue"); for(int i=0;i<ISP_DRV_P2_CQ_NUM;i++){ for(int j=0;j<ISP_TUNING_QUEUE_NUM;j++){ if((mTuningQueInf[i][j].queFd>=0) && (mTuningQueInf[i][j].pTuningQue!=0)){ m_ispTmpBufInfo.size = mTuningQueInf[i][j].queSize; m_ispTmpBufInfo.memID = mTuningQueInf[i][j].queFd; m_ispTmpBufInfo.virtAddr = (MUINTPTR)mTuningQueInf[i][j].pTuningQue; if ( m_pIMemDrv->freeVirtBuf(&m_ispTmpBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->freeVirtBuf"); } mTuningQueInf[i][j].queFd = -1; mTuningQueInf[i][j].pTuningQue = NULL; }else{ LOG_ERR("[Error]free TuningQue error i(%d),j(%d),fd(%d),va(0x%08x)",i,j,mTuningQueInf[i][j].queFd,mTuningQueInf[i][j].pTuningQue); } } // free keepP1Que if((mTuningQueIdx[i].keepP1Que.queFd>=0) && (mTuningQueIdx[i].keepP1Que.pTuningQue!=0)){ m_ispTmpBufInfo.size = mTuningQueIdx[i].keepP1Que.queSize; m_ispTmpBufInfo.memID = mTuningQueIdx[i].keepP1Que.queFd; m_ispTmpBufInfo.virtAddr = (MUINTPTR)mTuningQueIdx[i].keepP1Que.pTuningQue; if ( m_pIMemDrv->freeVirtBuf(&m_ispTmpBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->freeVirtBuf"); } mTuningQueIdx[i].keepP1Que.queFd = -1; mTuningQueIdx[i].keepP1Que.pTuningQue = NULL; }else{ LOG_ERR("[Error]free keepP1Que error i(%d),fd(%d),va(0x%08x)",i,mTuningQueIdx[i].keepP1Que.queFd,mTuningQueIdx[i].keepP1Que.pTuningQue); } mTuningQueIdx[i].isApplyTuning = MFALSE; mTuningQueIdx[i].pCurReadP1TuningQue = NULL; mTuningQueIdx[i].pCurWriteTuningQue = NULL; mTuningQueIdx[i].eCurReadP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepP1UpdateFuncBit = eIspTuningMgrFunc_Null; mTuningQueIdx[i].keepReadP1CtlEn1 = 0; mTuningQueIdx[i].keepReadP1CtlEn2 = 0; mTuningQueIdx[i].keepReadP1CtlDmaEn = 0; mTuningQueIdx[i].curWriteIdx = ISP_TUNING_INIT_IDX; //mTuningQueIdx[i].isInitP2 = MFALSE; mTuningQueIdx[i].isInitP1 = MFALSE; } #endif // // //IMEM m_pIMemDrv->uninit(); LOCAL_PROFILING_LOG_PRINT("m_pIMemDrv->uninit()"); m_pIMemDrv->destroyInstance(); LOCAL_PROFILING_LOG_PRINT("m_pIMemDrv->destroyInstance()"); m_pIMemDrv = NULL; // mpIspHwRegAddr = NULL; mIspVirRegFd = 0; mpIspVirRegBufferBaseAddr = NULL; mIspVirRegSize = 0; mIspCQDescFd = -1; mpIspCQDescBufferVirt = NULL; mIspCQDescSize = 0; mpIspCQDescBufferPhy = 0; // if(mFd >= 0) { //revert kernel flag CAM_HAL_VER_IS3 = 0; if(ioctl(mFd,ISP_SET_CAM_VERSION,&CAM_HAL_VER_IS3) < 0){ LOG_ERR("SetCamVer error\n"); } // #if defined(_use_kernel_ref_cnt_) ISP_REF_CNT_CTRL_STRUCT_FRMB ref_cnt; MINT32 count; // For ISP global reference count. ref_cnt.ctrl = ISP_REF_CNT_DEC_FRMB; ref_cnt.id = ISP_REF_CNT_ID_ISP_FUNC_FRMB; ref_cnt.data_ptr = &count; // if ( MFALSE == kRefCntCtrl(&ref_cnt) ) { // LOG_ERR("ISP_REF_CNT_GET fail, errno(%d):%s.", errno, strerror(errno)); } LOG_INF("ISP Global Count: %d.", count); #endif close(mFd); mFd = -1; } LOCAL_PROFILING_LOG_PRINT("close isp mFd"); // if(mpIspVirRegMap != NULL) { free((MUINT32*)mpIspVirRegMap); mpIspVirRegMap = NULL; } LOCAL_PROFILING_LOG_PRINT("free(mpIspVirRegMap)"); if(mpTempIspHWRegValues != NULL) { free((MUINT32*)mpTempIspHWRegValues); mpTempIspHWRegValues = NULL; } LOCAL_PROFILING_LOG_PRINT("free(mpTempIspHWRegValues)"); // EXIT: LOG_INF(" - X. ret: %d. mInitCount: %d.", Result, mInitCount); LOCAL_PROFILING_LOG_PRINT("Exit"); return Result; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::loadInitSetting(void) { isp_reg_t ispReg; LOG_INF("+"); #if 0 // fix it later //enable DMA error check writeReg((((UINT32)&ispReg.CAM_IMGI_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_BPCI_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_LSCI_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_UFDI_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_LCEI_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_VIPI_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_VIP2I_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_VIP3I_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_IMGO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_RRZO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_LCSO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_ESFKO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_AAO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_UFEO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_MFBO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_IMG3BO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_IMG3CO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_IMG2O_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_IMG3O_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_FEO_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_BPCI_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_LSCI_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_IMGO_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_RRZO_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_LCSO_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_AFO_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); writeReg((((UINT32)&ispReg.CAM_AAO_D_ERR_STAT-(UINT32)&ispReg)), 0xFFFF0000, ISP_DRV_USER_ISPF, 0); //disable p2 DB writeReg((((UINT32)&ispReg.CAM_CTL_SEL_GLOBAL_P2-(UINT32)&ispReg)), 0x00000000, ISP_DRV_USER_ISPF, 0); // #endif LOG_INF("-"); return MTRUE; } //----------------------------------------------------------------------------- // burst Queue num are only supported in p2 MBOOL IspDrvImp::cqTableControl(ISP_DRV_CQTABLE_CTRL_ENUM cmd,int burstQnum) { MUINTPTR dummyaddr; bool ret=true; IMEM_BUF_INFO ispTmpImemInfo; LOG_INF("cmd(%d),burstQnum(%d),mTotalCQNum(%d)",cmd,burstQnum,mTotalCQNum); switch(cmd) { case ISP_DRV_CQTABLE_CTRL_ALLOC: //[1] virtual isp(virtual register map) mIspVirRegSize = sizeof(MUINT32) * ISP_BASE_RANGE * mTotalCQNum; if(mpIspVirRegAddrPA!=NULL) { LOG_ERR("mpIspVirRegAddrPA not a null point"); return -1; } if(mpIspVirRegAddrVA!=NULL) { LOG_ERR("mpIspVirRegAddrPA not a null point"); return -1; } #if defined(__PMEM_ONLY__) mpIspVirRegAddrPA=(MUINT32 **)pmem_alloc_sync((mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32)), &mIspVirRegAddrPAFd); #else ispTmpImemInfo.size = mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32); ispTmpImemInfo.useNoncache = 1; //alloc non-cacheable mem. if ( m_pIMemDrv->allocVirtBuf(&ispTmpImemInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->allocVirtBuf"); ret=false; break; } mIspVirRegAddrPAFd = ispTmpImemInfo.memID; mpIspVirRegAddrPA = (MUINT32**)ispTmpImemInfo.virtAddr; #endif for( int i=0; i<mTotalCQNum; i++ ) { mpIspVirRegAddrPA[i] = ((MUINT32 *)(mpIspVirRegAddrPA+mTotalCQNum)) + i*1*sizeof(MUINT32); } if(mpIspVirRegAddrPA==NULL) { LOG_ERR("malloc mpIspVirRegAddrPA fail"); ret = false; break; } #if defined(__PMEM_ONLY__) mpIspVirRegAddrVA=(MUINT32 **)pmem_alloc_sync((mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32)), &mIspVirRegAddrVAFd); #else ispTmpImemInfo.size = mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32); ispTmpImemInfo.useNoncache = 1; //alloc non-cacheable mem. if ( m_pIMemDrv->allocVirtBuf(&ispTmpImemInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->allocVirtBuf"); ret=false; break; } mIspVirRegAddrVAFd = ispTmpImemInfo.memID; mpIspVirRegAddrVA = (MUINT32**)ispTmpImemInfo.virtAddr; #endif for( int i=0; i<mTotalCQNum; i++ ) { mpIspVirRegAddrVA[i] = ((MUINT32 *)(mpIspVirRegAddrVA+mTotalCQNum)) + i*1*sizeof(MUINT32); } if(mpIspVirRegAddrVA==NULL) { LOG_ERR("malloc mpIspVirRegAddrVA fail"); ret = false; break; } // allocation #if defined(__PMEM_ONLY__) mpIspVirRegBufferBaseAddr = (MUINT32*)pmem_alloc_sync((mIspVirRegSize+(ISP_DRV_VIR_ADDR_ALIGN+1)), &mIspVirRegFd); mpIspVirRegAddrPA[0] = (MUINT32*)pmem_get_phys(mIspVirRegFd); #else m_ispVirRegBufInfo.size = mIspVirRegSize + (ISP_DRV_VIR_ADDR_ALIGN+1); m_ispVirRegBufInfo.useNoncache = 1; //alloc non-cacheable mem. LOG_INF("m_ispVirRegBufInfo.size: %d.", m_ispVirRegBufInfo.size); // if ( m_pIMemDrv->allocVirtBuf(&m_ispVirRegBufInfo) ){ LOG_ERR("ERROR:m_pIMemDrv->allocVirtBuf"); ret=false; break; } #endif mIspVirRegFd = m_ispVirRegBufInfo.memID; //virtual isp base adrress should be 4 bytes alignment mpIspVirRegBufferBaseAddr = (MUINT32*)( (m_ispVirRegBufInfo.virtAddr + ISP_DRV_VIR_ADDR_ALIGN) & (~ISP_DRV_VIR_ADDR_ALIGN) ); // if ( m_pIMemDrv->mapPhyAddr(&m_ispVirRegBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->mapPhyAddr"); ret=false; break; } //virtual isp base adrress should be 4 bytes alignment mpIspVirRegAddrPA[0] = (MUINT32*)( (m_ispVirRegBufInfo.phyAddr + ISP_DRV_VIR_ADDR_ALIGN) & (~ISP_DRV_VIR_ADDR_ALIGN) ); LOG_VRB("v(0x%x)(0x%x)(0x%x)(0x%x)(0x%x)(0x%x)",mIspVirRegSize,m_ispVirRegBufInfo.size, \ m_ispVirRegBufInfo.virtAddr,m_ispVirRegBufInfo.phyAddr, \ mpIspVirRegBufferBaseAddr,mpIspVirRegAddrPA[0]); // if(mpIspVirRegBufferBaseAddr == NULL) { LOG_ERR("mem alloc fail, size(%d)",mIspVirRegSize); ret = false; break; } // initialization memset((MUINT8*)mpIspVirRegBufferBaseAddr,ISP_DRV_VIR_DEFAULT_DATA,mIspVirRegSize); for (int i = 0; i < mTotalCQNum; i++) { mpIspVirRegAddrVA[i] = mpIspVirRegBufferBaseAddr + i * ISP_BASE_RANGE; mpIspVirRegAddrPA[i] = mpIspVirRegAddrPA[0] + i * ISP_BASE_RANGE; LOG_INF("cq:[%d],virtIspAddr:virt[0x%08x]/phy[0x%08x]",i,mpIspVirRegAddrVA[i], mpIspVirRegAddrPA[i] ); } //[3]CQ descriptor if(mpIspCQDescriptorVirt!=NULL) { free(mpIspCQDescriptorVirt); } if(mpIspCQDescriptorVirt!=NULL) { free(mpIspCQDescriptorPhy); } mpIspCQDescriptorVirt=(ISP_DRV_CQ_CMD_DESC_STRUCT **)malloc(mTotalCQNum*sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT *)+ mTotalCQNum*1*sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT)); for( int i=0; i<mTotalCQNum; i++ ) { mpIspCQDescriptorVirt[i] = ((ISP_DRV_CQ_CMD_DESC_STRUCT *)(mpIspCQDescriptorVirt+mTotalCQNum)) + i*1*sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT); } if(mpIspCQDescriptorVirt==NULL) { LOG_ERR("malloc mpIspCQDescriptorVirt fail"); ret = false; break; } mpIspCQDescriptorPhy=(MUINT32 **)malloc(mTotalCQNum*sizeof(MUINT32*)); if(mpIspCQDescriptorPhy==NULL) { LOG_ERR("malloc mpIspCQDescriptorVirt fail"); ret = false; break; } mIspCQDescSize = sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT) * mTotalCQNum * CAM_MODULE_MAX ; // // allocation #if defined(__PMEM_ONLY__) mpIspCQDescBufferVirt = (MUINT32*)pmem_alloc_sync( (mIspCQDescSize+ (ISP_DRV_CQ_DESCRIPTOR_ADDR_ALIGN+1)), &mIspCQDescFd); mpIspCQDescBufferPhy = (MUINT32)pmem_get_phys(mIspCQDescFd); #else // m_ispCQDescBufInfo.size = mIspCQDescSize+ (ISP_DRV_CQ_DESCRIPTOR_ADDR_ALIGN+1); m_ispCQDescBufInfo.useNoncache = 1; //alloc non-cacheable mem. if ( m_pIMemDrv->allocVirtBuf(&m_ispCQDescBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->allocVirtBuf"); ret=false; break; } mIspCQDescFd = m_ispCQDescBufInfo.memID; //CQ decriptor base address should be 8 bytes alignment mpIspCQDescBufferVirt = (MUINT32*)( (m_ispCQDescBufInfo.virtAddr+ISP_DRV_CQ_DESCRIPTOR_ADDR_ALIGN) & (~ISP_DRV_CQ_DESCRIPTOR_ADDR_ALIGN) ); if ( m_pIMemDrv->mapPhyAddr(&m_ispCQDescBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->mapPhyAddr"); ret=false; break; } //CQ decriptor base address should be 8 bytes alignment mpIspCQDescBufferPhy = (MUINT32*) ( (m_ispCQDescBufInfo.phyAddr+ISP_DRV_CQ_DESCRIPTOR_ADDR_ALIGN) & (~ISP_DRV_CQ_DESCRIPTOR_ADDR_ALIGN) ); LOG_DBG("cq(0x%x)(0x%x)(0x%x)(0x%x)(0x%x)(0x%x)",mIspCQDescSize,m_ispCQDescBufInfo.size, \ m_ispCQDescBufInfo.virtAddr,m_ispCQDescBufInfo.phyAddr, \ mpIspCQDescBufferVirt,mpIspCQDescBufferPhy); #endif // __PMEM_ONLY__ // initialization dummyaddr =(MUINTPTR)((MUINTPTR)mpIspVirRegAddrPA[0] + ISP_DRV_CQ_DUMMY_WR_TOKEN); for (int i = 0; i < (CAM_MODULE_MAX-1); i++) { mIspCQDescInit[i].v_reg_addr =(MUINT32)dummyaddr & 0xFFFFFFFF; //why use mpIspVirRegAddrPA[0] for all initialization } for (int i = 0; i < mTotalCQNum; i++) { if ( 0 == i ) { mpIspCQDescriptorVirt[i] = (ISP_DRV_CQ_CMD_DESC_STRUCT*)mpIspCQDescBufferVirt; mpIspCQDescriptorPhy[i] = mpIspCQDescBufferPhy; } else { mpIspCQDescriptorVirt[i] = (ISP_DRV_CQ_CMD_DESC_STRUCT *)((unsigned long)mpIspCQDescriptorVirt[i-1] + sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT)*CAM_MODULE_MAX); mpIspCQDescriptorPhy[i] = (MUINT32*)(( (unsigned long)mpIspCQDescriptorPhy[i-1]) + (sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT)*CAM_MODULE_MAX)); } memcpy((MUINT8*)mpIspCQDescriptorVirt[i], mIspCQDescInit, sizeof(mIspCQDescInit)); LOG_INF("cq:[%d],mpIspCQDescriptor:Virt[0x%08x]/Phy[0x%08x],size/num(%d/%d/%d)",i,mpIspCQDescriptorVirt[i],mpIspCQDescriptorPhy[i],sizeof(ISP_DRV_CQ_CMD_DESC_STRUCT),CAM_MODULE_MAX,sizeof(mIspCQDescInit)); } #if defined(_rtbc_use_cq0c_) //reset cq0c all 0 for rtbc if (sizeof(CQ_RTBC_RING_ST_FRMB) <= sizeof(mIspCQDescInit)) { memset((MUINT8*)mpIspCQDescriptorVirt[ISP_DRV_DESCRIPTOR_CQ0C], 0, sizeof(CQ_RTBC_RING_ST_FRMB)); } else { LOG_ERR("rtbc data too large(%d)>(%d)",sizeof(CQ_RTBC_RING_ST_FRMB),sizeof(mIspCQDescInit)); return MFALSE; } #endif // _rtbc_use_cq0c_ break; case ISP_DRV_CQTABLE_CTRL_DEALLOC: //virtual CQ if ( 0 != mpIspVirRegBufferBaseAddr ) { #if defined(__PMEM_ONLY__) if(mIspVirRegFd >= 0) { pmem_free((MUINT8*)mpIspVirRegBufferBaseAddr,mIspVirRegSize,mIspVirRegFd); mIspVirRegFd = -1; } #else if ( m_pIMemDrv->unmapPhyAddr(&m_ispVirRegBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->unmapPhyAddr"); } // if ( m_pIMemDrv->freeVirtBuf(&m_ispVirRegBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->freeVirtBuf"); } LOG_DBG("free/unmap mpIspVirRegBuffer"); #endif //__PMEM_ONLY__ mpIspVirRegBufferBaseAddr = NULL; } // #if defined(__PMEM_ONLY__) if(mIspVirRegAddrPAFd >= 0) { pmem_free((MUINT8*)mpIspVirRegAddrPA,mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32),mIspVirRegAddrPAFd); mIspVirRegAddrPAFd = -1; } mIspVirRegAddrPAFd = NULL; // if(mIspVirRegAddrVAFd >= 0) { pmem_free((MUINT8*)mpIspVirRegAddrVA,mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32),mIspVirRegAddrVAFd); mIspVirRegAddrVAFd = -1; } mIspVirRegAddrVAFd = NULL; #else ispTmpImemInfo.size = mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32); ispTmpImemInfo.memID = mIspVirRegAddrPAFd; ispTmpImemInfo.virtAddr = (MUINTPTR)mpIspVirRegAddrPA; if ( m_pIMemDrv->freeVirtBuf(&ispTmpImemInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->freeVirtBuf"); } mIspVirRegAddrPAFd = NULL; mpIspVirRegAddrPA = NULL; // ispTmpImemInfo.size = mTotalCQNum*sizeof(MUINT32 *)+mTotalCQNum*1*sizeof(MUINT32); ispTmpImemInfo.memID = mIspVirRegAddrVAFd; ispTmpImemInfo.virtAddr = (MUINTPTR)mpIspVirRegAddrVA; if ( m_pIMemDrv->freeVirtBuf(&ispTmpImemInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->freeVirtBuf"); } mIspVirRegAddrVAFd = NULL; mpIspVirRegAddrVA = NULL; #endif //descriptor if( 0 != mpIspCQDescBufferVirt ) { #if defined(__PMEM_ONLY__) if(mIspCQDescFd >= 0) { pmem_free((MUINT8*)mpIspCQDescBufferVirt,mIspCQDescSize,mIspCQDescFd); mIspCQDescFd = -1; } #else if ( m_pIMemDrv->unmapPhyAddr(&m_ispCQDescBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->unmapPhyAddr"); } // if ( m_pIMemDrv->freeVirtBuf(&m_ispCQDescBufInfo) ) { LOG_ERR("ERROR:m_pIMemDrv->freeVirtBuf"); } LOG_DBG("free/unmap mpIspCQDescBufferVirt"); #endif mpIspCQDescBufferVirt = NULL; } // if(mpIspCQDescriptorVirt!=NULL) { free(mpIspCQDescriptorVirt); mpIspCQDescriptorVirt=NULL; } if(mpIspCQDescriptorPhy!=NULL) { free(mpIspCQDescriptorPhy); mpIspCQDescriptorPhy=NULL; } break; default: LOG_ERR("wrong cmd(%d)",cmd); ret=false; break; } return ret; } //----------------------------------------------------------------------------- MINT32 IspDrvImp::cqNumInfoControl(ISP_DRV_CQNUMINFO_CTRL_ENUM cmd,int newValue) { MINT32 num=0; MBOOL ret=MTRUE; MUINT32 value; pthread_mutex_lock(&IspCQinfoMutex); switch(cmd) { case ISP_DRV_CQNUMINFO_CTRL_GET_CURBURSTQNUM: //get current supported burst queue number #if 1 num = 1; // for 82 #else //hint: burstQnum may not sync in user/kernel space cuz mw flow that user space thread all release isp driver // but imem driver may not be released (some buffer would be keeped) //action, all burstQ number are based on user space ret = ioctl(mFd,ISP_QUERY_BURSTQNUM_FRMB,&value); if(ret<0) { LOG_ERR("ISP_QUERY_BURSTQNUM_FRMB fail(%d).", ret); } if(value != mCurBurstQNum) { LOG_WRN("update kernel bQ cuz timing(%d,%d)",mCurBurstQNum,value); value=mCurBurstQNum; ret=ioctl(mFd,ISP_UPDATE_BURSTQNUM_FRMB,&value); if(ret<0) { LOG_ERR("ISP_UPDATE_BURSTQNUM_FRMB fail(%d).", ret); } } num=mCurBurstQNum; #endif break; case ISP_DRV_CQNUMINFO_CTRL_GET_TOTALCQNUM: //get total cq number including p1 cq and p2 cq num=mTotalCQNum; break; case ISP_DRV_CQNUMINFO_CTRL_GET_P2DUPCQNUM: //get duplicate number of p2 cq num=ISP_DRV_P2_CQ_DUPLICATION_NUM; break; case ISP_DRV_CQNUMINFO_CTRL_GET_P1DUPCQNUM: //get duplicate number of p2 cq num=ISP_DRV_P1_CQ_DUPLICATION_NUM; break; case ISP_DRV_CQNUMINFO_CTRL_SET_CURBURSTQNUM: //set current supported burst queue number /* do nothing in 82 */ if(newValue>1) { LOG_ERR("do not support burstQ number > 1 "); } #if 0 mCurBurstQNum=newValue; //update value in kernel layer value=newValue; ret=ioctl(mFd,ISP_UPDATE_BURSTQNUM_FRMB,&value); if(ret<0) { LOG_ERR("ISP_UPDATE_BURSTQNUM_FRMB fail(%d).", ret); } #endif break; case ISP_DRV_CQNUMINFO_CTRL_UPDATE_TOTALCQNUM: //update total cq number including p1 cq and p2 cq mTotalCQNum= mCurBurstQNum * ((ISP_DRV_P1_CQ_DUPLICATION_NUM * ISP_DRV_P1_PER_CQ_SET_NUM)\ +(ISP_DRV_P2_CQ_DUPLICATION_NUM * ISP_DRV_P2_PER_CQ_SET_NUM)); break; case ISP_DRV_CQNUMINFO_CTRL_SET_P1DUPCQNUM: //set duplicate number of p1 cq case ISP_DRV_CQNUMINFO_CTRL_SET_P2DUPCQNUM: //set duplicate number of p2 cq break; default: LOG_WRN("wrong cmd"); break; } pthread_mutex_unlock(&IspCQinfoMutex); return num; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::dumpP2DebugLog(IspDumpDbgLogP2Package* pP2Package) { isp_reg_t ispReg; MUINT32 i; MUINT32 dumpTpipeLine; MUINT32 regTpipePA; //isp_reg_t tmpIspReg; LOG_INF("pP2Package(0x%x)",pP2Package); // //dump tpipe regTpipePA = readReg((MUINT32)((MUINT8*)&ispReg.CAM_TDRI_BASE_ADDR-(MUINT8*)&ispReg)); LOG_INF("[Tpipe]va(0x%08x),pa(0x%08x),regPa(0x%08x)",pP2Package->tpipeTableVa,pP2Package->tpipeTablePa,regTpipePA); dumpTpipeLine = DUMP_TPIPE_SIZE / DUMP_TPIPE_NUM_PER_LINE; for(i=0;i<dumpTpipeLine;i++){ LOG_INF("[Tpipe](%02d)-0x%08x-0x%08x-0x%08x-0x%08x-0x%08x-0x%08x-0x%08x-0x%08x-0x%08x-0x%08x",i, pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE],pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+1],pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+2], pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+3],pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+4],pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+5], pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+6],pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+7],pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+8], pP2Package->tpipeTableVa[i*DUMP_TPIPE_NUM_PER_LINE+9]); } //dump isp register for(i=0x4000;i<=0x5000;i+=20){ LOG_INF("(0x%04x,0x%08x)(0x%04x,0x%08x)(0x%04x,0x%08x)(0x%04x,0x%08x)(0x%04x,0x%08x)", i,readReg(i, ISP_DRV_USER_ISPF),i+4,readReg(i+4, ISP_DRV_USER_ISPF),i+8,readReg(i+8, ISP_DRV_USER_ISPF),i+12,readReg(i+12, ISP_DRV_USER_ISPF),i+16,readReg(i+16, ISP_DRV_USER_ISPF)); } //compare the difference between isp reg and tpipe if(pP2Package->pIspReg || pP2Package->pIspTpipeCfgInfo){ LOG_INF("start to check the defference between tpipe and hw reg"); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.scenario ,pP2Package->pIspReg,CAM_CTL_FMT_SEL,SCENARIO); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.mode ,pP2Package->pIspReg,CAM_CTL_FMT_SEL,SUB_MODE); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.cam_in_fmt ,pP2Package->pIspReg,CAM_CTL_FMT_SEL,CAM_IN_FMT); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.tcm_load_en ,pP2Package->pIspReg,CAM_CTL_TCM_EN ,TCM_LOAD_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.ctl_extension_en ,pP2Package->pIspReg,CAM_CTL_PIX_ID ,CTL_EXTENSION_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.rsp_en ,pP2Package->pIspReg,CAM_CTL_TCM_EN ,TCM_RSP_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.mdp_crop_en ,pP2Package->pIspReg,CAM_CTL_CROP_X ,MDP_CROP_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.imgi_en ,pP2Package->pIspReg,CAM_CTL_DMA_EN ,IMGI_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.lsci_en ,pP2Package->pIspReg,CAM_CTL_DMA_EN ,LSCI_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.unp_en ,pP2Package->pIspReg,CAM_CTL_EN1 ,UNP_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.bnr_en ,pP2Package->pIspReg,CAM_CTL_EN1 ,BNR_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.lsc_en ,pP2Package->pIspReg,CAM_CTL_EN1 ,LSC_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.sl2_en ,pP2Package->pIspReg,CAM_CTL_EN1 ,SL2_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.c24_en ,pP2Package->pIspReg,CAM_CTL_EN1 ,C24_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.cfa_en ,pP2Package->pIspReg,CAM_CTL_EN1 ,CFA_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.c42_en ,pP2Package->pIspReg,CAM_CTL_EN2 ,C42_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.nbc_en ,pP2Package->pIspReg,CAM_CTL_EN2 ,NBC_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.seee_en ,pP2Package->pIspReg,CAM_CTL_EN2 ,SEEE_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.imgo_en ,pP2Package->pIspReg,CAM_CTL_DMA_EN ,IMGO_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.img2o_en ,pP2Package->pIspReg,CAM_CTL_DMA_EN ,IMG2O_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.cdrz_en ,pP2Package->pIspReg,CAM_CTL_EN2 ,CDRZ_EN); CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.mdp_sel ,pP2Package->pIspReg,CAM_CTL_PIX_ID ,MDP_SEL); //CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.pixel_id,pP2Package->pIspReg,CAM_CTL_FMT_SEL,SUB_MODE); //CHECH_TPIPE_REG(pP2Package->pIspTpipeCfgInfo,top.interlace_mode ,pP2Package->pIspReg,CAM_CTL_EN1,SUB_MODE); LOG_INF("end to check the defference between tpipe and hw reg"); #if 0 if(pP2Package->pIspTpipeCfgInfo->top.scenario != (int)pP2Package->pIspReg->CAM_CTL_FMT_SEL.Bits.SUB_MODE){ // backup the original value oriVal = pP2Package->pIspReg->CAM_CTL_FMT_SEL.Raw; // start to parse union bits pP2Package->pIspReg->CAM_CTL_FMT_SEL.Raw = 0; pP2Package->pIspReg->CAM_CTL_FMT_SEL.Bits.SUB_MODE = 0xffffffff; parseVal = pP2Package->pIspReg->CAM_CTL_FMT_SEL.Raw; for(i=0;i<intSize;i++){ if(parseVal & (0x01)<<i) break; } // recover the original value pP2Package->pIspReg->CAM_CTL_FMT_SEL.Raw = oriVal; LOG_INF("[Diff][0x%x][Bit-%d]", \ (int)(&pP2Package->pIspReg->CAM_CTL_FMT_SEL)-(int)(&pP2Package->pIspReg->rsv_0000[0]), \ i); } #endif } else { LOG_ERR("[Error] fail to dump tpipe difference"); } //LOG_INF("(0x%04x,0x%08x)(0x%04x,0x%08x)",0x5ff0,readReg(0x5ff0, ISP_DRV_USER_ISPF),0x5ff4,readReg(0x5ff4, ISP_DRV_USER_ISPF)); return MTRUE; } #define DMA_CHK(dma,out){\ out = 0;\ if(dma[0] & 0xffff){\ LOG_ERR("IMGI ERR:0x%x\n",dma[0]);\ out = 1;\ }\ if(dma[1] & 0xffff){\ LOG_ERR("LSCI ERR:0x%x\n",dma[1]);\ out = 1;\ }\ if(dma[2] & 0xffff){\ LOG_ERR("IMGO ERR:0x%x\n",dma[2]);\ out = 1;\ }\ if(dma[3] & 0xffff){\ LOG_ERR("IMG2O ERR:0x%x\n",dma[3]);\ out = 1;\ }\ if(dma[4] & 0xffff){\ LOG_ERR("ESFKO ERR:0x%x\n",dma[4]);\ out = 1;\ }\ if(dma[5] & 0xffff){\ LOG_ERR("AAO ERR:0x%x\n",dma[5]);\ out = 1;\ }\ } //idx0:0 for p1 , 1 for p1_d , 2 for camsv, 3 for camsv_d //idx1:debug flag init. MTRUE/FALSE, if idx1 is true , idx2 map to function_DbgLogEnable_VERBOSE, // idx3:function_DbgLogEnable_DEBUG, idx4 map to function_DbgLogEnable_INFO //idx2:prt log. MTRUE/FALSE //idx3:get sof //idx4:get dma_err msg //idx5:1 for get int err //idx5:2 for get drop frame status, which idx0: in/out param, in for TG, out for frame status,0:normal, 1:drop frame, 2:last working frame MBOOL IspDrvImp::dumpP1DebugLog(MUINT32* p1) { if(mFd >= 0 ){ MUINT32 _flag[2] = {0x0}; //enable kernel debug log if(p1[1] == MTRUE){ if(p1[2]){ _flag[0] |= 0x400;//ISP_DBG_INT_2 } if(p1[3]){//(isp_drv_DbgLogEnable_DEBUG){ _flag[0] |= 0x1;//ISP_DBG_INT } if(p1[4]){ _flag[0] |= 0x100;//ISP_DBG_BUF_CTRL } if(p1[5]) _flag[0] |= 0x800;//isp_dbg_int_3 //timestamp interval _flag[1] = p1[0];//_IRQ if(ioctl(mFd,ISP_DEBUG_FLAG_FRMB,_flag) < 0){ LOG_ERR("kernel log enable error\n"); } } if(p1[2] == MTRUE){ _flag[0] = p1[0]; LOG_DBG("prt kernel log"); if(ioctl(mFd,ISP_DUMP_ISR_LOG_FRMB,_flag) < 0){ LOG_ERR("kernel log enable error\n"); } } else if(p1[3] == MTRUE){ if(ioctl(mFd,ISP_GET_CUR_SOF_FRMB,p1) < 0){ LOG_ERR("dump sof error\n"); } } else if(p1[4] == MTRUE){ MUINT32 _flag[18] = {0}; if(ioctl(mFd,ISP_GET_DMA_ERR_FRMB,_flag) < 0){ LOG_ERR("dump sof error\n"); } DMA_CHK(_flag,p1[4]); } else if(p1[5] == 1){ MUINT32 _flag[4] = {0}; if(ioctl(mFd,ISP_GET_INT_ERR_FRMB,_flag) < 0){ LOG_ERR("dump int_err error\n"); }else LOG_ERR("p1 int err: 0x%x,0x%x,0x%x,0x%x",_flag[0],_flag[1],_flag[2],_flag[3]); } else if(p1[5] == 2){ if(ioctl(mFd,ISP_GET_DROP_FRAME_FRMB,p1) < 0){ LOG_ERR("dump drop frame status error\n"); } } else{ if(p1[1]!= MTRUE) LOG_ERR("p1 dump log err"); } } return MTRUE; } MBOOL IspDrvImp::dumpDBGLog(MUINT32* P1,IspDumpDbgLogP2Package* pP2Package){ if(pP2Package) dumpP2DebugLog(pP2Package); if(P1!= NULL) dumpP1DebugLog(P1); return MTRUE; } MBOOL IspDrvImp::SetFPS(MUINT32 _fps){ #ifdef T_STAMP_2_0 if(ioctl(mFd,ISP_SET_FPS_FRMB,&_fps) < 0){ LOG_ERR("SetFPS error\n"); } return MTRUE; #else LOG_DBG("FPS can't pass 2 kernel\n"); return MFALSE; #endif } //----------------------------------------------------------------------------- MBOOL IspDrvImp::dumpCQTable(ISP_DRV_CQ_ENUM cq, MINT32 burstQIdx,MUINT32 dupCqIdx, ISP_DRV_CQ_CMD_DESC_STRUCT* cqDesVa, MUINT32* cqVirVa) { MUINT32 i; MUINT32 cqLabel; ISP_DRV_DESCRIPTOR_CQ_ENUM cqDesTab; MUINT32 *pIspVirCqVa; ISP_DRV_CQ_CMD_DESC_STRUCT *pIspDesCqVa; isp_reg_t ispReg; MINT32 realCQIdx=getRealCQIndex(cq,burstQIdx,dupCqIdx); LOG_INF("+,realCQIdx(%d),cq(%d),burstQIdx(%d),dupCqIdx(%d),cqDesVa(0x%x),cqVirVa(0x%x)",realCQIdx,cq,burstQIdx,dupCqIdx,cqDesVa,cqVirVa); switch(cq){ case ISP_DRV_CQ0: cqLabel=0x0; break; case ISP_DRV_CQ0B: cqLabel=0x0B; break; case ISP_DRV_CQ0C: cqLabel=0x0C; break; case ISP_DRV_CQ01: cqLabel=0x01; break; case ISP_DRV_CQ02: cqLabel=0x02; break; case ISP_DRV_CQ03: cqLabel=0x03; break; default: LOG_ERR("[Error]Not support this CQ(%d)",realCQIdx); return MTRUE; break; } cqDesTab=(ISP_DRV_DESCRIPTOR_CQ_ENUM)(realCQIdx); if(cqDesVa==0 || cqVirVa==0){ pIspDesCqVa = mpIspCQDescriptorVirt[cqDesTab]; pIspVirCqVa = mpIspVirRegAddrVA[realCQIdx]; LOG_INF("ISP_CQ_PA(0x%x)",mpIspCQDescriptorPhy[realCQIdx]); LOG_INF("[BasePA]CQ1(0x%x),CQ2(0x%x),CQ3(0x%x)",readReg(( (MUINT32)((MUINT8*)&ispReg.CAM_CTL_CQ1_BASEADDR-(MUINT8*)&ispReg)), ISP_DRV_USER_ISPF), readReg(((MUINT32)((MUINT8*)&ispReg.CAM_CTL_CQ2_BASEADDR-(MUINT8*)&ispReg)), ISP_DRV_USER_ISPF),readReg(((MUINT32)((MUINT8*)&ispReg.CAM_CTL_CQ3_BASEADDR-(MUINT8*)&ispReg)), ISP_DRV_USER_ISPF)); // LOG_INF("[REG]P2_EN(0x%x),P2_EN_DMA(0x%x),SCENARIO_REG(0x%x),CQ_EN_P2(0x%x)",readReg((((UINT32)&ispReg.CAM_CTL_EN_P2-(UINT32)&ispReg)), ISP_DRV_USER_ISPF), // readReg((((UINT32)&ispReg.CAM_CTL_EN_P2_DMA-(UINT32)&ispReg)), ISP_DRV_USER_ISPF),readReg((((UINT32)&ispReg.CAM_CTL_SCENARIO-(UINT32)&ispReg)), ISP_DRV_USER_ISPF), // readReg((((UINT32)&ispReg.CAM_CTL_SEL_P2-(UINT32)&ispReg)), ISP_DRV_USER_ISPF)); } else { // for dpframe work process pIspDesCqVa = (ISP_DRV_CQ_CMD_DESC_STRUCT*)cqDesVa; pIspVirCqVa = (MUINT32*)cqVirVa; } for(i=0;i<=CAM_DUMMY_;i++){ if(pIspDesCqVa[i].u.cmd != ISP_DRV_CQ_DUMMY_WR_TOKEN) { LOG_INF("[CQ%03X]:[%02d][0x%08x]",cqLabel,i,pIspDesCqVa[i].u.cmd); LOG_CQ_VIRTUAL_TABLE(pIspVirCqVa,i,mIspCQModuleInfo[i].reg_num); } } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::waitIrq(ISP_DRV_WAIT_IRQ_STRUCT* pwaitIrq) { MINT32 Ret; #if 1 MUINT32 dumpStatus = (ISP_DRV_IRQ_INT_STATUS_PASS1_TG1_DON_ST| \ ISP_DRV_IRQ_INT_STATUS_SOF1_INT_ST| \ ISP_DRV_IRQ_INT_STATUS_VS1_ST); #else // fix it later MUINT32 dumpStatus = (CAM_CTL_INT_P1_STATUS_PASS1_DON_ST|CAM_CTL_INT_P1_STATUS_D_PASS1_DON_ST| \ CAMSV2_INT_STATUS_PASS1_DON_ST|CAMSV_INT_STATUS_PASS1_DON_ST|CAM_CTL_INT_P1_STATUS_SOF1_INT_ST|CAM_CTL_INT_P1_STATUS_D_SOF1_INT_ST| \ CAMSV_INT_STATUS_TG_SOF1_ST|CAMSV2_INT_STATUS_TG_SOF1_ST|CAM_CTL_INT_P1_STATUS_VS1_INT_ST|CAM_CTL_INT_P1_STATUS_D_VS1_INT_ST); #endif // IspDbgTimer dbgTmr("waitIrq"); MUINT32 Ta=0,Tb=0; // LOG_DBG(" - E. Type(%d),Status(0x%08x),Timeout(%d).", pwaitIrq->UserInfo.Type, pwaitIrq->UserInfo.Status, pwaitIrq->Timeout); // ISP_DRV_WAIT_IRQ_STRUCT waitirq; waitirq.Clear=pwaitIrq->Clear; waitirq.UserInfo=pwaitIrq->UserInfo; waitirq.TimeInfo.tLastEvent_sec=0; waitirq.TimeInfo.tLastEvent_usec=0; waitirq.TimeInfo.tmark2read_sec=0; waitirq.TimeInfo.tmark2read_usec=0; waitirq.TimeInfo.tevent2read_sec=0; waitirq.TimeInfo.tevent2read_usec=0; waitirq.TimeInfo.passedbySigcnt=0; waitirq.Timeout=pwaitIrq->Timeout; waitirq.EisMeta.tLastSOF2P1done_sec=0; waitirq.EisMeta.tLastSOF2P1done_usec=0; waitirq.SpecUser=pwaitIrq->SpecUser; //dump only pass1|pass1_d|camsv|camsv2 sof|done if((pwaitIrq->bDumpReg == 0xfe) || ((waitirq.UserInfo.Status & dumpStatus) == 0)) waitirq.bDumpReg = MFALSE; else waitirq.bDumpReg = MTRUE; Ta=dbgTmr.getUs(); Ret = ioctl(mFd,ISP_WAIT_IRQ_FRMB,&waitirq); Tb=dbgTmr.getUs(); //us //receive restart system call signal if(Ret== (-512))//-ERESTARTSYS=-512 { //change to non-clear wait and start to wait again LOG_INF("ioctrl Ret(%d),Type(%d),Status(0x%08x),Timeout(%d),Tb-Ta(%d us).",Ret,pwaitIrq->UserInfo.Type, pwaitIrq->UserInfo.Status, pwaitIrq->Timeout,Tb-Ta); waitirq.Timeout=waitirq.Timeout - ((Tb-Ta)/1000); while((waitirq.Timeout > 0) && (Ret== (-512)))//receive restart system call again, -ERESTARTSYS=-512 { waitirq.Clear=ISP_DRV_IRQ_CLEAR_NONE; Ta=dbgTmr.getUs(); Ret = ioctl(mFd,ISP_WAIT_IRQ_FRMB,&waitirq); Tb=dbgTmr.getUs(); waitirq.Timeout=waitirq.Timeout - ((Tb-Ta)/1000); } LOG_INF("Leave ERESTARTSYS,Type(%d),Status(0x%08x),Timeout(%d),Tb-Ta(%d us).",Ret,pwaitIrq->UserInfo.Type, pwaitIrq->UserInfo.Status, pwaitIrq->Timeout,Tb-Ta); } //err handler if(Ret<0 || MTRUE==isp_drv_DbgLogEnable_DEBUG) { LOG_INF("Type(%d),Status(0x%08x),Timeout(%d).", pwaitIrq->UserInfo.Type, pwaitIrq->UserInfo.Status, pwaitIrq->Timeout); if(pwaitIrq->UserInfo.Type==4 && (pwaitIrq->UserInfo.Status==0x80||pwaitIrq->UserInfo.Status==0x40||pwaitIrq->UserInfo.Status==0x20||pwaitIrq->UserInfo.Status==0x2)){ dumpCQTable(ISP_DRV_CQ0); if(pwaitIrq->UserInfo.Status==0x2 || pwaitIrq->UserInfo.Status==0x20){ dumpCQTable(ISP_DRV_CQ01,0,0); dumpCQTable(ISP_DRV_CQ01,0,1); }else if(pwaitIrq->UserInfo.Status==0x40){ dumpCQTable(ISP_DRV_CQ02,0,0); dumpCQTable(ISP_DRV_CQ02,0,1); }else if(pwaitIrq->UserInfo.Status==0x80){ dumpCQTable(ISP_DRV_CQ03,0,0); dumpCQTable(ISP_DRV_CQ03,0,1); } } } if(Ret < 0) { LOG_ERR("ISP_WAIT_IRQ_FRMB fail(%d). Type(%d), Status(0x%08x), Timeout(%d).", Ret, pwaitIrq->UserInfo.Type, pwaitIrq->UserInfo.Status, pwaitIrq->Timeout); return MFALSE; } //return information pwaitIrq->TimeInfo=waitirq.TimeInfo; pwaitIrq->EisMeta=waitirq.EisMeta; if(waitirq.TimeInfo.tLastEvent_sec < 0) { pwaitIrq->TimeInfo.tLastEvent_sec=0;} if(waitirq.TimeInfo.tLastEvent_usec < 0) { pwaitIrq->TimeInfo.tLastEvent_usec=0;} if(waitirq.TimeInfo.tmark2read_sec < 0) { pwaitIrq->TimeInfo.tmark2read_sec=0;} if(waitirq.TimeInfo.tmark2read_usec < 0) { pwaitIrq->TimeInfo.tmark2read_usec=0;} if(waitirq.TimeInfo.tevent2read_sec < 0) { pwaitIrq->TimeInfo.tevent2read_sec=0;} if(waitirq.TimeInfo.tevent2read_usec < 0) { pwaitIrq->TimeInfo.tevent2read_usec=0;} if(waitirq.EisMeta.tLastSOF2P1done_sec < 0) { pwaitIrq->EisMeta.tLastSOF2P1done_sec=0;} if(waitirq.EisMeta.tLastSOF2P1done_usec < 0) { pwaitIrq->EisMeta.tLastSOF2P1done_usec=0;} return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::readIrq(ISP_DRV_READ_IRQ_STRUCT* pReadIrq) { MINT32 Ret; #if 0 ISP_DRV_READ_IRQ_STRUCT ReadIrq; // LOG_INF(" - E. Type(%d), Status(%d)",pReadIrq->Type, pReadIrq->Status); // ReadIrq.Type = pReadIrq->Type; ReadIrq.Status = (ISP_DRV_IRQ_USER_ENUM)0; // Ret = ioctl(mFd,ISP_READ_IRQ,&ReadIrq); if(Ret < 0) { LOG_ERR("ISP_READ_IRQ fail(%d)",Ret); return MFALSE; } // pReadIrq->Status = ReadIrq.Status; #endif LOG_ERR("NOT SUPPORT THIS"); return MFALSE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::checkIrq(ISP_DRV_CHECK_IRQ_STRUCT CheckIrq) { MINT32 Ret; #if 0 ISP_DRV_READ_IRQ_STRUCT ReadIrq; // LOG_DBG(" - E. Type(%d), Status(%d)",CheckIrq.Type, CheckIrq.Status); // ReadIrq.Type = CheckIrq.Type; ReadIrq.Status = (ISP_DRV_IRQ_USER_ENUM)0; if(!readIrq(&ReadIrq)) { return MFALSE; } // if((CheckIrq.Status & ReadIrq.Status) != CheckIrq.Status) { LOG_ERR("Status:Check(0x%08X),Read(0x%08X)",CheckIrq.Status,ReadIrq.Status); return MFALSE; } return MTRUE; #endif LOG_ERR("NOT SUPPORT THIS"); return MFALSE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::clearIrq(ISP_DRV_CLEAR_IRQ_STRUCT ClearIrq) { MINT32 Ret; #if 0 // LOG_INF(" - E. Type(%d),Status(%d)",ClearIrq.Type, ClearIrq.Status); // Ret = ioctl(mFd,ISP_CLEAR_IRQ,&ClearIrq); if(Ret < 0) { LOG_ERR("ISP_CLEAR_IRQ fail(%d)",Ret); return MFALSE; } return MTRUE; #endif LOG_ERR("NOT SUPPORT THIS"); return MFALSE; } //----------------------------------------------------------------------------- MINT32 IspDrvImp::registerIrq(const char* userName) { MINT32 Ret; MINT32 key=-1; IISP_DRV_USERKEY_STRUCT userKeyStruct; userKeyStruct.userName=const_cast<char *>(userName); Ret = ioctl(mFd,ISP_REGISTER_IRQ_USER_KEY,&userKeyStruct); LOG_INF("userName(%s),userKey(%d)",userKeyStruct.userName,userKeyStruct.userKey); if(Ret < 0) { LOG_ERR("registerIrq fail, no more space for user to do irq operation"); return -1; } key=userKeyStruct.userKey; if(key<0) { LOG_ERR("Invalid userKey(%d)",key); return -1; } return key; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::markIrq(ISP_DRV_WAIT_IRQ_STRUCT Irqinfo) { MINT32 Ret; Irqinfo.Clear = ISP_DRV_IRQ_CLEAR_NONE; Irqinfo.Timeout=0; Irqinfo.bDumpReg=0; Ret = ioctl(mFd,ISP_MARK_IRQ_REQUEST,&Irqinfo); if(Ret < 0) { LOG_ERR("mark irq fail, user key/type/status (%d/%d/0x%x)",Irqinfo.UserInfo.UserKey,Irqinfo.UserInfo.Type,Irqinfo.UserInfo.Status); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::flushIrq(ISP_DRV_WAIT_IRQ_STRUCT Irqinfo) { MINT32 Ret; Irqinfo.Clear = ISP_DRV_IRQ_CLEAR_NONE; Irqinfo.Timeout=0; Irqinfo.bDumpReg=0; Ret = ioctl(mFd,ISP_FLUSH_IRQ_REQUEST,&Irqinfo); LOG_INF("flush irq, user key/type/status (%d/%d/0x%x)",Irqinfo.UserInfo.UserKey,Irqinfo.UserInfo.Type,Irqinfo.UserInfo.Status); if(Ret < 0) { LOG_ERR("flush irq fail, user key/type/status (%d/%d/0x%x)",Irqinfo.UserInfo.UserKey,Irqinfo.UserInfo.Type,Irqinfo.UserInfo.Status); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::queryirqtimeinfo(ISP_DRV_WAIT_IRQ_STRUCT* Irqinfo) { MINT32 Ret; LOG_DBG(" - E. key(%d),Type(%d),Status(0x%08x).",Irqinfo->UserInfo.UserKey, Irqinfo->UserInfo.Type, Irqinfo->UserInfo.Status); ISP_DRV_WAIT_IRQ_STRUCT qirq; qirq.UserInfo = Irqinfo->UserInfo; qirq.TimeInfo.tLastEvent_sec=0; qirq.TimeInfo.tLastEvent_usec=0; qirq.TimeInfo.tmark2read_sec=0; qirq.TimeInfo.tmark2read_usec=0; qirq.TimeInfo.tevent2read_sec=0; qirq.TimeInfo.tevent2read_usec=0; qirq.TimeInfo.passedbySigcnt=0; Ret = ioctl(mFd,ISP_GET_MARK2QUERY_TIME,&qirq); if(Ret < 0) { LOG_ERR("flush irq fail, user key/type/status (%d/%d/0x%x)",Irqinfo->UserInfo.UserKey,Irqinfo->UserInfo.Type,Irqinfo->UserInfo.Status); return MFALSE; } else { Irqinfo->TimeInfo=qirq.TimeInfo; if(qirq.TimeInfo.tLastEvent_sec < 0) { Irqinfo->TimeInfo.tLastEvent_sec=0;} if(qirq.TimeInfo.tLastEvent_usec < 0) { Irqinfo->TimeInfo.tLastEvent_usec=0;} if(qirq.TimeInfo.tmark2read_sec < 0) { Irqinfo->TimeInfo.tmark2read_sec=0;} if(qirq.TimeInfo.tmark2read_usec < 0) { Irqinfo->TimeInfo.tmark2read_usec=0;} if(qirq.TimeInfo.tevent2read_sec < 0) { Irqinfo->TimeInfo.tevent2read_sec=0;} if(qirq.TimeInfo.tevent2read_usec < 0) { Irqinfo->TimeInfo.tevent2read_usec=0;} } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::reset(MINT32 rstpath) { MINT32 Ret; LOG_INF("ISP SW RESET[0x%08x]",mFd); Ret = ioctl(mFd,ISP_RESET,NULL); if(Ret < 0) { LOG_ERR("ISP_RESET fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::resetBuf(void) { MINT32 Ret; // LOG_DBG(""); // Ret = ioctl(mFd,ISP_RESET_BUF,NULL); if(Ret < 0) { LOG_ERR("ISP_RESET_BUF fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::readRegs( ISP_DRV_REG_IO_STRUCT* pRegIo, MUINT32 Count, MINT32 caller) { MINT32 Ret; switch(caller) { //assume that user do not burst read/write top related registers case ISP_DRV_RWREG_CALLFROM_MACRO: Ret=readRegsviaIO(pRegIo,Count); break; default: pthread_mutex_lock(&IspOtherRegMutex); Ret=readRegsviaIO(pRegIo,Count); pthread_mutex_unlock(&IspOtherRegMutex); break; } if(Ret < 0) { LOG_ERR("ISP_READ_REG_NOPROTECT fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MUINT32 IspDrvImp::readReg(MUINT32 Addr,MINT32 caller) { MBOOL ret=0; MUINT32 value=0x0; MUINT32* pISPmmapAddr = this->getMMapRegAddr(); if(m_regRWMode==ISP_DRV_RWREG_MODE_RW) { //value=*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr)); value = pISPmmapAddr[(Addr>>2)]; } else if(m_regRWMode==ISP_DRV_RWREG_MODE_RO) { ISP_DRV_REG_IO_STRUCT RegIo; RegIo.Addr = Addr; if(!readRegsviaIO(&RegIo, 1)) { return 0; } value=RegIo.Data; } return value; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::writeRegs( ISP_DRV_REG_IO_STRUCT* pRegIo, MUINT32 Count, MINT32 userEnum, MINT32 caller) { MINT32 Ret; switch(userEnum) { case ISP_DRV_USER_ISPF: break; case ISP_DRV_USER_SENF: break; case ISP_DRV_USER_FD: break; default: LOG_ERR("data[0x%x] cn[0x%x] only ispDrv/isp_function/seninf have authorization to directly write hw registers\n",pRegIo,Count); return MFALSE; } switch(caller) { case ISP_DRV_RWREG_CALLFROM_MACRO: Ret=writeRegsviaIO(pRegIo,Count); break; default: pthread_mutex_lock(&IspOtherRegMutex); Ret=writeRegsviaIO(pRegIo,Count); pthread_mutex_unlock(&IspOtherRegMutex); break; } if(Ret < 0) { LOG_ERR("ISP_WRITE_REG fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::writeReg( MUINT32 Addr, MUINT32 Data, MINT32 userEnum, MINT32 caller) { // //LOG_VRB("Addr(0x%08X),Data(0x%08X)",Addr,Data); // MBOOL ret=0; MUINT32* pISPmmapAddr = this->getMMapRegAddr(); switch(userEnum) { case ISP_DRV_USER_ISPF: break; case ISP_DRV_USER_SENF: break; case ISP_DRV_USER_FD: break; default: LOG_ERR("ad[0x%x] vl[0x%x] only ispDrv/isp_function/seninf have authorization to directly write hw registers\n",Addr,Data); return MFALSE; } switch(caller) { case ISP_DRV_RWREG_CALLFROM_MACRO: if(m_regRWMode==ISP_DRV_RWREG_MODE_RW) { //*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr))=Data; pISPmmapAddr[(Addr>>2)] = Data; } else { ISP_DRV_REG_IO_STRUCT RegIo; RegIo.Addr = Addr; if(!writeRegsviaIO(&RegIo, 1)) { return 0; } } break; default: //check range ret=checkTopReg(Addr); if(ret==1) { pthread_mutex_lock(&IspTopRegMutex); if(m_regRWMode==ISP_DRV_RWREG_MODE_RW) { //*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr))=Data; pISPmmapAddr[(Addr>>2)] = Data; //dsb(); } else { ISP_DRV_REG_IO_STRUCT RegIo; RegIo.Addr = Addr; if(!writeRegsviaIO(&RegIo, 1)) { return 0; } //dsb(); } pthread_mutex_unlock(&IspTopRegMutex); } else { pthread_mutex_lock(&IspOtherRegMutex); if(m_regRWMode==ISP_DRV_RWREG_MODE_RW) { //*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr))=Data; pISPmmapAddr[(Addr>>2)] = Data; } else { ISP_DRV_REG_IO_STRUCT RegIo; RegIo.Addr = Addr; if(!writeRegsviaIO(&RegIo, 1)) { return 0; } } pthread_mutex_unlock(&IspOtherRegMutex); } break; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::holdReg(MBOOL En) { MINT32 Ret; // LOG_DBG("En(%d)",En); // Ret = ioctl(mFd, ISP_HOLD_REG, &En); if(Ret < 0) { LOG_ERR("ISP_HOLD_REG fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::dumpReg(void) { MINT32 Ret; // LOG_DBG(""); // Ret = ioctl(mFd, ISP_DUMP_REG, NULL); if(Ret < 0) { LOG_ERR("ISP_DUMP_REG fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- isp_reg_t* IspDrvImp::getCurHWRegValues() { MUINT32 size=sizeof(isp_reg_t); MUINT32* startAddr=getMMapRegAddr(); //startAddr+=0x4000; //LOG_INF("isp_reg_t size(0x%x),starting Addr(0x%x),size/sizeof(MUINT32) (0x%x),0x4000Addr(0x%x)\n",size,getMMapRegAddr(),size/sizeof(MUINT32),startAddr); for(MINT32 i=0;i<size/sizeof(MUINT32);i++) { //LOG_INF("addr(0x%x) value (0x%x)\n",((MUINT32*)startAddr+i),*((MUINT32*)startAddr+i)); *((MUINT32*)mpTempIspHWRegValues+i)=*((MUINT32*)startAddr+i); } return (mpTempIspHWRegValues); } //----------------------------------------------------------------------------- MBOOL IspDrvImp::readRegsviaIO( ISP_DRV_REG_IO_STRUCT* pRegIo, MUINT32 Count) { MINT32 Ret; ISP_REG_IO_STRUCT_FRMB IspRegIo; // //LOG_DBG("Count(%d)",Count); // if(pRegIo == NULL) { LOG_ERR("pRegIo is NULL"); return MFALSE; } // IspRegIo.pData_FrmB= (ISP_REG_STRUCT_FRMB*)pRegIo; IspRegIo.Count_FrmB = Count; // Ret = ioctl(mFd, ISP_READ_REGISTER, &IspRegIo); if(Ret < 0) { LOG_ERR("ISP_READ_REG_NOPROTECT via IO fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::writeRegsviaIO( ISP_DRV_REG_IO_STRUCT* pRegIo, MUINT32 Count) { MINT32 Ret; ISP_REG_IO_STRUCT_FRMB IspRegIo; // //LOG_MSG("Count(%d) ",Count); // if(pRegIo == NULL) { LOG_ERR("pRegIo is NULL"); return MFALSE; } // IspRegIo.pData_FrmB= (ISP_REG_STRUCT_FRMB*)pRegIo; IspRegIo.Count_FrmB = Count; // Ret = ioctl(mFd, ISP_WRITE_REGISTER, &IspRegIo); if(Ret < 0) { LOG_ERR("ISP_WRITE_REG via IO fail(%d)",Ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MUINT32* IspDrvImp::getRegAddr(void) { //only return virtual register struct for user to calculate register offset if(mpIspVirRegMap == NULL) { LOG_ERR("NULL temp register struct for calculating offset\n"); } else { return (MUINT32*)mpIspVirRegMap; } return 0; } //----------------------------------------------------------------------------- ///// //temp remove later isp_reg_t* IspDrvImp::getRegAddrMap(void) { LOG_ERR("We do not support this interface and would remove this later\n"); return 0; } //----------------------------------------------------------------------------- #if defined(_use_kernel_ref_cnt_) MBOOL IspDrvImp::kRefCntCtrl(ISP_REF_CNT_CTRL_STRUCT_FRMB* pCtrl) { MINT32 Ret; // LOG_DBG("(%d)(%d)(0x%x)",pCtrl->ctrl,pCtrl->id,pCtrl->data_ptr); // Ret = ioctl(mFd,ISP_REF_CNT_CTRL,pCtrl); if(Ret < 0) { LOG_ERR("ISP_REF_CNT_CTRL fail(%d)[errno(%d):%s] ",Ret, errno, strerror(errno)); return MFALSE; } // return MTRUE; } #endif //----------------------------------------------------------------------------- MBOOL IspDrvImp::rtBufCtrl(void *pBuf_ctrl) { MINT32 Ret; // ISP_BUFFER_CTRL_STRUCT_FRMB *pbuf_ctrl = (ISP_BUFFER_CTRL_STRUCT_FRMB *)pBuf_ctrl; //for debug log ONLY if ( ISP_RT_BUF_CTRL_MAX_FRMB == pbuf_ctrl->ctrl ) { LOG_DBG("[rtbc]cq(%d),vIspV/P(0x%x,0x%x),descV/P(0x%x,0x%x),mmap(0x%x)", \ pbuf_ctrl->buf_id, \ IspDrv::mpIspVirRegAddrVA[pbuf_ctrl->buf_id], \ IspDrv::mpIspVirRegAddrPA[pbuf_ctrl->buf_id], \ IspDrv::mpIspCQDescriptorVirt[pbuf_ctrl->buf_id], \ IspDrv::mpIspCQDescriptorPhy[pbuf_ctrl->buf_id], \ this->getMMapRegAddr()); return MTRUE; } #if defined(_rtbc_use_cq0c_) if(MFALSE == cqRingBuf(pBuf_ctrl)) { LOG_ERR("cqRingBuf(%d) ",Ret); return MFALSE; } #endif // Ret = ioctl(mFd,ISP_BUFFER_CTRL,pBuf_ctrl); if(Ret < 0) { LOG_ERR("ISP_BUFFER_CTRL(%d) ",Ret); return MFALSE; } // return MTRUE; } //----------------------------------------------------------------------------- MUINT32 IspDrvImp::pipeCountInc(EIspDrvPipePath ePipePath) { LOG_INF("+,ePipePath(%d)",ePipePath); MBOOL Result = MTRUE; MINT32 ret = 0; ISP_REF_CNT_CTRL_STRUCT ref_cnt; MINT32 count; // Increase global pipe count. ref_cnt.ctrl = ISP_REF_CNT_INC; ref_cnt.id = ISP_REF_CNT_ID_GLOBAL_PIPE; ref_cnt.data_ptr = &count; ret = ioctl(mFd, ISP_REF_CNT_CTRL, &ref_cnt); if(ret < 0) { LOG_ERR("ISP_REF_CNT_INC fail(%d)[errno(%d):%s]",ret, errno, strerror(errno)); Result = MFALSE; } LOG_INF("-,Result(%d),count(%d)", Result, count); return Result; } MUINT32 IspDrvImp::pipeCountDec(EIspDrvPipePath ePipePath) { LOG_INF("+,ePipePath(%d)",ePipePath); MBOOL Result = MTRUE; MINT32 ret = 0; ISP_REF_CNT_CTRL_STRUCT ref_cnt; MINT32 count; ref_cnt.ctrl = ISP_REF_CNT_DEC_AND_RESET_IF_LAST_ONE; ref_cnt.id = ISP_REF_CNT_ID_GLOBAL_PIPE; ref_cnt.data_ptr = &count; ret = ioctl(mFd, ISP_REF_CNT_CTRL, &ref_cnt); if(ret < 0) { LOG_ERR("ISP_REF_CNT_DEC fail(%d)[errno(%d):%s]",ret, errno, strerror(errno)); Result = MFALSE; } LOG_INF("-,Result(%d),count(%d)", Result, count); return Result; } MBOOL IspDrvImp::updateCq0bRingBuf(void *pOBval) { MINT32 Ret = MTRUE; MUINT32 *pOB = (MUINT32 *)pOBval; // #define RTBC_GET_PA_FROM_VA(va,bva,bpa) ( ( (unsigned long)(va) - (unsigned long)(bva) ) + (unsigned long)(bpa) ) //LOG_DBG("size of CQ_RTBC_RING_ST is (%d) ",sizeof(CQ0B_RTBC_RING_ST_FRMB)); CQ0B_RTBC_RING_ST_FRMB *pcqrtbcring_va = (CQ0B_RTBC_RING_ST_FRMB*)IspDrv::mpIspCQDescriptorVirt[ISP_DRV_DESCRIPTOR_CQ0B]; CQ0B_RTBC_RING_ST_FRMB *pcqrtbcring_pa = (CQ0B_RTBC_RING_ST_FRMB*)IspDrv::mpIspCQDescriptorPhy[ISP_DRV_DESCRIPTOR_CQ0B]; LOG_DBG("[rtbc]va(0x%x),pa(0x%x)", pcqrtbcring_va, pcqrtbcring_pa); // pcqrtbcring_va->rtbc_ring_frmb.pNext_frmb = &pcqrtbcring_va->rtbc_ring_frmb; pcqrtbcring_va->rtbc_ring_frmb.next_pa_frmb = \ (MUINT32)RTBC_GET_PA_FROM_VA(pcqrtbcring_va->rtbc_ring_frmb.pNext_frmb,pcqrtbcring_va,pcqrtbcring_pa); //vir isp drv int realCQIdx = this->getRealCQIndex(ISP_DRV_CQ0B,0,ISP_DRV_P1_DEFAULT_DUPCQIDX); IspDrv *_targetVirDrv = this->getCQInstance(ISP_DRV_CQ0B); //ob gain ISP_WRITE_REG(_targetVirDrv, CAM_OBC_GAIN0, (*pOB),ISP_DRV_USER_ISPF); ISP_WRITE_REG(_targetVirDrv, CAM_OBC_GAIN1, (*pOB),ISP_DRV_USER_ISPF); ISP_WRITE_REG(_targetVirDrv, CAM_OBC_GAIN2, (*pOB),ISP_DRV_USER_ISPF); ISP_WRITE_REG(_targetVirDrv, CAM_OBC_GAIN3, (*pOB),ISP_DRV_USER_ISPF); //cmd pcqrtbcring_va->rtbc_ring_frmb.cq0b_rtbc_frmb.ob_frmb.inst = 0x00034510; //reg_4510 pcqrtbcring_va->rtbc_ring_frmb.cq0b_rtbc_frmb.ob_frmb.data_ptr_pa = \ (unsigned long)(&mpIspVirRegAddrPA[realCQIdx][0x00004510>>2]); // >>2 for MUINT32* pointer; //end pcqrtbcring_va->rtbc_ring_frmb.cq0b_rtbc_frmb.end_frmb.inst = 0xFC000000; pcqrtbcring_va->rtbc_ring_frmb.cq0b_rtbc_frmb.end_frmb.data_ptr_pa = 0; //CQ0B baseaddress LOG_DBG("CQ0B(0x%x)\n", this->getCQDescBufPhyAddr(ISP_DRV_CQ0B,0,ISP_DRV_P1_DEFAULT_DUPCQIDX)); ISP_WRITE_REG(this,CAM_CTL_CQ0B_BASEADDR,(unsigned long)this->getCQDescBufPhyAddr(ISP_DRV_CQ0B,0,ISP_DRV_P1_DEFAULT_DUPCQIDX),ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this, CAM_CTL_EN2_SET, CQ0B_EN_SET, 1,ISP_DRV_USER_ISPF); #if 0 { int *pdata = (int*)&pcqrtbcring_va->rtbc_ring_frmb; for (int i=0 ; i<(sizeof(CQ0B_RING_CMD_ST_FRMB)>>2) ; i++ ) { LOG_DBG("[rtbc][des] addr:(0x%08x) val:(0x%08x)",pdata+i,pdata[i]); } LOG_DBG("X"); } #endif return MTRUE; } #if defined(_rtbc_use_cq0c_) MBOOL IspDrvImp::_updateEnqCqRingBuf(void *pBuf_ctrl) { MINT32 Ret = MTRUE; // #define RTBC_GET_PA_FROM_VA(va,bva,bpa) ( ( (unsigned long)(va) - (unsigned long)(bva) ) + (unsigned long)(bpa) ) //LOG_DBG("size of CQ_RTBC_RING_ST is (%d) ",sizeof(CQ_RTBC_RING_ST_FRMB)); CQ_RTBC_RING_ST_FRMB *pcqrtbcring_va = (CQ_RTBC_RING_ST_FRMB*)IspDrv::mpIspCQDescriptorVirt[ISP_DRV_DESCRIPTOR_CQ0C]; CQ_RTBC_RING_ST_FRMB *pcqrtbcring_pa = (CQ_RTBC_RING_ST_FRMB*)IspDrv::mpIspCQDescriptorPhy[ISP_DRV_DESCRIPTOR_CQ0C]; //isp_reg_t* pIspPhyReg = (isp_reg_t*)getMMapRegAddr(); ISP_BUFFER_CTRL_STRUCT_FRMB *pbuf_ctrl = (ISP_BUFFER_CTRL_STRUCT_FRMB *)pBuf_ctrl; ISP_RT_BUF_INFO_STRUCT_FRMB *pbuf_info = (ISP_RT_BUF_INFO_STRUCT_FRMB *)pbuf_ctrl->data_ptr; ISP_RT_BUF_INFO_STRUCT_FRMB *pex_buf_info = (ISP_RT_BUF_INFO_STRUCT_FRMB *)pbuf_ctrl->ex_data_ptr; // MUINT32 i = 0; MUINT32 cam_tg_vf; MUINT32 size; cam_tg_vf = ISP_READ_REG_NOPROTECT(this, CAM_TG_VF_CON); LOG_DBG("[rtbc] VF(0x%x), mod_id=%d",cam_tg_vf, pbuf_ctrl->buf_id); //VF_EN==0 if ( 0 == (cam_tg_vf & 0x01) ) { // LOG_DBG("[rtbc]va(0x%x),pa(0x%x),ctrl(%d),dma(%d),PA(0x%x),o_size(%d),2o_size(%d)", \ pcqrtbcring_va, \ pcqrtbcring_pa, \ pbuf_ctrl->ctrl, \ pbuf_ctrl->buf_id, \ pbuf_info->base_pAddr, \ pcqrtbcring_va->imgo_ring_size_frmb,\ pcqrtbcring_va->img2o_ring_size_frmb); // if ( _imgo_ == pbuf_ctrl->buf_id) { i = pcqrtbcring_va->imgo_ring_size_frmb; } else if (_img2o_ == pbuf_ctrl->buf_id) { i = pcqrtbcring_va->img2o_ring_size_frmb; } else { LOG_ERR("ERROR:DMA id (%d)",pbuf_ctrl->buf_id); return MFALSE; } // pcqrtbcring_va->rtbc_ring_frmb[i].pNext_frmb = &pcqrtbcring_va->rtbc_ring_frmb[(i>0)?0:i]; pcqrtbcring_va->rtbc_ring_frmb[i].next_pa_frmb = \ (MUINT32)RTBC_GET_PA_FROM_VA(pcqrtbcring_va->rtbc_ring_frmb[i].pNext_frmb,pcqrtbcring_va,pcqrtbcring_pa); //imgo/ if ( 0 == pcqrtbcring_va->imgo_ring_size_frmb ) { pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_frmb.inst = ISP_DRV_CQ_DUMMY_WR_TOKEN; //0x00007300 } //imgo if ( _imgo_ == pbuf_ctrl->buf_id ) { pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_frmb.inst = 0x00004300; //reg_4300 pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb = pbuf_info->base_pAddr; // ISP_CQ_DUMMY_PA; // pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_buf_idx_frmb = pbuf_info->bufIdx; } pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_frmb.data_ptr_pa = \ (MUINT32)RTBC_GET_PA_FROM_VA(&pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb,pcqrtbcring_va,pcqrtbcring_pa); //img2o if ( 0 == pcqrtbcring_va->img2o_ring_size_frmb ) { pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_frmb.inst = ISP_DRV_CQ_DUMMY_WR_TOKEN; //0x00007320; //reg_7320 } // if (_img2o_ == pbuf_ctrl->buf_id ) { pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_frmb.inst = 0x00004320; //reg_4320 pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb = pbuf_info->base_pAddr; pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_buf_idx_frmb = pbuf_info->bufIdx; } pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_frmb.data_ptr_pa = \ (MUINT32)RTBC_GET_PA_FROM_VA(&pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb,pcqrtbcring_va,pcqrtbcring_pa); //cq0c pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.next_cq0ci_frmb.inst = 0x000040BC; //reg_40BC pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.next_cq0ci_frmb.data_ptr_pa = \ (MUINT32)RTBC_GET_PA_FROM_VA(&pcqrtbcring_va->rtbc_ring_frmb[i].next_pa_frmb,pcqrtbcring_va,pcqrtbcring_pa); //end pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.end_frmb.inst = 0xFC000000; pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.end_frmb.data_ptr_pa = 0; // if (i>0) { pcqrtbcring_va->rtbc_ring_frmb[i-1].pNext_frmb = &pcqrtbcring_va->rtbc_ring_frmb[i]; pcqrtbcring_va->rtbc_ring_frmb[i-1].next_pa_frmb = \ (MUINT32)RTBC_GET_PA_FROM_VA(&pcqrtbcring_va->rtbc_ring_frmb[i],pcqrtbcring_va,pcqrtbcring_pa); // pcqrtbcring_va->rtbc_ring_frmb[i-1].cq_rtbc_frmb.next_cq0ci_frmb.data_ptr_pa = \ (MUINT32)RTBC_GET_PA_FROM_VA(&pcqrtbcring_va->rtbc_ring_frmb[i-1].next_pa_frmb,pcqrtbcring_va,pcqrtbcring_pa); } // if ( _imgo_ == pbuf_ctrl->buf_id) { pcqrtbcring_va->imgo_ring_size_frmb++; size = pcqrtbcring_va->imgo_ring_size_frmb; // ISP_WRITE_BITS(this,CAM_CTL_IMGO_FBC,FB_NUM,size,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this,CAM_CTL_IMGO_FBC,FBC_EN,1,ISP_DRV_USER_ISPF); } else if ( _img2o_ == pbuf_ctrl->buf_id) { pcqrtbcring_va->img2o_ring_size_frmb++; size = pcqrtbcring_va->img2o_ring_size_frmb; // ISP_WRITE_BITS(this,CAM_CTL_IMG2O_FBC,FB_NUM,size,ISP_DRV_USER_ISPF); ISP_WRITE_BITS(this,CAM_CTL_IMG2O_FBC,FBC_EN,1,ISP_DRV_USER_ISPF); } // if ( _imgo_ == pbuf_ctrl->buf_id || _img2o_ == pbuf_ctrl->buf_id) { //LOG_INF("[rtbc] Update CAM_CTL_CQ0C_BASEADDR"); ISP_WRITE_REG(this,CAM_CTL_CQ0C_BASEADDR,(unsigned long)this->getCQDescBufPhyAddr(ISP_DRV_CQ0C,0,ISP_DRV_P1_DEFAULT_DUPCQIDX) + ((1==size)?0:sizeof(CQ_RING_CMD_ST_FRMB)),ISP_DRV_USER_ISPF); } // LOG_DBG("[rtbc]imgo_sz(%d),img2o_sz(%d), BufIdx=0x%x",pcqrtbcring_va->imgo_ring_size_frmb,pcqrtbcring_va->img2o_ring_size_frmb,pbuf_info->bufIdx); // { int *pdata = (int*)&pcqrtbcring_va->rtbc_ring_frmb[0]; for ( i=0 ; i<(sizeof(CQ_RING_CMD_ST_FRMB)>>2)*size ; i++ ) { LOG_DBG("[rtbc][des] addr:(0x%08x) val:(0x%08x)",pdata+i,pdata[i]); } } } //VF_EN==1 else { if ( pex_buf_info ) { MUINT32 findTarget = 0; LOG_DBG("[rtbc]va(0x%x),pa(0x%x),ctrl(%d),dma(%d),PA(0x%x),o_size(%d),2o_size(%d)", \ pcqrtbcring_va, \ pcqrtbcring_pa, \ pbuf_ctrl->ctrl, \ pbuf_ctrl->buf_id, \ pbuf_info->base_pAddr, \ pcqrtbcring_va->imgo_ring_size_frmb,\ pcqrtbcring_va->img2o_ring_size_frmb); // i = 0; if ( _imgo_ == pbuf_ctrl->buf_id) { // if (pex_buf_info->bufIdx != 0xFFFF) { //LOG_INF("[rtbc]ByIdx: IMGO"); //replace the specific buffer with same bufIdx for ( i=0 ; i<pcqrtbcring_va->imgo_ring_size_frmb ; i++ ) { if ( pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_buf_idx_frmb == pbuf_info->bufIdx) { //LOG_INF("[rtbc]ByIdx: idx(%d) old/new imgo buffer(0x%x/0x%x)",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb,pex_buf_info->base_pAddr); pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb = pex_buf_info->base_pAddr; findTarget = 1; break; } } } else { //replace the specific buffer with same buf Address //LOG_INF("[rtbc]ByAddr: IMGO"); for ( i=0 ; i<pcqrtbcring_va->imgo_ring_size_frmb ; i++ ) { if ( pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb == pbuf_info->base_pAddr ) { //LOG_INF("[rtbc]ByAddr: idx(%d) old/new imgo buffer(0x%x/0x%x)",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb,pex_buf_info->base_pAddr); pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_base_pAddr_frmb = pex_buf_info->base_pAddr; findTarget = 1; break; } } } if (!findTarget) { LOG_ERR("[rtbc]error exIMGO-Fail. BufIdx(0x%x/0x%x) new imgo buffer(0x%x)",\ pbuf_info->bufIdx, pex_buf_info->bufIdx,pex_buf_info->base_pAddr); for ( i=0 ; i<pcqrtbcring_va->imgo_ring_size_frmb ; i++ ) { LOG_DBG("[rtbc][%d] old/new BufIdx(%d/%d) ",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.imgo_buf_idx_frmb, pbuf_info->bufIdx); } } } else if (_img2o_ == pbuf_ctrl->buf_id) { // if (pex_buf_info->bufIdx != 0xFFFF) { //replace the specific buffer with same bufIdx //LOG_INF("[rtbc]ByIdx: IMG2O"); for ( i=0 ; i<pcqrtbcring_va->img2o_ring_size_frmb ; i++ ) { //LOG_INF("[rtbc]ByIdx:[%d] old/new BufIdx(%d/%d) ",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_buf_idx_frmb, pbuf_info->bufIdx); if ( pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_buf_idx_frmb == pbuf_info->bufIdx ) { //LOG_INF("[rtbc]ByIdx: idx(%d) old/new img2o buffer(0x%x/0x%x)",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb, pex_buf_info->base_pAddr); pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb = pex_buf_info->base_pAddr; findTarget = 1; break; } } } else { //replace the specific buffer with same buf Address //LOG_INF("[rtbc]ByAddr: IMG2O"); for ( i=0 ; i<pcqrtbcring_va->img2o_ring_size_frmb ; i++ ) { if ( pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb == pbuf_info->base_pAddr ) { //LOG_INF("[rtbc]ByAddr: idx(%d) old/new img2o buffer(0x%x/0x%x)",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb, pex_buf_info->base_pAddr); pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb = pex_buf_info->base_pAddr; findTarget = 1; break; } } } if (!findTarget) { LOG_ERR("[rtbc]error exIMG2O-Fail. Bufidx(0x%x/0x%x) old/new img2o buffer(0x%x/0x%x)",\ pbuf_info->bufIdx,pex_buf_info->bufIdx,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_base_pAddr_frmb,pex_buf_info->base_pAddr); for ( i=0 ; i<pcqrtbcring_va->img2o_ring_size_frmb ; i++ ) { LOG_DBG("[rtbc]ByIdx:[%d] old/new BufIdx(%d/%d) ",i,pcqrtbcring_va->rtbc_ring_frmb[i].cq_rtbc_frmb.img2o_buf_idx_frmb, pbuf_info->bufIdx); } } } else { LOG_ERR("ERROR:DMA id (%d)",pbuf_ctrl->buf_id); return MFALSE; } } else { // } } return MTRUE; } MBOOL IspDrvImp::cqRingBuf(void *pBuf_ctrl) { MINT32 Ret; // ISP_BUFFER_CTRL_STRUCT_FRMB *pbuf_ctrl = (ISP_BUFFER_CTRL_STRUCT_FRMB *)pBuf_ctrl; /*LOG_INF("[rtbc]pcqrtbcring_va/pa(0x%x/0x%x),ctrl(%d),dma(%d),pa(0x%x),imgor_size(%d),img2or_size(%d)", \ pcqrtbcring_va, \ pcqrtbcring_pa, \ pbuf_ctrl->ctrl, \ pbuf_ctrl->buf_id, \ pbuf_info->base_pAddr, \ pcqrtbcring_va->imgo_ring_size,\ pcqrtbcring_va->img2o_ring_size);*/ // //LOG_INF("[rtbc](%d)",sizeof(CQ_RING_CMD_ST_FRMB)); // switch( pbuf_ctrl->ctrl ) { // case ISP_RT_BUF_CTRL_ENQUE_IMD_FRMB: case ISP_RT_BUF_CTRL_ENQUE_FRMB: Ret = _updateEnqCqRingBuf(pBuf_ctrl); // break; #if 0 case ISP_RT_BUF_CTRL_EXCHANGE_ENQUE_FRMB: // #if 0 cam_tg_vf = ISP_READ_REG_NOPROTECT(this, CAM_TG_VF_CON); cam_tg2_vf = ISP_READ_REG_NOPROTECT(this, CAM_TG2_VF_CON); #else //fpga ldvt cam_tg_vf = ISP_READ_REG_NOPROTECT(this, CAM_TG_VF_CON); cam_tg2_vf = ISP_READ_REG_NOPROTECT(this, CAM_TG2_VF_CON); #endif //VF on line if ( (cam_tg_vf & 0x01) || (cam_tg2_vf & 0x01) ) { LOG_INF("[rtbc]exchange 1st buf. by 2nd buf. and enque it(0x%x)",pex_buf_info); #if 0 if ( pex_buf_info ) { // if ( _imgo_ == pbuf_ctrl->buf_id ) { // for ( i=0 ; i<pcqrtbcring_va->imgo_ring_size ; i++ ) { if ( pcqrtbcring_va->rtbc_ring[i].cq_rtbc.imgo_base_pAddr == pbuf_info->base_pAddr ) { LOG_INF("[rtbc]old(%d) imgo buffer(0x%x)",i,pcqrtbcring_va->rtbc_ring[i].cq_rtbc.imgo_base_pAddr); pcqrtbcring_va->rtbc_ring[i].cq_rtbc.imgo_base_pAddr = pex_buf_info->base_pAddr; LOG_INF("new(%d) imgo buffer(0x%x)",i,pcqrtbcring_va->rtbc_ring[i].cq_rtbc.imgo_base_pAddr); break; } } } else if (_rrzo_ == pbuf_ctrl->buf_id) { // for ( i=0 ; i<pcqrtbcring_va->rrzo_ring_size ; i++ ) { if ( pcqrtbcring_va->rtbc_ring[i].cq_rtbc.rrzo_base_pAddr == pbuf_info->base_pAddr ) { LOG_INF("[rtbc]old(%d) img2o buffer(0x%x)",i,pcqrtbcring_va->rtbc_ring[i].cq_rtbc.rrzo_base_pAddr); pcqrtbcring_va->rtbc_ring[i].cq_rtbc.rrzo_base_pAddr = pex_buf_info->base_pAddr; LOG_INF("new(%d) img2o buffer(0x%x)",i,pcqrtbcring_va->rtbc_ring[i].cq_rtbc.rrzo_base_pAddr); break; } } } else { LOG_ERR("ERROR:DMA id (%d)",pbuf_ctrl->buf_id); return MFALSE; } } else { // } #endif } break; #endif case ISP_RT_BUF_CTRL_CLEAR_FRMB: //reset cq0c all 0 for rtbc if (sizeof(CQ_RTBC_RING_ST_FRMB) <= sizeof(mIspCQDescInit)) { if ((_imgo_ == pbuf_ctrl->buf_id)||(_img2o_ == pbuf_ctrl->buf_id)) { LOG_DBG("[PIP]Clr P1 CQ0C"); memset((MUINT8*)mpIspCQDescriptorVirt[ISP_DRV_DESCRIPTOR_CQ0C],0,sizeof(CQ_RTBC_RING_ST_FRMB)); } } else { LOG_ERR("rtbc data exceed buffer size(%d)>(%d)",sizeof(CQ_RTBC_RING_ST_FRMB),sizeof(mIspCQDescInit)); } break; default: //LOG_ERR("ERROR:ctrl id(%d)",pbuf_ctrl->ctrl); break; } //reset cq0c all 0 for rtbc //memset((MUINT8*)mpIspCQDescriptorVirt[ISP_DRV_DESCRIPTOR_CQ0C],0,sizeof(CQ_RTBC_RING_ST_FRMB)); return MTRUE; } #endif MBOOL IspDrvImp::ISPWakeLockCtrl(MBOOL WakeLockEn) { MBOOL ret = MTRUE; MUINT32 wakelock_ctrl = WakeLockEn; ret = ioctl(mFd, ISP_WAKELOCK_CTRL, &wakelock_ctrl); if (ret < 0) { LOG_ERR("ISP_WAKELOCK_CTRL fail(%d).", ret); return MFALSE; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::bypassTuningQue( ESoftwareScenario softScenario, MINT32 magicNum ) { Mutex::Autolock lock(tuningQueueIdxLock); // MINT32 currQueueIdx = -1; MINT32 nextQueueIdx = -1; ISP_DRV_CQ_ENUM cq; ISP_DRV_P2_CQ_ENUM p2Cq; MBOOL ret = MTRUE; // LOG_INF("+,softScenario(%d),magicNum(0x%x)",softScenario,magicNum); // getP2cqInfoFromScenario(softScenario, p2Cq); if((mTuningQueIdx[p2Cq].curWriteIdx>=ISP_TUNING_QUEUE_NUM)||(mTuningQueIdx[p2Cq].curWriteIdx<0)){ LOG_WRN("[Warning]tuning queue index(%d) error",mTuningQueIdx[p2Cq].curWriteIdx); mTuningQueIdx[p2Cq].curWriteIdx = 0; } currQueueIdx = mTuningQueIdx[p2Cq].curWriteIdx; // // 1.set magic num for tuning queue mTuningQueInf[p2Cq][currQueueIdx].magicNum = magicNum; // // 2.set null point for current tuning queue mTuningQueIdx[p2Cq].pCurWriteTuningQue = NULL; // 3. set update function bit for tuning Queue mTuningQueInf[p2Cq][currQueueIdx].eUpdateFuncBit = eIspTuningMgrFunc_Null; nextQueueIdx = GET_NEXT_TUNING_QUEUE_IDX(currQueueIdx); LOG_INF("p2Cq(%d),pre-curWriteIdx(%d),next-curWriteIdx(%d)",p2Cq,mTuningQueIdx[p2Cq].curWriteIdx,nextQueueIdx); mTuningQueIdx[p2Cq].curWriteIdx = nextQueueIdx; return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::deTuningQueByCq( ETuningQueAccessPath path, ISP_DRV_CQ_ENUM eCq, MINT32 magicNum ) { Mutex::Autolock lock(tuningQueueIdxLock); MBOOL ret = MTRUE; MINT32 currQueueIdx = ISP_TUNING_INIT_IDX; MINT32 tarQueueIdx = ISP_TUNING_INIT_IDX; ISP_DRV_P2_CQ_ENUM p2Cq; isp_reg_t* pIspRegMap; MUINT32 camCtlEn1, camCtlEn2, camCtlDmaEn; MUINT32 addrOffset, moduleSize; MUINT32 i, j, k; MINT32 checkNum; //for tuning bypass issue in initial stage // mapCqToP2Cq(eCq, p2Cq); LOG_INF("+,path(%d),eCq(%d),p2Cq(%d),magic#(0x%x),curWIdx(%d)", \ path,eCq,p2Cq,magicNum,mTuningQueIdx[p2Cq].curWriteIdx); // if(path == eTuningQueAccessPath_featureio){ if((mTuningQueIdx[p2Cq].curWriteIdx>=ISP_TUNING_QUEUE_NUM)||(mTuningQueIdx[p2Cq].curWriteIdx<0)){ LOG_WRN("[Init]init tuningQue curWriteIdx index(%d)",mTuningQueIdx[p2Cq].curWriteIdx); mTuningQueIdx[p2Cq].curWriteIdx = 0; } currQueueIdx = mTuningQueIdx[p2Cq].curWriteIdx; // // 1.set magic num for tuning queue mTuningQueInf[p2Cq][currQueueIdx].magicNum = magicNum; // // 2.update current tuning queue point of feature mTuningQueIdx[p2Cq].pCurWriteTuningQue = mTuningQueInf[p2Cq][currQueueIdx].pTuningQue; LOG_DBG("p2Cq(%d),currQueueIdx(%d),pTuningQue(0x%x)",p2Cq,currQueueIdx,mTuningQueInf[p2Cq][currQueueIdx].pTuningQue); } else if(path == eTuningQueAccessPath_imageio_P1) { if(mTuningQueIdx[p2Cq].isInitP1 == MFALSE){ checkNum = mTuningQueIdx[p2Cq].curWriteIdx; if(checkNum <= 0) { LOG_ERR("[Error]P1 TuningMgr not ready yet! checkNum(%d)",checkNum); ret = MFALSE; goto EXIT; } } else { checkNum = 1; } LOG_DBG("checkNum(%d),curWriteIdx(%d),isInitP1(%d)",checkNum,mTuningQueIdx[p2Cq].curWriteIdx,mTuningQueIdx[p2Cq].isInitP1); for (k=0;k<(MUINT32)checkNum;k++){ if (mTuningQueIdx[p2Cq].isInitP1==MTRUE){ // [1]backward search the tuning que with magic# if(searchTuningQue(p2Cq, magicNum, currQueueIdx) != MTRUE){ LOG_ERR("[Error]curReadP1Idx search error"); ret = MFALSE; goto EXIT; } mTuningQueIdx[p2Cq].curReadP1Idx = currQueueIdx; } else { MUINT32 searchTar; LOG_INF("k(%d)",k); // [1] search the tuning que by order #if 0 if(((MUINT32)checkNum == k+1)){ // get currQueueIdx mTuningQueIdx[p2Cq].isInitP1 = MTRUE; LOG_INF("[P1]search ending, and Exit, k(%d)",k); if(k != 0) break; } currQueueIdx = (MINT32)k; #else searchTar = ((mTuningQueIdx[p2Cq].curWriteIdx-1)>=(k+1))?(k+1):(mTuningQueIdx[p2Cq].curWriteIdx-1); // if(orderSearchTuningQue(p2Cq, magicNum, k, (mTuningQueIdx[p2Cq].curWriteIdx-1), currQueueIdx) != MTRUE){ // get currQueueIdx if(orderSearchTuningQue(p2Cq, magicNum, k, searchTar, currQueueIdx) != MTRUE){ // get currQueueIdx mTuningQueIdx[p2Cq].isInitP1 = MTRUE; LOG_INF("search ending, and Exit,(%d-%d)",k,searchTar); break; } #endif mTuningQueIdx[p2Cq].curReadP1Idx = currQueueIdx; } // // [2]set the real pCurReadP1TuningQue mTuningQueIdx[p2Cq].pCurReadP1TuningQue = mTuningQueIdx[p2Cq].keepP1Que.pTuningQue; // // [3]update eCurReadP1UpdateFuncBit & keepP1UpdateFuncBit mTuningQueIdx[p2Cq].eCurReadP1UpdateFuncBit = mTuningQueInf[p2Cq][currQueueIdx].eUpdateFuncBit; mTuningQueIdx[p2Cq].keepP1UpdateFuncBit = (EIspTuningMgrFunc) ((MINT32)mTuningQueIdx[p2Cq].keepP1UpdateFuncBit | (MINT32)mTuningQueInf[p2Cq][currQueueIdx].eUpdateFuncBit); // // [4]update the current queue info. pIspRegMap = (isp_reg_t*)mTuningQueInf[p2Cq][currQueueIdx].pTuningQue; if (NULL == pIspRegMap){ LOG_ERR("[Error]pIspRegMap NULL"); ret = MFALSE; goto EXIT; } camCtlEn1 = pIspRegMap->CAM_CTL_EN1.Raw; camCtlEn2 = pIspRegMap->CAM_CTL_EN2.Raw; camCtlDmaEn = pIspRegMap->CAM_CTL_DMA_EN.Raw; LOG_DBG("camCtlEn1(0x%x),camCtlEn2(0x%x),camCtlDmaEn(%d),keepP1UpdateFuncBit(0x%x),eUpdateFuncBit(0x%x)",camCtlEn1,camCtlEn2,camCtlDmaEn,mTuningQueIdx[p2Cq].keepP1UpdateFuncBit,mTuningQueInf[p2Cq][currQueueIdx].eUpdateFuncBit); // for(i=0;i<eIspTuningMgrFuncBit_Num;i++){ if((1<<gIspTuningFuncBitMapp[i].eTuningFuncBit) & mTuningQueIdx[p2Cq].eCurReadP1UpdateFuncBit){ switch(gIspTuningFuncBitMapp[i].eTuningCtlByte){ case eTuningCtlByte_P1: if(gIspTuningFuncBitMapp[i].camCtlEn1 != -1){ // update for keepReadP1CtlEn1 mTuningQueIdx[p2Cq].keepReadP1CtlEn1 = ((~(1<<gIspTuningFuncBitMapp[i].camCtlEn1))&mTuningQueIdx[p2Cq].keepReadP1CtlEn1)| (camCtlEn1&(1<<gIspTuningFuncBitMapp[i].camCtlEn1)); // update keepP1Que if(gIspTuningFuncBitMapp[i].eTuningCqFunc1 != CAM_DUMMY_){ getCqModuleInf(gIspTuningFuncBitMapp[i].eTuningCqFunc1,addrOffset,moduleSize); LOG_DBG("[1]P1:addrOffset(0x%08x),moduleSize(%d)",addrOffset,moduleSize); for(j=0;j<moduleSize;j++){ mTuningQueIdx[p2Cq].keepP1Que.pTuningQue[addrOffset>>2] = mTuningQueInf[p2Cq][currQueueIdx].pTuningQue[addrOffset>>2]; addrOffset += 4; } } if(gIspTuningFuncBitMapp[i].eTuningCqFunc2 != CAM_DUMMY_){ getCqModuleInf(gIspTuningFuncBitMapp[i].eTuningCqFunc2,addrOffset,moduleSize); LOG_DBG("[2]P1:addrOffset(0x%08x),moduleSize(%d)",addrOffset,moduleSize); for(j=0;j<moduleSize;j++){ mTuningQueIdx[p2Cq].keepP1Que.pTuningQue[addrOffset>>2] = mTuningQueInf[p2Cq][currQueueIdx].pTuningQue[addrOffset>>2]; addrOffset += 4; } } } else { LOG_ERR("[Error]gIspTuningFuncBitMapp table error i(%d) = -1",i); ret = MFALSE; goto EXIT; } // // update for keepReadP1CtlEn2 if(gIspTuningFuncBitMapp[i].camCtlEn2 != -1){ mTuningQueIdx[p2Cq].keepReadP1CtlEn2 = ((~(1<<gIspTuningFuncBitMapp[i].camCtlEn2))&mTuningQueIdx[p2Cq].keepReadP1CtlEn2)| (camCtlEn2&(1<<gIspTuningFuncBitMapp[i].camCtlEn2)); } // // update for keepReadP1CtlDmaEn if(gIspTuningFuncBitMapp[i].camCtlDmaEn != -1){ mTuningQueIdx[p2Cq].keepReadP1CtlDmaEn = ((~(1<<gIspTuningFuncBitMapp[i].camCtlDmaEn))&mTuningQueIdx[p2Cq].keepReadP1CtlDmaEn)| (camCtlDmaEn&(1<<gIspTuningFuncBitMapp[i].camCtlDmaEn)); } break; case eTuningCtlByte_P1D: case eTuningCtlByte_P2: default: LOG_ERR("[Error]Not support this path(%d)",gIspTuningFuncBitMapp[i].eTuningCtlByte); /* do nothing */ break; }; } } } } else { LOG_ERR("[Error]Not support this path(%d)",path); ret = MFALSE; goto EXIT; } EXIT: LOG_DBG("-,"); return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::deTuningQue( ETuningQueAccessPath path, ESoftwareScenario softScenario, MINT32 magicNum ) { MBOOL ret; ISP_DRV_CQ_ENUM cq; // LOG_DBG("+,path(%d),softScenario(%d),magicNum(0x%x)",path,softScenario,magicNum); // getCqInfoFromScenario(softScenario, cq); ret = deTuningQueByCq(path, cq, magicNum); return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::enTuningQueByCq( ETuningQueAccessPath path, ISP_DRV_CQ_ENUM eCq, MINT32 magicNum, EIspTuningMgrFunc updateFuncBit ) { Mutex::Autolock lock(tuningQueueIdxLock); MBOOL ret = MTRUE; ISP_DRV_P2_CQ_ENUM p2Cq; MINT32 currQueueIdx = -1; MINT32 nextQueueIdx = -1; // // mapCqToP2Cq(eCq, p2Cq); LOG_DBG("path(%d),eCq(%d),p2Cq(%d),magicNum(0x%x),updateFuncBit(0x%08x)",path,eCq,p2Cq,magicNum,updateFuncBit); // if(path == eTuningQueAccessPath_featureio){ if((mTuningQueIdx[p2Cq].curWriteIdx>=ISP_TUNING_QUEUE_NUM)||(mTuningQueIdx[p2Cq].curWriteIdx<0)){ LOG_WRN("[Error]tuning queue index(%d) error",mTuningQueIdx[p2Cq].curWriteIdx); mTuningQueIdx[p2Cq].curWriteIdx = 0; ret = MFALSE; goto EXIT; } currQueueIdx = mTuningQueIdx[p2Cq].curWriteIdx; LOG_DBG("currQueueIdx(%d)",currQueueIdx); // set update function bit for tuning Queue mTuningQueInf[p2Cq][currQueueIdx].eUpdateFuncBit = updateFuncBit; nextQueueIdx = GET_NEXT_TUNING_QUEUE_IDX(currQueueIdx); if(nextQueueIdx==mTuningQueIdx[p2Cq].curReadP1Idx){ LOG_ERR("[Error]multi-access the same index==>nextQueueIdx(%d),curReadP1Idx(%d)", nextQueueIdx,mTuningQueIdx[p2Cq].curReadP1Idx); ret = MFALSE; goto EXIT; } mTuningQueIdx[p2Cq].curWriteIdx = nextQueueIdx; } else if(path == eTuningQueAccessPath_imageio_P1) { //release p1 tuning queue mTuningQueIdx[p2Cq].pCurReadP1TuningQue = NULL; mTuningQueIdx[p2Cq].curReadP1Idx = -1; } else { LOG_ERR("[Error]Not support this path(%d)",path); ret = MFALSE; goto EXIT; } EXIT: return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::enTuningQue( ETuningQueAccessPath path, ESoftwareScenario softScenario, MINT32 magicNum, EIspTuningMgrFunc updateFuncBit ) { MBOOL ret = MTRUE; ISP_DRV_CQ_ENUM cq; // LOG_DBG("path(%d),softScenario(%d),magicNum(0x%x)",path,softScenario,magicNum); // getCqInfoFromScenario(softScenario, cq); ret = enTuningQueByCq(path, cq, magicNum, updateFuncBit); return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::setP2TuningStatus( ISP_DRV_CQ_ENUM cq, MBOOL en) { Mutex::Autolock lock(tuningQueueIdxLock); // en = MFALSE;//kk test // ISP_DRV_P2_CQ_ENUM p2Cq; mapCqToP2Cq(cq, p2Cq); LOG_INF("p2Cq(%d),en(%d)",p2Cq,en); mTuningQueIdx[p2Cq].isApplyTuning = en; return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::getP2TuningStatus(ISP_DRV_CQ_ENUM cq) { Mutex::Autolock lock(tuningQueueIdxLock); // ISP_DRV_P2_CQ_ENUM p2Cq; mapCqToP2Cq(cq, p2Cq); LOG_DBG("p2Cq(%d),isApplyTuning(%d)",p2Cq,mTuningQueIdx[p2Cq].isApplyTuning); return mTuningQueIdx[p2Cq].isApplyTuning; } //----------------------------------------------------------------------------- MUINT32 IspDrvImp::getTuningUpdateFuncBit( ETuningQueAccessPath ePath, MINT32 cq, MUINT32 drvScenario, MBOOL isV3) { Mutex::Autolock lock(tuningQueueIdxLock); ISP_DRV_P2_CQ_ENUM p2Cq; MUINT32 mApplyTuningFuncBit; // if(isV3) { mapCqToP2Cq((ISP_DRV_CQ_ENUM)cq, p2Cq); if(ePath == eTuningQueAccessPath_imageio_P2){ switch (drvScenario){ case NSImageio_FrmB::NSIspio_FrmB::eDrvScenario_VSS: case NSImageio_FrmB::NSIspio_FrmB::eDrvScenario_CC: default: mApplyTuningFuncBit = (eIspTuningMgrFunc_Pgn|eIspTuningMgrFunc_Cfa|eIspTuningMgrFunc_Ccl|eIspTuningMgrFunc_G2g| eIspTuningMgrFunc_G2c|eIspTuningMgrFunc_Nbc|eIspTuningMgrFunc_Seee|eIspTuningMgrFunc_Sl2| eIspTuningMgrFunc_Ggmrb|eIspTuningMgrFunc_Ggmg|eIspTuningMgrFunc_Pca); break; case NSImageio_FrmB::NSIspio_FrmB::eDrvScenario_IP: mApplyTuningFuncBit = (eIspTuningMgrFunc_Obc|eIspTuningMgrFunc_Lsc|eIspTuningMgrFunc_Bnr| eIspTuningMgrFunc_Pgn|eIspTuningMgrFunc_Cfa|eIspTuningMgrFunc_Ccl|eIspTuningMgrFunc_G2g| eIspTuningMgrFunc_G2c|eIspTuningMgrFunc_Nbc|eIspTuningMgrFunc_Seee|eIspTuningMgrFunc_Sl2| eIspTuningMgrFunc_Ggmrb|eIspTuningMgrFunc_Ggmg|eIspTuningMgrFunc_Pca); break; }; } else if(ePath == eTuningQueAccessPath_imageio_P1){ mApplyTuningFuncBit = mTuningQueIdx[p2Cq].keepP1UpdateFuncBit; } else { LOG_ERR("[Error]Not support this path(%d)",ePath); mApplyTuningFuncBit = 0; } } else { LOG_ERR("[Error]Not support this function in V1"); } return mApplyTuningFuncBit; } //----------------------------------------------------------------------------- MUINT32* IspDrvImp::getTuningBuf( ETuningQueAccessPath ePath, MINT32 cq) { Mutex::Autolock lock(tuningQueueIdxLock); MUINT32* pBuf=NULL; ISP_DRV_P2_CQ_ENUM p2Cq; // mapCqToP2Cq((ISP_DRV_CQ_ENUM)cq, p2Cq); LOG_DBG("+,ePath(%d),p2Cq(%d)",ePath, p2Cq); // if(ePath == eTuningQueAccessPath_imageio_P1) { pBuf = mTuningQueIdx[p2Cq].pCurReadP1TuningQue; } else if(ePath == eTuningQueAccessPath_featureio){ pBuf = mTuningQueIdx[p2Cq].pCurWriteTuningQue; } else { LOG_ERR("[Error]Not support this path(%d)",ePath); } // if(pBuf==NULL){ LOG_WRN("[warning]pBuf=NULL,p2Cq(%d)",p2Cq); } return pBuf; } //----------------------------------------------------------------------------- MUINT32 IspDrvImp::getTuningTop( ETuningQueAccessPath ePath, ETuningTopEn top, MINT32 cq, MUINT32 magicNum) { Mutex::Autolock lock(tuningQueueIdxLock); MUINT32 en = 0; ISP_DRV_P2_CQ_ENUM p2Cq; MBOOL isPreview = MTRUE; // mapCqToP2Cq((ISP_DRV_CQ_ENUM)cq, p2Cq); LOG_DBG("+"); if(ePath == eTuningQueAccessPath_imageio_P1) { switch(top){ case eTuningTopEn1: en = mTuningQueIdx[p2Cq].keepReadP1CtlEn1; break; case eTuningTopEn2: en = mTuningQueIdx[p2Cq].keepReadP1CtlEn2; break; case eTuningTopDmaEn: en = mTuningQueIdx[p2Cq].keepReadP1CtlDmaEn; break; default: LOG_ERR("[Error]Not support this top(%d) for path(%d)",(MUINT32)top,ePath); break; } } else { LOG_ERR("[Error]Not support this path(%d)",ePath); } LOG_DBG("-,ePath(%d),top(%d),cq(%d),p2Cq(%d),magicNum(0x%x),en(0x%08x)",ePath,top, cq,p2Cq,magicNum,en); return en; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::searchTuningQue( ISP_DRV_P2_CQ_ENUM p2Cq, MINT32 magicNum, MINT32 &getQueIdx ) { MBOOL ret = MTRUE; MUINT32 searchCnt; MINT32 currQueueIdx = -1; MINT32 prevQueueIdx = -1; LOG_DBG("+,p2Cq(%d),magicNum(0x%x)",p2Cq,magicNum); //backward search if((mTuningQueIdx[p2Cq].curWriteIdx<ISP_TUNING_QUEUE_NUM)&&(mTuningQueIdx[p2Cq].curWriteIdx>=0)){ searchCnt = 0; currQueueIdx = mTuningQueIdx[p2Cq].curWriteIdx; do{ searchCnt++; prevQueueIdx = GET_PREV_TUNING_QUEUE_IDX(currQueueIdx); //LOG_INF("searchCnt(%d),currQueueIdx(%d),prevQueueIdx(%d),pre_magicNum(0x%x)",searchCnt,currQueueIdx,prevQueueIdx,mTuningQueInf[p2Cq][prevQueueIdx].magicNum); currQueueIdx = prevQueueIdx; }while((mTuningQueInf[p2Cq][currQueueIdx].magicNum != magicNum)&&(searchCnt<ISP_TUNING_QUEUE_NUM)); if(searchCnt>=ISP_TUNING_QUEUE_NUM){ LOG_ERR("[Error]search fail, magic#(0x%x)/curWriteIdx(0x%x)-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x-0x%x", magicNum, mTuningQueIdx[p2Cq].curWriteIdx, mTuningQueInf[p2Cq][0].magicNum,mTuningQueInf[p2Cq][1].magicNum,mTuningQueInf[p2Cq][2].magicNum, mTuningQueInf[p2Cq][3].magicNum,mTuningQueInf[p2Cq][4].magicNum,mTuningQueInf[p2Cq][5].magicNum, mTuningQueInf[p2Cq][6].magicNum,mTuningQueInf[p2Cq][7].magicNum,mTuningQueInf[p2Cq][8].magicNum, mTuningQueInf[p2Cq][9].magicNum,mTuningQueInf[p2Cq][10].magicNum,mTuningQueInf[p2Cq][11].magicNum, mTuningQueInf[p2Cq][12].magicNum,mTuningQueInf[p2Cq][13].magicNum,mTuningQueInf[p2Cq][14].magicNum, mTuningQueInf[p2Cq][15].magicNum,mTuningQueInf[p2Cq][16].magicNum); ret = MFALSE; } else { getQueIdx = currQueueIdx; } } else { LOG_ERR("[Error]tuningQue curWriteIdx(%d) not ready",mTuningQueIdx[p2Cq].curWriteIdx); ret = MFALSE; } LOG_DBG("-,getQueIdx(%d),curWriteIdx(%d)",getQueIdx,mTuningQueIdx[p2Cq].curWriteIdx); return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::orderSearchTuningQue( ISP_DRV_P2_CQ_ENUM p2Cq, MINT32 magicNum, MUINT32 start, MUINT32 end, MINT32 &getQueIdx ) { MBOOL ret = MTRUE; MUINT32 searchCnt; MINT32 currQueueIdx = -1; MINT32 prevQueueIdx = -1; MUINT32 i; LOG_INF("+,p2Cq(%d),magicNum(0x%x),start(%d),end(%d)",p2Cq,magicNum,start,end); if(start > end){ getQueIdx = -1; LOG_ERR("[Error]search range error, start(%d),end(%d)",start,end); ret = MFALSE; goto EXIT; } //order search for (i=start;i<=end;i++){ if (mTuningQueInf[p2Cq][i].magicNum==magicNum){ getQueIdx = i; break; } } if(i > end){ getQueIdx = -1; LOG_WRN("[warning]cant seach the identical magic#(0x%x),start(%d),end(%d)",magicNum,start,end); ret = MFALSE; } EXIT: LOG_INF("-,getQueIdx(%d),curWriteIdx(%d)",getQueIdx,mTuningQueIdx[p2Cq].curWriteIdx); return ret; } MBOOL IspDrvImp::getTuningTpipeFiled( ISP_DRV_P2_CQ_ENUM p2Cq, stIspTuningTpipeFieldInf &pTuningField ) { Mutex::Autolock lock(tuningQueueIdxLock); MBOOL ret = MTRUE; memcpy((char*)&pTuningField.sl2, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.sl2, sizeof(ISP_TPIPE_CONFIG_SL2_STRUCT)); memcpy((char*)&pTuningField.cfa, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.cfa, sizeof(ISP_TPIPE_CONFIG_CFA_STRUCT)); memcpy((char*)&pTuningField.nbc, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.nbc, sizeof(ISP_TPIPE_CONFIG_NBC_STRUCT)); memcpy((char*)&pTuningField.seee, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.seee, sizeof(ISP_TPIPE_CONFIG_SEEE_STRUCT)); memcpy((char*)&pTuningField.lce, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.lce, sizeof(ISP_TPIPE_CONFIG_LCE_STRUCT)); memcpy((char*)&pTuningField.bnr, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.bnr, sizeof(ISP_TPIPE_CONFIG_BNR_STRUCT)); memcpy((char*)&pTuningField.lsc, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.lsc, sizeof(ISP_TPIPE_CONFIG_LSC_STRUCT)); memcpy((char*)&pTuningField.lcei, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.lcei, sizeof(ISP_TPIPE_CONFIG_LCEI_STRUCT)); memcpy((char*)&pTuningField.lsci, (char*)&mTuningQueIdx[p2Cq].keepTpipeField.lsci, sizeof(ISP_TPIPE_CONFIG_LSCI_STRUCT)); LOG_DBG("tarCfa.bypass(%d),desCfa.bypass(%d)",mTuningQueIdx[p2Cq].keepTpipeField.cfa.bayer_bypass,pTuningField.cfa.bayer_bypass); LOG_INF("kk:get tuning seee_edge,s:(%d),d:(%d)",mTuningQueIdx[p2Cq].keepTpipeField.seee.se_edge,pTuningField.seee.se_edge); return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::getP2cqInfoFromScenario( ESoftwareScenario softScenario, ISP_DRV_P2_CQ_ENUM &p2Cq ) { MBOOL ret = MTRUE; switch(softScenario){ case eSoftwareScenario_Main_Normal_Stream: case eSoftwareScenario_Main_Normal_Capture: case eSoftwareScenario_Main_Pure_Raw_Stream: case eSoftwareScenario_Main_ZSD_Capture: case eSoftwareScenario_Sub_Normal_Stream: case eSoftwareScenario_Sub_Pure_Raw_Stream: case eSoftwareScenario_Sub_Normal_Capture: case eSoftwareScenario_Sub_ZSD_Capture: p2Cq = ISP_DRV_P2_CQ1; break; case eSoftwareScenario_Main_VSS_Capture: case eSoftwareScenario_Sub_VSS_Capture: p2Cq = ISP_DRV_P2_CQ2; break; default: LOG_ERR("[Error]Not support this scenario(%d)",softScenario); p2Cq = ISP_DRV_P2_CQ1; ret = MFALSE; break; }; return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::getCqInfoFromScenario( ESoftwareScenario softScenario, ISP_DRV_CQ_ENUM &cq ) { MBOOL ret = MTRUE; switch(softScenario){ case eSoftwareScenario_Main_Normal_Stream: case eSoftwareScenario_Main_Normal_Capture: case eSoftwareScenario_Main_Pure_Raw_Stream: case eSoftwareScenario_Main_ZSD_Capture: case eSoftwareScenario_Sub_Normal_Stream: case eSoftwareScenario_Sub_Pure_Raw_Stream: case eSoftwareScenario_Sub_Normal_Capture: case eSoftwareScenario_Sub_ZSD_Capture: cq = ISP_DRV_CQ01; break; case eSoftwareScenario_Main_VSS_Capture: case eSoftwareScenario_Sub_VSS_Capture: cq = ISP_DRV_CQ02; break; default: LOG_ERR("[Error]Not support this scenario(%d)",softScenario); cq = ISP_DRV_CQ01; ret = MFALSE; break; }; return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::mapCqToP2Cq( ISP_DRV_CQ_ENUM cq, ISP_DRV_P2_CQ_ENUM &p2Cq ) { MBOOL ret = MTRUE; switch(cq){ case ISP_DRV_CQ01: p2Cq = ISP_DRV_P2_CQ1; break; case ISP_DRV_CQ02: p2Cq = ISP_DRV_P2_CQ2; break; case ISP_DRV_CQ03: default: LOG_ERR("[Error]Not support this cq(%d) mapping",cq); p2Cq = ISP_DRV_P2_CQ1; break; }; return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvVirImp::getCqModuleInf( CAM_MODULE_ENUM moduleId, MUINT32 &addrOffset, MUINT32 &moduleSize) { MBOOL ret = MTRUE; addrOffset = mIspCQModuleInfo[moduleId].addr_ofst; moduleSize = mIspCQModuleInfo[moduleId].reg_num; return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::getCqModuleInf( CAM_MODULE_ENUM moduleId, MUINT32 &addrOffset, MUINT32 &moduleSize) { MBOOL ret = MTRUE; addrOffset = mIspCQModuleInfo[moduleId].addr_ofst; moduleSize = mIspCQModuleInfo[moduleId].reg_num; return ret; } //----------------------------------------------------------------------------- MBOOL IspDrvImp::enqueP2Frame(MUINT32 callerID,MINT32 p2burstQIdx,MINT32 p2dupCQIdx) { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_ENQUE_FRAME; edBufQueV.processID=0; //temp 0, would update in kernel edBufQueV.callerID=callerID; edBufQueV.p2burstQIdx=p2burstQIdx; edBufQueV.p2dupCQIdx=p2dupCQIdx; ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR("ISP_DRV_BUFQUE_CTRL_ENQUE_FRAME fail(%d). callerID(0x%x).", ret,callerID); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::waitP2Deque() { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_WAIT_DEQUE; edBufQueV.processID=0;//temp 0, would update in kernel ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR(" ISP_DRV_BUFQUE_CTRL_WAIT_DEQUE fail(%d). callerID(0x%x).", ret,edBufQueV.callerID); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::dequeP2FrameSuccess(MUINT32 callerID,MINT32 p2dupCQIdx) { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_DEQUE_SUCCESS; edBufQueV.processID=0;//temp 0, would update in kernel edBufQueV.callerID=callerID; edBufQueV.p2dupCQIdx=p2dupCQIdx; ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR("ISP_DRV_BUFQUE_CTRL_DEQUE_DONE fail(%d). callerID(0x%x).", ret,callerID); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::dequeP2FrameFail(MUINT32 callerID,MINT32 p2dupCQIdx) { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_DEQUE_FAIL; edBufQueV.processID=0;//temp 0, would update in kernel edBufQueV.callerID=callerID; edBufQueV.p2dupCQIdx=p2dupCQIdx; ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR("ISP_DRV_BUFQUE_CTRL_DEQUE_DONE fail(%d). callerID(0x%x).", ret,callerID); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::waitP2Frame(MUINT32 callerID,MINT32 p2dupCQIdx,MINT32 timeoutUs) { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_WAIT_FRAME; edBufQueV.processID=0;//temp 0, would update in kernel edBufQueV.callerID=callerID; edBufQueV.p2dupCQIdx=p2dupCQIdx; edBufQueV.timeoutUs=timeoutUs; ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR("ISP_DRV_BUFQUE_CTRL_WAIT_FRAME fail(%d).callerID(0x%x), Timeout(%d).", ret,callerID, timeoutUs); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::wakeP2WaitedFrames() { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_WAKE_WAITFRAME; ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR("ISP_DRV_BUFQUE_CTRL_WAKE_WAITFRAME fail(%d).", ret); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::freeAllP2Frames() { MBOOL ret=MTRUE; ISP_DRV_ED_BUFQUE_STRUCT edBufQueV; edBufQueV.ctrl=ISP_DRV_BUFQUE_CTRL_CLAER_ALL; ret=ioctl(mFd,ISP_ED_QUEBUF_CTRL_FRMB,&edBufQueV); if(ret<0) { LOG_ERR("ISP_DRV_BUFQUE_CTRL_CLAER_ALL fail(%d).", ret); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- //update/query register Scenario MBOOL IspDrvImp::updateScenarioValue( MUINT32 value) { MBOOL ret=MTRUE; MUINT32 qValue; qValue=value; #if 0 // fix it later ret=ioctl(mFd,ISP_UPDATE_REGSCEN_FRMB,&qValue); #endif if(ret<0) { LOG_ERR("ISP_UPDATE_REGSCEN_FRMB fail(%d).", ret); return MFALSE; } else { return MTRUE; } } //----------------------------------------------------------------------------- MBOOL IspDrvImp::queryScenarioValue( MUINT32& value) { MBOOL ret=MTRUE; MUINT32 qValue; #if 0 // fix it later ret=ioctl(mFd,ISP_QUERY_REGSCEN_FRMB,&qValue); #endif if(ret<0) { LOG_ERR("ISP_QUERY_REGSCEN_FRMB fail(%d).", ret); return MFALSE; } else { value=qValue; return MTRUE; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- IspDrvVirImp::IspDrvVirImp() { //LOG_INF(""); mpIspVirRegBuffer = NULL; } //----------------------------------------------------------------------------- IspDrvVirImp::~IspDrvVirImp() { //LOG_INF(""); } //----------------------------------------------------------------------------- IspDrv* IspDrvVirImp::getInstance(MINT32 cq, MUINT32* ispVirRegAddr, isp_reg_t* ispVirRegMap) { LOG_DBG("cq: %d. ispVirRegAddr: 0x%08x.", cq, ispVirRegAddr); if ((unsigned long) ispVirRegAddr & ISP_DRV_VIR_ADDR_ALIGN ) { LOG_ERR("NOT 8 bytes alignment "); return NULL; } //FIXME, need CHECK static IspDrvVirImp singleton[(ISP_DRV_DEFAULT_BURST_QUEUE_NUM*ISP_DRV_P1_CQ_DUPLICATION_NUM*ISP_DRV_P1_PER_CQ_SET_NUM)+(ISP_DVR_MAX_BURST_QUEUE_NUM*ISP_DRV_P2_CQ_DUPLICATION_NUM*ISP_DRV_P2_PER_CQ_SET_NUM)]; //static IspDrvVirImp singleton[ISP_DRV_TOTAL_CQ_NUM]; singleton[cq].mpIspVirRegBuffer = ispVirRegAddr; singleton[cq].mpIspVirRegMap =ispVirRegMap; return &singleton[cq]; } //----------------------------------------------------------------------------- void IspDrvVirImp::destroyInstance(void) { } //----------------------------------------------------------------------------- MBOOL IspDrvVirImp::reset(MINT32 rstpath) { //chrsitopher //NEEDFIX, we have to seperate the rst info in virtual reg table?? memset(mpIspVirRegBuffer,0x00,sizeof(MUINT32)*ISP_BASE_RANGE); return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvVirImp::readRegs( ISP_DRV_REG_IO_STRUCT* pRegIo, MUINT32 Count, MINT32 caller) { MUINT32 i; // //Mutex::Autolock lock(mLock); // //LOG_DBG("Count(%d)",Count); // if(mpIspVirRegBuffer == NULL) { LOG_ERR("mpIspVirRegBuffer is NULL"); return MFALSE; } switch(caller) { //assume that user do not burst read/write top related registers case ISP_DRV_RWREG_CALLFROM_MACRO: for(i=0; i<Count; i++) { pRegIo[i].Data = mpIspVirRegBuffer[(pRegIo[i].Addr)>>2]; } break; default: pthread_mutex_lock(&IspOtherRegMutex); for(i=0; i<Count; i++) { pRegIo[i].Data = mpIspVirRegBuffer[(pRegIo[i].Addr)>>2]; } pthread_mutex_unlock(&IspOtherRegMutex); break; } return MTRUE; } //----------------------------------------------------------------------------- MUINT32 IspDrvVirImp::readReg(MUINT32 Addr,MINT32 caller) { MBOOL ret=0; MUINT32 regData=0; // //Mutex::Autolock lock(mLock); // //LOG_DBG("Addr(0x%08X)",Addr); // if(mpIspVirRegBuffer == NULL) { LOG_ERR("mpIspVirRegBuffer is NULL"); return MFALSE; } regData = mpIspVirRegBuffer[(Addr)>>2]; return (regData); } //----------------------------------------------------------------------------- MBOOL IspDrvVirImp::writeRegs( ISP_DRV_REG_IO_STRUCT* pRegIo, MUINT32 Count, MINT32 userEnum, MINT32 caller) { MUINT32 i; // //Mutex::Autolock lock(mLock); // //LOG_DBG("Count(%d)",Count); // if(mpIspVirRegBuffer == NULL) { LOG_ERR("mpIspVirRegBuffer is NULL"); return MFALSE; } switch(caller) { case ISP_DRV_RWREG_CALLFROM_MACRO: for(i=0; i<Count; i++) { mpIspVirRegBuffer[(pRegIo[i].Addr)>>2] = pRegIo[i].Data; } break; default: pthread_mutex_lock(&IspOtherRegMutex); for(i=0; i<Count; i++) { mpIspVirRegBuffer[(pRegIo[i].Addr)>>2] = pRegIo[i].Data; } pthread_mutex_unlock(&IspOtherRegMutex); break; } return MTRUE; } //----------------------------------------------------------------------------- MBOOL IspDrvVirImp::writeReg( MUINT32 Addr, MUINT32 Data, MINT32 userEnum, MINT32 caller) { // //Mutex::Autolock lock(mLock); // //LOG_DBG("Addr(0x%08X),Data(0x%08X)",Addr,Data); // if(mpIspVirRegBuffer == NULL) { LOG_ERR("mpIspVirRegBuffer is NULL"); return MFALSE; } MBOOL ret=0; switch(caller) { case ISP_DRV_RWREG_CALLFROM_MACRO: //*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr))=Data; mpIspVirRegBuffer[Addr>>2] = Data; break; default: ret=checkTopReg(Addr); if(ret==1) { pthread_mutex_lock(&IspTopRegMutex); //*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr))=Data; mpIspVirRegBuffer[Addr>>2] = Data; pthread_mutex_unlock(&IspTopRegMutex); } else { pthread_mutex_lock(&IspOtherRegMutex); //*((MUINT32*)((int)this->getMMapRegAddr()+(int)Addr))=Data; mpIspVirRegBuffer[Addr>>2] = Data; pthread_mutex_unlock(&IspOtherRegMutex); } break; } return MTRUE; } //----------------------------------------------------------------------------- MUINT32* IspDrvVirImp::getRegAddr(void) { LOG_VRB("mpIspVirRegBuffer(0x%08X)",mpIspVirRegBuffer); if(mpIspVirRegBuffer != NULL) { return mpIspVirRegBuffer; } else { return NULL; } } MBOOL IspDrvVirImp:: getIspCQModuleInfo(CAM_MODULE_ENUM eModule,ISP_DRV_CQ_MODULE_INFO_STRUCT &outInfo) { outInfo.id = mIspCQModuleInfo[eModule].id; outInfo.addr_ofst = mIspCQModuleInfo[eModule].addr_ofst; outInfo.reg_num = mIspCQModuleInfo[eModule].reg_num; LOG_DBG("getIspCQModuleInfo: eModule=0x%d, ofst=0x%x, reg_num=0x%x", eModule, outInfo.addr_ofst, outInfo.reg_num); return MTRUE; } //-----------------------------------------------------------------------------
[ "peishengguo@yydrobot.com" ]
peishengguo@yydrobot.com
76599c683771629dd1263d46a90dbaa0e8fffa29
086423f9c23b3896d4b7fb6226f9e4dd141487dd
/CLI/test.cpp
224d79b683c0f711372ae8b36ac0647e4c5862fc
[]
no_license
jdhuanghub/Zeus
a6881468f4beb8563add7ed37709fe239f25ecd2
8dfb7cb54ae109d8d42215e24a96002b3507468a
refs/heads/master
2021-01-10T09:03:14.154971
2015-07-09T12:05:10
2015-07-09T12:05:10
36,774,038
0
0
null
null
null
null
GB18030
C++
false
false
396
cpp
// test.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <XnPlatform.h> #include <XnOS.h> #include <iostream> #include "cli.h" using namespace std; class cli cli; int _tmain(int argc, _TCHAR* argv[]) { #if 0 XnChar* strFileName; XnUInt64 nFileSize; XnStatus rc; rc = xnOSGetFileSize64(strFileName, &nFileSize); XN_IS_STATUS_OK(rc); #endif return 0; }
[ "jd.wong@hotmail.com" ]
jd.wong@hotmail.com
7813dc37c1d7d5ac3432ecb8c56a39a66a054624
64656183db06e5166295023c5c716432d595fa3c
/数据结构/NormalLinkList/main.cpp
917fadba6a1d317d7f66b3947401bdf9ba47b906
[]
no_license
tcliuyong/C-CPP
f8e1ab2568f211dc86e963289942bc6413228d65
51a01b9dd91453f3864f1b7bd8c059aeaaded8c7
refs/heads/master
2021-01-21T13:11:31.973912
2016-05-19T03:09:51
2016-05-19T03:09:51
54,297,376
0
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
#include "LinkList.h" int main() { LinkList l; link *list,*p; list = l.CreateTestLinkList(10); l.InsertLastLinkList(100); l.InsertLocationLinkList(2,1000); l.DelLinkList(2); p = l.GetHead(); while(p -> next != NULL) { cout<<p->data<<endl; p = p -> next; } cout<<p->data<<endl; int loc = l.GetLocLinkList(0); cout<<loc<<endl; int value = l.GetValueLinkList(9); cout<<value<<endl; l.ReverseLinkList(); while(p -> next != NULL) { cout<<p->data<<endl; p = p -> next; } cout<<p->data<<endl; return 0; }
[ "583633876@qq.com" ]
583633876@qq.com
6cb954bbb2f7698395281c6a40da73b1e20e70fa
388c754395990da30d6268f8fde5746bedd3c8e2
/InitiativeChart/mainwindow.cpp
bab9eb326b6a8584f170cfb5218953033d1669c6
[]
no_license
cbaroni0/PathfinderInitiativeSystem
8aff7d944ffc4af2cce579d2f846bfec9cd16b6e
ec5a1e9af35cc757aa4b25161cddbaa325353606
refs/heads/master
2021-07-05T07:00:45.616960
2020-08-19T05:33:02
2020-08-19T05:33:02
138,862,401
0
0
null
null
null
null
UTF-8
C++
false
false
8,257
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // set number of columns to 6 ui->tableWidget->setColumnCount(4); //set rows to size of list ui->tableWidget->setRowCount(0); //set error message to blank ui->errorLabel->setText(""); //create table headers for each column ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("Name")); ui->tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("Initiative")); ui->tableWidget->setHorizontalHeaderItem(2,new QTableWidgetItem("Init. Bonus")); ui->tableWidget->setHorizontalHeaderItem(3,new QTableWidgetItem("Status")); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_UPButton_clicked() { if(ui->tableWidget->currentItem() != NULL && ui->tableWidget->currentRow() > 0) { for(int i = 0; i < 4; i++) { //copy initial QTableWidgetItem* temp = new QTableWidgetItem(); temp->setBackgroundColor(ui->tableWidget->item(ui->tableWidget->currentRow(),i)->backgroundColor()); temp->setText(ui->tableWidget->item(ui->tableWidget->currentRow(),i)->text()); //replace initial with above ui->tableWidget->item(ui->tableWidget->currentRow(),i)->setText(ui->tableWidget->item(ui->tableWidget->currentRow()-1,i)->text()); ui->tableWidget->item(ui->tableWidget->currentRow(),i)->setBackgroundColor(ui->tableWidget->item(ui->tableWidget->currentRow()-1,i)->backgroundColor()); //replace above with copy ui->tableWidget->item(ui->tableWidget->currentRow()-1,i)->setText(temp->text()); ui->tableWidget->item(ui->tableWidget->currentRow()-1,i)->setBackgroundColor(temp->backgroundColor()); } } ui->tableWidget->setCurrentCell(ui->tableWidget->currentRow()-1,ui->tableWidget->currentColumn()); } void MainWindow::on_DOWNButton_clicked() { if(ui->tableWidget->currentItem() != NULL && ui->tableWidget->currentRow() < ui->tableWidget->rowCount()-1) { for(int i = 0; i < 4; i++) { //copy initial QTableWidgetItem* temp = new QTableWidgetItem(); temp->setBackgroundColor(ui->tableWidget->item(ui->tableWidget->currentRow(),i)->backgroundColor()); temp->setText(ui->tableWidget->item(ui->tableWidget->currentRow(),i)->text()); //replace initial with above ui->tableWidget->item(ui->tableWidget->currentRow(),i)->setText(ui->tableWidget->item(ui->tableWidget->currentRow()+1,i)->text()); ui->tableWidget->item(ui->tableWidget->currentRow(),i)->setBackgroundColor(ui->tableWidget->item(ui->tableWidget->currentRow()+1,i)->backgroundColor()); //replace above with copy ui->tableWidget->item(ui->tableWidget->currentRow()+1,i)->setText(temp->text()); ui->tableWidget->item(ui->tableWidget->currentRow()+1,i)->setBackgroundColor(temp->backgroundColor()); } } ui->tableWidget->setCurrentCell(ui->tableWidget->currentRow()+1,ui->tableWidget->currentColumn()); } void MainWindow::on_AddPlayerButton_clicked() { int size = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(size); for(int i = 0; i < 4; i++) { QTableWidgetItem* player = new QTableWidgetItem(); player->setBackgroundColor(QColor(0,204,255)); ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, i, player); } } void MainWindow::on_AddEnemyButton_clicked() { int size = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(size); for(int i = 0; i < 4; i++) { QTableWidgetItem* player = new QTableWidgetItem(); player->setBackgroundColor(QColor(255,102,102)); ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, i, player); } } void MainWindow::on_AddOtherButton_clicked() { int size = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(size); for(int i = 0; i < 4; i++) { QTableWidgetItem* player = new QTableWidgetItem(); player->setBackgroundColor(QColor(102,255,51)); ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, i, player); } } void MainWindow::on_RemoveCharacterButton_clicked() { if(ui->tableWidget->currentItem() != NULL) { ui->tableWidget->removeRow(ui->tableWidget->currentItem()->row()); } } void MainWindow::on_ROLLButton_clicked() { srand(time(NULL)); if(checkInitBonus()) { for(int i = 0; i < ui->tableWidget->rowCount(); i ++) { int tmpInt = rand() % 20 + 1 + ui->tableWidget->item(i,2)->text().toInt(); QString tmp = QString::number(tmpInt); ui->tableWidget->item(i,1)->setText(tmp); } } } void MainWindow::on_SORTButton_clicked() { qInfo() << "before init"; if(checkInitBonus()) { qInfo() << "after init"; for(int i = 0; i < ui->tableWidget->rowCount()-1; i++) { for (int j = 0; j < ui->tableWidget->rowCount()-1-i; j++) { //checks if lower is greater value if(ui->tableWidget->item(j, 1)->text().toInt() < ui->tableWidget->item(j+1, 1)->text().toInt()) { for(int k = 0; k < 4; k++) { //copy initial QTableWidgetItem* temp = new QTableWidgetItem(); temp->setBackgroundColor(ui->tableWidget->item(j, k)->backgroundColor()); temp->setText(ui->tableWidget->item(j, k)->text()); //replace initial with above ui->tableWidget->item(j,k)->setText(ui->tableWidget->item(j+1,k)->text()); ui->tableWidget->item(j,k)->setBackgroundColor(ui->tableWidget->item(j+1,k)->backgroundColor()); //replace above with copy ui->tableWidget->item(j+1,k)->setText(temp->text()); ui->tableWidget->item(j+1,k)->setBackgroundColor(temp->backgroundColor()); }//endfor }//endif else if(ui->tableWidget->item(j, 1)->text().toInt() == ui->tableWidget->item(j+1, 1)->text().toInt()) { if(ui->tableWidget->item(j, 2)->text().toInt() < ui->tableWidget->item(j+1, 2)->text().toInt()) { for(int k = 0; k < 4; k++) { //copy initial QTableWidgetItem* temp = new QTableWidgetItem(); temp->setBackgroundColor(ui->tableWidget->item(j, k)->backgroundColor()); temp->setText(ui->tableWidget->item(j, k)->text()); //replace initial with above ui->tableWidget->item(j,k)->setText(ui->tableWidget->item(j+1,k)->text()); ui->tableWidget->item(j,k)->setBackgroundColor(ui->tableWidget->item(j+1,k)->backgroundColor()); //replace above with copy ui->tableWidget->item(j+1,k)->setText(temp->text()); ui->tableWidget->item(j+1,k)->setBackgroundColor(temp->backgroundColor()); }//endfor }//endif } }//endfor }//endfor }//endif } bool MainWindow::checkInitBonus() { //used for regex check QRegularExpression rgx("[0-9]+"); QRegularExpressionMatch match; //Error Msg setup QString errorMsg = "Error in Initiative Bonus!"; ui->errorLabel->setText(""); //FOR - error checks init.bonus section. only numbers allowed for(int i = 0; i < ui->tableWidget->rowCount(); i++) { match = rgx.match(ui->tableWidget->item(i,2)->text()); if(!match.hasMatch()) { ui->errorLabel->setText(errorMsg); return false; } if(ui->tableWidget->item(i,2)->text() == "") { return false; } } return true; }
[ "baroni128@gmail.com" ]
baroni128@gmail.com
b0b5a89f3144d9cfc4a1a564b4a901dfec9b18aa
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/qvm/mat_operations.hpp
d6d5356a37692f56459d5afe6207997f04ab8b3a
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
84,255
hpp
//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef UUID_4F915D9ED30A11DF962186E3DFD72085 #define UUID_4F915D9ED30A11DF962186E3DFD72085 #include <sstd/boost/qvm/detail/mat_assign.hpp> #include <sstd/boost/qvm/mat_operations2.hpp> #include <sstd/boost/qvm/mat_operations3.hpp> #include <sstd/boost/qvm/mat_operations4.hpp> #include <sstd/boost/qvm/math.hpp> #include <sstd/boost/qvm/detail/determinant_impl.hpp> #include <sstd/boost/qvm/detail/cofactor_impl.hpp> #include <sstd/boost/qvm/detail/transp_impl.hpp> #include <sstd/boost/qvm/scalar_traits.hpp> #include <string> namespace boost { namespace qvm { namespace qvm_detail { BOOST_QVM_INLINE_CRITICAL void const * get_valid_ptr_mat_operations() { static int const obj=0; return &obj; } } //////////////////////////////////////////////// namespace qvm_to_string_detail { template <class T> std::string to_string( T const & x ); } namespace qvm_detail { template <int R,int C> struct to_string_m_defined { static bool const value=false; }; template <int I,int SizeMinusOne> struct to_string_matrix_elements { template <class A> static std::string f( A const & a ) { using namespace qvm_to_string_detail; return ( (I%mat_traits<A>::cols)==0 ? '(' : ',' ) + to_string(mat_traits<A>::template read_element<I/mat_traits<A>::cols,I%mat_traits<A>::cols>(a)) + ( (I%mat_traits<A>::cols)==mat_traits<A>::cols-1 ? ")" : "" ) + to_string_matrix_elements<I+1,SizeMinusOne>::f(a); } }; template <int SizeMinusOne> struct to_string_matrix_elements<SizeMinusOne,SizeMinusOne> { template <class A> static std::string f( A const & a ) { using namespace qvm_to_string_detail; return ( (SizeMinusOne%mat_traits<A>::cols)==0 ? '(' : ',' ) + to_string(mat_traits<A>::template read_element<SizeMinusOne/mat_traits<A>::cols,SizeMinusOne%mat_traits<A>::cols>(a)) + ')'; } }; } template <class A> inline typename boost::enable_if_c< is_mat<A>::value && !qvm_detail::to_string_m_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, std::string>::type to_string( A const & a ) { return "("+qvm_detail::to_string_matrix_elements<0,mat_traits<A>::rows*mat_traits<A>::cols-1>::f(a)+')'; } //////////////////////////////////////////////// template <class A,class B,class Cmp> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols, bool>::type cmp( A const & a, B const & b, Cmp f ) { typedef typename deduce_scalar< typename mat_traits<A>::scalar_type, typename mat_traits<B>::scalar_type>::type T; int const rows=mat_traits<A>::rows; int const cols=mat_traits<A>::cols; T m1[rows][cols]; assign(m1,a); T m2[rows][cols]; assign(m2,b); for( int i=0; i!=rows; ++i ) for( int j=0; j!=cols; ++j ) if( !f(m1[i][j],m2[i][j]) ) return false; return true; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct convert_to_m_defined { static bool const value=false; }; } template <class R,class A> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c< is_mat<R>::value && is_mat<A>::value && mat_traits<R>::rows==mat_traits<A>::rows && mat_traits<R>::cols==mat_traits<A>::cols && !qvm_detail::convert_to_m_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, R>::type convert_to( A const & a ) { R r; assign(r,a); return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int D> struct determinant_defined { static bool const value=false; }; } template <class A> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && !qvm_detail::determinant_defined<mat_traits<A>::rows>::value, typename mat_traits<A>::scalar_type>::type determinant( A const & a ) { return qvm_detail::determinant_impl(a); } //////////////////////////////////////////////// namespace qvm_detail { template <class T,int Dim> class identity_mat_ { identity_mat_( identity_mat_ const & ); identity_mat_ & operator=( identity_mat_ const & ); ~identity_mat_(); public: template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; } template <class T,int Dim> struct mat_traits< qvm_detail::identity_mat_<T,Dim> > { typedef qvm_detail::identity_mat_<T,Dim> this_matrix; typedef T scalar_type; static int const rows=Dim; static int const cols=Dim; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & /*x*/ ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<Dim); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<Dim); return scalar_traits<scalar_type>::value(Row==Col); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & /*x*/ ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(row<Dim); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(col<Dim); return scalar_traits<scalar_type>::value(row==col); } }; template <class T,int Dim> BOOST_QVM_INLINE_TRIVIAL qvm_detail::identity_mat_<T,Dim> const & identity_mat() { return *(qvm_detail::identity_mat_<T,Dim> const *)qvm_detail::get_valid_ptr_mat_operations(); } template <class A> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols, void>::type set_identity( A & a ) { assign(a,identity_mat<typename mat_traits<A>::scalar_type,mat_traits<A>::rows>()); } //////////////////////////////////////////////// namespace qvm_detail { template <class T> struct projection_ { T const _00; T const _11; T const _22; T const _23; T const _32; BOOST_QVM_INLINE_TRIVIAL projection_( T _00, T _11, T _22, T _23, T _32 ): _00(_00), _11(_11), _22(_22), _23(_23), _32(_32) { } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; template <int Row,int Col> struct projection_get { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( projection_<T> const & ) { return scalar_traits<T>::value(0); } }; template <> struct projection_get<0,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( projection_<T> const & m ) { return m._00; } }; template <> struct projection_get<1,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( projection_<T> const & m ) { return m._11; } }; template <> struct projection_get<2,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( projection_<T> const & m ) { return m._22; } }; template <> struct projection_get<2,3> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( projection_<T> const & m ) { return m._23; } }; template <> struct projection_get<3,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( projection_<T> const & m ) { return m._32; } }; } template <class T> struct mat_traits< qvm_detail::projection_<T> > { typedef qvm_detail::projection_<T> this_matrix; typedef T scalar_type; static int const rows=4; static int const cols=4; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<rows); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<cols); return qvm_detail::projection_get<Row,Col>::get(x); } }; template <class T> qvm_detail::projection_<T> BOOST_QVM_INLINE_OPERATIONS perspective_lh( T fov_y, T aspect_ratio, T z_near, T z_far ) { T const one = scalar_traits<T>::value(1); T const ys = one/tan<T>(fov_y/scalar_traits<T>::value(2)); T const xs = ys/aspect_ratio; T const zd = z_far-z_near; T const z1 = z_far/zd; T const z2 = -z_near*z1; return qvm_detail::projection_<T>(xs,ys,z1,z2,one); } template <class T> qvm_detail::projection_<T> BOOST_QVM_INLINE_OPERATIONS perspective_rh( T fov_y, T aspect_ratio, T z_near, T z_far ) { T const one = scalar_traits<T>::value(1); T const ys = one/tan<T>(fov_y/scalar_traits<T>::value(2)); T const xs = ys/aspect_ratio; T const zd = z_near-z_far; T const z1 = z_far/zd; T const z2 = z_near*z1; return qvm_detail::projection_<T>(xs,ys,z1,z2,-one); } //////////////////////////////////////////////// namespace qvm_detail { template <class OriginalType,class Scalar> class matrix_scalar_cast_ { matrix_scalar_cast_( matrix_scalar_cast_ const & ); matrix_scalar_cast_ & operator=( matrix_scalar_cast_ const & ); ~matrix_scalar_cast_(); public: template <class T> BOOST_QVM_INLINE_TRIVIAL matrix_scalar_cast_ & operator=( T const & x ) { assign(*this,x); return *this; } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; template <bool> struct scalar_cast_matrix_filter { }; template <> struct scalar_cast_matrix_filter<true> { typedef int type; }; } template <class OriginalType,class Scalar> struct mat_traits< qvm_detail::matrix_scalar_cast_<OriginalType,Scalar> > { typedef Scalar scalar_type; typedef qvm_detail::matrix_scalar_cast_<OriginalType,Scalar> this_matrix; static int const rows=mat_traits<OriginalType>::rows; static int const cols=mat_traits<OriginalType>::cols; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<rows); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<cols); return scalar_type(mat_traits<OriginalType>::template read_element<Row,Col>(reinterpret_cast<OriginalType const &>(x))); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(row<rows); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(col<cols); return scalar_type(mat_traits<OriginalType>::read_element_idx(col,row,reinterpret_cast<OriginalType const &>(x))); } }; template <class OriginalType,class Scalar,int R,int C> struct deduce_mat<qvm_detail::matrix_scalar_cast_<OriginalType,Scalar>,R,C> { typedef mat<Scalar,R,C> type; }; template <class Scalar,class T> BOOST_QVM_INLINE_TRIVIAL qvm_detail::matrix_scalar_cast_<T,Scalar> const & scalar_cast( T const & x, typename qvm_detail::scalar_cast_matrix_filter<is_mat<T>::value>::type=0 ) { return reinterpret_cast<qvm_detail::matrix_scalar_cast_<T,Scalar> const &>(x); } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct div_eq_ms_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_scalar<B>::value && !qvm_detail::div_eq_ms_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, A &>::type operator/=( A & a, B b ) { for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<A>::write_element_idx(i,j,a)/=b; return a; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct div_ms_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_mat<A>::value && is_scalar<B>::value && !qvm_detail::div_ms_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, deduce_mat<A> >::type operator/( A const & a, B b ) { typedef typename deduce_mat<A>::type R; R r; for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<R>::write_element_idx(i,j,r)=mat_traits<A>::read_element_idx(i,j,a)/b; return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct eq_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::eq_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, bool>::type operator==( A const & a, B const & b ) { for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) if( mat_traits<A>::read_element_idx(i,j,a)!=mat_traits<B>::read_element_idx(i,j,b) ) return false; return true; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct minus_eq_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::minus_eq_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, A &>::type operator-=( A & a, B const & b ) { for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<A>::write_element_idx(i,j,a)-=mat_traits<B>::read_element_idx(i,j,b); return a; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct minus_m_defined { static bool const value=false; }; } template <class A> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_mat<A>::value && !qvm_detail::minus_m_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, deduce_mat<A> >::type operator-( A const & a ) { typedef typename deduce_mat<A>::type R; R r; for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<R>::write_element_idx(i,j,r)=-mat_traits<A>::read_element_idx(i,j,a); return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct minus_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::minus_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, deduce_mat2<A,B,mat_traits<A>::rows,mat_traits<A>::cols> >::type operator-( A const & a, B const & b ) { typedef typename deduce_mat2<A,B,mat_traits<A>::rows,mat_traits<A>::cols>::type R; R r; for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<R>::write_element_idx(i,j,r)=mat_traits<A>::read_element_idx(i,j,a)-mat_traits<B>::read_element_idx(i,j,b); return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int D> struct mul_eq_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::mul_eq_mm_defined<mat_traits<A>::rows>::value, A &>::type operator*=( A & r, B const & b ) { typedef typename mat_traits<A>::scalar_type Ta; Ta a[mat_traits<A>::rows][mat_traits<A>::cols]; for( int i=0; i<mat_traits<A>::rows; ++i ) for( int j=0; j<mat_traits<B>::cols; ++j ) a[i][j]=mat_traits<A>::read_element_idx(i,j,r); for( int i=0; i<mat_traits<A>::rows; ++i ) for( int j=0; j<mat_traits<B>::cols; ++j ) { Ta x(scalar_traits<Ta>::value(0)); for( int k=0; k<mat_traits<A>::cols; ++k ) x += a[i][k]*mat_traits<B>::read_element_idx(k,j,b); mat_traits<A>::write_element_idx(i,j,r) = x; } return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct mul_eq_ms_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_scalar<B>::value && !qvm_detail::mul_eq_ms_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, A &>::type operator*=( A & a, B b ) { for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<A>::write_element_idx(i,j,a)*=b; return a; } //////////////////////////////////////////////// namespace qvm_detail { template <int R,int CR,int C> struct mul_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::cols==mat_traits<B>::rows && !qvm_detail::mul_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols,mat_traits<B>::cols>::value, deduce_mat2<A,B,mat_traits<A>::rows,mat_traits<B>::cols> >::type operator*( A const & a, B const & b ) { typedef typename deduce_mat2<A,B,mat_traits<A>::rows,mat_traits<B>::cols>::type R; R r; for( int i=0; i<mat_traits<A>::rows; ++i ) for( int j=0; j<mat_traits<B>::cols; ++j ) { typedef typename mat_traits<A>::scalar_type Ta; Ta x(scalar_traits<Ta>::value(0)); for( int k=0; k<mat_traits<A>::cols; ++k ) x += mat_traits<A>::read_element_idx(i,k,a)*mat_traits<B>::read_element_idx(k,j,b); mat_traits<R>::write_element_idx(i,j,r) = x; } return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct mul_ms_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_mat<A>::value && is_scalar<B>::value && !qvm_detail::mul_ms_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, deduce_mat<A> >::type operator*( A const & a, B b ) { typedef typename deduce_mat<A>::type R; R r; for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<R>::write_element_idx(i,j,r)=mat_traits<A>::read_element_idx(i,j,a)*b; return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct mul_sm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_scalar<A>::value && is_mat<B>::value && !qvm_detail::mul_sm_defined<mat_traits<B>::rows,mat_traits<B>::cols>::value, deduce_mat<B> >::type operator*( A a, B const & b ) { typedef typename deduce_mat<B>::type R; R r; for( int i=0; i!=mat_traits<B>::rows; ++i ) for( int j=0; j!=mat_traits<B>::cols; ++j ) mat_traits<R>::write_element_idx(i,j,r)=a*mat_traits<B>::read_element_idx(i,j,b); return r; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct neq_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::neq_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, bool>::type operator!=( A const & a, B const & b ) { for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) if( mat_traits<A>::read_element_idx(i,j,a)!=mat_traits<B>::read_element_idx(i,j,b) ) return true; return false; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct plus_eq_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::plus_eq_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, A &>::type operator+=( A & a, B const & b ) { for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<A>::write_element_idx(i,j,a)+=mat_traits<B>::read_element_idx(i,j,b); return a; } //////////////////////////////////////////////// namespace qvm_detail { template <int M,int N> struct plus_mm_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows==mat_traits<B>::rows && mat_traits<A>::cols==mat_traits<B>::cols && !qvm_detail::plus_mm_defined<mat_traits<A>::rows,mat_traits<A>::cols>::value, deduce_mat2<A,B,mat_traits<A>::rows,mat_traits<A>::cols> >::type operator+( A const & a, B const & b ) { typedef typename deduce_mat2<A,B,mat_traits<A>::rows,mat_traits<A>::cols>::type R; R r; for( int i=0; i!=mat_traits<A>::rows; ++i ) for( int j=0; j!=mat_traits<A>::cols; ++j ) mat_traits<R>::write_element_idx(i,j,r)=mat_traits<A>::read_element_idx(i,j,a)+mat_traits<B>::read_element_idx(i,j,b); return r; } //////////////////////////////////////////////// namespace qvm_detail { template <class T> class mref_ { mref_( mref_ const & ); mref_ & operator=( mref_ const & ); ~mref_(); public: template <class R> BOOST_QVM_INLINE_TRIVIAL mref_ & operator=( R const & x ) { assign(*this,x); return *this; } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; } template <class M> struct mat_traits< qvm_detail::mref_<M> > { typedef typename mat_traits<M>::scalar_type scalar_type; typedef qvm_detail::mref_<M> this_matrix; static int const rows=mat_traits<M>::rows; static int const cols=mat_traits<M>::cols; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<rows); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<cols); return mat_traits<M>::template read_element<Row,Col>(reinterpret_cast<M const &>(x)); } template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type & write_element( this_matrix & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<rows); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<cols); return mat_traits<M>::template write_element<Row,Col>(reinterpret_cast<M &>(x)); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(row<rows); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(col<cols); return mat_traits<M>::read_element_idx(row,col,reinterpret_cast<M const &>(x)); } static BOOST_QVM_INLINE_CRITICAL scalar_type & write_element_idx( int row, int col, this_matrix & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(row<rows); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(col<cols); return mat_traits<M>::write_element_idx(row,col,reinterpret_cast<M &>(x)); } }; template <class M,int R,int C> struct deduce_mat<qvm_detail::mref_<M>,R,C> { typedef mat<typename mat_traits<M>::scalar_type,R,C> type; }; template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c< is_mat<M>::value, qvm_detail::mref_<M> const &>::type mref( M const & a ) { return reinterpret_cast<qvm_detail::mref_<M> const &>(a); } template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c< is_mat<M>::value, qvm_detail::mref_<M> &>::type mref( M & a ) { return reinterpret_cast<qvm_detail::mref_<M> &>(a); } //////////////////////////////////////////////// namespace qvm_detail { template <class T,int Rows,int Cols> class zero_mat_ { zero_mat_( zero_mat_ const & ); zero_mat_ & operator=( zero_mat_ const & ); ~zero_mat_(); public: template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; } template <class T,int Rows,int Cols> struct mat_traits< qvm_detail::zero_mat_<T,Rows,Cols> > { typedef qvm_detail::zero_mat_<T,Rows,Cols> this_matrix; typedef T scalar_type; static int const rows=Rows; static int const cols=Cols; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<Rows); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<Cols); return scalar_traits<scalar_type>::value(0); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(row<rows); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(col<cols); return scalar_traits<scalar_type>::value(0); } }; template <class T,int Rows,int Cols,int R,int C> struct deduce_mat<qvm_detail::zero_mat_<T,Rows,Cols>,R,C> { typedef mat<T,R,C> type; }; template <class T,int Rows,int Cols> BOOST_QVM_INLINE_TRIVIAL qvm_detail::zero_mat_<T,Rows,Cols> const & zero_mat() { return *(qvm_detail::zero_mat_<T,Rows,Cols> const *)qvm_detail::get_valid_ptr_mat_operations(); } template <class T,int Dim> BOOST_QVM_INLINE_TRIVIAL qvm_detail::zero_mat_<T,Dim,Dim> const & zero_mat() { return *(qvm_detail::zero_mat_<T,Dim,Dim> const *)qvm_detail::get_valid_ptr_mat_operations(); } template <class A> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value, void>::type set_zero( A & a ) { assign(a,zero_mat<typename mat_traits<A>::scalar_type,mat_traits<A>::rows,mat_traits<A>::cols>()); } //////////////////////////////////////////////// namespace qvm_detail { template <int D,class S> struct rot_mat_ { typedef S scalar_type; scalar_type a[3][3]; BOOST_QVM_INLINE rot_mat_( scalar_type a00, scalar_type a01, scalar_type a02, scalar_type a10, scalar_type a11, scalar_type a12, scalar_type a20, scalar_type a21, scalar_type a22 ) { a[0][0] = a00; a[0][1] = a01; a[0][2] = a02; a[1][0] = a10; a[1][1] = a11; a[1][2] = a12; a[2][0] = a20; a[2][1] = a21; a[2][2] = a22; } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; template <int Row,int Col> struct rot_m_get { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&)[3][3] ) { return scalar_traits<T>::value(Row==Col); } }; template <> struct rot_m_get<0,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[0][0]; } }; template <> struct rot_m_get<0,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[0][1]; } }; template <> struct rot_m_get<0,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[0][2]; } }; template <> struct rot_m_get<1,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[1][0]; } }; template <> struct rot_m_get<1,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[1][1]; } }; template <> struct rot_m_get<1,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[1][2]; } }; template <> struct rot_m_get<2,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[2][0]; } }; template <> struct rot_m_get<2,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[2][1]; } }; template <> struct rot_m_get<2,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const (&a)[3][3] ) { return a[2][2]; } }; } template <class M> struct mat_traits; template <int D,class S> struct mat_traits< qvm_detail::rot_mat_<D,S> > { typedef qvm_detail::rot_mat_<D,S> this_matrix; typedef typename this_matrix::scalar_type scalar_type; static int const rows=D; static int const cols=D; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Row<D); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Col<D); return qvm_detail::rot_m_get<Row,Col>::get(x.a); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(row<D); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(col<D); return row<3 && col<3? x.a[row][col] : scalar_traits<scalar_type>::value(row==col); } }; template <int Dim,class V,class Angle> BOOST_QVM_INLINE typename enable_if_c< is_vec<V>::value && vec_traits<V>::dim==3, qvm_detail::rot_mat_<Dim,Angle> >::type rot_mat( V const & axis, Angle angle ) { typedef Angle scalar_type; scalar_type const x=vec_traits<V>::template read_element<0>(axis); scalar_type const y=vec_traits<V>::template read_element<1>(axis); scalar_type const z=vec_traits<V>::template read_element<2>(axis); scalar_type const m2=x*x+y*y+z*z; if( m2==scalar_traits<scalar_type>::value(0) ) BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error()); scalar_type const s = sin<scalar_type>(angle); scalar_type const c = cos<scalar_type>(angle); scalar_type const x2 = x*x; scalar_type const y2 = y*y; scalar_type const z2 = z*z; scalar_type const xy = x*y; scalar_type const xz = x*z; scalar_type const yz = y*z; scalar_type const xs = x*s; scalar_type const ys = y*s; scalar_type const zs = z*s; scalar_type const one = scalar_traits<scalar_type>::value(1); scalar_type const c1 = one-c; return qvm_detail::rot_mat_<Dim,Angle>( x2+(one-x2)*c, xy*c1-zs, xz*(one-c)+ys, xy*c1+zs, y2+(one-y2)*c, yz*c1-xs, xz*c1-ys, yz*c1+xs, z2+(one-z2)*c ); } template <class A,class B,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3 && is_vec<B>::value && vec_traits<B>::dim==3, void>::type set_rot( A & a, B const & axis, Angle angle ) { assign(a,rot_mat<mat_traits<A>::rows>(axis,angle)); } template <class A,class B,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3 && is_vec<B>::value && vec_traits<B>::dim==3, void>::type rotate( A & a, B const & axis, Angle angle ) { a *= rot_mat<mat_traits<A>::rows>(axis,angle); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_xzy( Angle x1, Angle z2, Angle y3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(x1); scalar_type const s1 = sin<scalar_type>(x1); scalar_type const c2 = cos<scalar_type>(z2); scalar_type const s2 = sin<scalar_type>(z2); scalar_type const c3 = cos<scalar_type>(y3); scalar_type const s3 = sin<scalar_type>(y3); return qvm_detail::rot_mat_<Dim,Angle>( c2*c3, -s2, c2*s3, s1*s3 + c1*c3*s2, c1*c2, c1*s2*s3 - c3*s1, c3*s1*s2 - c1*s3, c2*s1, c1*c3 + s1*s2*s3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_xzy( A & a, Angle x1, Angle z2, Angle y3 ) { assign(a,rot_mat_xzy<mat_traits<A>::rows>(x1,z2,y3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_xzy( A & a, Angle x1, Angle z2, Angle y3 ) { a *= rot_mat_xzy<mat_traits<A>::rows>(x1,z2,y3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_xyz( Angle x1, Angle y2, Angle z3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(x1); scalar_type const s1 = sin<scalar_type>(x1); scalar_type const c2 = cos<scalar_type>(y2); scalar_type const s2 = sin<scalar_type>(y2); scalar_type const c3 = cos<scalar_type>(z3); scalar_type const s3 = sin<scalar_type>(z3); return qvm_detail::rot_mat_<Dim,Angle>( c2*c3, -c2*s3, s2, c1*s3 + c3*s1*s2, c1*c3 - s1*s2*s3, -c2*s1, s1*s3 - c1*c3*s2, c3*s1 + c1*s2*s3, c1*c2 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_xyz( A & a, Angle x1, Angle y2, Angle z3 ) { assign(a,rot_mat_xyz<mat_traits<A>::rows>(x1,y2,z3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_xyz( A & a, Angle x1, Angle y2, Angle z3 ) { a *= rot_mat_xyz<mat_traits<A>::rows>(x1,y2,z3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_yxz( Angle y1, Angle x2, Angle z3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(y1); scalar_type const s1 = sin<scalar_type>(y1); scalar_type const c2 = cos<scalar_type>(x2); scalar_type const s2 = sin<scalar_type>(x2); scalar_type const c3 = cos<scalar_type>(z3); scalar_type const s3 = sin<scalar_type>(z3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c3 + s1*s2*s3, c3*s1*s2 - c1*s3, c2*s1, c2*s3, c2*c3, -s2, c1*s2*s3 - c3*s1, c1*c3*s2 + s1*s3, c1*c2 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_yxz( A & a, Angle y1, Angle x2, Angle z3 ) { assign(a,rot_mat_yxz<mat_traits<A>::rows>(y1,x2,z3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_yxz( A & a, Angle y1, Angle x2, Angle z3 ) { a *= rot_mat_yxz<mat_traits<A>::rows>(y1,x2,z3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_yzx( Angle y1, Angle z2, Angle x3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(y1); scalar_type const s1 = sin<scalar_type>(y1); scalar_type const c2 = cos<scalar_type>(z2); scalar_type const s2 = sin<scalar_type>(z2); scalar_type const c3 = cos<scalar_type>(x3); scalar_type const s3 = sin<scalar_type>(x3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c2, s1*s3 - c1*c3*s2, c3*s1 + c1*s2*s3, s2, c2*c3, -c2*s3, -c2*s1, c1*s3 + c3*s1*s2, c1*c3 - s1*s2*s3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_yzx( A & a, Angle y1, Angle z2, Angle x3 ) { assign(a,rot_mat_yzx<mat_traits<A>::rows>(y1,z2,x3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_yzx( A & a, Angle y1, Angle z2, Angle x3 ) { a *= rot_mat_yzx<mat_traits<A>::rows>(y1,z2,x3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_zyx( Angle z1, Angle y2, Angle x3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(z1); scalar_type const s1 = sin<scalar_type>(z1); scalar_type const c2 = cos<scalar_type>(y2); scalar_type const s2 = sin<scalar_type>(y2); scalar_type const c3 = cos<scalar_type>(x3); scalar_type const s3 = sin<scalar_type>(x3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c2, c1*s2*s3 - c3*s1, s1*s3 + c1*c3*s2, c2*s1, c1*c3 + s1*s2*s3, c3*s1*s2 - c1*s3, -s2, c2*s3, c2*c3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_zyx( A & a, Angle z1, Angle y2, Angle x3 ) { assign(a,rot_mat_zyx<mat_traits<A>::rows>(z1,y2,x3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_zyx( A & a, Angle z1, Angle y2, Angle x3 ) { a *= rot_mat_zyx<mat_traits<A>::rows>(z1,y2,x3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_zxy( Angle z1, Angle x2, Angle y3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(z1); scalar_type const s1 = sin<scalar_type>(z1); scalar_type const c2 = cos<scalar_type>(x2); scalar_type const s2 = sin<scalar_type>(x2); scalar_type const c3 = cos<scalar_type>(y3); scalar_type const s3 = sin<scalar_type>(y3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c3 - s1*s2*s3, -c2*s1, c1*s3 + c3*s1*s2, c3*s1 + c1*s2*s3, c1*c2, s1*s3 - c1*c3*s2, -c2*s3, s2, c2*c3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_zxy( A & a, Angle z1, Angle x2, Angle y3 ) { assign(a,rot_mat_zxy<mat_traits<A>::rows>(z1,x2,y3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_zxy( A & a, Angle z1, Angle x2, Angle y3 ) { a *= rot_mat_zxy<mat_traits<A>::rows>(z1,x2,y3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_xzx( Angle x1, Angle z2, Angle x3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(x1); scalar_type const s1 = sin<scalar_type>(x1); scalar_type const c2 = cos<scalar_type>(z2); scalar_type const s2 = sin<scalar_type>(z2); scalar_type const c3 = cos<scalar_type>(x3); scalar_type const s3 = sin<scalar_type>(x3); return qvm_detail::rot_mat_<Dim,Angle>( c2, -c3*s2, s2*s3, c1*s2, c1*c2*c3 - s1*s3, -c3*s1 - c1*c2*s3, s1*s2, c1*s3 + c2*c3*s1, c1*c3 - c2*s1*s3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_xzx( A & a, Angle x1, Angle z2, Angle x3 ) { assign(a,rot_mat_xzx<mat_traits<A>::rows>(x1,z2,x3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_xzx( A & a, Angle x1, Angle z2, Angle x3 ) { a *= rot_mat_xzx<mat_traits<A>::rows>(x1,z2,x3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_xyx( Angle x1, Angle y2, Angle x3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(x1); scalar_type const s1 = sin<scalar_type>(x1); scalar_type const c2 = cos<scalar_type>(y2); scalar_type const s2 = sin<scalar_type>(y2); scalar_type const c3 = cos<scalar_type>(x3); scalar_type const s3 = sin<scalar_type>(x3); return qvm_detail::rot_mat_<Dim,Angle>( c2, s2*s3, c3*s2, s1*s2, c1*c3 - c2*s1*s3, -c1*s3 - c2*c3*s1, -c1*s2, c3*s1 + c1*c2*s3, c1*c2*c3 - s1*s3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_xyx( A & a, Angle x1, Angle y2, Angle x3 ) { assign(a,rot_mat_xyx<mat_traits<A>::rows>(x1,y2,x3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_xyx( A & a, Angle x1, Angle y2, Angle x3 ) { a *= rot_mat_xyx<mat_traits<A>::rows>(x1,y2,x3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_yxy( Angle y1, Angle x2, Angle y3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(y1); scalar_type const s1 = sin<scalar_type>(y1); scalar_type const c2 = cos<scalar_type>(x2); scalar_type const s2 = sin<scalar_type>(x2); scalar_type const c3 = cos<scalar_type>(y3); scalar_type const s3 = sin<scalar_type>(y3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c3 - c2*s1*s3, s1*s2, c1*s3 + c2*c3*s1, s2*s3, c2, -c3*s2, -c3*s1 - c1*c2*s3, c1*s2, c1*c2*c3 - s1*s3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_yxy( A & a, Angle y1, Angle x2, Angle y3 ) { assign(a,rot_mat_yxy<mat_traits<A>::rows>(y1,x2,y3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_yxy( A & a, Angle y1, Angle x2, Angle y3 ) { a *= rot_mat_yxy<mat_traits<A>::rows>(y1,x2,y3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_yzy( Angle y1, Angle z2, Angle y3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(y1); scalar_type const s1 = sin<scalar_type>(y1); scalar_type const c2 = cos<scalar_type>(z2); scalar_type const s2 = sin<scalar_type>(z2); scalar_type const c3 = cos<scalar_type>(y3); scalar_type const s3 = sin<scalar_type>(y3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c2*c3 - s1*s3, -c1*s2, c3*s1 + c1*c2*s3, c3*s2, c2, s2*s3, -c1*s3 - c2*c3*s1, s1*s2, c1*c3 - c2*s1*s3 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_yzy( A & a, Angle y1, Angle z2, Angle y3 ) { assign(a,rot_mat_yzy<mat_traits<A>::rows>(y1,z2,y3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_yzy( A & a, Angle y1, Angle z2, Angle y3 ) { a *= rot_mat_yzy<mat_traits<A>::rows>(y1,z2,y3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_zyz( Angle z1, Angle y2, Angle z3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(z1); scalar_type const s1 = sin<scalar_type>(z1); scalar_type const c2 = cos<scalar_type>(y2); scalar_type const s2 = sin<scalar_type>(y2); scalar_type const c3 = cos<scalar_type>(z3); scalar_type const s3 = sin<scalar_type>(z3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c2*c3 - s1*s3, -c3*s1 - c1*c2*s3, c1*s2, c1*s3 + c2*c3*s1, c1*c3 - c2*s1*s3, s1*s2, -c3*s2, s2*s3, c2 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_zyz( A & a, Angle z1, Angle y2, Angle z3 ) { assign(a,rot_mat_zyz<mat_traits<A>::rows>(z1,y2,z3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_zyz( A & a, Angle z1, Angle y2, Angle z3 ) { a *= rot_mat_zyz<mat_traits<A>::rows>(z1,y2,z3); } //////////////////////////////////////////////// template <int Dim,class Angle> BOOST_QVM_INLINE qvm_detail::rot_mat_<Dim,Angle> rot_mat_zxz( Angle z1, Angle x2, Angle z3 ) { typedef Angle scalar_type; scalar_type const c1 = cos<scalar_type>(z1); scalar_type const s1 = sin<scalar_type>(z1); scalar_type const c2 = cos<scalar_type>(x2); scalar_type const s2 = sin<scalar_type>(x2); scalar_type const c3 = cos<scalar_type>(z3); scalar_type const s3 = sin<scalar_type>(z3); return qvm_detail::rot_mat_<Dim,Angle>( c1*c3 - c2*s1*s3, -c1*s3 - c2*c3*s1, s1*s2, c3*s1 + c1*c2*s3, c1*c2*c3 - s1*s3, -c1*s2, s2*s3, c3*s2, c2 ); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type set_rot_zxz( A & a, Angle z1, Angle x2, Angle z3 ) { assign(a,rot_mat_zxz<mat_traits<A>::rows>(z1,x2,z3)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3, void>::type rotate_zxz( A & a, Angle z1, Angle x2, Angle z3 ) { a *= rot_mat_zxz<mat_traits<A>::rows>(z1,x2,z3); } //////////////////////////////////////////////// namespace qvm_detail { template <int Dim,class Angle> struct rotx_mat_ { BOOST_QVM_INLINE_TRIVIAL rotx_mat_() { } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } private: rotx_mat_( rotx_mat_ const & ); rotx_mat_ & operator=( rotx_mat_ const & ); ~rotx_mat_(); }; template <int Row,int Col> struct rotx_m_get { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & ) { return scalar_traits<T>::value(Row==Col); } }; template <> struct rotx_m_get<1,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return cos<T>(angle); } }; template <> struct rotx_m_get<1,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return -sin<T>(angle); } }; template <> struct rotx_m_get<2,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return sin<T>(angle); } }; template <> struct rotx_m_get<2,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return cos<T>(angle); } }; } template <int Dim,class Angle> struct mat_traits< qvm_detail::rotx_mat_<Dim,Angle> > { typedef qvm_detail::rotx_mat_<Dim,Angle> this_matrix; typedef Angle scalar_type; static int const rows=Dim; static int const cols=Dim; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Row<Dim); BOOST_QVM_STATIC_ASSERT(Col<Dim); return qvm_detail::rotx_m_get<Row,Col>::get(reinterpret_cast<Angle const &>(x)); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(row<Dim); BOOST_QVM_ASSERT(col<Dim); Angle const & a=reinterpret_cast<Angle const &>(x); if( row==1 ) { if( col==1 ) return cos<scalar_type>(a); if( col==2 ) return -sin<scalar_type>(a); } if( row==2 ) { if( col==1 ) return sin<scalar_type>(a); if( col==2 ) return cos<scalar_type>(a); } return scalar_traits<scalar_type>::value(row==col); } }; template <int Dim,class Angle> struct deduce_mat<qvm_detail::rotx_mat_<Dim,Angle>,Dim,Dim> { typedef mat<Angle,Dim,Dim> type; }; template <int Dim,class Angle> struct deduce_mat2<qvm_detail::rotx_mat_<Dim,Angle>,qvm_detail::rotx_mat_<Dim,Angle>,Dim,Dim> { typedef mat<Angle,Dim,Dim> type; }; template <int Dim,class Angle> BOOST_QVM_INLINE_TRIVIAL qvm_detail::rotx_mat_<Dim,Angle> const & rotx_mat( Angle const & angle ) { BOOST_QVM_STATIC_ASSERT(Dim>=3); return reinterpret_cast<qvm_detail::rotx_mat_<Dim,Angle> const &>(angle); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows>=3 && mat_traits<A>::rows==mat_traits<A>::cols, void>::type set_rotx( A & a, Angle angle ) { assign(a,rotx_mat<mat_traits<A>::rows>(angle)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows>=3 && mat_traits<A>::rows==mat_traits<A>::cols, void>::type rotate_x( A & a, Angle angle ) { a *= rotx_mat<mat_traits<A>::rows>(angle); } //////////////////////////////////////////////// namespace qvm_detail { template <int Dim,class Angle> struct roty_mat_ { BOOST_QVM_INLINE_TRIVIAL roty_mat_() { } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } private: roty_mat_( roty_mat_ const & ); roty_mat_ & operator=( roty_mat_ const & ); ~roty_mat_(); }; template <int Row,int Col> struct roty_m_get { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & ) { return scalar_traits<T>::value(Row==Col); } }; template <> struct roty_m_get<0,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return cos<T>(angle); } }; template <> struct roty_m_get<0,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return sin<T>(angle); } }; template <> struct roty_m_get<2,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return -sin<T>(angle); } }; template <> struct roty_m_get<2,2> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return cos<T>(angle); } }; } template <int Dim,class Angle> struct mat_traits< qvm_detail::roty_mat_<Dim,Angle> > { typedef qvm_detail::roty_mat_<Dim,Angle> this_matrix; typedef Angle scalar_type; static int const rows=Dim; static int const cols=Dim; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Row<Dim); BOOST_QVM_STATIC_ASSERT(Col<Dim); return qvm_detail::roty_m_get<Row,Col>::get(reinterpret_cast<Angle const &>(x)); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(row<Dim); BOOST_QVM_ASSERT(col<Dim); Angle const & a=reinterpret_cast<Angle const &>(x); if( row==0 ) { if( col==0 ) return cos<scalar_type>(a); if( col==2 ) return sin<scalar_type>(a); } if( row==2 ) { if( col==0 ) return -sin<scalar_type>(a); if( col==2 ) return cos<scalar_type>(a); } return scalar_traits<scalar_type>::value(row==col); } }; template <int Dim,class Angle> struct deduce_mat<qvm_detail::roty_mat_<Dim,Angle>,Dim,Dim> { typedef mat<Angle,Dim,Dim> type; }; template <int Dim,class Angle> struct deduce_mat2<qvm_detail::roty_mat_<Dim,Angle>,qvm_detail::roty_mat_<Dim,Angle>,Dim,Dim> { typedef mat<Angle,Dim,Dim> type; }; template <int Dim,class Angle> BOOST_QVM_INLINE_TRIVIAL qvm_detail::roty_mat_<Dim,Angle> const & roty_mat( Angle const & angle ) { BOOST_QVM_STATIC_ASSERT(Dim>=3); return reinterpret_cast<qvm_detail::roty_mat_<Dim,Angle> const &>(angle); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows>=2 && mat_traits<A>::rows==mat_traits<A>::cols, void>::type set_roty( A & a, Angle angle ) { assign(a,roty_mat<mat_traits<A>::rows>(angle)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows>=3 && mat_traits<A>::rows==mat_traits<A>::cols, void>::type rotate_y( A & a, Angle angle ) { a *= roty_mat<mat_traits<A>::rows>(angle); } //////////////////////////////////////////////// namespace qvm_detail { template <int Dim,class Angle> struct rotz_mat_ { BOOST_QVM_INLINE_TRIVIAL rotz_mat_() { } template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } private: rotz_mat_( rotz_mat_ const & ); rotz_mat_ & operator=( rotz_mat_ const & ); ~rotz_mat_(); }; template <int Row,int Col> struct rotz_m_get { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & ) { return scalar_traits<T>::value(Row==Col); } }; template <> struct rotz_m_get<0,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return cos<T>(angle); } }; template <> struct rotz_m_get<0,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return -sin<T>(angle); } }; template <> struct rotz_m_get<1,0> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return sin<T>(angle); } }; template <> struct rotz_m_get<1,1> { template <class T> static BOOST_QVM_INLINE_CRITICAL T get( T const & angle ) { return cos<T>(angle); } }; } template <int Dim,class Angle> struct mat_traits< qvm_detail::rotz_mat_<Dim,Angle> > { typedef qvm_detail::rotz_mat_<Dim,Angle> this_matrix; typedef Angle scalar_type; static int const rows=Dim; static int const cols=Dim; template <int Row,int Col> static BOOST_QVM_INLINE_CRITICAL scalar_type read_element( this_matrix const & x ) { BOOST_QVM_STATIC_ASSERT(Row>=0); BOOST_QVM_STATIC_ASSERT(Col>=0); BOOST_QVM_STATIC_ASSERT(Row<Dim); BOOST_QVM_STATIC_ASSERT(Col<Dim); return qvm_detail::rotz_m_get<Row,Col>::get(reinterpret_cast<Angle const &>(x)); } static BOOST_QVM_INLINE_CRITICAL scalar_type read_element_idx( int row, int col, this_matrix const & x ) { BOOST_QVM_ASSERT(row>=0); BOOST_QVM_ASSERT(col>=0); BOOST_QVM_ASSERT(row<Dim); BOOST_QVM_ASSERT(col<Dim); Angle const & a=reinterpret_cast<Angle const &>(x); if( row==0 ) { if( col==0 ) return cos<scalar_type>(a); if( col==1 ) return -sin<scalar_type>(a); } if( row==1 ) { if( col==0 ) return sin<scalar_type>(a); if( col==1 ) return cos<scalar_type>(a); } return scalar_traits<scalar_type>::value(row==col); } }; template <int Dim,class Angle> struct deduce_mat<qvm_detail::rotz_mat_<Dim,Angle>,Dim,Dim> { typedef mat<Angle,Dim,Dim> type; }; template <int Dim,class Angle,int R,int C> struct deduce_mat2<qvm_detail::rotz_mat_<Dim,Angle>,qvm_detail::rotz_mat_<Dim,Angle>,R,C> { typedef mat<Angle,R,C> type; }; template <int Dim,class Angle> BOOST_QVM_INLINE_TRIVIAL qvm_detail::rotz_mat_<Dim,Angle> const & rotz_mat( Angle const & angle ) { BOOST_QVM_STATIC_ASSERT(Dim>=2); return reinterpret_cast<qvm_detail::rotz_mat_<Dim,Angle> const &>(angle); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows>=2 && mat_traits<A>::rows==mat_traits<A>::cols, void>::type set_rotz( A & a, Angle angle ) { assign(a,rotz_mat<mat_traits<A>::rows>(angle)); } template <class A,class Angle> BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_mat<A>::value && mat_traits<A>::rows>=2 && mat_traits<A>::rows==mat_traits<A>::cols, void>::type rotate_z( A & a, Angle angle ) { a *= rotz_mat<mat_traits<A>::rows>(angle); } //////////////////////////////////////////////// namespace qvm_detail { template <int D> struct inverse_m_defined { static bool const value=false; }; } template <class A,class B> BOOST_QVM_INLINE_TRIVIAL typename lazy_enable_if_c< is_mat<A>::value && is_scalar<B>::value && mat_traits<A>::rows==mat_traits<A>::cols && !qvm_detail::inverse_m_defined<mat_traits<A>::rows>::value, deduce_mat<A> >::type inverse( A const & a, B det ) { typedef typename mat_traits<A>::scalar_type T; BOOST_QVM_ASSERT(det!=scalar_traits<T>::value(0)); T f=scalar_traits<T>::value(1)/det; typedef typename deduce_mat<A>::type cofactor_return_type; cofactor_return_type c=qvm_detail::cofactor_impl(a); return reinterpret_cast<qvm_detail::transposed_<cofactor_return_type> const &>(c) * f; } template <class A> BOOST_QVM_INLINE_TRIVIAL typename lazy_enable_if_c< is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && !qvm_detail::inverse_m_defined<mat_traits<A>::rows>::value, deduce_mat<A> >::type inverse( A const & a ) { typedef typename mat_traits<A>::scalar_type T; T det=determinant(a); if( det==scalar_traits<T>::value(0) ) BOOST_QVM_THROW_EXCEPTION(zero_determinant_error()); return inverse(a,det); } //////////////////////////////////////////////// namespace sfinae { using ::boost::qvm::to_string; using ::boost::qvm::assign; using ::boost::qvm::determinant; using ::boost::qvm::cmp; using ::boost::qvm::convert_to; using ::boost::qvm::set_identity; using ::boost::qvm::set_zero; using ::boost::qvm::scalar_cast; using ::boost::qvm::operator/=; using ::boost::qvm::operator/; using ::boost::qvm::operator==; using ::boost::qvm::operator-=; using ::boost::qvm::operator-; using ::boost::qvm::operator*=; using ::boost::qvm::operator*; using ::boost::qvm::operator!=; using ::boost::qvm::operator+=; using ::boost::qvm::operator+; using ::boost::qvm::mref; using ::boost::qvm::rot_mat; using ::boost::qvm::set_rot; using ::boost::qvm::rotate; using ::boost::qvm::set_rotx; using ::boost::qvm::rotate_x; using ::boost::qvm::set_roty; using ::boost::qvm::rotate_y; using ::boost::qvm::set_rotz; using ::boost::qvm::rotate_z; using ::boost::qvm::inverse; } //////////////////////////////////////////////// } } #endif
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
b894e5c78b7d11f96079313fc0182877ff747301
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/renderer/modules/bluetooth/bluetooth_device.cc
9d6204000e32a7cf2eeedf58358c498690afdc58
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
4,185
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/bluetooth/bluetooth_device.h" #include <memory> #include <utility> #include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth_attribute_instance_map.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth_error.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_server.h" namespace blink { BluetoothDevice::BluetoothDevice(ExecutionContext* context, mojom::blink::WebBluetoothDevicePtr device, Bluetooth* bluetooth) : ContextLifecycleObserver(context), attribute_instance_map_( MakeGarbageCollected<BluetoothAttributeInstanceMap>(this)), device_(std::move(device)), gatt_(MakeGarbageCollected<BluetoothRemoteGATTServer>(context, this)), bluetooth_(bluetooth) {} BluetoothRemoteGATTService* BluetoothDevice::GetOrCreateRemoteGATTService( mojom::blink::WebBluetoothRemoteGATTServicePtr service, bool is_primary, const String& device_instance_id) { return attribute_instance_map_->GetOrCreateRemoteGATTService( std::move(service), is_primary, device_instance_id); } bool BluetoothDevice::IsValidService(const String& service_instance_id) { return attribute_instance_map_->ContainsService(service_instance_id); } BluetoothRemoteGATTCharacteristic* BluetoothDevice::GetOrCreateRemoteGATTCharacteristic( ExecutionContext* context, mojom::blink::WebBluetoothRemoteGATTCharacteristicPtr characteristic, BluetoothRemoteGATTService* service) { return attribute_instance_map_->GetOrCreateRemoteGATTCharacteristic( context, std::move(characteristic), service); } bool BluetoothDevice::IsValidCharacteristic( const String& characteristic_instance_id) { return attribute_instance_map_->ContainsCharacteristic( characteristic_instance_id); } BluetoothRemoteGATTDescriptor* BluetoothDevice::GetOrCreateBluetoothRemoteGATTDescriptor( mojom::blink::WebBluetoothRemoteGATTDescriptorPtr descriptor, BluetoothRemoteGATTCharacteristic* characteristic) { return attribute_instance_map_->GetOrCreateBluetoothRemoteGATTDescriptor( std::move(descriptor), characteristic); } bool BluetoothDevice::IsValidDescriptor(const String& descriptor_instance_id) { return attribute_instance_map_->ContainsDescriptor(descriptor_instance_id); } void BluetoothDevice::ClearAttributeInstanceMapAndFireEvent() { attribute_instance_map_->Clear(); DispatchEvent( *Event::CreateBubble(event_type_names::kGattserverdisconnected)); } const WTF::AtomicString& BluetoothDevice::InterfaceName() const { return event_target_names::kBluetoothDevice; } ExecutionContext* BluetoothDevice::GetExecutionContext() const { return ContextLifecycleObserver::GetExecutionContext(); } void BluetoothDevice::Trace(blink::Visitor* visitor) { visitor->Trace(attribute_instance_map_); visitor->Trace(gatt_); visitor->Trace(bluetooth_); EventTargetWithInlineData::Trace(visitor); ContextLifecycleObserver::Trace(visitor); } void BluetoothDevice::AddedEventListener( const AtomicString& event_type, RegisteredEventListener& registered_listener) { EventTargetWithInlineData::AddedEventListener(event_type, registered_listener); if (event_type == event_type_names::kGattserverdisconnected) { UseCounter::Count(GetExecutionContext(), WebFeature::kGATTServerDisconnectedEvent); } } } // namespace blink
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
e424cf608f0c79f91a1c0513dd1111f934a2b3b6
111c9510a12ed2f79fc5ec0c7a1c308dcac515f0
/Arduino/cc3000/HTTPServer/HTTPServer.ino
71f6fec90799a8e6c481fd7b96e6d09b3b63b144
[ "Beerware" ]
permissive
torstefan/derp
7b693ecc0c1ef9066ec1c9f399260da69d26ecb1
9fb26f339560fc44d8a499dc7f0ef0a56d8389ce
refs/heads/master
2020-04-24T04:37:22.452796
2015-11-29T20:09:38
2015-11-29T20:09:38
24,864,094
0
0
null
null
null
null
UTF-8
C++
false
false
10,293
ino
/*************************************************** Adafruit CC3000 Breakout/Shield Simple HTTP Server This is a simple implementation of a bare bones HTTP server that can respond to very simple requests. Note that this server is not meant to handle high load, concurrent connections, SSL, etc. A 16mhz Arduino with 2K of memory can only handle so much complexity! This server example is best for very simple status messages or REST APIs. See the CC3000 tutorial on Adafruit's learning system for more information on setting up and using the CC3000: http://learn.adafruit.com/adafruit-cc3000-wifi Requirements: This sketch requires the Adafruit CC3000 library. You can download the library from: https://github.com/adafruit/Adafruit_CC3000_Library For information on installing libraries in the Arduino IDE see this page: http://arduino.cc/en/Guide/Libraries Usage: Update the SSID and, if necessary, the CC3000 hardware pin information below, then run the sketch and check the output of the serial port. After connecting to the wireless network successfully the sketch will output the IP address of the server and start listening for connections. Once listening for connections, connect to the server IP from a web browser. For example if your server is listening on IP 192.168.1.130 you would access http://192.168.1.130/ from your web browser. Created by Tony DiCola and adapted from HTTP server code created by Eric Friedrich. This code was adapted from Adafruit CC3000 library example code which has the following license: Designed specifically to work with the Adafruit WiFi products: ----> https://www.adafruit.com/products/1469 Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried & Kevin Townsend for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ #include <Adafruit_CC3000.h> #include <SPI.h> #include "utility/debug.h" #include "utility/socket.h" // These are the interrupt and control pins #define ADAFRUIT_CC3000_IRQ 3 // MUST be an interrupt pin! // These can be any two pins #define ADAFRUIT_CC3000_VBAT 5 #define ADAFRUIT_CC3000_CS 10 // Use hardware SPI for the remaining pins // On an UNO, SCK = 13, MISO = 12, and MOSI = 11 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER); // you can change this clock speed #define WLAN_SSID "Lura_1" // cannot be longer than 32 characters! #define WLAN_PASS "12345678" // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2 #define WLAN_SECURITY WLAN_SEC_WPA2 #define LISTEN_PORT 80 // What TCP port to listen on for connections. // The HTTP protocol uses port 80 by default. #define MAX_ACTION 10 // Maximum length of the HTTP action that can be parsed. #define MAX_PATH 64 // Maximum length of the HTTP request path that can be parsed. // There isn't much memory available so keep this short! #define BUFFER_SIZE MAX_ACTION + MAX_PATH + 20 // Size of buffer for incoming request data. // Since only the first line is parsed this // needs to be as large as the maximum action // and path plus a little for whitespace and // HTTP version. #define TIMEOUT_MS 500 // Amount of time in milliseconds to wait for // an incoming request to finish. Don't set this // too high or your server could be slow to respond. Adafruit_CC3000_Server httpServer(LISTEN_PORT); uint8_t buffer[BUFFER_SIZE+1]; int bufindex = 0; char action[MAX_ACTION+1]; char path[MAX_PATH+1]; void setup(void) { Serial.begin(115200); Serial.println(F("Hello, CC3000!\n")); Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC); // Initialise the module Serial.println(F("\nInitializing...")); if (!cc3000.begin()) { Serial.println(F("Couldn't begin()! Check your wiring?")); while(1); } Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID); if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) { Serial.println(F("Failed!")); while(1); } Serial.println(F("Connected!")); Serial.println(F("Request DHCP")); while (!cc3000.checkDHCP()) { delay(100); // ToDo: Insert a DHCP timeout! } // Display the IP address DNS, Gateway, etc. while (! displayConnectionDetails()) { delay(1000); } // ****************************************************** // You can safely remove this to save some flash memory! // ****************************************************** Serial.println(F("\r\nNOTE: This sketch may cause problems with other sketches")); Serial.println(F("since the .disconnect() function is never called, so the")); Serial.println(F("AP may refuse connection requests from the CC3000 until a")); Serial.println(F("timeout period passes. This is normal behaviour since")); Serial.println(F("there isn't an obvious moment to disconnect with a server.\r\n")); // Start listening for connections httpServer.begin(); Serial.println(F("Listening for connections...")); } void loop(void) { // Try to get a client which is connected. Adafruit_CC3000_ClientRef client = httpServer.available(); if (client) { Serial.println(F("Client connected.")); // Process this request until it completes or times out. // Note that this is explicitly limited to handling one request at a time! // Clear the incoming data buffer and point to the beginning of it. bufindex = 0; memset(&buffer, 0, sizeof(buffer)); // Clear action and path strings. memset(&action, 0, sizeof(action)); memset(&path, 0, sizeof(path)); // Set a timeout for reading all the incoming data. unsigned long endtime = millis() + TIMEOUT_MS; // Read all the incoming data until it can be parsed or the timeout expires. bool parsed = false; while (!parsed && (millis() < endtime) && (bufindex < BUFFER_SIZE)) { if (client.available()) { buffer[bufindex++] = client.read(); } parsed = parseRequest(buffer, bufindex, action, path); } // Handle the request if it was parsed. if (parsed) { Serial.println(F("Processing request")); Serial.print(F("Action: ")); Serial.println(action); Serial.print(F("Path: ")); Serial.println(path); // Check the action to see if it was a GET request. if (strcmp(action, "GET") == 0) { // Respond with the path that was accessed. // First send the success response code. client.fastrprintln(F("HTTP/1.1 200 OK")); // Then send a few headers to identify the type of data returned and that // the connection will not be held open. client.fastrprintln(F("Content-Type: text/plain")); client.fastrprintln(F("Connection: close")); client.fastrprintln(F("Server: Adafruit CC3000")); // Send an empty line to signal start of body. client.fastrprintln(F("")); // Now send the response data. client.fastrprintln(F("Hello world!")); client.fastrprint(F("You accessed path: ")); client.fastrprintln(path); } else { // Unsupported action, respond with an HTTP 405 method not allowed error. client.fastrprintln(F("HTTP/1.1 405 Method Not Allowed")); client.fastrprintln(F("")); } } // Wait a short period to make sure the response had time to send before // the connection is closed (the CC3000 sends data asyncronously). delay(100); // Close the connection when done. Serial.println(F("Client disconnected")); client.close(); } } // Return true if the buffer contains an HTTP request. Also returns the request // path and action strings if the request was parsed. This does not attempt to // parse any HTTP headers because there really isn't enough memory to process // them all. // HTTP request looks like: // [method] [path] [version] \r\n // Header_key_1: Header_value_1 \r\n // ... // Header_key_n: Header_value_n \r\n // \r\n bool parseRequest(uint8_t* buf, int bufSize, char* action, char* path) { // Check if the request ends with \r\n to signal end of first line. if (bufSize < 2) return false; if (buf[bufSize-2] == '\r' && buf[bufSize-1] == '\n') { parseFirstLine((char*)buf, action, path); return true; } return false; } // Parse the action and path from the first line of an HTTP request. void parseFirstLine(char* line, char* action, char* path) { // Parse first word up to whitespace as action. char* lineaction = strtok(line, " "); if (lineaction != NULL) strncpy(action, lineaction, MAX_ACTION); // Parse second word up to whitespace as path. char* linepath = strtok(NULL, " "); if (linepath != NULL) strncpy(path, linepath, MAX_PATH); } // Tries to read the IP address and other connection details bool displayConnectionDetails(void) { uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv; if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv)) { Serial.println(F("Unable to retrieve the IP Address!\r\n")); return false; } else { Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress); Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask); Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway); Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv); Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv); Serial.println(); return true; } }
[ "torstefan@gmail.com" ]
torstefan@gmail.com
ed822664f2675c84c2a853ca41dfc660bb5839e1
88c07d71d7fcdecea69f5df8ca10972f1b02f038
/HttpPortalServer/HttpPortalServer/TokenAuthor.cpp
75caef9220fb5212e7cb3c9cf02e1d9b70b7ee36
[]
no_license
zjf984078330/HttpPortalServer
b791c13786fb80aa3bcf21839ad1a7d09753cd87
4cc20945f649659771520ba273fade6827e63dc6
refs/heads/master
2022-04-05T17:41:18.186504
2020-03-02T16:20:35
2020-03-02T16:20:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
cpp
#include "BaseHeader.h" #include "TokenAuthor.h" const string TokenAuthor::XAUTHOR = "ve_x_au"; TokenAuthor * TokenAuthor::Inst() { static TokenAuthor *pInst = new TokenAuthor(); return pInst; } bool TokenAuthor::tokenIsAvalaible(string & token,int &cause) { cause = TokenAuthor::OK; try { t_map.at(token); } catch (const out_of_range& oor) { cause = TokenAuthor::NOTEXIST; } return true; } bool TokenAuthor::updateToken(string &token) { t_map[token] = tockenSample(); return true; } void TokenAuthor::removeToken(string &token) { try { t_map.at(token); } catch (const out_of_range& oor) { return; } t_map.erase(token); } //Build simply UUID-MD5 token here,i think maybe merge ip, user, and creation time //to token and change MD5 to DES,this should downgrade the risk. string createToken() { UUIDGenerator& gen = Poco::UUIDGenerator::defaultGenerator(); string strUUID = gen.createRandom().toString(); MD5Engine md5; md5.update(strUUID.c_str(), strUUID.length()); return MD5Engine::digestToHex(md5.digest()); }
[ "progmalover@hotmail.com" ]
progmalover@hotmail.com
04aba68c0a5ab7d8484ee0002711c8ac4172fad9
5464d8f847aecb3cbab7629485a1fdff707f0a3d
/s32v234_sdk/libs/arm/apexcv_base/interpolation/graphs/interp_bicubic_grayscale_graph.hpp
3d4f085b9e0ae851c828597263cefed1472992bf
[]
no_license
kernal88/VisionSDK
73e0d1280ac1574a43f129e0ab8940e8be86000e
63dfbbb8800c647ac9d23dae08de946e7c1ab6f3
refs/heads/master
2021-06-02T14:26:44.838058
2016-03-22T00:34:08
2016-03-22T00:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,860
hpp
/****************************************************************************** * (C) Copyright CogniVue Corporation. 2014 All right reserved. * * Confidential Information * * All parts of the CogniVue Program Source are protected by copyright law * and all rights are reserved. * This documentation may not, in whole or in part, be copied, photocopied, * reproduced, translated, or reduced to any electronic medium or machine * readable form without prior consent, in writing, from CogniVue. * ******************************************************************************/ /*!********************************************************************************* * @file bicubic.hpp * @brief ACF graph for bicubic 08u interpolation ***********************************************************************************/ #include <acf_graph.hpp> #include "interpolation_kernels.h" class interp_bicubic_grayscale_graph : public ACF_Graph { public: interp_bicubic_grayscale_graph() : ACF_Graph() { #ifdef APEX2_EMULATE XREGISTER_ACF_KERNEL(INTERP_BICUBIC_GRAYSC_K); #endif } void Create() { //set identifier for graph SetIdentifier("interp_bicubic_grayscale_graph"); //add kernels AddKernel("_interp_bicubic_grayscale", INTERP_BICUBIC_GRAYSC_KN); //add graph ports AddInputPort("INPUT_0"); AddInputPort("Y_OFFSET"); AddInputPort("X_OFFSET"); AddOutputPort("OUTPUT_0"); //specify connections Connect(GraphPort("INPUT_0"), KernelPort("_interp_bicubic_grayscale", "INPUT_0")); Connect(GraphPort("Y_OFFSET"), KernelPort("_interp_bicubic_grayscale", "X_OFFSET")); Connect(GraphPort("X_OFFSET"), KernelPort("_interp_bicubic_grayscale", "Y_OFFSET")); Connect(KernelPort("_interp_bicubic_grayscale", "OUTPUT_0"), GraphPort("OUTPUT_0")); } };
[ "uw.infotainment@gmail.com" ]
uw.infotainment@gmail.com
9c655ba97ea59b8fd602cd73cc8dff03ae6ff514
afd1e4f62f53201c95f33d86b2a5ec7454b7a457
/includes/vendor/glm/mat3x2.hpp
369576bad6d4712379487a02c47cc25a799e4643
[]
no_license
ormskirk77/oxford_car_visualiser2
426570e6aa91bc283492672ba0d7a50e1241460a
6d26ef909bd24ab17ba135bc2e193df2dbf52cbc
refs/heads/master
2022-11-16T20:10:00.851951
2020-07-14T20:03:14
2020-07-14T20:03:14
263,434,267
2
0
null
null
null
null
UTF-8
C++
false
false
260
hpp
/// @ref core /// @file glm/mat3x2.hpp #pragma once #include "vendor/glm/ext/matrix_double3x2.hpp" #include "vendor/glm/ext/matrix_double3x2_precision.hpp" #include "vendor/glm/ext/matrix_float3x2.hpp" #include "vendor/glm/ext/matrix_float3x2_precision.hpp"
[ "tim.fernandezhart@gmail.com" ]
tim.fernandezhart@gmail.com
c2bd89ed43d9b91e3d611fd4e5733c43a3cdc7e2
ee6d19e7976f4c07b17004d326a4e1be4306990c
/practice/oct 21/19 oct day 14/cherry.cpp
bde0439551fc368d5ae6b8a09a7cd06e896f50c1
[]
no_license
samahuja642/competitive-programming
b37eab547ac59ba6f4cdd9f4173fbfac9b46e292
031a7d38db557b4b6058af5d5e246543821011b5
refs/heads/main
2023-09-03T08:14:09.558871
2021-10-20T17:55:29
2021-10-20T17:55:29
350,995,005
0
1
null
null
null
null
UTF-8
C++
false
false
515
cpp
#include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(); cout.tie(); long long t; cin>>t; while(t--){ long long n; cin>>n; long long a[n]; for(long long i=0;i<n;i++){ cin>>a[i]; } long long product = 0; for(long long i=0;i<n-1;i++){ long long temp = a[i] * a[i+1]; product = max(product,temp); } cout<<product<<endl; } return 0; }
[ "samahuja642@gmail.com" ]
samahuja642@gmail.com
dd31e9dd6545d2e93d63da4d52eb114dcd13ef32
a026a4060d30813ab4e15b9ff0904381a7e74290
/Chess/Turn.h
017a5c280660f7b15fa4b5f12eafaa52ea40ba1e
[ "Apache-2.0" ]
permissive
NanoBreeze/TCP-Chess
259e7bea085af7538a9c7bfb4590b3d46397fd8a
2cf51a8b6991dbeced7714b18429640394b04641
refs/heads/master
2021-01-17T21:41:17.101749
2016-03-27T17:44:18
2016-03-27T17:44:18
52,834,417
1
0
null
null
null
null
UTF-8
C++
false
false
928
h
#pragma once //Includes info for each turn (meant to be placed onto the turn stack). Info includes: //Piece moved //from and to coordinate //Piece captured (if any) #include "Piece.h" #include "Coordinate.h" class Turn { public: Turn(); ~Turn(); Piece* getPieceMoved() const; void setPieceMoved(Piece*); Coordinate getFromCoordinate() const; void setFromCoordinate(Coordinate); Coordinate getToCoordinate() const; void setToCoordinate(Coordinate); Piece* getCapturedPiece() const; void setCapturedPiece(Piece*); private: //The piece that just moved Piece* pieceMoved = nullptr; //the Coordinate of pieceMoved before it moved Coordinate fromCoordinate; //the Coordinate of pieceMoved after it moved Coordinate toCoordinate; //the Piece that the pieceMoved captured (aka, occupied toCoordinate before pieceMoved moved Piece* capturedPiece = nullptr; };
[ "dreambigbebigger@gmail.com" ]
dreambigbebigger@gmail.com
c147cd719461a6f311d56bb98e0ab842d7af1438
56338b005797b1e032821030f2b9c03e346b1ac6
/main.cpp
0a48de2f9e4a791e225c9e7e2edcf18775551fae
[]
no_license
callumthomson/cpp_hangman
e04612c6f5a1c2e369ed627d89b3495d6dc5d38d
189cc16c82f6ce7c3a17af4982001cbecf494221
refs/heads/master
2022-04-25T21:47:31.970097
2020-04-23T14:18:46
2020-04-23T14:18:46
258,229,524
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
#include <iostream> #include <stdexcept> #include <fstream> #include "include/Hangman.h" #include "include/State.h" #include "include/Renderer.h" using std::cin; int main() { std::fstream file("words.txt"); vector<string> words{}; Hangman game{}; Renderer renderer(&game); char guess{}; std::string file_line{}; while(file >> file_line) { words.push_back(file_line); } game.load_words(words); while(game.get_state() == State::Playing) { renderer.fresh(); renderer.dashed_word(); renderer.guesses(); renderer.lives(); renderer.ask_input(); cin >> guess; try { game.guess(guess); } catch (std::invalid_argument& e) { renderer.err_already_guessed(guess); } } switch (game.get_state()) { case State::Won: renderer.win_message(); break; case State::Lost: renderer.loss_message(); break; case State::Playing: default: break; } }
[ "callum@callumthomson.co.uk" ]
callum@callumthomson.co.uk
1eb8dc3ad181a6e220b3e093424a1c24dc54dfb1
616f5710199eb247a0f68bec9e9602e412e7e8bd
/src/engine/particle/ParticleTube.h
a30b741fa742472ec70e5c027ffeeb018ab6fbfb
[]
no_license
maximilianfuller/sphere
524fadfd330c661c5621a2fb7c422a2b41191117
65ef2e02f6f0aa177ca4938093e6063a84a77a39
refs/heads/master
2021-05-06T03:53:25.669067
2016-10-11T00:47:15
2016-10-11T00:47:15
114,930,166
0
0
null
null
null
null
UTF-8
C++
false
false
820
h
#ifndef PARTICLETUBE_H #define PARTICLETUBE_H #include "util/CommonIncludes.h" #include "engine/particle/ParticleSystem.h" #include <QString> class ParticleTube : public ParticleSystem { public: ParticleTube(QString textureKey, glm::vec3 source, glm::vec3 target, glm::vec3 color, float radius, float particleSize = 1); void setColor(glm::vec3 color); /* Create particles */ void start(); void stop(); bool getStarted(); void createParticle(); void draw(Graphics *graphics, glm::mat4x4 look); private: glm::vec3 m_source; glm::vec3 m_target; glm::vec3 m_color; float m_radius; float m_particleSize; bool m_started; int m_startTimer; int m_particleTimer; int m_particleTimeout; }; #endif // PARTICLETUBE_H
[ "attal.benjamin@gmail.com" ]
attal.benjamin@gmail.com
2051728e26f8a7cdbb9b215fc1a1c98a2cdea72f
a552cd0cd0e3445f2119fcb9019a421983f43306
/contest_volumes/volume_105/10576.cpp
7ea9fbf32ad312aa0aa39f613cf9c79d8cb34d62
[]
no_license
yftsai/uva-online-judge
dbb3fd485efa27f391c11ceb31effc423cfa8b40
cf204240502bbce89ab746c0f5be74e29d923ea3
refs/heads/master
2022-08-27T10:08:19.642502
2021-10-04T00:33:09
2022-08-07T06:12:03
50,548,610
0
0
null
null
null
null
UTF-8
C++
false
false
923
cpp
// #easy #include <iostream> using namespace std; void enumerate( const int s, const int d, const uint16_t m, const int slice, const int sum, int surpluses[12], int &max_surplus) { if (m == 12) max_surplus = max(sum, max_surplus); else { const int t = slice - ((m >= 5) ? surpluses[m - 5] : 0); surpluses[m] = s; if (m < 4 || t + s < 0) enumerate(s, d, m + 1, t + s, sum + s, surpluses, max_surplus); surpluses[m] = -d; if (m < 4 || t - d < 0) enumerate(s, d, m + 1, t - d, sum - d, surpluses, max_surplus); } } int main() { for (int s, d; cin >> s >> d; ) { int surpluses[12]; int max_surplus = 0; enumerate(s, d, 0, 0, 0, surpluses, max_surplus); if (max_surplus > 0) cout << max_surplus << endl; else cout << "Deficit" << endl; } return 0; }
[ "yifan.tsai@gmail.com" ]
yifan.tsai@gmail.com
74d2a0fd590c276d5c8c0d3fff32825f0219b3bb
e589cc2225cd96c37211643cb896efb90d8c42ef
/Atcoder/ABC069/B.cpp
317784017d5e006b12fead14d55a90bc630e5225
[]
no_license
nenuon/CompetitiveProgramming
e33ed59495fb8fa3f308e69eef92f148d4b152b7
54b2769d9054136501b0a95d8f64bb6aafcd418a
refs/heads/master
2021-10-24T11:24:11.120228
2019-03-25T15:06:07
2019-03-25T15:06:07
112,305,142
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include <algorithm> #include <cstdio> #include <iostream> #include <map> #include <cmath> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <vector> #include <stdlib.h> #include <stdio.h> #include <bitset> using namespace std; #define FOR(I,A,B) for(int I = (A); I < (B); ++I) typedef long long ll; int main() { string s; cin >> s; cout << s[0] << s.length() - 2 << s[s.length()-1] << endl; return 0; }
[ "" ]
bff07075886be58a1edc93b8b78602f5f148ea7a
b0b0b7ad6b0984594686dffd81be69199a3a71bb
/Charts/TRCharts/TRCharts/Axis.hpp
f9790dd28a77b2d5524ed4d72f615ea5b2c48411
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thesurix/TRCharts
582ddf4de95b4b963cf164d771cddccf3b7f1c09
24f2dbc1bbd234e7bb8aa802578a3a5ff72eb7a2
refs/heads/master
2020-04-17T00:54:06.566075
2019-01-20T13:38:43
2019-01-20T13:38:43
166,066,992
0
0
null
2019-01-16T15:51:16
2019-01-16T15:51:15
null
UTF-8
C++
false
false
3,317
hpp
/******************************************************************************* * Copyright 2015 Thomson Reuters * * 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. *******************************************************************************/ /* NOTE: This file is autogenerated, do not edit this file directly.*/ #ifndef Charts_Axis_hpp #define Charts_Axis_hpp #include <TRCharts/Common.hpp> #include <TRCharts/ChartElement.hpp> #include <TRCharts/Edge.hpp> #include <TRCharts/Color.hpp> #include <TRCharts/LineStyle.hpp> #include <TRCharts/Font.hpp> namespace Charts { class Axis; class Label; class GeneratedAxis : public Charts::ChartElement { public: virtual ~GeneratedAxis(void); std::shared_ptr<Axis> getSharedPtr(void); std::shared_ptr<const Axis> getSharedPtr(void) const; virtual Charts::Edge getEdge(void) const = 0; virtual void setEdge(Charts::Edge value) = 0; virtual const std::shared_ptr<Charts::Label> & getTitle(void) const = 0; virtual void setTitle(const std::shared_ptr<Charts::Label> & value) = 0; virtual const Charts::Color & getAxisColor(void) const = 0; virtual void setAxisColor(const Charts::Color & value) = 0; virtual const Charts::LineStyle & getAxisLineStyle(void) const = 0; virtual void setAxisLineStyle(const Charts::LineStyle & value) = 0; virtual bool isGridVisible(void) const = 0; virtual void setGridVisible(bool value) = 0; virtual const Charts::Color & getGridColor(void) const = 0; virtual void setGridColor(const Charts::Color & value) = 0; virtual const Charts::LineStyle & getGridLineStyle(void) const = 0; virtual void setGridLineStyle(const Charts::LineStyle & value) = 0; virtual const Charts::Color & getTickColor(void) const = 0; virtual void setTickColor(const Charts::Color & value) = 0; virtual const Charts::LineStyle & getTickLineStyle(void) const = 0; virtual void setTickLineStyle(const Charts::LineStyle & value) = 0; virtual double getTickOffset(void) const = 0; virtual void setTickOffset(double value) = 0; virtual double getTickSize(void) const = 0; virtual void setTickSize(double value) = 0; virtual const Charts::Color & getTickLabelColor(void) const = 0; virtual void setTickLabelColor(const Charts::Color & value) = 0; virtual const Charts::Font & getTickLabelFont(void) const = 0; virtual void setTickLabelFont(const Charts::Font & value) = 0; virtual double getTickLabelMaxSize(void) const = 0; virtual void setTickLabelMaxSize(double value) = 0; virtual double getTickLabelOffset(void) const = 0; virtual void setTickLabelOffset(double value) = 0; virtual double getScreenLength(void) const = 0; virtual void relayout(void) = 0; protected: GeneratedAxis(void); }; } #include <TRCharts/Impl/AxisImpl.hpp> #endif
[ "francisco.estevezgarcia@thomsonreuters.com" ]
francisco.estevezgarcia@thomsonreuters.com
c3cfdcdaac43c876c55dbd7726a36751f0784db9
b291be76ba3e228c44a9a6bb422ffa9d83ab5a39
/java/rocksjni/ratelimiterjni.cc
5413978a0067fc472c1e2800ed0e319b7c6752ea
[ "BSD-3-Clause" ]
permissive
dyu/rocksdb
bd3c8efd724d37c8e6db5a55257752dfa6b54e73
d439451fab490ce0cabc90f2880443c93d9eab12
refs/heads/master
2020-12-25T20:30:37.438981
2014-09-25T23:45:37
2014-09-25T23:45:37
15,468,469
1
0
null
null
null
null
UTF-8
C++
false
false
1,004
cc
// Copyright (c) 2014, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // This file implements the "bridge" between Java and C++ for RateLimiter. #include "rocksjni/portal.h" #include "include/org_rocksdb_GenericRateLimiterConfig.h" #include "rocksdb/rate_limiter.h" /* * Class: org_rocksdb_GenericRateLimiterConfig * Method: newRateLimiterHandle * Signature: (JJI)J */ jlong Java_org_rocksdb_GenericRateLimiterConfig_newRateLimiterHandle( JNIEnv* env, jobject jobj, jlong jrate_bytes_per_second, jlong jrefill_period_micros, jint jfairness) { return reinterpret_cast<jlong>(rocksdb::NewGenericRateLimiter( rocksdb::jlong_to_size_t(jrate_bytes_per_second), rocksdb::jlong_to_size_t(jrefill_period_micros), static_cast<int32_t>(jfairness))); }
[ "aigupta@linkedin.com" ]
aigupta@linkedin.com
f312b9c47a9e261f0e9cae3ef5fc4a20b8d39a05
aec0af8e55b9bcd61956d38fb6072f074ddd6733
/MFCMyApp/MFCMyApp/StudentManagement.cpp
2fe0518f17428087173f9480d66de8d7942f446c
[]
no_license
hndung98/MFCMyApp
93233b970dd02225a85b0c6fb54ff7e0d3b1bdde
36f6d419b404748bac96d63fb05e958d5e094c42
refs/heads/master
2022-11-29T07:22:59.409014
2020-08-14T08:40:52
2020-08-14T08:40:52
287,165,200
0
0
null
null
null
null
UTF-8
C++
false
false
18,481
cpp
// StudentManagement.cpp : implementation file // #include "pch.h" #include "MFCMyApp.h" #include "StudentManagement.h" #include "afxdialogex.h" //#include "stdafx.h" #define ARRAY_SIZE 10 // StudentManagement dialog IMPLEMENT_DYNAMIC(StudentManagement, CDialogEx) StudentManagement::StudentManagement(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DLG_STUDENT, pParent) , rad_search_id(0) , rad_search_name(1) { } StudentManagement::~StudentManagement() { if (sql_add_handle != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, sql_add_handle); sql_add_handle = NULL; } if (sql_delete_handle != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, sql_delete_handle); sql_delete_handle = NULL; } if (sql_update_handle != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, sql_update_handle); sql_update_handle = NULL; } if (sql_check_handle != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, sql_check_handle); sql_check_handle = NULL; } if (sql_connection_handle != SQL_NULL_HDBC) { SQLDisconnect(sql_connection_handle); SQLFreeHandle(SQL_HANDLE_DBC, sql_connection_handle); sql_connection_handle = NULL; } if (sql_env_handle != SQL_NULL_HENV) { SQLFreeHandle(SQL_HANDLE_ENV, sql_env_handle); sql_env_handle = NULL; } } BOOL StudentManagement::OnInitDialog() { CDialogEx::OnInitDialog(); HICON hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_ICON_STD)); SetIcon(hIcon, FALSE); return TRUE; // return TRUE unless you set the focus to a control } void StudentManagement::startDialog() { edt_sid.SetLimitText(9); edt_sname.SetLimitText(49); edt_email.SetLimitText(49); cbx_sfalculty.AddString(_T("Computer Engineering")); cbx_sfalculty.AddString(_T("Computer Science")); cbx_sfalculty.SetCurSel(0); lcl_list_student.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVCFMT_FIXED_RATIO); lcl_list_student.InsertColumn(0, _T("ON"), LVCFMT_LEFT, 40); lcl_list_student.InsertColumn(1, _T("ID"), LVCFMT_LEFT, 70); lcl_list_student.InsertColumn(2, _T("NAME"), LVCFMT_LEFT, 140); lcl_list_student.InsertColumn(3, _T("EMAIL"), LVCFMT_LEFT, 140); lcl_list_student.InsertColumn(4, _T("FALCULTY"), LVCFMT_LEFT, 130); lcl_list_student.InsertColumn(5, _T("COMPANY"), LVCFMT_LEFT, 130); hstmt = SQL_NULL_HSTMT; if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sql_env_handle)) { connected = false; } if (SQL_SUCCESS != SQLSetEnvAttr(sql_env_handle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) { connected = false; } if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sql_env_handle, &sql_connection_handle)) { connected = false; } SQLCHAR retconstring[1024]; switch (SQLDriverConnect(sql_connection_handle, NULL, (SQLCHAR*)"DRIVER={SQL Server};SERVER=LAPTOP-V3RHTVBG\\SQLEXPRESS;DATABASE=Intern;Trusted_Connection=yes;", SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT)) { case SQL_SUCCESS_WITH_INFO: break; case SQL_INVALID_HANDLE: break; case SQL_ERROR: retcode = -1; break; default: break; } if (retcode == -1) { connected = false; return; } if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_update_handle)) { connected = false; return; } if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_add_handle)) { connected = false; return; } if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_delete_handle)) { connected = false; return; } // if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_get_handle)) { MessageBox(_T("get handle failed")); } if (SQL_SUCCESS != SQLExecDirect(sql_get_handle, (SQLCHAR*)"select * from company", SQL_NTS)) { MessageBox(_T("execdirect get failed")); } else { char id[50], intro[100], addr[50], email[50]; int num; while (SQLFetch(sql_get_handle) == SQL_SUCCESS) { SQLGetData(sql_get_handle, 1, SQL_C_CHAR, id, 50, NULL); cbx_company_list.AddString((CString)id); } } SQLFreeStmt(sql_get_handle, SQL_CLOSE); SQLFreeStmt(sql_get_handle, SQL_UNBIND); SQLFreeStmt(sql_get_handle, SQL_RESET_PARAMS); // } void StudentManagement::UpdateStudentCount() { int position = lcl_list_student.GetItemCount(); CString str_count = std::to_string(position).c_str(); txt_count_student_stddlg.SetWindowText(str_count); } void StudentManagement::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDT_SID, edt_sid); DDX_Control(pDX, IDC_EDT_SNAME, edt_sname); DDX_Control(pDX, IDC_EDT_SEMAIL, edt_email); //DDX_Control(pDX, IDC_EDT_SCOMPANY, edt_scompany); DDX_Control(pDX, IDC_CBX_SFALCULTY, cbx_sfalculty); DDX_Control(pDX, IDC_LBX_STUDENT, lcl_list_student); DDX_Control(pDX, IDC_TXT_COUNT_STUDENT, txt_count_student_stddlg); DDX_Control(pDX, IDC_CBX_COMPANY, cbx_company_list); DDX_Control(pDX, IDC_EDT_SEARCH, edt_search_stddlg); DDX_Check(pDX, IDC_RAD_SEARCH_ID, rad_search_id); DDX_Check(pDX, IDC_RAD_SEARCH_NAME, rad_search_name); if (start == TRUE) { start = FALSE; startDialog(); } } BEGIN_MESSAGE_MAP(StudentManagement, CDialogEx) ON_BN_CLICKED(IDC_BTN_SM_ADD, &StudentManagement::OnBnClickedBtnSmAdd) ON_BN_CLICKED(IDC_BTN_GET_DATA, &StudentManagement::OnBnClickedBtnGetData) ON_BN_CLICKED(IDC_BTN_DELETE, &StudentManagement::OnBnClickedBtnDelete) ON_WM_LBUTTONDBLCLK() ON_BN_CLICKED(IDC_BTN_EDIT_STDDLG, &StudentManagement::OnBnClickedBtnEditStddlg) ON_STN_CLICKED(IDC_TXT_COUNT_STUDENT, &StudentManagement::OnStnClickedTxtCountStudent) ON_BN_CLICKED(IDC_BTN_EDIT_SCORE, &StudentManagement::OnBnClickedBtnEditScore) END_MESSAGE_MAP() void StudentManagement::UpdateStudentList() { UpdateData(TRUE); do { if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_get_handle)) { MessageBox(_T("get handle failed")); } if (SQL_SUCCESS != SQLExecDirect(sql_get_handle, (SQLCHAR*)"select * from student", SQL_NTS)) { MessageBox(_T("execdirect get failed")); break; } else { lcl_list_student.SetRedraw(FALSE); lcl_list_student.DeleteAllItems(); lcl_list_student.SetRedraw(TRUE); int stt = 0; char id[10], username[50], email[50], sname[50], falculty[50], company[50]; while (SQLFetch(sql_get_handle) == SQL_SUCCESS) { SQLGetData(sql_get_handle, 1, SQL_C_CHAR, id, 10, NULL); SQLGetData(sql_get_handle, 2, SQL_C_CHAR, username, 50, NULL); SQLGetData(sql_get_handle, 3, SQL_C_CHAR, sname, 50, NULL); SQLGetData(sql_get_handle, 4, SQL_C_CHAR, email, 50, NULL); SQLGetData(sql_get_handle, 5, SQL_C_CHAR, falculty, 50, NULL); SQLGetData(sql_get_handle, 6, SQL_C_CHAR, company, 50, NULL); lcl_list_student.InsertItem(stt, std::to_string(stt+1).c_str()); lcl_list_student.SetItemText(stt, 1, id); lcl_list_student.SetItemText(stt, 2, sname); lcl_list_student.SetItemText(stt, 3, email); lcl_list_student.SetItemText(stt, 4, falculty); lcl_list_student.SetItemText(stt++, 5, company); } /*MessageBox(_T("Successfully!"));*/ } } while (FALSE); SQLFreeStmt(sql_get_handle, SQL_CLOSE); SQLFreeStmt(sql_get_handle, SQL_UNBIND); SQLFreeStmt(sql_get_handle, SQL_RESET_PARAMS); UpdateData(FALSE); UpdateStudentCount(); /*if (sql_get_handle != SQL_NULL_HSTMT) { SQLFreeHandle(SQL_HANDLE_STMT, sql_get_handle); sql_get_handle = NULL; }*/ } void StudentManagement::OnLButtonDblClk(UINT nFlags, CPoint point) { /*POSITION pos = lcl_list_student.GetFirstSelectedItemPosition(); if (pos == NULL) { } else { int n = lcl_list_student.GetNextSelectedItem(pos); CString str = std::to_string(n).c_str(); MessageBox(str); }*/ //MessageBox(_T(output)); /*CString str_ = _T("-"); CString str0 = lcl_list_student.GetItemText(0,1); CString str1 = lcl_list_student.GetItemText(1,1); CString str2 = lcl_list_student.GetItemText(2,1); MessageBox(str + str_ + str0 + str_ + str1 + str_ + str2);*/ /*int position = lcl_list_student.GetSelectionMark(); CString str_position = std::to_string(position).c_str(); MessageBox(str_position);*/ } void StudentManagement::OnBnClickedBtnSmAdd() { UpdateData(TRUE); bool allow_add = true; CString str_ID, str_name, str_email, str_company, str_falculty; edt_sid.GetWindowText(str_ID); edt_sname.GetWindowText(str_name); edt_email.GetWindowText(str_email); cbx_sfalculty.GetLBText(cbx_sfalculty.GetCurSel(), str_falculty); if (str_ID.GetLength() == 0) { MessageBox(_T("ID IS EMPTY!")); } else if (str_name.GetLength() == 0){ MessageBox(_T("NAME IS EMPTY!")); } else if (str_email.GetLength() == 0) { MessageBox(_T("EMAIL IS EMPTY!")); } else if (cbx_company_list.GetCurSel() == -1) { MessageBox(_T("COMPANY IS EMPTY!")); } else { cbx_company_list.GetLBText(cbx_company_list.GetCurSel(), str_company); if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_check_handle)) { MessageBox(_T("check handle failed")); } if (SQL_SUCCESS != SQLExecDirect(sql_check_handle, (SQLCHAR*)"select * from Student", SQL_NTS)) { MessageBox(_T("execDirect check error")); return; } CString cs_id, cs_sname, cs_email; char id[10], username[50], email[50], sname[50], falculty[50], company[50]; while (SQLFetch(sql_check_handle) == SQL_SUCCESS) { SQLGetData(sql_check_handle, 1, SQL_C_CHAR, id, 10, NULL); SQLGetData(sql_check_handle, 2, SQL_C_CHAR, username, 50, NULL); SQLGetData(sql_check_handle, 3, SQL_C_CHAR, sname, 50, NULL); SQLGetData(sql_check_handle, 4, SQL_C_CHAR, email, 50, NULL); SQLGetData(sql_check_handle, 5, SQL_C_CHAR, falculty, 50, NULL); SQLGetData(sql_check_handle, 6, SQL_C_CHAR, company, 50, NULL); if (str_ID == (CString)id) { allow_add = false; MessageBox(_T("ID is already exists")); break; } else if (str_email == (CString)email) { allow_add = false; MessageBox(_T("EMAIL is already exists")); break; } } SQLFreeStmt(sql_check_handle, SQL_CLOSE); SQLFreeStmt(sql_check_handle, SQL_UNBIND); SQLFreeStmt(sql_check_handle, SQL_RESET_PARAMS); if (allow_add == false) { //MessageBox(_T("allow = false")); return; } else { /*lcl_list_student.InsertItem(0, 0); lcl_list_student.SetItemText(0, 1, str_ID); lcl_list_student.SetItemText(0, 2, str_name); lcl_list_student.SetItemText(0, 3, str_email); lcl_list_student.SetItemText(0, 4, str_falculty); lcl_list_student.SetItemText(0, 5, str_company);*/ SQLINTEGER cb1 = SQL_NTS, cb2 = SQL_NTS, cb3 = SQL_NTS, cb4 = SQL_NTS, cb5 = SQL_NTS, cb6 = SQL_NTS; char id[10], name[50], uname[30], email[50], falculty[50], company[50]; SQLBindParameter(sql_add_handle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 10, 0, id, 0, &cb1); SQLBindParameter(sql_add_handle, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 30, 0, uname, 0, &cb2); SQLBindParameter(sql_add_handle, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 50, 0, name, 0, &cb3); SQLBindParameter(sql_add_handle, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 50, 0, email, 0, &cb4); SQLBindParameter(sql_add_handle, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 50, 0, falculty, 0, &cb5); SQLBindParameter(sql_add_handle, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 50, 0, company, 0, &cb6); sprintf_s(id, "%s", str_ID); sprintf_s(name, "%s", str_name); sprintf_s(uname, "%s", _T("Pep")); sprintf_s(email, "%s", str_email); sprintf_s(falculty, "%s", str_falculty); sprintf_s(company, "%s", str_company); //MessageBox(uname); SQLExecDirect(sql_add_handle, (SQLCHAR*)"INSERT INTO student(id,username,s_name,email,falculty,company) VALUES(?,?,?,?,?,?);", SQL_NTS); //SQLExecDirect(sql_edit_handle, (SQLCHAR*)"DELETE FROM student where id='123'", SQL_NTS); //SQLExecDirect(sql_edit_handle, (SQLCHAR*)"INSERT INTO student(id,username,s_name,email,falculty,company) VALUES('123','Jose','Dung','nul','nul','nul');", SQL_NTS); edt_sid.SetWindowText(_T("")); edt_sname.SetWindowText(_T("")); edt_email.SetWindowText(_T("")); cbx_company_list.SetCurSel(-1); } } SQLFreeStmt(sql_add_handle, SQL_CLOSE); SQLFreeStmt(sql_add_handle, SQL_UNBIND); SQLFreeStmt(sql_add_handle, SQL_RESET_PARAMS); UpdateData(FALSE); UpdateStudentList(); UpdateStudentCount(); } void StudentManagement::OnBnClickedBtnGetData() { //Search CString condition; edt_search_stddlg.GetWindowText(condition); if (condition.GetLength() > 0) { UpdateData(TRUE); do { if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_get_handle)) { MessageBox(_T("get handle failed")); } else { SQLINTEGER cb1 = SQL_NTS; char con[50]; SQLBindParameter(sql_get_handle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 50, 0, con, 0, &cb1); sprintf_s(con, "%s", condition); if (rad_search_id == 1) { SQLExecDirect(sql_get_handle, (SQLCHAR*)"select * from searchID(?)", SQL_NTS); } else if (rad_search_name == 1) { SQLExecDirect(sql_get_handle, (SQLCHAR*)"select * from searchName(?)", SQL_NTS); } lcl_list_student.SetRedraw(FALSE); lcl_list_student.DeleteAllItems(); lcl_list_student.SetRedraw(TRUE); char id[10], username[50], email[50], sname[50], falculty[50], company[50]; int stt = 0; while (SQLFetch(sql_get_handle) == SQL_SUCCESS) { SQLGetData(sql_get_handle, 1, SQL_C_CHAR, id, 10, NULL); SQLGetData(sql_get_handle, 2, SQL_C_CHAR, username, 50, NULL); SQLGetData(sql_get_handle, 3, SQL_C_CHAR, sname, 50, NULL); SQLGetData(sql_get_handle, 4, SQL_C_CHAR, email, 50, NULL); SQLGetData(sql_get_handle, 5, SQL_C_CHAR, falculty, 50, NULL); SQLGetData(sql_get_handle, 6, SQL_C_CHAR, company, 50, NULL); lcl_list_student.InsertItem(stt, std::to_string(stt+1).c_str()); lcl_list_student.SetItemText(stt, 1, id); lcl_list_student.SetItemText(stt, 2, sname); lcl_list_student.SetItemText(stt, 3, email); lcl_list_student.SetItemText(stt, 4, falculty); lcl_list_student.SetItemText(stt++, 5, company); } } } while (FALSE); SQLFreeStmt(sql_get_handle, SQL_CLOSE); SQLFreeStmt(sql_get_handle, SQL_UNBIND); SQLFreeStmt(sql_get_handle, SQL_RESET_PARAMS); UpdateData(FALSE); UpdateStudentCount(); } else { UpdateStudentList(); } //UpdateData(TRUE); //do //{ // if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sql_connection_handle, &sql_get_handle)) { // return; // } // if (SQL_SUCCESS != SQLExecDirect(sql_get_handle, (SQLCHAR*)"select * from Student", SQL_NTS)) // { // /*MessageBox(_T("get data error")); // return;*/ // } // else // { // lcl_list_student.SetRedraw(FALSE); // lcl_list_student.DeleteAllItems(); // lcl_list_student.SetRedraw(TRUE); // char id[30], username[50], email[50], sname[50], falculty[50], company[50]; // while (SQLFetch(sql_get_handle) == SQL_SUCCESS) // { // SQLGetData(sql_get_handle, 1, SQL_C_CHAR, id, 30, NULL); // SQLGetData(sql_get_handle, 2, SQL_C_CHAR, username, 50, NULL); // SQLGetData(sql_get_handle, 3, SQL_C_CHAR, sname, 50, NULL); // SQLGetData(sql_get_handle, 4, SQL_C_CHAR, email, 50, NULL); // SQLGetData(sql_get_handle, 5, SQL_C_CHAR, falculty, 50, NULL); // SQLGetData(sql_get_handle, 6, SQL_C_CHAR, company, 50, NULL); // lcl_list_student.InsertItem(0, id); // lcl_list_student.SetItemText(0, 1, sname); // lcl_list_student.SetItemText(0, 2, email); // lcl_list_student.SetItemText(0, 3, falculty); // lcl_list_student.SetItemText(0, 4, company); // } // /*MessageBox(_T("Successfully!"));*/ // // } //} while (FALSE); //UpdateStudentCount(); //UpdateData(FALSE); } void StudentManagement::OnBnClickedBtnDelete() { UpdateData(TRUE); int num_student = lcl_list_student.GetItemCount(); int int_select_pos = -1; for (int i = 0; i < num_student; i++) { if (lcl_list_student.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED) { int_select_pos = i; break; } } if (int_select_pos != -1) { if (MessageBox(_T("Are you sure?"), _T("Delete confirm"), MB_OKCANCEL) == IDOK) { CString selected_id = lcl_list_student.GetItemText(int_select_pos, 0); //get id select SQLINTEGER cb1 = SQL_NTS; char id[10]; SQLBindParameter(sql_delete_handle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 10, 0, id, 0, &cb1); sprintf_s(id, "%s", selected_id); SQLExecDirect(sql_delete_handle, (SQLCHAR*)"delete from student where id =?", SQL_NTS); lcl_list_student.DeleteItem(int_select_pos); UpdateStudentCount(); SQLFreeStmt(sql_delete_handle, SQL_CLOSE); SQLFreeStmt(sql_delete_handle, SQL_UNBIND); SQLFreeStmt(sql_delete_handle, SQL_RESET_PARAMS); }; } UpdateData(FALSE); } void StudentManagement::OnBnClickedBtnEditStddlg() { int num_student = lcl_list_student.GetItemCount(); int int_select_pos = -1; for (int i = 0; i < num_student; i++) { if (lcl_list_student.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED) { int_select_pos = i; break; } } if (int_select_pos != -1) { CString str_select_pos = std::to_string(int_select_pos).c_str(); CString str_select_id = lcl_list_student.GetItemText(int_select_pos, 1); CString str_select_name = lcl_list_student.GetItemText(int_select_pos, 2); CString str_select_email = lcl_list_student.GetItemText(int_select_pos, 3); CString str_select_falculty = lcl_list_student.GetItemText(int_select_pos, 4); CString str_select_company = lcl_list_student.GetItemText(int_select_pos, 5); EditStudent es; es.SetHandle(sql_connection_handle); es.SetID(str_select_id); es.SetInfo(str_select_falculty, str_select_name, str_select_email, str_select_company); es.DoModal(); UpdateStudentList(); } } void StudentManagement::CheckInputValues() { } void StudentManagement::OnStnClickedTxtCountStudent() { // TODO: Add your control notification handler code here } void StudentManagement::OnBnClickedBtnEditScore() { int num_student = lcl_list_student.GetItemCount(); int int_select_pos = -1; for (int i = 0; i < num_student; i++) { if (lcl_list_student.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED) { int_select_pos = i; break; } } if (int_select_pos != -1) { CString sid = lcl_list_student.GetItemText(int_select_pos, 1); CString sname = lcl_list_student.GetItemText(int_select_pos, 2); CString scompany = lcl_list_student.GetItemText(int_select_pos, 5); EditScore es; es.GetHandle(sql_connection_handle); es.GetInfo(sid, sname, scompany); es.DoModal(); } }
[ "hoangdung.200298@gmail.com" ]
hoangdung.200298@gmail.com
fba195b52b46a2da0b990f55752ed52f646d89d3
3495a7c49d883e024098dfbee510a4147ee23d59
/Source/Conquest/Private/Conquest.cpp
8298fd0af5daf5f166efc9a8d586361fc8c4df49
[]
no_license
1016640/19T1_Conquest
c99f6413ec5161000b99b9f185dfbccbcfe7e452
f8b5cb0549c3f4ba77206a28adabb498455736f9
refs/heads/master
2022-01-05T22:48:24.343057
2019-05-23T05:06:57
2019-05-23T05:06:57
175,132,479
2
0
null
2019-05-14T04:41:01
2019-03-12T04:00:35
C++
UTF-8
C++
false
false
136
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Conquest.h" DEFINE_LOG_CATEGORY(LogConquest);
[ "1016640@student.sae.edu.au" ]
1016640@student.sae.edu.au
bd46cf63814f19f99c0820b84325710f43e6e6bc
4f5921bf5bea6663fb09a1850cbd1244f5fa5a3f
/TP4-ex2/exercise2.cpp
7d1cafbc4a5c304e5b9be7fd54c5024d10e2caa6
[]
no_license
maryaryspayeva/TP4
e323fd43b4fc261d800293c7ba389742e3a3f168
b47fe4f7b8789288f0e725f74278bbb4211198f3
refs/heads/master
2023-01-28T06:35:35.579553
2020-12-09T07:30:59
2020-12-09T07:30:59
319,876,562
0
0
null
null
null
null
UTF-8
C++
false
false
161
cpp
#include "exercise2.h" Exercise2::Exercise2(int a, int b){ integerA = a; integerB = b; } int Exercise2::Addition(){ return integerA + integerB; }
[ "marya.rys1@mail.ru" ]
marya.rys1@mail.ru
295ebb44f361f7b85e1dba711b608eef86e7740f
5da799088d5b10258831ed3da1a8e349ab2d7c78
/moogerfucker/synth.ino
97e70e20f7daf619739d7d513519e87f8fc12b05
[ "BSD-2-Clause" ]
permissive
ozkar99/moogerfucker
e039e43ba562b2dad61e5fcab1810c77e261e2ae
6f11cc27d7fc84ca039b54e9508d893c2d29d727
refs/heads/master
2021-01-01T16:19:57.962978
2013-09-29T21:09:06
2013-09-29T21:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,532
ino
/*Moreno Garza Oscar, "the moogerfucker" */ /* oscarmg99@gmail.com */ /* referencias: http://en.wikipedia.org/wiki/Scientific_pitch_notation http://arduino.cc/en/Tutorial/Tone */ int sensorNota = A0; int sensorOctava = A1; int sensorPitch = A2; int sensorDelay = A3; int bocinaOut = 8; int notas[] = { 0, 16, 18, 20, 22, 25, 28, 31, 0}; // nada, DO, RE, MI, FA, SOL, LA, SI, nada // son los valores de frecuencias para la octava 0. void setup ( ) { // se ocupa :( pinMode(bocinaOut, OUTPUT); } void loop() { int valorNota = map(analogRead(sensorNota), 0, 1024, 100, 800); // de 1 a 8 (con valores de 10^3), basados en el potenciometro de A0. // este caso va de silencio,do,re,mi,fa,sol,la,si,silencio int numNota = valorNota/100; // magia //se toman rangos de 10^3 para tener una zona muerta de ~100~ en el softpot en lugar de ~1~ //10% de margen de error en lugar de 1% int valorDelay = map(analogRead(sensorDelay), 0, 1024, 0, 250); //agarramos retraso de 0ms hasta 250ms int valorOctava = map(analogRead(sensorOctava), 0, 1024, 2, 7); // agarramos valores de un segundo potenciometro para establecer la octava. // de 2 a 7 por que es lo que aguanta la bocina de rango :( valorOctava = pow(2, valorOctava); // 2^octava. int tono = notas[numNota]*valorOctava ; // tono = valor_base_de_frec*(2^numero_de_octava) int rango = tono/4; //un cuarto de tono, asi no sobrelapamos los tonos. //los extremos serian un semi-tono abajo y medio semi-tono arriba. int pitchMod = map(analogRead(sensorPitch), 0, 1024, -rango, rango*2); //tenemos la mitad de nuestro tono para rango hacia abajo para llegar a un semi-tono en el minimo. //para arriba tenemos el doble para llegar a un semi-tono arriba. /*RUTINA PRINCIPAL: */ if (valorNota < 800 && valorNota > 100 ) { // si esta en rango valido, de 1 a 7: if ( valorDelay <= 5 ) { tone(bocinaOut, tono + pitchMod); // si es 0 no cortamos. //0.5% de margen de error } else { tone (bocinaOut, tono + pitchMod); delay(valorDelay); //mandamos sonido en tiempo basado en sensorDelay noTone(bocinaOut); //no mandamos sonido en el mismo tiemp. delay(valorDelay); } // silencio. } else { //si no esta en rango valido: noTone(bocinaOut); // no mandamos nada. } delay(1); // por estabilidad esperamos 1 milisegundo. }
[ "oscarmg99@gmail.com" ]
oscarmg99@gmail.com
6f8f2d27f443049047ba0030134abc36ca936eee
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/sdk/samples/vc/objpathparser/pathtest.cpp
040a22470d8a933e7df48bb61bb3086e8401371c
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,782
cpp
// ************************************************************************** // // Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved // // File: pathtest.cpp // // Description: // Test app to test the object path parser // // History: // // ************************************************************************** #include <windows.h> #include <stdio.h> #include "genlex.h" #include "objpath.h" void main(int argc, char **argv) { ParsedObjectPath* pOutput = 0; wchar_t *pPath = L"\\\\.\\root\\default:MyClass=\"keyval\""; CObjectPathParser p; int nStatus = p.Parse(pPath, &pOutput); printf("Return code is %d\n", nStatus); if (nStatus != 0) return; printf("----Output----\n"); LPWSTR pKey = pOutput->GetKeyString(); printf("Key String = <%S>\n", pKey); delete pKey; printf("Server = %S\n", pOutput->m_pServer); for (DWORD dwIx = 0; dwIx < pOutput->m_dwNumNamespaces; dwIx++) { printf("Namespace = <%S>\n", pOutput->m_paNamespaces[dwIx]); } printf("Class = <%S>\n", pOutput->m_pClass); // If here, the key ref is complete. // ================================= for (dwIx = 0; dwIx < pOutput->m_dwNumKeys; dwIx++) { KeyRef *pTmp = pOutput->m_paKeys[dwIx]; printf("*** KeyRef contents:\n"); printf(" Name = %S Value=", pTmp->m_pName); switch (V_VT(&pTmp->m_vValue)) { case VT_I4: printf("%d", V_I4(&pTmp->m_vValue)); break; case VT_R8: printf("%f", V_R8(&pTmp->m_vValue)); break; case VT_BSTR: printf("<%S>", V_BSTR(&pTmp->m_vValue)); break; default: printf("BAD KEY REF\n"); } printf("\n"); } p.Free(pOutput); }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
ece35ac362e011c484cd5b495f51f9c50bfc8cad
f0a26ec6b779e86a62deaf3f405b7a83868bc743
/Engine/Source/Runtime/Engine/Classes/Distributions/DistributionFloat.h
29d6d3d362a33a6be810dd5f4bdeb611c4843641
[]
no_license
Tigrouzen/UnrealEngine-4
0f15a56176439aef787b29d7c80e13bfe5c89237
f81fe535e53ac69602bb62c5857bcdd6e9a245ed
refs/heads/master
2021-01-15T13:29:57.883294
2014-03-20T15:12:46
2014-03-20T15:12:46
18,375,899
1
0
null
null
null
null
UTF-8
C++
false
false
3,910
h
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #pragma once #include "DistributionFloat.generated.h" /** Type-safe floating point distribution. */ #if !CPP //noexport struct USTRUCT(noexport) struct FFloatDistribution { UPROPERTY() FDistributionLookupTable Table; }; #endif USTRUCT() struct FRawDistributionFloat : public FRawDistribution { GENERATED_USTRUCT_BODY() private: UPROPERTY() float MinValue; UPROPERTY() float MaxValue; public: UPROPERTY(EditAnywhere, export, noclear, Category=RawDistributionFloat) class UDistributionFloat* Distribution; FRawDistributionFloat() : MinValue(0) , MaxValue(0) , Distribution(NULL) { } #if WITH_EDITOR /**` * Initialize a raw distribution from the original Unreal distribution */ void Initialize(); #endif /** * Gets a pointer to the raw distribution if you can just call FRawDistribution::GetValue1 on it, otherwise NULL */ const FRawDistribution* GetFastRawDistribution(); /** * Get the value at the specified F */ ENGINE_API float GetValue(float F=0.0f, UObject* Data=NULL, class FRandomStream* InRandomStream = NULL); /** * Get the min and max values */ void GetOutRange(float& MinOut, float& MaxOut); /** * Is this distribution a uniform type? (ie, does it have two values per entry?) */ inline bool IsUniform() { return LookupTable.SubEntryStride != 0; } }; UCLASS(abstract, customconstructor,MinimalAPI) class UDistributionFloat : public UDistribution { GENERATED_UCLASS_BODY() /** Can this variable be baked out to a FRawDistribution? Should be true 99% of the time*/ UPROPERTY(EditAnywhere, Category=Baked) uint32 bCanBeBaked:1; /** Set internally when the distribution is updated so that that FRawDistribution can know to update itself*/ uint32 bIsDirty:1; /** Script-accessible way to query a float distribution */ virtual float GetFloatValue(float F = 0); UDistributionFloat(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP) , bCanBeBaked(true) , bIsDirty(true) // make sure the FRawDistribution is initialized { } //@todo.CONSOLE: Currently, consoles need this? At least until we have some sort of cooking/packaging step! /** * Return the operation used at runtime to calculate the final value */ virtual ERawDistributionOperation GetOperation() const { return RDO_None; } /** * Returns the lock axes flag used at runtime to swizzle random stream values. Not used for distributions derived from UDistributionFloat. */ virtual uint8 GetLockFlag() const { return 0; } /** * Fill out an array of floats and return the number of elements in the entry * * @param Time The time to evaluate the distribution * @param Values An array of values to be filled out, guaranteed to be big enough for 4 values * @return The number of elements (values) set in the array */ virtual uint32 InitializeRawEntry(float Time, float* Values) const; /** @todo document */ virtual float GetValue( float F = 0.f, UObject* Data = NULL, class FRandomStream* InRandomStream = NULL ) const; // Begin FCurveEdInterface Interface virtual void GetInRange(float& MinIn, float& MaxIn) const OVERRIDE; virtual void GetOutRange(float& MinOut, float& MaxOut) const OVERRIDE; // End FCurveEdInterface Interface /** @return true of this distribution can be baked into a FRawDistribution lookup table, otherwise false */ virtual bool CanBeBaked() const { return true; } /** * Returns the number of values in the distribution. 1 for float. */ int32 GetValueCount() const { return 1; } /** Begin UObject interface */ #if WITH_EDITOR virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) OVERRIDE; #endif // WITH_EDITOR virtual bool NeedsLoadForClient() const OVERRIDE; virtual bool NeedsLoadForServer() const OVERRIDE; /** End UObject interface */ };
[ "michaellam430@gmail.com" ]
michaellam430@gmail.com
2a042a93ddc5366f7bc6a176011f8080de8253fc
d78ab1e4cb8a669fbd4b5346683345c3926f4e07
/Editor/scintilla/include/PropSet.h
563a3291bec075547db0ffeb3d1dd5559b63acfa
[ "LicenseRef-scancode-unknown-license-reference", "Artistic-2.0", "LicenseRef-scancode-scintilla" ]
permissive
sonneveld/ags
4baca2321a1c1a13621322eb107d5338e9231fbf
539a40a25f4caa7b7cec678084cfcde252418c77
refs/heads/ags3--sdl2
2022-04-30T19:38:51.480211
2019-07-27T11:08:38
2019-11-03T06:53:44
40,235,193
2
0
NOASSERTION
2022-02-20T11:15:37
2015-08-05T08:54:39
C
UTF-8
C++
false
false
3,372
h
// Scintilla source code edit control /** @file PropSet.h ** A Java style properties file module. **/ // Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef PROPSET_H #define PROPSET_H #include "SString.h" bool EqualCaseInsensitive(const char *a, const char *b); bool isprefix(const char *target, const char *prefix); struct Property { unsigned int hash; char *key; char *val; Property *next; Property() : hash(0), key(0), val(0), next(0) {} }; /** */ class PropSet { protected: enum { hashRoots=31 }; Property *props[hashRoots]; Property *enumnext; int enumhash; static bool caseSensitiveFilenames; static unsigned int HashString(const char *s, size_t len) { unsigned int ret = 0; while (len--) { ret <<= 4; ret ^= *s; s++; } return ret; } static bool IncludesVar(const char *value, const char *key); public: PropSet *superPS; PropSet(); ~PropSet(); void Set(const char *key, const char *val, int lenKey=-1, int lenVal=-1); void Set(const char *keyVal); void Unset(const char *key, int lenKey=-1); void SetMultiple(const char *s); SString Get(const char *key); SString GetExpanded(const char *key); SString Expand(const char *withVars, int maxExpands=100); int GetInt(const char *key, int defaultValue=0); SString GetWild(const char *keybase, const char *filename); SString GetNewExpand(const char *keybase, const char *filename=""); void Clear(); char *ToString(); // Caller must delete[] the return value bool GetFirst(char **key, char **val); bool GetNext(char **key, char **val); static void SetCaseSensitiveFilenames(bool caseSensitiveFilenames_) { caseSensitiveFilenames = caseSensitiveFilenames_; } private: // copy-value semantics not implemented PropSet(const PropSet &copy); void operator=(const PropSet &assign); }; /** */ class WordList { public: // Each word contains at least one character - a empty word acts as sentinel at the end. char **words; char **wordsNoCase; char *list; int len; bool onlyLineEnds; ///< Delimited by any white space or only line ends bool sorted; bool sortedNoCase; int starts[256]; WordList(bool onlyLineEnds_ = false) : words(0), wordsNoCase(0), list(0), len(0), onlyLineEnds(onlyLineEnds_), sorted(false), sortedNoCase(false) {} ~WordList() { Clear(); } operator bool() { return len ? true : false; } char *operator[](int ind) { return words[ind]; } void Clear(); void Set(const char *s); char *Allocate(int size); void SetFromAllocated(); bool InList(const char *s); bool InListAbbreviated(const char *s, const char marker); const char *GetNearestWord(const char *wordStart, int searchLen, bool ignoreCase = false, SString wordCharacters="", int wordIndex = -1); char *GetNearestWords(const char *wordStart, int searchLen, bool ignoreCase=false, char otherSeparator='\0', bool exactLen=false); }; inline bool IsAlphabetic(unsigned int ch) { return ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')); } #ifdef _MSC_VER // Visual C++ doesn't like the private copy idiom for disabling // the default copy constructor and operator=, but it's fine. #pragma warning(disable: 4511 4512) #endif #endif
[ "tobias.han@gmx.de" ]
tobias.han@gmx.de
15bc5eca02f6edccdb9dd4d44f69fb241b0f8402
bc8e8fdf8224f852e32676fa219c1451296e61c0
/Logger/Logger.h
1ca7f0167bfb9d680ceaa2d98e3bad0847993765
[]
no_license
funkynicco/irc-bouncer
f303404cf710b1849bcf33ee238a6a804adec7b2
b4633ab0900a79e22a3c6b8d3d3183ddef8b0673
refs/heads/master
2022-12-17T04:45:49.845235
2014-05-03T05:11:03
2014-05-03T05:11:03
295,461,301
0
0
null
null
null
null
UTF-8
C++
false
false
468
h
#pragma once class CLogger { public: CLogger(); virtual ~CLogger(); void Write( const char* format, ... ); static CLogger* GetInstance() { static CLogger instance; return &instance; } private: CRITICAL_SECTION m_cs; time_t m_tmInstanceId; char m_szFilename[ 256 ]; }; void ConvertToHex( const void* data, size_t sizeOfData, char* destination ); void LogData( BOOL bIsOutgoing, const void* data, size_t length );
[ "funkynicco@gmail.com" ]
funkynicco@gmail.com
229c1f1369f6899cbf1d98b6984c8e8e717eb070
ebe2890f04f28b1f7a37bff55504a8635855e235
/source/BaseEngine/Controllers/CharacterController.cpp
bbfab430ea777a293d29818f16534e05dfc2e7a6
[]
no_license
wbach/OpenGL_Game
f6c8f606d2be66aace5aa4189c43a13d33978e9c
4f019a69cbd84b3c4d0053132df4759e8df327ff
refs/heads/master
2021-01-12T09:49:17.267739
2017-01-27T15:21:23
2017-01-27T15:21:23
76,265,360
0
0
null
null
null
null
UTF-8
C++
false
false
90
cpp
#include "CharacterController.h" void CCharacterController::Translate(glm::vec3 vec) { }
[ "wbach.projects@gmail.com" ]
wbach.projects@gmail.com
6d7f5e392c0404724358a5211f6b940939429fa9
0ff000614356fc894d3eea5bffcdb2714a2ca98a
/proton-c/bindings/cpp/include/proton/fwd.hpp
3ed92835f8307fcacd194de929f6355d9510efa3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
salmander/qpid-proton
ff4014ec9bc804c8f1b4f0053ce910cefce4dc37
e0ec0b61d970a95a21ff7ea53bec5ea3e82bbbab
refs/heads/master
2020-12-31T05:56:42.554972
2017-01-31T10:10:31
2017-01-31T10:10:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,579
hpp
#ifndef PROTON_FWD_HPP #define PROTON_FWD_HPP /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ namespace proton { class annotation_key; class connection; class connection_options; class container; class delivery; class error_condition; class event; class message; class message_id; class messaging_handler; class listen_handler; class listener; class receiver; class receiver_iterator; class receiver_options; class reconnect_timer; class sasl; class sender; class sender_iterator; class sender_options; class session; class session_options; class source_options; class ssl; class target_options; class tracker; class transport; class url; class void_function0; namespace io { class connection_driver; } template <class T> class returned; template <class T> class thread_safe; } #endif // PROTON_FWD_HPP
[ "astitcher@apache.org" ]
astitcher@apache.org
4ceecfc62ab1d4762810611ed438490de365b63c
1172e863a62ec1a681859a439537a85f32ce6b43
/Libraries/Webbotlib/Sensors/Encoder/Generic/fastquad.h
ee24ec5f00eda1bdffab079a5796762faedbb5e2
[]
no_license
yashmanian/AVR-code
48dc638f1a4bad3b3845d574db484d07b615d31f
2ad9cf0291e548db5a1f38f5607b2af8bd7b5434
refs/heads/master
2021-04-30T09:04:38.299765
2018-02-13T13:55:44
2018-02-13T13:55:44
121,388,700
0
0
null
null
null
null
UTF-8
C++
false
false
5,808
h
/* * $Id: fastquad.h,v 1.7 2010/09/08 18:26:52 clivewebster Exp $ * * $Log: fastquad.h,v $ * Revision 1.7 2010/09/08 18:26:52 clivewebster * Add encoder interpolation * * Revision 1.6 2010/08/10 22:47:18 clivewebster * Add fastquadx2 stuff * * Revision 1.5 2010/06/14 19:05:35 clivewebster * Add copyright license info * * Revision 1.4 2010/06/14 18:25:20 clivewebster * Initial version * * * Copyright (C) 2010 Clive Webster (webbot@webbot.org.uk) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * fastquad.h * * Created on: 9 Jun 2010 * Author: Clive Webster * * If the encoder has a large number of ticks per revolution then the * pinchange interrupts used in quadrature.h may be handled too slowly. * This version is optimised for speed of the IRQ handling */ #ifndef FASTQUAD_H_ #define FASTQUAD_H_ #include "../_encoder_common.h" #ifdef __cplusplus /* ===================== C Code ===============================================*/ extern "C" { #endif extern const ENCODER_CLASS c_fastquad_INT0; extern const ENCODER_CLASS c_fastquad_INT1; extern const ENCODER_CLASS c_fastquad_INT2; extern const ENCODER_CLASS c_fastquad_INT3; extern const ENCODER_CLASS c_fastquad_INT4; extern const ENCODER_CLASS c_fastquad_INT5; extern const ENCODER_CLASS c_fastquad_INT6; extern const ENCODER_CLASS c_fastquad_INT7; typedef struct s_fastquad{ ENCODER encoder; // const IOPin* channelB; // The Channel B pin }FAST_QUADRATURE; #define MAKE_GENERIC_FAST_QUADRATURE(channelA, channelB, inverted, numStripes,interpolate) {\ MAKE_ENCODER_SENSOR(c_fastquad_##channelA, inverted,numStripes,interpolate), \ /*channelB*/} extern const ENCODER_CLASS c_fastquadx2_INT0_INT1; extern const ENCODER_CLASS c_fastquadx2_INT0_INT2; extern const ENCODER_CLASS c_fastquadx2_INT0_INT3; extern const ENCODER_CLASS c_fastquadx2_INT0_INT4; extern const ENCODER_CLASS c_fastquadx2_INT0_INT5; extern const ENCODER_CLASS c_fastquadx2_INT0_INT6; extern const ENCODER_CLASS c_fastquadx2_INT0_INT7; extern const ENCODER_CLASS c_fastquadx2_INT1_INT0; extern const ENCODER_CLASS c_fastquadx2_INT1_INT2; extern const ENCODER_CLASS c_fastquadx2_INT1_INT3; extern const ENCODER_CLASS c_fastquadx2_INT1_INT4; extern const ENCODER_CLASS c_fastquadx2_INT1_INT5; extern const ENCODER_CLASS c_fastquadx2_INT1_INT6; extern const ENCODER_CLASS c_fastquadx2_INT1_INT7; extern const ENCODER_CLASS c_fastquadx2_INT2_INT0; extern const ENCODER_CLASS c_fastquadx2_INT2_INT1; extern const ENCODER_CLASS c_fastquadx2_INT2_INT3; extern const ENCODER_CLASS c_fastquadx2_INT2_INT4; extern const ENCODER_CLASS c_fastquadx2_INT2_INT5; extern const ENCODER_CLASS c_fastquadx2_INT2_INT6; extern const ENCODER_CLASS c_fastquadx2_INT2_INT7; extern const ENCODER_CLASS c_fastquadx2_INT3_INT0; extern const ENCODER_CLASS c_fastquadx2_INT3_INT1; extern const ENCODER_CLASS c_fastquadx2_INT3_INT2; extern const ENCODER_CLASS c_fastquadx2_INT3_INT4; extern const ENCODER_CLASS c_fastquadx2_INT3_INT5; extern const ENCODER_CLASS c_fastquadx2_INT3_INT6; extern const ENCODER_CLASS c_fastquadx2_INT3_INT7; extern const ENCODER_CLASS c_fastquadx2_INT4_INT0; extern const ENCODER_CLASS c_fastquadx2_INT4_INT1; extern const ENCODER_CLASS c_fastquadx2_INT4_INT2; extern const ENCODER_CLASS c_fastquadx2_INT4_INT3; extern const ENCODER_CLASS c_fastquadx2_INT4_INT5; extern const ENCODER_CLASS c_fastquadx2_INT4_INT6; extern const ENCODER_CLASS c_fastquadx2_INT4_INT7; extern const ENCODER_CLASS c_fastquadx2_INT5_INT0; extern const ENCODER_CLASS c_fastquadx2_INT5_INT1; extern const ENCODER_CLASS c_fastquadx2_INT5_INT2; extern const ENCODER_CLASS c_fastquadx2_INT5_INT3; extern const ENCODER_CLASS c_fastquadx2_INT5_INT4; extern const ENCODER_CLASS c_fastquadx2_INT5_INT6; extern const ENCODER_CLASS c_fastquadx2_INT5_INT7; extern const ENCODER_CLASS c_fastquadx2_INT6_INT0; extern const ENCODER_CLASS c_fastquadx2_INT6_INT1; extern const ENCODER_CLASS c_fastquadx2_INT6_INT2; extern const ENCODER_CLASS c_fastquadx2_INT6_INT3; extern const ENCODER_CLASS c_fastquadx2_INT6_INT4; extern const ENCODER_CLASS c_fastquadx2_INT6_INT5; extern const ENCODER_CLASS c_fastquadx2_INT6_INT7; extern const ENCODER_CLASS c_fastquadx2_INT7_INT0; extern const ENCODER_CLASS c_fastquadx2_INT7_INT1; extern const ENCODER_CLASS c_fastquadx2_INT7_INT2; extern const ENCODER_CLASS c_fastquadx2_INT7_INT3; extern const ENCODER_CLASS c_fastquadx2_INT7_INT4; extern const ENCODER_CLASS c_fastquadx2_INT7_INT5; extern const ENCODER_CLASS c_fastquadx2_INT7_INT6; typedef struct s_fastquadx2{ ENCODER encoder; }FAST_QUADRATUREx2; #define MAKE_GENERIC_FAST_QUADRATUREx2(channelA, channelB, inverted, numStripes,interpolate) {\ MAKE_ENCODER_SENSOR(c_fastquadx2_ ## channelA ## _ ## channelB, inverted,2*(numStripes),interpolate) } #ifdef __cplusplus } class FastQuadrature : public Encoder{ public: FastQuadrature(FAST_QUADRATURE* cstr) : Encoder(&cstr->encoder){} FastQuadrature(FAST_QUADRATUREx2* cstr) : Encoder(&cstr->encoder){} }; #endif #endif /* FASTQUAD_H_ */
[ "ymanian@umd.edu" ]
ymanian@umd.edu
029c1bcc7f68c0ad4ba5754e4cdded15612df75e
e0a2058402dd7434885cfec8d38d8a2b3a9d49fb
/ThirdYear/SecondSemester/CG/Engine/headers/light.h
23db6f773f208ebc58daf8848cbc574990380a2d
[]
no_license
pCosta99/Graduation
71017530976e1b9b7cdd0ac30c6936149fb9f42e
9acfe29f78dfe9b27c8b31ddd8b8255911e3e25f
refs/heads/main
2023-02-25T10:18:03.848767
2021-01-29T07:53:41
2021-01-29T07:53:41
334,024,574
0
0
null
null
null
null
UTF-8
C++
false
false
231
h
#ifndef _LIGHT_H_ #define _LIGHT_H_ #ifdef __APPLE__ #include <GLUT/glut.h> #include <GL/glew.h> #else #include <GL/glew.h> #include <GL/glut.h> #endif class Light{ public: virtual void execute(void) = 0; }; #endif
[ "costapedro.a1999@gmail.com" ]
costapedro.a1999@gmail.com
f13dd386386b6421e59a004618ede7366c69426e
1086ef8bcd54d4417175a4a77e5d63b53a47c8cf
/Forks/Online-Judges-Problems-SourceCode-master/UVa/567 - Risk.cpp
7105d4b97006a1c2c0f22f687eb62e9c9e5d1d22
[]
no_license
wisdomtohe/CompetitiveProgramming
b883da6380f56af0c2625318deed3529cb0838f6
a20bfea8a2fd539382a100d843fb91126ab5ad34
refs/heads/master
2022-12-18T17:33:48.399350
2020-09-25T02:24:41
2020-09-25T02:24:41
298,446,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,067
cpp
//============================================================================ // File : 567 - Risk.cpp // Author : AHMED HANI IBRAHIM // Copyright : AHani // Version : UVa - Accepted - 0.112 // Created on August 17, 2012, 10:08 AM //============================================================================ #include <cstdlib> #include <stdio.h> #include <string.h> #include<string> #include<iostream> #include<map> #include<algorithm> #include<functional> #define Max 20 + 5 #define MaxCountries 19 #define INF 1000000000 //#define INT_MAX 2147483647 #define FOR(i , N) for( int i = 0 ; i < N ; i++ ) #define FOR1e(i , N) for( int i = 1 ; i <= N ; i++ ) #define FORe(i , N) for(int i = 0 ; i <= N ; i++ ) #define FOR1(i , N) for(int i = 1 ; i < N ; i++ ) using namespace std; int NumberOfCountries; int First , Second; int Distance[Max][Max]; int main(int argc, char** argv) { // freopen("Trojan.txt", "r", stdin); int Cases = 1; while ( scanf("%d" , &NumberOfCountries) != EOF ){ FOR(i , Max){ FOR(j , Max) Distance[i][j] = INF; Distance[i][i] = 1; } FOR(i , MaxCountries){ if ( i ) scanf("%d" , &NumberOfCountries); First = i + 1; FOR(j , NumberOfCountries){ scanf("%d" , &Second); Distance[First][Second] = Distance[Second][First] = 1; } } FOR(k , Max){ FOR(i , Max){ FOR(j , Max){ Distance[i][j] = min(Distance[i][j] , Distance[i][k] + Distance[k][j] ); } } } scanf("%d" , &NumberOfCountries); printf("Test Set #%d\n" , Cases++); FOR(i , NumberOfCountries){ scanf("%d %d" , &First , &Second); printf("%2d to %2d: %d\n" , First , Second ,Distance[First][Second]); } printf("\n"); } return 0; }
[ "elmanciowisdom@gmail.com" ]
elmanciowisdom@gmail.com
e482db61fea8c554a8d9b76fd8b5b18326fa06a8
bee1f33853c3fa8dbfd5d35f8d2220ffd0575e7a
/negele/matrix.cpp
d0b437a17039db68dea10d0cef7201c6c6ae9739
[ "MIT" ]
permissive
cheshyre/negele-srg-solver-cpp
df1e2712608a4c2aaa78f98f2219dfb204069634
9510a40665480508c28de784f9af2eb4c7e6c0ae
refs/heads/main
2023-01-07T10:44:52.970407
2020-11-11T13:47:24
2020-11-11T13:47:24
311,983,009
0
0
null
null
null
null
UTF-8
C++
false
false
10,400
cpp
// Copyright 2020 Matthias Heinz #include "negele/matrix.h" #include <lapack.h> #include <cmath> #include <iostream> #include <vector> #include <boost/numeric/odeint.hpp> #include "negele/constants.h" namespace boost { namespace numeric { namespace odeint { template <> struct is_resizeable<negele::matrix::MomentumSpaceMatrix> { // declare // resizeability typedef boost::true_type type; const static bool value = type::value; }; template <> struct same_size_impl<negele::matrix::MomentumSpaceMatrix, negele::matrix::MomentumSpaceMatrix> { // define how to // check size static bool same_size(const negele::matrix::MomentumSpaceMatrix& v1, const negele::matrix::MomentumSpaceMatrix& v2) { return v1.same_size(v2); } }; template <> struct resize_impl<negele::matrix::MomentumSpaceMatrix, negele::matrix::MomentumSpaceMatrix> { // define how to // resize static void resize(negele::matrix::MomentumSpaceMatrix& v1, const negele::matrix::MomentumSpaceMatrix& v2) { v1.resize(v2); } }; } // namespace odeint } // namespace numeric } // namespace boost negele::matrix::SquareMatrix::SquareMatrix(int dim, double value) : m_dim(dim), m_matrix(dim * dim, value) {} negele::matrix::SquareMatrix::SquareMatrix(int dim, const std::vector<double>& mels) : m_dim(dim), m_matrix(mels) { if (m_matrix.size() != m_dim * m_dim) { std::cout << "Matrix initialized with incompatible dimensions: \n" << "\tsingle-axis dimension given: " << m_dim << "\n" << "\tactual size of matrix: " << m_matrix.size() << "\n"; exit(EXIT_FAILURE); } } negele::matrix::SquareMatrix negele::matrix::SquareMatrix::from_diag( const std::vector<double>& diag_mels) { int dim = diag_mels.size(); std::vector<double> mels(dim * dim, 0.0); for (int i = 0; i < dim; i++) { mels[i * dim + i] = diag_mels[i]; } return negele::matrix::SquareMatrix(dim, mels); } negele::matrix::SquareMatrix& negele::matrix::SquareMatrix::operator+=( const negele::matrix::SquareMatrix& other) { if (m_dim != other.m_dim) { std::cout << "Matrices have incompatible dimensions: " << m_dim << ", and " << other.m_dim << "\n"; exit(EXIT_FAILURE); } for (int i = 0; i < m_dim * m_dim; i++) { m_matrix[i] += other.m_matrix[i]; } return *this; } negele::matrix::SquareMatrix& negele::matrix::SquareMatrix::operator-=( const negele::matrix::SquareMatrix& other) { if (m_dim != other.m_dim) { std::cout << "Matrices have incompatible dimensions: " << m_dim << ", and " << other.m_dim << "\n"; exit(EXIT_FAILURE); } for (int i = 0; i < m_dim * m_dim; i++) { m_matrix[i] -= other.m_matrix[i]; } return *this; } negele::matrix::SquareMatrix& negele::matrix::SquareMatrix::operator*=( double factor) { for (int i = 0; i < m_dim * m_dim; i++) { m_matrix[i] *= factor; } return *this; } negele::matrix::SquareMatrix& negele::matrix::SquareMatrix::operator/=( double factor) { if (factor == 0.0) { std::cout << "Attempted division by 0.\n"; exit(EXIT_FAILURE); } for (int i = 0; i < m_dim * m_dim; i++) { m_matrix[i] /= factor; } return *this; } negele::matrix::SquareMatrix& negele::matrix::SquareMatrix::operator/=( const negele::matrix::SquareMatrix& other) { if (m_dim != other.m_dim) { std::cout << "Matrices have incompatible dimensions: " << m_dim << ", and " << other.m_dim << "\n"; exit(EXIT_FAILURE); } for (int i = 0; i < m_dim * m_dim; i++) { if (other.m_matrix[i] != 0.0) { m_matrix[i] /= other.m_matrix[i]; } } return *this; } negele::matrix::SquareMatrix& negele::matrix::SquareMatrix::abs() { for (int i = 0; i < m_dim * m_dim; i++) { m_matrix[i] = fabs(m_matrix[i]); } return *this; } double negele::matrix::SquareMatrix::max() const { double val = 0.0; if (m_dim > 0) { val = m_matrix[0]; } for (int i = 0; i < m_dim * m_dim; i++) { if (m_matrix[i] > val) { val = m_matrix[i]; } } return val; } negele::matrix::SquareMatrix negele::matrix::operator+( const SquareMatrix& a, const negele::matrix::SquareMatrix& b) { negele::matrix::SquareMatrix c(a); c += b; return c; } negele::matrix::SquareMatrix negele::matrix::operator-( const negele::matrix::SquareMatrix& a, const negele::matrix::SquareMatrix& b) { negele::matrix::SquareMatrix c(a); c -= b; return c; } negele::matrix::SquareMatrix negele::matrix::operator*( double factor, const negele::matrix::SquareMatrix& mat) { negele::matrix::SquareMatrix c(mat); c *= factor; return c; } negele::matrix::SquareMatrix negele::matrix::operator*( const negele::matrix::SquareMatrix& mat, double factor) { negele::matrix::SquareMatrix c(mat); c *= factor; return c; } negele::matrix::SquareMatrix negele::matrix::operator/( const negele::matrix::SquareMatrix& mat, double factor) { negele::matrix::SquareMatrix c(mat); c /= factor; return c; } negele::matrix::SquareMatrix negele::matrix::operator/( const negele::matrix::SquareMatrix& a, const negele::matrix::SquareMatrix& b) { negele::matrix::SquareMatrix c(a); c /= b; return c; } negele::matrix::SquareMatrix negele::matrix::abs( const negele::matrix::SquareMatrix& a) { negele::matrix::SquareMatrix c(a); c.abs(); return c; } negele::matrix::SquareMatrix negele::matrix::operator*( const negele::matrix::SquareMatrix& a, const negele::matrix::SquareMatrix& b) { if (a.m_dim != b.m_dim) { std::cout << "Matrices have incompatible dimensions: " << a.m_dim << ", and " << b.m_dim << "\n"; exit(EXIT_FAILURE); } auto new_mels = negele::matrix::mat_mul(a.m_matrix, b.m_matrix, a.m_dim); return negele::matrix::SquareMatrix(a.m_dim, new_mels); } std::vector<double> negele::matrix::SquareMatrix::eigenvalues() const { std::vector<double> evs(m_dim, 0.0); std::vector<double> matrix_copy(m_matrix); std::vector<double> work(20 * m_dim, 0.0); int info = 0; char uplo = 'U'; char jobz = 'N'; int lwork = work.size(); LAPACK_dsyev(&jobz, &uplo, &m_dim, matrix_copy.data(), &m_dim, evs.data(), work.data(), &lwork, &info); return evs; } negele::matrix::MomentumSpaceMatrix::MomentumSpaceMatrix( const std::vector<double>& pts, const std::vector<double>& weights, const std::vector<double>& mels) : m_dim(pts.size()), m_pts(pts), m_weights(weights), m_mels_with_weights(pts.size(), 0.0), m_kin_e(pts.size(), 0.0) { std::vector<double> weights_sqrt; for (const auto& w : m_weights) { weights_sqrt.push_back(sqrt(w)); } auto weights_mat = negele::matrix::SquareMatrix::from_diag(weights_sqrt); negele::matrix::SquareMatrix mels_wo_weights(m_dim, mels); m_mels_with_weights = weights_mat * mels_wo_weights * weights_mat; std::vector<double> kin_diag; for (const auto& p : pts) { kin_diag.push_back(p * p * HBARC * HBARC / (2 * MASS)); } m_kin_e = negele::matrix::SquareMatrix::from_diag(kin_diag); } void negele::matrix::MomentumSpaceMatrix::clear_mels() { m_mels_with_weights *= 0.0; } double negele::matrix::MomentumSpaceMatrix::max() const { return negele::matrix::abs(m_mels_with_weights).max(); } void negele::matrix::MomentumSpaceMatrix::resize( const negele::matrix::MomentumSpaceMatrix& other) { m_dim = other.m_dim; m_pts = std::vector<double>(other.m_pts); m_weights = std::vector<double>(other.m_weights); m_mels_with_weights = negele::matrix::SquareMatrix(m_dim, 0.0); m_kin_e = negele::matrix::SquareMatrix(m_dim, 0.0); } bool negele::matrix::MomentumSpaceMatrix::same_size( const negele::matrix::MomentumSpaceMatrix& other) const { if (m_dim != other.m_dim) { return false; } for (int i = 0; i < m_dim; i++) { if (m_pts[i] != other.m_pts[i]) { return false; } if (m_weights[i] != other.m_weights[i]) { return false; } } if (m_mels_with_weights.size() != other.m_mels_with_weights.size()) { return false; } if (m_kin_e.size() != other.m_kin_e.size()) { return false; } return true; } negele::matrix::SquareMatrix negele::matrix::MomentumSpaceMatrix::matrix_elements() const { std::vector<double> weights_inv_sqrt; for (const auto& w : m_weights) { weights_inv_sqrt.push_back(1.0 / sqrt(w)); } auto weights_inv_mat = negele::matrix::SquareMatrix::from_diag(weights_inv_sqrt); return weights_inv_mat * m_mels_with_weights * weights_inv_mat; } std::vector<double> negele::matrix::mat_mul(const std::vector<double>& a, const std::vector<double>& b, int dim) { std::vector<double> new_matrix(dim * dim, 0.0); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { for (int k = 0; k < dim; k++) { new_matrix[i * dim + j] += a[i * dim + k] * b[k * dim + j]; } } } return new_matrix; } negele::matrix::MomentumSpaceMatrix& negele::matrix::MomentumSpaceMatrix:: operator+=(const negele::matrix::MomentumSpaceMatrix& other) { m_mels_with_weights += other.m_mels_with_weights; return *this; } negele::matrix::MomentumSpaceMatrix& negele::matrix::MomentumSpaceMatrix:: operator+=(const double other) { for (int i = 0; i < m_dim * m_dim; i++) { m_mels_with_weights[i] += copysign(other, m_mels_with_weights[i]); } return *this; } negele::matrix::MomentumSpaceMatrix& negele::matrix::MomentumSpaceMatrix:: operator*=(const double factor) { m_mels_with_weights *= factor; return *this; } negele::matrix::MomentumSpaceMatrix negele::matrix::operator/( const negele::matrix::MomentumSpaceMatrix& a, const negele::matrix::MomentumSpaceMatrix& b) { negele::matrix::MomentumSpaceMatrix c(a); c.m_mels_with_weights /= b.m_mels_with_weights; return c; } negele::matrix::MomentumSpaceMatrix negele::matrix::abs( const negele::matrix::MomentumSpaceMatrix& a) { negele::matrix::MomentumSpaceMatrix c(a); c.m_mels_with_weights.abs(); return c; }
[ "heinz.matthias.3@gmail.com" ]
heinz.matthias.3@gmail.com
cfd0d70ee8096669234bdd1e86c6840c594a8a0b
d4439b0bd12a6cdd6d7cc1f56ed3e0311d896192
/CodeChef/gcd.cpp
297a7cb589e31ffb8e06dea7b97f89b31c51a7d0
[]
no_license
anuroop2501/Competitive-Coding-
d3e3240fa0b0f62bdb95ea34163491439e301de4
a9fe6d217668a4c1b681e3bfe7c584d5765e7ebd
refs/heads/master
2021-01-10T13:52:34.712176
2015-05-23T06:41:30
2015-05-23T06:41:30
36,110,574
0
0
null
null
null
null
UTF-8
C++
false
false
207
cpp
#include<iostream> #include<cmath> using namespace std; int gcd(int a, int b) { if(b==0) return a; else return gcd(b,a%b); } main() { int a,b; cin>>a>>b; cout<<gcd(a,b)<<endl; }
[ "anuroop.iitj@gmail.com" ]
anuroop.iitj@gmail.com
29ea81fba1525b431e8a905b5a192fab83a8981e
01dcf27514d7bb32a06258a42d3838188d7b871a
/main/cpp/Drivetrain.cpp
4825421063fe20c993db1b00ff97bd66dbee9304
[]
no_license
team7053/betabots-cpp
696ab1647c15c85918f94228ea05a67c62c6e6a4
2a45dfe934afa5ddcb767695c4960be109a93403
refs/heads/master
2020-12-02T13:39:02.139815
2020-01-04T02:55:53
2020-01-04T02:55:53
231,002,544
1
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include <Drivetrain.h> Drivetrain::Drivetrain(int ml, int mr) : lm(ml), rm(mr), drive(lm, rm) { } void Drivetrain::setDrive(double fwd, double turn) { drive.ArcadeDrive(fwd, turn); } bool Drivetrain::isMoving() { if (lm.Get() > 0.2 || lm.Get() < -0.2 || rm.Get() > 0.2 || rm.Get() < -0.2) { return true; } else { return false; } }
[ "nathan1salmard@gmail.com" ]
nathan1salmard@gmail.com
57492970a6fb8149b43efc84889aa07c5fc17fa1
5bb97298116fc28a1463e6879b5a85265660f407
/4 Basic Input Output/tut.cpp
ab2d9ec75b167676a9dfdc524e3e06c8aa67b31c
[]
no_license
rahulgolani/C-plus-plus
37ed21d4250bbd0a25fabbfc2d6a2f37cbfd88ea
eb8e673b8352a46bad73bfc75481baf07fba95d7
refs/heads/master
2023-06-06T17:40:58.094078
2021-07-09T13:31:41
2021-07-09T13:31:41
382,661,569
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
/* Input Stream -> Direction of flow of bytes from input device to main memory Output Stream -> Direction of flow of byte from main memory to output device */ #include<iostream> using namespace std; int main(){ int num1,num2; // << is a insertion operator cout<<"Enter values of num1 \n"; cin>>num1; cout<<"Enter values of num2 \n"; // >> is a extraction operator cin>>num2; cout<<"The sum of num1 and num2 is "<<num1+num2; return 0; }
[ "rahulgolani24@live.com" ]
rahulgolani24@live.com
7de969e3b5ef6cfa1d7db4e8be3130c6acb99965
6aab4199ab2cab0b15d9af390a251f37802366ab
/api/audio/echo_canceller3_factory.h
3fa6922a3b1bff4ae66644a77642f21232c552f4
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm" ]
permissive
adwpc/webrtc
f288a600332e5883b2ca44492e02bea81e45b4fa
a30eb44013b8472ea6a042d7ed2909eb7346f9a8
refs/heads/master
2021-05-24T13:18:44.227242
2021-02-01T14:54:12
2021-02-01T14:54:12
174,692,051
0
0
MIT
2019-03-09T12:32:13
2019-03-09T12:32:13
null
UTF-8
C++
false
false
1,297
h
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef API_AUDIO_ECHO_CANCELLER3_FACTORY_H_ #define API_AUDIO_ECHO_CANCELLER3_FACTORY_H_ #include <memory> #include "api/audio/echo_canceller3_config.h" #include "api/audio/echo_control.h" #include "rtc_base/system/rtc_export.h" namespace webrtc { class RTC_EXPORT EchoCanceller3Factory : public EchoControlFactory { public: // Factory producing EchoCanceller3 instances with the default configuration. EchoCanceller3Factory(); // Factory producing EchoCanceller3 instances with the specified // configuration. explicit EchoCanceller3Factory(const EchoCanceller3Config& config); // Creates an EchoCanceller3 running at the specified sampling rate using a // mono setup std::unique_ptr<EchoControl> Create(int sample_rate_hz) override; private: const EchoCanceller3Config config_; }; } // namespace webrtc #endif // API_AUDIO_ECHO_CANCELLER3_FACTORY_H_
[ "adwpc@hotmail.com" ]
adwpc@hotmail.com