hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1646f6cfdc0e1c95857e9ef9a0754cfe0d94d27a | 3,206 | cpp | C++ | src/cpp/utils/StringMatching.cpp | DimaRU/Fast-DDS | 4874d11575f396f7787c0f93254a989e7f523e68 | [
"Apache-2.0"
] | 548 | 2020-06-02T11:59:31.000Z | 2022-03-30T00:59:33.000Z | src/cpp/utils/StringMatching.cpp | DimaRU/Fast-DDS | 4874d11575f396f7787c0f93254a989e7f523e68 | [
"Apache-2.0"
] | 1,068 | 2020-06-01T12:36:33.000Z | 2022-03-31T09:57:34.000Z | src/cpp/utils/StringMatching.cpp | DimaRU/Fast-DDS | 4874d11575f396f7787c0f93254a989e7f523e68 | [
"Apache-2.0"
] | 230 | 2020-06-04T02:46:23.000Z | 2022-03-30T01:35:58.000Z | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file StringMatching.cpp
*
*/
#include <fastrtps/utils/StringMatching.h>
#include <limits.h>
#include <errno.h>
#if defined(__cplusplus_winrt)
#include <algorithm>
#include <regex>
#elif defined(_WIN32)
#include "Shlwapi.h"
#else
#include <fnmatch.h>
#endif // if defined(__cplusplus_winrt)
namespace eprosima {
namespace fastrtps {
namespace rtps {
StringMatching::StringMatching()
{
// TODO Auto-generated constructor stub
}
StringMatching::~StringMatching()
{
// TODO Auto-generated destructor stub
}
#if defined(__cplusplus_winrt)
void replace_all(
std::string& subject,
const std::string& search,
const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
bool StringMatching::matchPattern(
const char* pattern,
const char* str)
{
std::string path(pattern);
std::string spec(str);
replace_all(pattern, "*", ".*");
replace_all(pattern, "?", ".");
std::regex path_regex(path);
std::smatch spec_match;
if (std::regex_match(spec, spec_match, path_regex))
{
return true;
}
return false;
}
bool StringMatching::matchString(
const char* str1,
const char* str2)
{
if (StringMatching::matchPattern(str1, str2))
{
return true;
}
if (StringMatching::matchPattern(str2, str1))
{
return true;
}
return false;
}
#elif defined(_WIN32)
bool StringMatching::matchPattern(
const char* pattern,
const char* str)
{
if (PathMatchSpec(str, pattern))
{
return true;
}
return false;
}
bool StringMatching::matchString(
const char* str1,
const char* str2)
{
if (PathMatchSpec(str1, str2))
{
return true;
}
if (PathMatchSpec(str2, str1))
{
return true;
}
return false;
}
#else
bool StringMatching::matchPattern(
const char* pattern,
const char* str)
{
if (fnmatch(pattern, str, FNM_NOESCAPE) == 0)
{
return true;
}
return false;
}
bool StringMatching::matchString(
const char* str1,
const char* str2)
{
if (fnmatch(str1, str2, FNM_NOESCAPE) == 0)
{
return true;
}
if (fnmatch(str2, str1, FNM_NOESCAPE) == 0)
{
return true;
}
return false;
}
#endif // if defined(__cplusplus_winrt)
} // namespace rtps
} /* namespace rtps */
} /* namespace eprosima */
| 20.291139 | 75 | 0.635059 | DimaRU |
16475c8f69d0e87b1ff43e8d1d661a5ffb0da94f | 1,984 | inl | C++ | 3rdParty/glm-0.9.7.5/test/external/gli/core/texture2d_array.inl | fakhirsh/3DRenderer | f46292ef7af54d2545d22623b1c12af5867cf9cd | [
"MIT"
] | 41 | 2016-03-25T18:14:37.000Z | 2022-01-20T11:16:52.000Z | src/lib/glm-0.9.8.4/test/external/gli/core/texture2d_array.inl | Rydgel/chip8 | 8d2aaecd90ec8a64d6d08e8fe3c33643b4d1977d | [
"BSD-3-Clause"
] | 31 | 2019-10-25T11:28:21.000Z | 2019-12-10T16:57:30.000Z | src/lib/glm-0.9.8.4/test/external/gli/core/texture2d_array.inl | Rydgel/chip8 | 8d2aaecd90ec8a64d6d08e8fe3c33643b4d1977d | [
"BSD-3-Clause"
] | 9 | 2016-05-23T01:51:25.000Z | 2021-08-21T15:32:37.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Image Copyright (c) 2008 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2011-04-06
// Updated : 2011-04-06
// Licence : This source is under MIT License
// File : gli/core/texture_cube.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace gli
{
inline texture2DArray::texture2DArray()
{}
inline texture2DArray::texture2DArray
(
texture2DArray::layer_type const & Layers,
texture2DArray::level_type const & Levels
)
{
this->Arrays.resize(Layers);
for(texture2DArray::size_type i = 0; i < this->Arrays.size(); ++i)
this->Arrays[i].resize(Levels);
}
inline texture2DArray::~texture2DArray()
{}
inline texture2D & texture2DArray::operator[]
(
layer_type const & Layer
)
{
return this->Arrays[Layer];
}
inline texture2D const & texture2DArray::operator[]
(
layer_type const & Layer
) const
{
return this->Arrays[Layer];
}
inline bool texture2DArray::empty() const
{
return this->Arrays.empty();
}
inline texture2DArray::format_type texture2DArray::format() const
{
return this->Arrays.empty() ? FORMAT_NULL : this->Arrays[0].format();
}
inline texture2DArray::layer_type texture2DArray::layers() const
{
return this->Arrays.size();
}
inline texture2DArray::level_type texture2DArray::levels() const
{
if(this->empty())
return 0;
return this->Arrays[0].levels();
}
inline void texture2DArray::resize
(
texture2DArray::layer_type const & Layers,
texture2DArray::level_type const & Levels
)
{
this->Arrays.resize(Layers);
for(texture2DArray::layer_type i = 0; i < this->Arrays.size(); ++i)
this->Arrays[i].resize(Levels);
}
}//namespace gli
| 25.113924 | 100 | 0.561996 | fakhirsh |
16485af28f3bbcfb93e31d8ef700c6925714eaa4 | 4,169 | cpp | C++ | TEST_TOOL/project/Hermes/Novatel_Log_Handler/controllwidget.cpp | EIDOSDATA/ARGOS_QT_Series | f451312249607b03ed4d6848ec8bc068f245718f | [
"Unlicense"
] | null | null | null | TEST_TOOL/project/Hermes/Novatel_Log_Handler/controllwidget.cpp | EIDOSDATA/ARGOS_QT_Series | f451312249607b03ed4d6848ec8bc068f245718f | [
"Unlicense"
] | null | null | null | TEST_TOOL/project/Hermes/Novatel_Log_Handler/controllwidget.cpp | EIDOSDATA/ARGOS_QT_Series | f451312249607b03ed4d6848ec8bc068f245718f | [
"Unlicense"
] | null | null | null | #include "controllwidget.h"
#include "ui_controllwidget.h"
#include <QFileDialog>
#include <QDropEvent>
#include <QMimeData>
#include <sstream>
std::vector<std::string> tokenize(const std::string& data, const char delimiter = ' ')
{
std::vector<std::string> result;
std::string token;
std::stringstream ss(data);
while (getline(ss, token, delimiter)) {
result.push_back(token);
}
return result;
}
ControllWidget::ControllWidget(QWidget *parent) :
QDockWidget(parent),
ui(new Ui::ControllWidget)
{
ui->setupUi(this);
}
ControllWidget::~ControllWidget()
{
delete ui;
}
void ControllWidget::setCountTable(MESSAGE_ID id, int count)
{
recvSetCountTable(id, count);
}
QString ControllWidget::getColumnColor(MESSAGE_ID id)
{
switch (id)
{
case MESSAGE_ID::BESTPOS:
return ui->cb_bestpos->currentText();
break;
case MESSAGE_ID::MARKPOS:
return ui->cb_markpos->currentText();
break;
case MESSAGE_ID::MARK2POS:
return ui->cb_mark2pos->currentText();
break;
case MESSAGE_ID::MARK3POS:
return ui->cb_mark3pos->currentText();
break;
case MESSAGE_ID::MARK4POS:
return ui->cb_mark4pos->currentText();
break;
case MESSAGE_ID::MARK1PVA:
return ui->cb_mark1pva->currentText();
break;
case MESSAGE_ID::MARK2PVA:
return ui->cb_mark2pva->currentText();
break;
case MESSAGE_ID::MARK3PVA:
return ui->cb_mark3pva->currentText();
break;
case MESSAGE_ID::MARK4PVA:
return ui->cb_mark4pva->currentText();
break;
default:
return "";
}
}
std::vector<bool> ControllWidget::getShowingList()
{
std::vector<bool> temp;
temp.push_back(ui->checkBox->isChecked());
temp.push_back(ui->checkBox_2->isChecked());
temp.push_back(ui->checkBox_3->isChecked());
temp.push_back(ui->checkBox_4->isChecked());
temp.push_back(ui->checkBox_5->isChecked());
temp.push_back(ui->checkBox_6->isChecked());
temp.push_back(ui->checkBox_7->isChecked());
temp.push_back(ui->checkBox_8->isChecked());
temp.push_back(ui->checkBox_9->isChecked());
return temp;
}
void ControllWidget::on_pb_open_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,tr("Select pwrpak7 log File"),"/home/",tr("log file (*.*)"));
if(fileName != NULL)
{
ui->lb_filepath->setText(fileName);
std::vector<std::string> tempString = tokenize(fileName.toStdString(), '/');
ui->le_label->setText(QString::fromStdString(tempString.back()));
emit sendFilePath(ui->lb_filepath->text());
}
}
void ControllWidget::recvSetCountTable(MESSAGE_ID id, int count)
{
QLineEdit *lineEdit = NULL;
switch (id)
{
case MESSAGE_ID::BESTPOS:
lineEdit = ui->le_count_bestpos;
break;
case MESSAGE_ID::MARKPOS:
lineEdit = ui->le_count_markpos;
break;
case MESSAGE_ID::MARK2POS:
lineEdit = ui->le_count_mark2pos;
break;
case MESSAGE_ID::MARK3POS:
lineEdit = ui->le_count_mark3pos;
break;
case MESSAGE_ID::MARK4POS:
lineEdit = ui->le_count_mark4pos;
break;
case MESSAGE_ID::MARK1PVA:
lineEdit = ui->le_count_mark1pva;
break;
case MESSAGE_ID::MARK2PVA:
lineEdit = ui->le_count_mark2pva;
break;
case MESSAGE_ID::MARK3PVA:
lineEdit = ui->le_count_mark3pva;
break;
case MESSAGE_ID::MARK4PVA:
lineEdit = ui->le_count_mark4pva;
break;
default:
return;
}
if(lineEdit != NULL)
lineEdit->setText(QString::number(count));
}
void ControllWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
#include <iostream>
void ControllWidget::dropEvent(QDropEvent *event)
{
for(int i = 0; i < event->mimeData()->urls().size(); i++)
{
std::cout << event->mimeData()->urls().at(i).toLocalFile().toStdString() << std::endl;
}
ui->lb_filepath->setText(event->mimeData()->urls().at(0).toLocalFile());
std::vector<std::string> tempString = tokenize(event->mimeData()->urls().at(0).toLocalFile().toStdString(), '/');
ui->le_label->setText(QString::fromStdString(tempString.back()));
emit sendFilePath(ui->lb_filepath->text());
}
void ControllWidget::on_pb_export_clicked()
{
emit sendExport();
}
void ControllWidget::on_pb_upload_clicked()
{
emit sendUpload(ui->le_date->text(), ui->le_maker->text(), ui->le_label->text(), ui->cb_db->currentText());
}
| 23.6875 | 115 | 0.716479 | EIDOSDATA |
164c2a4dc4f13f853934ab5e0655b88ddd932900 | 3,225 | cpp | C++ | test/main.cpp | DuinoDu/MotionDetection | da9ba307948882fe66910f3936743309fda07fbc | [
"MIT"
] | 1 | 2017-07-12T09:01:40.000Z | 2017-07-12T09:01:40.000Z | test/main.cpp | DuinoDu/MotionDetection | da9ba307948882fe66910f3936743309fda07fbc | [
"MIT"
] | null | null | null | test/main.cpp | DuinoDu/MotionDetection | da9ba307948882fe66910f3936743309fda07fbc | [
"MIT"
] | null | null | null | #include <iostream>
#include "windows.h"
#include "interface.h"
#include <opencv2/opencv.hpp>
using namespace std;
void __stdcall getResult(int* px, int* py, size_t size, void* context)
{
for (size_t i = 0; i < size; i++){
cout << "x: " << *px << ", y:" << *py << endl;
}
}
int main(int argc, char* argv[])
{
cout << "hello, vs" << endl;
SetCurrentDirectory(L"D:\\code\\MotionDetection\\release");
HINSTANCE m_hMotionDetectorDll;
m_hMotionDetectorDll = LoadLibrary(L"D:\\code\\MotionDetection\\release\\MotionDetection.dll");
if (m_hMotionDetectorDll != NULL){
cout << "Load dll success!" << endl;
}
else{
cout << "Load dll failed! " << GetLastError() << endl;
return -1;
}
_createMotionDetector m_pfnCreateMotionDetector;
_deleteMotionDetector m_pfnDestroyMotionDetector;
_setRoomSize m_pfnSetRoomSize;
_setStudentRegion m_pfnSetStudentRegion;
_setCaffemodelPath m_pfnCaffemodelPath;
_setCallback m_pfnSetCallback;
_setShowWindows m_pfnSetShowWindows;
_setFrame m_pfnSetFrame;
m_pfnCreateMotionDetector = (_createMotionDetector)GetProcAddress(m_hMotionDetectorDll, "createMotionDetector");
m_pfnDestroyMotionDetector = (_deleteMotionDetector)GetProcAddress(m_hMotionDetectorDll, "deleteMotionDetector");
m_pfnSetRoomSize = (_setRoomSize)GetProcAddress(m_hMotionDetectorDll, "setRoomSize");
m_pfnSetStudentRegion = (_setStudentRegion)GetProcAddress(m_hMotionDetectorDll, "setStudentRegion");
m_pfnCaffemodelPath = (_setCaffemodelPath)GetProcAddress(m_hMotionDetectorDll, "setCaffemodelPath");
m_pfnSetCallback = (_setCallback)GetProcAddress(m_hMotionDetectorDll, "setCallback");
m_pfnSetShowWindows = (_setShowWindows)GetProcAddress(m_hMotionDetectorDll, "setShowWindows");
m_pfnSetFrame = (_setFrame)GetProcAddress(m_hMotionDetectorDll, "setFrame");
LPVOID m_lpMotionDetection;
m_lpMotionDetection = m_pfnCreateMotionDetector();
if (!m_pfnCreateMotionDetector)
{
FreeLibrary(m_hMotionDetectorDll);
m_hMotionDetectorDll = NULL;
}
else {
m_pfnSetRoomSize(m_lpMotionDetection, 100, 100);
m_pfnSetShowWindows(m_lpMotionDetection, false, true);
m_pfnSetCallback(m_lpMotionDetection, getResult, NULL);
char szCaffemodelPath[1000] = { 0 };
sprintf(szCaffemodelPath, "D:\\code\\mtcnn\\mtcnn\\model");
m_pfnCaffemodelPath(m_lpMotionDetection, szCaffemodelPath);
string videoPath = "D:\\video\\4.mp4";
//if (argc == 2) videoPath = argv[1];
cv::VideoCapture cam;
cv::Mat frame;
if (cam.open(0)){
cam >> frame;
m_pfnSetStudentRegion(m_lpMotionDetection, 0, 0, 0, frame.cols, frame.rows, frame.cols, frame.rows, 0);
while (frame.isContinuous() && !frame.empty()){
resize(frame, frame, cv::Size(frame.cols/3, frame.rows/3));
uchar *data = frame.data;
int height = frame.rows;
int width = frame.cols;
int length = height*width*frame.channels();
m_pfnSetFrame(m_lpMotionDetection, data, height, width, length);
//cv::imshow("aaa", frame);
cv::waitKey(20);
cam >> frame;
}
}
else{
cout << "invalid video" << endl;
}
FreeLibrary(m_hMotionDetectorDll);
}
int a;
cin >> a;
return 0;
}
| 33.59375 | 115 | 0.714419 | DuinoDu |
164ef01f7b42bc218f8484b263fab96515a96651 | 945 | cpp | C++ | src/carl-logging/carl-logging.cpp | sjunges/carl | 5013c31c035990d9912a6265944e7d4add4c378b | [
"MIT"
] | 29 | 2015-05-19T12:17:16.000Z | 2021-03-05T17:53:00.000Z | src/carl-logging/carl-logging.cpp | sjunges/carl | 5013c31c035990d9912a6265944e7d4add4c378b | [
"MIT"
] | 36 | 2016-10-26T12:47:11.000Z | 2021-03-03T15:19:38.000Z | src/carl-logging/carl-logging.cpp | sjunges/carl | 5013c31c035990d9912a6265944e7d4add4c378b | [
"MIT"
] | 16 | 2015-05-27T07:35:19.000Z | 2021-03-05T17:53:08.000Z | #include "carl-logging.h"
#include "logging.h"
#include "Logger.h"
namespace carl {
namespace logging {
void setInitialLogLevel()
{
carl::logging::logger().configure("carl_logfile", "carl.log");
carl::logging::logger().filter("carl_logfile")
("carl", carl::logging::LogLevel::LVL_INFO)
("carl.ran", carl::logging::LogLevel::LVL_DEBUG)
("carl.converter", carl::logging::LogLevel::LVL_DEBUG)
;
carl::logging::logger().configure("stdout", std::cout);
carl::logging::logger().filter("stdout")
("carl", carl::logging::LogLevel::LVL_WARN)
// ("carl.algsubs", carl::logging::LogLevel::LVL_DEBUG)
("carl.ran", carl::logging::LogLevel::LVL_DEBUG)
("carl.converter", carl::logging::LogLevel::LVL_DEBUG)
// ("carl.ran.realroots", carl::logging::LogLevel::LVL_TRACE)
// ("carl.fieldext", carl::logging::LogLevel::LVL_TRACE)
// ("carl.formula", carl::logging::LogLevel::LVL_WARN)
;
carl::logging::logger().resetFormatter();
}
}
}
| 28.636364 | 63 | 0.691005 | sjunges |
16501f43eed203126863529622aa43d9f9a295cf | 26,971 | cpp | C++ | src/compiler/EncodeDecode.cpp | yudanli/fast_ber | d3e790f86ff91df8b6d6a0f308803606f59452af | [
"BSL-1.0"
] | 74 | 2019-02-07T03:24:10.000Z | 2022-03-22T04:40:44.000Z | src/compiler/EncodeDecode.cpp | yudanli/fast_ber | d3e790f86ff91df8b6d6a0f308803606f59452af | [
"BSL-1.0"
] | 32 | 2019-06-02T10:13:13.000Z | 2021-12-09T08:56:08.000Z | src/compiler/EncodeDecode.cpp | yudanli/fast_ber | d3e790f86ff91df8b6d6a0f308803606f59452af | [
"BSL-1.0"
] | 11 | 2019-05-26T18:06:00.000Z | 2021-11-21T16:08:07.000Z | #include "fast_ber/compiler/EncodeDecode.hpp"
#include "fast_ber/compiler/CppGeneration.hpp"
#include "fast_ber/compiler/Identifier.hpp"
#include "fast_ber/compiler/ResolveType.hpp"
#include "fast_ber/compiler/Visit.hpp"
#include "absl/strings/string_view.h"
#include <iostream>
#include <string>
#include <vector>
std::string make_component_function(const std::string& function, const NamedType& component, const Module& module,
const Asn1Tree& tree)
{
if (is_generated(resolve_type(tree, module.module_reference, component).type))
{
auto id = identifier(component.type, module, tree);
if (!id.is_default_tagged)
return function + "_with_id<" + id.name() + ">";
}
return function;
}
template <typename CollectionType>
CodeBlock create_collection_encode_functions(const std::string& name, const CollectionType& collection,
const Module& module, const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("inline EncodeResult " + name + "::encode_with_id(absl::Span<uint8_t> output) const noexcept");
{
auto scope = CodeScope(block);
block.add_line("constexpr std::size_t header_length_guess = fast_ber::encoded_length(0, Identifier_{});");
block.add_line("if (output.length() < header_length_guess)");
{
auto scope2 = CodeScope(block);
block.add_line("return EncodeResult{false, 0};");
}
if (collection.components.size() != 0)
{
block.add_line("EncodeResult res;");
block.add_line("auto content = output;");
block.add_line("content.remove_prefix(header_length_guess);");
}
block.add_line("std::size_t content_length = 0;");
for (const ComponentType& component : collection.components)
{
block.add_line("res = " + component.named_type.name + "." +
make_component_function("encode", component.named_type, module, tree) + "(content);");
block.add_line("if (!res.success)");
{
auto scope2 = CodeScope(block);
block.add_line("return res;");
}
block.add_line("content.remove_prefix(res.length);");
block.add_line("content_length += res.length;");
}
block.add_line("return wrap_with_ber_header(output, content_length, Identifier_{}, header_length_guess);");
}
block.add_line();
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("std::size_t " + name + "::encoded_length_with_id() const noexcept");
{
auto scope = CodeScope(block);
block.add_line("std::size_t content_length = 0;");
block.add_line();
for (const ComponentType& component : collection.components)
{
block.add_line("content_length += this->" + component.named_type.name + "." +
make_component_function("encoded_length", component.named_type, module, tree) + "();");
}
block.add_line();
block.add_line("return fast_ber::encoded_length(content_length, Identifier_{});");
}
block.add_line();
return block;
}
CodeBlock create_choice_encode_functions(const std::string& name, const ChoiceType& choice, const Module& module,
const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("inline EncodeResult " + name + "::encode_with_id(absl::Span<uint8_t> output) const noexcept");
{
auto scope1 = CodeScope(block);
block.add_line("EncodeResult res;");
block.add_line("auto content = output;");
// If an alternative (non ChoiceId) identifier is provided choice type should be wrapped,
// else use identifier of selected choice
block.add_line("std::size_t header_length_guess = 0;");
block.add_line("if (!IsChoiceId<Identifier_>::value)");
{
auto scope2 = CodeScope(block);
block.add_line(" header_length_guess = fast_ber::encoded_length(0,Identifier_{});");
block.add_line("if (output.length() < header_length_guess)");
{
auto scope3 = CodeScope(block);
block.add_line("return EncodeResult{false, 0};");
}
block.add_line("content.remove_prefix(header_length_guess);");
}
block.add_line("switch (this->index())");
{
auto scope2 = CodeScope(block);
for (std::size_t i = 0; i < choice.choices.size(); i++)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line(" res = fast_ber::get<" + std::to_string(i) + ">(*this)." +
make_component_function("encode", choice.choices[i], module, tree) + "(content);");
block.add_line(" break;");
}
block.add_line("default: assert(0);");
}
block.add_line("if (!IsChoiceId<Identifier_>::value)");
{
auto scope2 = CodeScope(block);
block.add_line("if (!res.success)");
{
auto scope3 = CodeScope(block);
block.add_line("return res;");
}
block.add_line("const std::size_t content_length = res.length;");
block.add_line("res = wrap_with_ber_header(output, content_length, Identifier_{}, header_length_guess);");
block.add_line("return res;");
}
block.add_line("else");
{
auto scope2 = CodeScope(block);
block.add_line("return res;");
}
}
block.add_line();
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("inline std::size_t " + name + "::encoded_length_with_id() const noexcept");
{
auto scope1 = CodeScope(block);
block.add_line("std::size_t content_length = 0;");
block.add_line("switch (this->index())");
{
auto scope2 = CodeScope(block);
for (std::size_t i = 0; i < choice.choices.size(); i++)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line(" content_length = fast_ber::get<" + std::to_string(i) + ">(*this)." +
make_component_function("encoded_length", choice.choices[i], module, tree) + "();");
block.add_line(" break;");
}
block.add_line("default: assert(0);");
}
block.add_line("if (!IsChoiceId<Identifier_>::value)");
{
auto scope2 = CodeScope(block);
block.add_line("return fast_ber::encoded_length(content_length, Identifier_{});");
}
block.add_line("else");
{
auto scope2 = CodeScope(block);
block.add_line("return content_length;");
}
}
block.add_line();
return block;
}
template <typename CollectionType>
CodeBlock create_collection_decode_functions(const std::string& name, const CollectionType& collection,
const Module& module, const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier_"}));
block.add_line("DecodeResult " + name + "::decode_with_id(BerView input) noexcept");
{
auto scope = CodeScope(block);
block.add_line("if (!input.is_valid())");
{
auto scope2 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Invalid packet when decoding collection [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line("if (!has_correct_header(input, Identifier_{}, Construction::constructed))");
{
auto scope2 = CodeScope(block);
block.add_line(
R"(FAST_BER_ERROR("Invalid identifier [", input.identifier(), "] when decoding collection [)" + name +
R"(]");)");
block.add_line("return DecodeResult{false};");
}
if (collection.components.size() > 0)
{
block.add_line("DecodeResult res;");
block.add_line("auto iterator = (Identifier_::depth() == 1) ? input.begin()");
block.add_line(" : input.begin()->begin();");
if (std::is_same<CollectionType, SetType>::value)
{
block.add_line("auto const end = (Identifier_::depth() == 1) ? input.end()");
block.add_line(" : input.begin()->end();");
block.add_line();
block.add_line("std::array<std::size_t, " + std::to_string(collection.components.size()) +
"> decode_counts = {};");
block.add_line("while (iterator != end)");
{
auto scope2 = CodeScope(block);
if (module.tagging_default == TaggingMode::automatic)
{
block.add_line("if (iterator->class_() == " + to_string(Class::context_specific) + ")");
auto scope3 = CodeScope(block);
{
block.add_line("switch (iterator->tag())");
auto scope4 = CodeScope(block);
std::size_t i = 0;
for (const ComponentType& component : collection.components)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type, module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope5 = CodeScope(block);
{
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" +
component.named_type.name + R"(] of collection [)" + name +
R"(]");)");
block.add_line("return res;");
}
}
block.add_line("++decode_counts[" + std::to_string(i) + "];");
block.add_line("++iterator;");
block.add_line("continue;");
i++;
}
}
}
else
{
for (Class class_ : {
Class::universal,
Class::application,
Class::context_specific,
Class::private_,
})
{
if (std::any_of(collection.components.begin(), collection.components.end(),
[&](const ComponentType& component) {
const std::vector<Identifier>& outer_ids =
outer_identifiers(component.named_type.type, module, tree);
return std::any_of(
outer_ids.begin(), outer_ids.end(),
[class_](const Identifier& id) { return id.class_ == class_; });
}))
{
block.add_line("if (iterator->class_() == " + to_string(class_) + ")");
auto scope3 = CodeScope(block);
{
block.add_line("switch (iterator->tag())");
auto scope4 = CodeScope(block);
std::size_t i = 0;
for (const ComponentType& component : collection.components)
{
const std::vector<Identifier>& ids =
outer_identifiers(component.named_type.type, module, tree);
for (const Identifier& id : ids)
{
if (id.class_ == class_)
{
block.add_line("case " + std::to_string(id.tag_number) + ":");
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type,
module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope5 = CodeScope(block);
{
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" +
component.named_type.name +
R"(] of collection [)" + name + R"(]");)");
block.add_line("return res;");
}
}
block.add_line("++decode_counts[" + std::to_string(i) + "];");
block.add_line("++iterator;");
block.add_line("continue;");
}
}
i++;
}
}
}
}
}
if (!collection.allow_extensions)
{
block.add_line(R"(FAST_BER_ERROR("Invalid ID when decoding set [)" + name +
R"(] [", iterator->identifier(), "]");)");
block.add_line("return fast_ber::DecodeResult{false};");
}
else
{
block.add_line("++iterator;");
}
}
std::size_t i = 0;
for (const ComponentType& component : collection.components)
{
block.add_line("if (decode_counts[" + std::to_string(i) + "] == 0)");
{
auto scope3 = CodeScope(block);
if (component.is_optional)
{
block.add_line("this->" + component.named_type.name + " = fast_ber::empty;");
}
else if (component.default_value)
{
block.add_line("this->" + component.named_type.name + ".set_to_default();");
}
else
{
block.add_line(R"(FAST_BER_ERROR("Missing non-optional member [)" +
component.named_type.name + R"(] of set [)" + name + R"(]");)");
block.add_line("return fast_ber::DecodeResult{false};");
}
}
block.add_line("if (decode_counts[" + std::to_string(i) + "] > 1)");
{
auto scope3 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Member [)" + component.named_type.name +
R"(] present multiple times in set [)" + name + R"(]");)");
block.add_line("return fast_ber::DecodeResult{false};");
}
i++;
}
}
else
{
for (const ComponentType& component : collection.components)
{
if (component.is_optional || component.default_value)
{
std::string id_check = "if (iterator->is_valid() && (false ";
for (const Identifier& id : outer_identifiers(component.named_type.type, module, tree))
{
id_check += " || " + id.name() + "::check_id_match(iterator->class_(), iterator->tag())";
}
id_check += "))";
block.add_line(id_check);
{
auto scope2 = CodeScope(block);
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type, module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope3 = CodeScope(block);
{
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" +
component.named_type.name + R"(] of collection [)" + name +
R"(]");)");
block.add_line("return res;");
}
}
block.add_line("++iterator;");
}
block.add_line("else");
{
auto scope3 = CodeScope(block);
if (component.is_optional)
{
block.add_line("this->" + component.named_type.name + " = fast_ber::empty;");
}
else
{
block.add_line("this->" + component.named_type.name + ".set_to_default();");
}
}
}
else
{
block.add_line("res = this->" + component.named_type.name + "." +
make_component_function("decode", component.named_type, module, tree) +
"(*iterator);");
block.add_line("if (!res.success)");
{
auto scope2 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("failed to decode member [)" + component.named_type.name +
R"(] of collection [)" + name + R"(]");)");
block.add_line("return res;");
}
block.add_line("++iterator;");
}
}
}
}
block.add_line("return DecodeResult{true};");
}
return block;
}
CodeBlock create_choice_decode_functions(const std::string& name, const ChoiceType& choice, const Module& module,
const Asn1Tree& tree)
{
CodeBlock block;
block.add_line(create_template_definition({"Identifier"}));
block.add_line("inline DecodeResult " + name + "::decode_with_id(BerView input) noexcept");
{
auto scope1 = CodeScope(block);
block.add_line("BerView content(input);");
block.add_line("if (!IsChoiceId<Identifier>::value)");
{
auto scope2 = CodeScope(block);
block.add_line("if (!input.is_valid())");
{
auto scope3 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Invalid packet when decoding choice [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line("if (!has_correct_header(input, Identifier{}, Construction::constructed))");
{
auto scope3 = CodeScope(block);
block.add_line(
R"(FAST_BER_ERROR("Invalid header when decoding choice type [", input.identifier(), "] in choice [)" +
name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line(
"BerViewIterator child = (Identifier::depth() == 1) ? input.begin() : input.begin()->begin();");
block.add_line("if (!child->is_valid())");
{
auto scope3 = CodeScope(block);
block.add_line(R"(FAST_BER_ERROR("Invalid child packet when decoding choice [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line("content = *child;");
}
if (module.tagging_default == TaggingMode::automatic)
{
block.add_line("switch (content.tag())");
{
auto scope2 = CodeScope(block);
for (std::size_t i = 0; i < choice.choices.size(); i++)
{
block.add_line("case " + std::to_string(i) + ":");
block.add_line(" return this->template emplace<" + std::to_string(i) + ">()." +
make_component_function("decode", choice.choices[i], module, tree) + "(content);");
}
}
}
else
{
for (Class class_ : {
Class::universal,
Class::application,
Class::context_specific,
Class::private_,
})
{
const std::vector<Identifier>& outer_ids = outer_identifiers(choice, module, tree);
if (std::any_of(outer_ids.begin(), outer_ids.end(),
[class_](const Identifier& id) { return id.class_ == class_; }))
{
block.add_line("switch (content.tag())");
auto scope2 = CodeScope(block);
std::size_t i = 0;
for (const NamedType& named_type : choice.choices)
{
const std::vector<Identifier>& ids = outer_identifiers(named_type.type, module, tree);
for (const Identifier& id : ids)
{
if (id.class_ == class_)
{
block.add_line("case " + std::to_string(id.tag_number) + ":");
block.add_line(" return this->template emplace<" + std::to_string(i) + ">()." +
make_component_function("decode", choice.choices[i], module, tree) +
"(content);");
}
}
i++;
}
}
}
}
block.add_line(R"(FAST_BER_ERROR("Unknown tag [", content.identifier(), "] in choice [)" + name + R"(]");)");
block.add_line("return DecodeResult{false};");
}
block.add_line();
return block;
}
CodeBlock create_encode_functions_impl(const Asn1Tree& tree, const Module& module, const Type& type,
const std::string& name)
{
if (is_sequence(type))
{
const SequenceType& sequence = absl::get<SequenceType>(absl::get<BuiltinType>(type));
return create_collection_encode_functions(name, sequence, module, tree);
}
else if (is_set(type))
{
const SetType& set = absl::get<SetType>(absl::get<BuiltinType>(type));
return create_collection_encode_functions(name, set, module, tree);
}
else if (is_choice(type))
{
const ChoiceType& choice = absl::get<ChoiceType>(absl::get<BuiltinType>(type));
return create_choice_encode_functions(name, choice, module, tree);
}
return {};
}
CodeBlock create_decode_functions_impl(const Asn1Tree& tree, const Module& module, const Type& type,
const std::string& name)
{
if (is_sequence(type))
{
const SequenceType& sequence = absl::get<SequenceType>(absl::get<BuiltinType>(type));
return create_collection_decode_functions(name, sequence, module, tree);
}
else if (is_set(type))
{
const SetType& set = absl::get<SetType>(absl::get<BuiltinType>(type));
return create_collection_decode_functions(name, set, module, tree);
}
else if (is_choice(type))
{
const ChoiceType& choice = absl::get<ChoiceType>(absl::get<BuiltinType>(type));
return create_choice_decode_functions(name, choice, module, tree);
}
return {};
}
std::string create_encode_functions(const Assignment& assignment, const Module& module, const Asn1Tree& tree)
{
if (absl::holds_alternative<TypeAssignment>(assignment.specific))
{
return visit_all_types(tree, module, assignment, create_encode_functions_impl).to_string();
}
return "";
}
std::string create_decode_functions(const Assignment& assignment, const Module& module, const Asn1Tree& tree)
{
if (absl::holds_alternative<TypeAssignment>(assignment.specific))
{
return visit_all_types(tree, module, assignment, create_decode_functions_impl).to_string();
}
return "";
}
| 46.262436 | 122 | 0.45497 | yudanli |
16517c730c5ab6812c064ae5c6a1bfbda0aafbaf | 2,906 | cpp | C++ | Lab 8/src/utils/source/outUtils.cpp | chemizt/parallel-programming-labs | b8ba6e41bc03cf8c9e9bff1e353f8c7af9a45c20 | [
"WTFPL"
] | 1 | 2019-11-25T10:19:46.000Z | 2019-11-25T10:19:46.000Z | Lab 8/src/utils/source/outUtils.cpp | chemizt/parallel-programming-labs | b8ba6e41bc03cf8c9e9bff1e353f8c7af9a45c20 | [
"WTFPL"
] | 3 | 2019-12-01T22:27:43.000Z | 2019-12-01T22:38:54.000Z | Lab 8/src/utils/source/outUtils.cpp | chemizt/parallel-programming-labs | b8ba6e41bc03cf8c9e9bff1e353f8c7af9a45c20 | [
"WTFPL"
] | null | null | null | #include "outUtils.hpp"
struct Comma final : std::numpunct<char> // inspired by (copy-typed from) https://stackoverflow.com/a/42331536
{
char do_decimal_point() const override { return ','; }
};
void outputIntMatrix(intMatrix matrix)
{
uInt maxNumLength = getMaxNumberLengthInIntMatrix(matrix);
for (uInt i = 0; i < matrix.size(); i++)
{
for (uInt j = 0; j < matrix.at(i).size(); j++)
{
cout << matrix.at(i).at(j) << getSpaces(maxNumLength * 2 - getIntNumberLength(matrix.at(i).at(j)));
}
cout << "\n";
}
cout << "\n";
}
void outputIntVector(vector<int> vector)
{
for (uInt i = 0; i < vector.size(); i++)
{
cout << vector.at(i) << " ";
}
cout << "\n\n";
}
void outputDoubleMatrix(doubleMatrix matrix)
{
uInt maxNumLength = getMaxNumberLengthInDoubleMatrix(matrix);
cout << fixed << setprecision(2);
for (uInt i = 0; i < matrix.size(); i++)
{
for (uInt j = 0; j < matrix.at(i).size(); j++)
{
cout << matrix.at(i).at(j) << getSpaces(maxNumLength * 2 - getDoubleNumberLength(matrix.at(i).at(j)));
}
cout << "\n";
}
cout << "\n";
}
void outputDoubleVector(vector<double> vector)
{
cout << fixed << setprecision(2);
for (uInt i = 0; i < vector.size(); i++)
{
cout << vector.at(i) << " ";
}
cout << "\n\n";
}
void logOutput(string message)
{
ofstream resultsFile;
string timeStamp = getCurrentTimeStampAsString();
resultsFile.open(LOG_FILE_NAME, std::ios_base::app);
cout << timeStamp << ": " << message << endl;
resultsFile << timeStamp << ": " << message << endl;
resultsFile.close();
}
template <typename type>
void outputMatrixToFile(vector<vector<type>> matrix, string fileName)
{
ofstream resultsFile;
resultsFile.open(fileName, std::ios_base::app);
resultsFile.imbue(locale(locale::classic(), new Comma));
for (uInt i = 0; i < matrix.size(); i++)
{
for (uInt j = 0; j < matrix.at(i).size(); j++)
{
if (j < matrix.at(i).size() - 1)
{
resultsFile << matrix.at(i).at(j) << ";";
}
else
{
resultsFile << matrix.at(i).at(j) << "\n";
}
}
}
resultsFile << "\n\n";
resultsFile.close();
}
template <typename type>
void outputVectorToFile(vector<type> vector, string fileName)
{
ofstream resultsFile;
resultsFile.open(fileName, std::ios_base::app);
resultsFile.imbue(locale(locale::classic(), new Comma));
for (uInt i = 0; i < vector.size(); i++)
{
if (i < vector.size() - 1)
{
resultsFile << vector.at(i) << ";";
}
else
{
resultsFile << vector.at(i) << "\n";
}
}
resultsFile << "\n\n";
resultsFile.close();
} | 24.216667 | 114 | 0.538885 | chemizt |
165191a2f7f5f5f718fe2c045b55e1df7b870e19 | 20,173 | cpp | C++ | sp/src/game/server/mod/npc_base_custom.cpp | jarnar85/source-sdk-2013 | 8c279299883421fd78e7691545522ea863e0b646 | [
"Unlicense"
] | null | null | null | sp/src/game/server/mod/npc_base_custom.cpp | jarnar85/source-sdk-2013 | 8c279299883421fd78e7691545522ea863e0b646 | [
"Unlicense"
] | 8 | 2019-09-07T10:19:52.000Z | 2020-03-31T19:44:45.000Z | sp/src/game/server/mod/npc_base_custom.cpp | jarnar85/source-sdk-2013 | 8c279299883421fd78e7691545522ea863e0b646 | [
"Unlicense"
] | null | null | null | //=//=============================================================================//
//
// Purpose: A base class from which to extend new custom NPCs.
// This class may seem redundant with CAI_BaseNPC and a lot of Valve's NPC classes.
// However, the redundancy is necessary for compatibility with a variety of mods;
// I want all new NPC content to be isolated from existing classes.
//
// Author: 1upD
//
//=============================================================================//
#include "cbase.h"
#include "npc_base_custom.h"
#include "ai_hull.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "engine/IEngineSound.h"
#include "basehlcombatweapon_shared.h"
#include "ai_squadslot.h"
#include "ai_squad.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//---------------------------------------------------------
// Constants
//---------------------------------------------------------
// TODO: Replace these with fields so that other NPCs can override them
const float MIN_TIME_NEXT_SOUND = 0.5f;
const float MAX_TIME_NEXT_SOUND = 1.0f;
const float MIN_TIME_NEXT_FOUNDENEMY_SOUND = 2.0f;
const float MAX_TIME_NEXT_FOUNDENEMY_SOUND = 5.0f;
LINK_ENTITY_TO_CLASS(npc_base_custom, CNPC_BaseCustomNPC);
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC(CNPC_BaseCustomNPC)
DEFINE_KEYFIELD(m_iszWeaponModelName, FIELD_STRING, "WeaponModel"),
DEFINE_KEYFIELD(m_iHealth, FIELD_INTEGER, "Health"),
DEFINE_KEYFIELD(m_iszFearSound, FIELD_SOUNDNAME, "FearSound"),
DEFINE_KEYFIELD(m_iszDeathSound, FIELD_SOUNDNAME, "DeathSound"),
DEFINE_KEYFIELD(m_iszIdleSound, FIELD_SOUNDNAME, "IdleSound"),
DEFINE_KEYFIELD(m_iszPainSound, FIELD_SOUNDNAME, "PainSound"),
DEFINE_KEYFIELD(m_iszAlertSound, FIELD_SOUNDNAME, "AlertSound"),
DEFINE_KEYFIELD(m_iszLostEnemySound, FIELD_SOUNDNAME, "LostEnemySound"),
DEFINE_KEYFIELD(m_iszFoundEnemySound, FIELD_SOUNDNAME, "FoundEnemySound"),
DEFINE_KEYFIELD(m_bUseBothSquadSlots, FIELD_BOOLEAN, "UseBothSquadSlots"),
DEFINE_KEYFIELD(m_bCannotOpenDoors, FIELD_BOOLEAN, "CannotOpenDoors"),
DEFINE_KEYFIELD(m_bCanPickupWeapons, FIELD_BOOLEAN, "CanPickupWeapons"),
DEFINE_FIELD(m_iNumSquadmates, FIELD_INTEGER),
DEFINE_FIELD(m_bWanderToggle, FIELD_BOOLEAN),
DEFINE_FIELD(m_flNextSoundTime, FIELD_TIME),
DEFINE_FIELD(m_flNextFoundEnemySoundTime, FIELD_TIME),
DEFINE_FIELD(m_flSpeedModifier, FIELD_TIME),
DEFINE_INPUTFUNC(FIELD_FLOAT, "SetSpeedModifier", InputSetSpeedModifier),
DEFINE_INPUTFUNC(FIELD_VOID, "EnableOpenDoors", InputEnableOpenDoors),
DEFINE_INPUTFUNC(FIELD_VOID, "DisableOpenDoors", InputDisableOpenDoors),
DEFINE_INPUTFUNC(FIELD_VOID, "EnablePickupWeapons", InputEnablePickupWeapons),
DEFINE_INPUTFUNC(FIELD_VOID, "DisablePickupWeapons", InputDisablePickupWeapons)
END_DATADESC()
AI_BEGIN_CUSTOM_NPC(npc_base_custom, CNPC_BaseCustomNPC)
//=========================================================
// > Melee_Attack_NoInterrupt
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MELEE_ATTACK_NOINTERRUPT,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_ANNOUNCE_ATTACK 1" // 1 = primary attack
" TASK_MELEE_ATTACK1 0"
""
" Interrupts"
" COND_ENEMY_DEAD"
" COND_ENEMY_OCCLUDED"
);
//=========================================================
// SCHED_HIDE
//=========================================================
DEFINE_SCHEDULE
(
SCHED_HIDE,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBAT_FACE"
" TASK_STOP_MOVING 0"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_HEAR_DANGER"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
);
AI_END_CUSTOM_NPC()
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::Precache( void )
{
// If no model name is supplied, use the default citizen model
if (!GetModelName())
{
SetModelName(MAKE_STRING("models/monster/subject.mdl")); // TODO replace this with citizen
}
if (&m_iszWeaponModelName && m_iszWeaponModelName != MAKE_STRING("")) {
PrecacheModel(STRING(m_iszWeaponModelName));
}
else {
PrecacheModel("models/props_canal/mattpipe.mdl"); // Default weapon model
}
PrecacheModel(STRING(GetModelName()));
PrecacheNPCSoundScript(&m_iszFearSound, MAKE_STRING("NPC_BaseCustomr.Fear"));
PrecacheNPCSoundScript(&m_iszIdleSound, MAKE_STRING("NPC_BaseCustom.Idle"));
PrecacheNPCSoundScript(&m_iszAlertSound, MAKE_STRING("NPC_BaseCustom.Alert"));
PrecacheNPCSoundScript(&m_iszPainSound, MAKE_STRING("NPC_BaseCustom.Pain"));
PrecacheNPCSoundScript(&m_iszLostEnemySound, MAKE_STRING("NPC_BaseCustom.LostEnemy"));
PrecacheNPCSoundScript(&m_iszFoundEnemySound, MAKE_STRING("NPC_BaseCustom.FoundEnemy"));
PrecacheNPCSoundScript(&m_iszDeathSound, MAKE_STRING("NPC_BaseCustom.Death"));
m_bWanderToggle = false;
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::Spawn( void )
{
Precache();
SetModel(STRING(GetModelName()));
SetHullType(HULL_HUMAN);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
SetMoveType( MOVETYPE_STEP );
SetBloodColor( BLOOD_COLOR_RED );
// If the health has not been set through Hammer, use a default health value of 75
if (m_iHealth < 1)
{
m_iHealth = 75;
}
m_flFieldOfView = 0.5;
m_flNextSoundTime = gpGlobals->curtime;
m_flNextFoundEnemySoundTime = gpGlobals->curtime;
m_NPCState = NPC_STATE_NONE;
m_flSpeedModifier = 1.0f;
CapabilitiesClear();
if (!HasSpawnFlags(SF_NPC_START_EFFICIENT))
{
CapabilitiesAdd(bits_CAP_ANIMATEDFACE | bits_CAP_TURN_HEAD); // The default model has no face animations, but a custom model might
CapabilitiesAdd(bits_CAP_SQUAD);
CapabilitiesAdd(bits_CAP_USE_WEAPONS | bits_CAP_AIM_GUN | bits_CAP_MOVE_SHOOT);
CapabilitiesAdd(bits_CAP_WEAPON_MELEE_ATTACK1 || bits_CAP_WEAPON_MELEE_ATTACK2);
CapabilitiesAdd(bits_CAP_DUCK);
CapabilitiesAdd(bits_CAP_USE_SHOT_REGULATOR);
if (!m_bCannotOpenDoors) {
CapabilitiesAdd(bits_CAP_DOORS_GROUP);
}
}
CapabilitiesAdd(bits_CAP_MOVE_GROUND);
SetMoveType(MOVETYPE_STEP);
NPCInit();
}
void CNPC_BaseCustomNPC::Activate()
{
BaseClass::Activate();
FixupWeapon();
}
//-----------------------------------------------------------------------------
// Purpose: If this NPC has some kind of custom weapon behavior,
// set up the weapon after spawn.
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::FixupWeapon()
{
// Do nothing
}
//-----------------------------------------------------------------------------
// Purpose: Choose a schedule after schedule failed
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode)
{
switch (failedSchedule)
{
case SCHED_NEW_WEAPON:
// If failed trying to pick up a weapon, try again in one second. This is because other AI code
// has put this off for 10 seconds under the assumption that the citizen would be able to
// pick up the weapon that they found.
m_flNextWeaponSearchTime = gpGlobals->curtime + 1.0f;
break;
}
return BaseClass::SelectFailSchedule(failedSchedule, failedTask, taskFailCode);
}
//-----------------------------------------------------------------------------
// Purpose: Select a schedule to retrieve better weapons if they are available.
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectScheduleRetrieveItem()
{
if (m_bCanPickupWeapons && HasCondition(COND_BETTER_WEAPON_AVAILABLE))
{
CBaseHLCombatWeapon *pWeapon = dynamic_cast<CBaseHLCombatWeapon *>(Weapon_FindUsable(WEAPON_SEARCH_DELTA));
if (pWeapon)
{
m_flNextWeaponSearchTime = gpGlobals->curtime + 10.0;
// Now lock the weapon for several seconds while we go to pick it up.
pWeapon->Lock(10.0, this);
SetTarget(pWeapon);
return SCHED_NEW_WEAPON;
}
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
// Purpose: Select ideal state.
// Conditions for custom states are defined here.
//-----------------------------------------------------------------------------
NPC_STATE CNPC_BaseCustomNPC::SelectIdealState(void)
{
switch ((int)this->m_NPCState) {
case NPC_STATE_AMBUSH:
return SelectAmbushIdealState();
case NPC_STATE_SURRENDER:
return SelectSurrenderIdealState();
default:
return BaseClass::SelectIdealState();
}
}
NPC_STATE CNPC_BaseCustomNPC::SelectAmbushIdealState()
{
// AMBUSH goes to ALERT upon death of enemy
if (GetEnemy() == NULL)
{
return NPC_STATE_ALERT;
}
// If I am not in a squad, there is no reason to ambush
if (!m_pSquad) {
return NPC_STATE_COMBAT;
}
// If I am the last in a squad, attack!
if (m_pSquad->NumMembers() == 1) {
return NPC_STATE_COMBAT;
}
if (OccupyStrategySlotRange(SQUAD_SLOT_CHASE_1, SQUAD_SLOT_CHASE_2)) {
return NPC_STATE_COMBAT;
}
// The best ideal state is the current ideal state.
return (NPC_STATE)NPC_STATE_AMBUSH;
}
NPC_STATE CNPC_BaseCustomNPC::SelectSurrenderIdealState()
{
return NPC_STATE_ALERT;
}
//-----------------------------------------------------------------------------
// Purpose: Select a schedule to retrieve better weapons if they are available.
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectScheduleWander()
{
m_bWanderToggle = !m_bWanderToggle;
if (m_bWanderToggle) {
return SCHED_IDLE_WANDER;
}
else {
return SCHED_NONE;
}
}
//-----------------------------------------------------------------------------
// Purpose: Select a schedule to execute based on conditions.
// This is the most critical AI method.
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectSchedule()
{
switch ((int)m_NPCState)
{
case NPC_STATE_IDLE:
AssertMsgOnce(GetEnemy() == NULL, "NPC has enemy but is not in combat state?");
return SelectIdleSchedule();
case NPC_STATE_ALERT:
AssertMsgOnce(GetEnemy() == NULL, "NPC has enemy but is not in combat state?");
return SelectAlertSchedule();
case NPC_STATE_COMBAT:
return SelectCombatSchedule();
case NPC_STATE_AMBUSH:
return SelectAmbushSchedule();
case NPC_STATE_SURRENDER:
return SelectSurrenderSchedule();
default:
return BaseClass::SelectSchedule();
}
}
//-----------------------------------------------------------------------------
// Idle schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectIdleSchedule()
{
int nSched = SelectFlinchSchedule();
if (nSched != SCHED_NONE)
return nSched;
if (HasCondition(COND_HEAR_DANGER) ||
HasCondition(COND_HEAR_COMBAT) ||
HasCondition(COND_HEAR_WORLD) ||
HasCondition(COND_HEAR_BULLET_IMPACT) ||
HasCondition(COND_HEAR_PLAYER))
{
// Investigate sound source
return SCHED_ALERT_FACE_BESTSOUND;
}
nSched = SelectScheduleRetrieveItem();
if (nSched != SCHED_NONE)
return nSched;
// no valid route! Wander instead
if (GetNavigator()->GetGoalType() == GOALTYPE_NONE) {
return SCHED_IDLE_STAND;
}
// valid route. Get moving
return SCHED_IDLE_WALK;
}
//-----------------------------------------------------------------------------
// Alert schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectAlertSchedule()
{
// Per default base NPC, check flinch schedule first
int nSched = SelectFlinchSchedule();
if (nSched != SCHED_NONE)
return nSched;
// Scan around for new enemies
if (HasCondition(COND_ENEMY_DEAD) && SelectWeightedSequence(ACT_VICTORY_DANCE) != ACTIVITY_NOT_AVAILABLE)
return SCHED_ALERT_SCAN;
if (HasCondition(COND_HEAR_DANGER) ||
HasCondition(COND_HEAR_PLAYER) ||
HasCondition(COND_HEAR_WORLD) ||
HasCondition(COND_HEAR_BULLET_IMPACT) ||
HasCondition(COND_HEAR_COMBAT))
{
// Investigate sound source
AlertSound();
return SCHED_ALERT_FACE_BESTSOUND;
}
nSched = SelectScheduleRetrieveItem();
if (nSched != SCHED_NONE)
return nSched;
// no valid route! Wander instead
if (GetNavigator()->GetGoalType() == GOALTYPE_NONE) {
return SCHED_ALERT_STAND;
}
// valid route. Get moving
return SCHED_ALERT_WALK;
}
//-----------------------------------------------------------------------------
// Combat schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectCombatSchedule()
{
return BaseClass::SelectSchedule(); // Let Base NPC handle it
}
//-----------------------------------------------------------------------------
// Combat schedule selection
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::SelectAmbushSchedule()
{
// Check enemy death
if (HasCondition(COND_ENEMY_DEAD))
{
// clear the current (dead) enemy and try to find another.
SetEnemy(NULL);
if (ChooseEnemy())
{
SetState(NPC_STATE_COMBAT);
FoundEnemySound();
ClearCondition(COND_ENEMY_DEAD);
return SelectSchedule();
}
SetState(NPC_STATE_ALERT);
return SelectSchedule();
}
CBaseEntity* pEnemy = GetEnemy();
if (pEnemy && EnemyDistance(pEnemy) < 128)
{
SetState(NPC_STATE_COMBAT);
return SelectSchedule();
}
if (pEnemy == NULL || HasCondition(COND_LOST_ENEMY)) {
SetState(NPC_STATE_ALERT);
return SelectSchedule();
}
// If I am the last in a squad, attack!
if (m_iNumSquadmates > m_pSquad->NumMembers())
SetState(SelectAmbushIdealState());
if (HasCondition(COND_LIGHT_DAMAGE)) {
SetState(NPC_STATE_COMBAT);
}
if (HasCondition(COND_SEE_ENEMY) && HasCondition(COND_ENEMY_FACING_ME) && HasCondition(COND_HAVE_ENEMY_LOS)) {
if(GetState() != NPC_STATE_COMBAT)
SetState(SelectAmbushIdealState());
return SCHED_HIDE;
}
m_iNumSquadmates = m_pSquad->NumMembers();
return SCHED_COMBAT_FACE;
}
int CNPC_BaseCustomNPC::SelectSurrenderSchedule()
{
return BaseClass::SelectSchedule();
}
bool CNPC_BaseCustomNPC::HasRangedWeapon()
{
CBaseCombatWeapon *pWeapon = GetActiveWeapon();
if (pWeapon)
return !(FClassnameIs(pWeapon, "weapon_crowbar") || FClassnameIs(pWeapon, "weapon_stunstick") || FClassnameIs(pWeapon, "weapon_custommelee"));
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Override base class activiites
//-----------------------------------------------------------------------------
Activity CNPC_BaseCustomNPC::NPC_TranslateActivity(Activity activity)
{
switch (activity) {
case ACT_RUN_AIM_SHOTGUN:
return ACT_RUN_AIM_RIFLE;
case ACT_WALK_AIM_SHOTGUN:
return ACT_WALK_AIM_RIFLE;
case ACT_IDLE_ANGRY_SHOTGUN:
return ACT_IDLE_ANGRY_SMG1;
case ACT_RANGE_ATTACK_SHOTGUN_LOW:
return ACT_RANGE_ATTACK_SMG1_LOW;
case ACT_IDLE_MELEE:
case ACT_IDLE_ANGRY_MELEE: // If the NPC has a melee weapon but is in an idle state, don't raise the weapon
if (m_NPCState == NPC_STATE_IDLE)
return ACT_IDLE_SUITCASE;
default:
return BaseClass::NPC_TranslateActivity(activity);
}
}
//-----------------------------------------------------------------------------
// Purpose: Override base class schedules
//-----------------------------------------------------------------------------
int CNPC_BaseCustomNPC::TranslateSchedule(int scheduleType)
{
return BaseClass::TranslateSchedule(scheduleType);
}
//-----------------------------------------------------------------------------
// Purpose: Play sound when an enemy is spotted. This sound has a separate
// timer from other sounds to prevent looping if the NPC gets caught
// in a 'found enemy' condition.
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::FoundEnemySound(void)
{
if (gpGlobals->curtime > m_flNextFoundEnemySoundTime)
{
m_flNextFoundEnemySoundTime = gpGlobals->curtime + random->RandomFloat(MIN_TIME_NEXT_FOUNDENEMY_SOUND, MAX_TIME_NEXT_FOUNDENEMY_SOUND);
PlaySound(m_iszFoundEnemySound, true);
}
}
//-----------------------------------------------------------------------------
// Purpose: Play NPC soundscript
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::PlaySound(string_t soundname, bool required /*= false */)
{
// TODO: Check if silent
if (required || gpGlobals->curtime > m_flNextSoundTime)
{
m_flNextSoundTime = gpGlobals->curtime + random->RandomFloat(MIN_TIME_NEXT_SOUND, MAX_TIME_NEXT_SOUND);
//CPASAttenuationFilter filter2(this, STRING(soundname));
EmitSound(STRING(soundname));
}
}
//-----------------------------------------------------------------------------
// Purpose: Assign a default soundscript if none is provided, then precache
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::PrecacheNPCSoundScript(string_t * SoundName, string_t defaultSoundName)
{
if (!SoundName) {
*SoundName = defaultSoundName;
}
PrecacheScriptSound(STRING(*SoundName));
}
//-----------------------------------------------------------------------------
// Purpose: Get movement speed, multipled by modifier
//-----------------------------------------------------------------------------
float CNPC_BaseCustomNPC::GetSequenceGroundSpeed(CStudioHdr *pStudioHdr, int iSequence)
{
float t = SequenceDuration(pStudioHdr, iSequence);
if (t > 0)
{
return (GetSequenceMoveDist(pStudioHdr, iSequence) * m_flSpeedModifier / t);
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to change the speed of the NPC
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputSetSpeedModifier(inputdata_t &inputdata)
{
this->m_flSpeedModifier = inputdata.value.Float();
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable opening doors
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputEnableOpenDoors(inputdata_t &inputdata)
{
m_bCannotOpenDoors = false;
if (!HasSpawnFlags(SF_NPC_START_EFFICIENT))
{
CapabilitiesAdd(bits_CAP_DOORS_GROUP);
}
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable opening doors
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputDisableOpenDoors(inputdata_t &inputdata)
{
m_bCannotOpenDoors = true;
if (!HasSpawnFlags(SF_NPC_START_EFFICIENT))
{
CapabilitiesRemove(bits_CAP_DOORS_GROUP);
}
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable weapon pickup behavior
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputEnablePickupWeapons(inputdata_t &inputdata)
{
m_bCanPickupWeapons = true;
}
//-----------------------------------------------------------------------------
// Purpose: Hammer input to enable weapon pickup behavior
//-----------------------------------------------------------------------------
void CNPC_BaseCustomNPC::InputDisablePickupWeapons(inputdata_t &inputdata)
{
m_bCanPickupWeapons = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
// Output :
//-----------------------------------------------------------------------------
Class_T CNPC_BaseCustomNPC::Classify( void )
{
return CLASS_NONE;
}
| 31.768504 | 144 | 0.598374 | jarnar85 |
16526570f5c665f6ef3d7f50e27cc69083c71453 | 489 | cpp | C++ | 53_soma_casas_forca_bruta.cpp | dannluciano/codcad | a226fa11dab0e1cc6524c42859b01435d58ce4f0 | [
"MIT"
] | null | null | null | 53_soma_casas_forca_bruta.cpp | dannluciano/codcad | a226fa11dab0e1cc6524c42859b01435d58ce4f0 | [
"MIT"
] | null | null | null | 53_soma_casas_forca_bruta.cpp | dannluciano/codcad | a226fa11dab0e1cc6524c42859b01435d58ce4f0 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
int main() {
int numero_de_casas;
scanf("%d", &numero_de_casas);
int casas[numero_de_casas];
for (int i = 0; i < numero_de_casas; i++) {
scanf("%d", &casas[i]);
}
int soma_das_casas;
scanf("%d", &soma_das_casas);
for (int i = 0; i < numero_de_casas - 1; i++) {
for (int j = i + 1; j < numero_de_casas; j++) {
if (casas[i] + casas[j] == soma_das_casas) {
printf("%d %d", casas[i], casas[j]);
}
}
}
return 0;
} | 21.26087 | 51 | 0.543967 | dannluciano |
1653587cd532458098b42d5b442feaf4cd2a72ec | 3,993 | cpp | C++ | sources/libcore/mesh/xatlas.cpp | Gaeldrin/cage | 6399a5cdcb3932e8d422901ce7d72099dc09273c | [
"MIT"
] | null | null | null | sources/libcore/mesh/xatlas.cpp | Gaeldrin/cage | 6399a5cdcb3932e8d422901ce7d72099dc09273c | [
"MIT"
] | null | null | null | sources/libcore/mesh/xatlas.cpp | Gaeldrin/cage | 6399a5cdcb3932e8d422901ce7d72099dc09273c | [
"MIT"
] | null | null | null | #include <cstddef> // fix missing size_t in xatlas
#include <cstdarg> // va_start
#include <cstdio> // vsprintf
#include <xatlas.h>
#include "mesh.h"
namespace cage
{
namespace
{
int xAtlasPrint(const char *format, ...)
{
char buffer[1000];
va_list arg;
va_start(arg, format);
auto result = vsprintf(buffer, format, arg);
va_end(arg);
CAGE_LOG_DEBUG(SeverityEnum::Warning, "xatlas", buffer);
return result;
}
struct Initializer
{
Initializer()
{
xatlas::SetPrint(&xAtlasPrint, false);
}
} initializer;
const string xAtlasCategoriesNames[] = {
"AddModel",
"ComputeCharts",
"PackCharts",
"BuildOutputModeles"
};
bool xAtlasProgress(xatlas::ProgressCategory category, int progress, void *userData)
{
CAGE_LOG(SeverityEnum::Info, "xatlas", stringizer() + xAtlasCategoriesNames[(int)category] + ": " + progress + " %");
return true; // continue processing
}
void destroyAtlas(void *ptr)
{
xatlas::Destroy((xatlas::Atlas*)ptr);
}
Holder<xatlas::Atlas> newAtlas(bool reportProgress)
{
struct Atl : Immovable
{
xatlas::Atlas *a = nullptr;
Atl()
{
a = xatlas::Create();
}
~Atl()
{
xatlas::Destroy(a);
}
};
Holder<Atl> h = systemArena().createHolder<Atl>();
return Holder<xatlas::Atlas>(h->a, std::move(h));
}
}
uint32 meshUnwrap(Mesh *poly, const MeshUnwrapConfig &config)
{
CAGE_ASSERT(poly->type() == MeshTypeEnum::Triangles);
CAGE_ASSERT((config.targetResolution == 0) != (config.texelsPerUnit == 0));
if (poly->facesCount() == 0)
return 0;
const bool useNormals = !poly->normals().empty();
Holder<xatlas::Atlas> atlas = newAtlas(config.logProgress);
{
xatlas::MeshDecl decl;
decl.vertexCount = poly->verticesCount();
decl.vertexPositionData = poly->positions().data();
decl.vertexPositionStride = sizeof(vec3);
if (useNormals)
{
decl.vertexNormalData = poly->normals().data();
decl.vertexNormalStride = sizeof(vec3);
}
if (poly->indicesCount())
{
decl.indexFormat = xatlas::IndexFormat::UInt32;
decl.indexCount = poly->indicesCount();
decl.indexData = poly->indices().data();
}
xatlas::AddMesh(atlas.get(), decl);
}
{
xatlas::ChartOptions chart;
chart.maxChartArea = config.maxChartArea.value;
chart.maxBoundaryLength = config.maxChartBoundaryLength.value;
chart.normalDeviationWeight = config.chartNormalDeviation.value;
chart.roundnessWeight = config.chartRoundness.value;
chart.straightnessWeight = config.chartStraightness.value;
chart.normalSeamWeight = config.chartNormalSeam.value;
chart.textureSeamWeight = config.chartTextureSeam.value;
chart.maxCost = config.chartGrowThreshold.value;
chart.maxIterations = config.maxChartIterations;
xatlas::ComputeCharts(atlas.get(), chart);
}
{
xatlas::PackOptions pack;
pack.bilinear = true;
pack.blockAlign = true;
pack.padding = config.padding;
pack.texelsPerUnit = config.texelsPerUnit.value;
pack.resolution = config.targetResolution;
xatlas::PackCharts(atlas.get(), pack);
CAGE_ASSERT(atlas->meshCount == 1);
CAGE_ASSERT(atlas->atlasCount == 1);
}
{
const xatlas::Mesh *m = atlas->meshes;
std::vector<vec3> vs;
std::vector<vec3> ns;
std::vector<vec2> us;
// todo copy all other attributes too
vs.reserve(m->vertexCount);
if (useNormals)
ns.reserve(m->vertexCount);
us.reserve(m->vertexCount);
const vec2 whInv = 1 / vec2(atlas->width, atlas->height);
for (uint32 i = 0; i < m->vertexCount; i++)
{
const xatlas::Vertex &a = m->vertexArray[i];
vs.push_back(poly->position(a.xref));
if (useNormals)
ns.push_back(poly->normal(a.xref));
us.push_back(vec2(a.uv[0], a.uv[1]) * whInv);
}
poly->clear();
poly->positions(vs);
if (useNormals)
poly->normals(ns);
poly->uvs(us);
poly->indices({ m->indexArray, m->indexArray + m->indexCount });
return atlas->width;
}
}
}
| 25.928571 | 120 | 0.664663 | Gaeldrin |
16539d4786d8054ccbdf0a94c1b13186c357fbdd | 67 | cpp | C++ | data_server/src/http_headers.cpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | 2 | 2020-06-07T16:47:20.000Z | 2021-03-20T10:41:34.000Z | data_server/src/http_headers.cpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | null | null | null | data_server/src/http_headers.cpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | null | null | null | #include "data_server/http_headers.hpp"
namespace carpi::data {
} | 13.4 | 39 | 0.761194 | Yanick-Salzmann |
165a6df728a6e2219358f09a3a64fbd3f2f87886 | 101,521 | cpp | C++ | Framewave/domain/fwImage/src/Rotate.cpp | dbremner/framewave | 94babe445689538e6c3b44b1575cca27893b9bb4 | [
"Apache-2.0"
] | null | null | null | Framewave/domain/fwImage/src/Rotate.cpp | dbremner/framewave | 94babe445689538e6c3b44b1575cca27893b9bb4 | [
"Apache-2.0"
] | 1 | 2019-01-14T04:00:23.000Z | 2019-01-14T04:00:23.000Z | Framewave/domain/fwImage/src/Rotate.cpp | dbremner/framewave | 94babe445689538e6c3b44b1575cca27893b9bb4 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2006-2009 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#include "fwdev.h"
#include "fwImage.h"
#include "FwSharedCode_SSE2.h"
#include "PointHandle.h"
namespace OPT_LEVEL
{
//Parameters
//pSrc - Pointer to the source image origin.
//srcSize Size - pixels of the source image.
//srcStep Step - bytes through the source image buffer.
//srcRoi - Region of interest in the source image.
//pDst - Pointer to the destination image origin.
//dstStep - Step in bytes through the destination image buffer.
//dstRoi - Region of interest in the destination image.
//angle - The angle of rotation in degrees. The source image is rotated counterclockwise
// around the origin (0,0).
//xShift and yShift - The shifts along horizontal and vertical axes to perform after
// the rotation.
//interpolation - The type of interpolation to perform for resampling the image.
// Use one of the following he following values:
// FWI_INTER_NN nearest neighbor interpolation
// FWI_INTER_LINEAR linear interpolation
// FWI_INTER_CUBIC cubic interpolation
//Description:
//
// The function fwiRotate is declared in the fwi.h file. This function rotates the Roi
//of the source image by angle degrees (counterclockwise for positive angle values)
//around the origin (0,0) that is implied to be in the top left corner, and shifts it
//by xShift and yShift values along the x- and y- axes, respectively. The result is
//resampled using the interpolation method specified by the interpolation parameter,
//and written to the destination image Roi.
//
// If you need to rotate an image about an arbitrary center (xCenter, yCenter),
//use the function fwiGetRotateShift to compute the appropriate xShift, yShift values,
//and then call fwiRotate with these values as input parameters. Alternatively, you can
//use the fwiRotateCenter function instead.
#ifndef __ROTATE_DEF
#define __ROTATE_DEF
#define FW_SWAP(x,y,z) z=x;x=y;y=z
#define FW_MIN(x,y) (x>y)?y:x
#define FW_MAX(x,y) (x>y)?x:y
//Define epsilon for calculation error
#define FW_EPSILON 0.0001
#define FW_ZERO(x) (((x)<FW_EPSILON) && ((x) > - FW_EPSILON))
#endif //__ROTATE_DEF
template< class TS, DispatchType disp >
void My_FW_Rotate_Region(float xltop, float yltop, float xlbot, float ylbot,
float xrtop, float yrtop, float xrbot, float yrbot,
int ystart, int yend, float coeffs[2][3],
const TS* pSrc, int srcStep, FwiRect srcRoi,
TS* pDst, int dstStep, FwiRect dstRoi,
int interpolation, int *flag,
int channel, int channel1, Fw32f round)
{
float ratel, rater, coeffl, coeffr, xleft, xright;
float tx, ty, cx, cy, xmap, ymap;
int x, y, xstart, xend;
ratel = (xlbot-xltop)/(ylbot-yltop);
coeffl = xltop - yltop * ratel;
rater = (xrbot-xrtop)/(yrbot-yrtop);
coeffr = xrtop - yrtop * rater;
for (y=ystart;y<=yend;y++) {
xleft = ratel * y + coeffl;
xright = rater * y + coeffr;
xstart = (int) (FW_MAX(xleft, dstRoi.x));
xend = (int) (FW_MIN(xright, (dstRoi.x + dstRoi.width -1)));
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
for (x=xstart; x<=xend; x++) {
cx = x - coeffs[0][2];
xmap = coeffs[0][0] * cx + tx;
ymap = coeffs[0][1] * cx + ty;
My_FW_PointHandle<TS, disp> (xmap, ymap, x, y, pSrc, srcStep, srcRoi,
pDst, dstStep, interpolation, flag, channel, channel1, round);
}
}
return;
}
template< class TS, DispatchType disp >
void My_FW_Rotate_Region_8u_SSE2(float xltop, float yltop, float xlbot, float ylbot,
float xrtop, float yrtop, float xrbot, float yrbot,
int ystart, int yend, float coeffs[2][3],
const TS* pSrc, int srcStep, FwiRect srcRoi,
TS* pDst, int dstStep, FwiRect dstRoi,
int /*interpolation*/, int* flag,
int channel, int chSrc, Fw32f /*round*/)
{
float ratel, rater, coeffl, coeffr, xleft, xright;
float tx, ty,cy;//, xmap, ymap;
int x, y, xstart, xend;
ratel = (xlbot-xltop)/(ylbot-yltop);
coeffl = xltop - yltop * ratel;
rater = (xrbot-xrtop)/(yrbot-yrtop);
coeffr = xrtop - yrtop * rater;
float* cx = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff00 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff01 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
for (x=dstRoi.x; x<(dstRoi.x+dstRoi.width); x++)
{
cx[x - dstRoi.x] = x - coeffs[0][2];
cx_coeff00[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][0];
cx_coeff01[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][1];
}
for (y=ystart;y<=yend;y++) {
xleft = ratel * y + coeffl;
xright = rater * y + coeffr;
xstart = (int) (FW_MAX(xleft, dstRoi.x));
xend = (int) (FW_MIN(xright, (dstRoi.x + dstRoi.width -1)));
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
__m128 txXMM = _mm_set1_ps(tx);
__m128 tyXMM = _mm_set1_ps(ty);
XMM128 cxCoeff00 = {0}, cxCoeff01 = {0};
XMM128 dst = {0};
int y_dstStep = y * dstStep;
if(chSrc == C1)
{
for (x=xstart; x<=xend-16; x+=16) {
for(int xx = 0 ; xx < 16; xx = xx + 4)
{
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x+xx-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x+xx-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
dst.u8[xx + xxx] = *(pSrc+ ymap*srcStep+xmap);
*flag = 1;
}
}
_mm_storeu_si128((__m128i *)(pDst+y_dstStep+x), dst.i);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
*(pDst+y_dstStep+x) = *(pSrc+ ymap*srcStep+xmap);
*flag = 1;
}
}//end of C1
else //if(chSrc == C4 || chSrc == AC4)
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
else
{
*((Fw16u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw16u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+(x+xxx) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel+2);
}
*flag = 1;
}
//}
//_mm_storeu_si128((__m128i *)(pDst+y_dstStep+x * channel), dst.i);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
*((Fw32u*)(pDst+y_dstStep+x * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
else
{
*((Fw16u*)(pDst+y_dstStep+x * channel)) = *((Fw16u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+x * channel +2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
*flag = 1;
}
}//end of C4, AC4
}
fwFree (cx);
fwFree (cx_coeff00);
fwFree (cx_coeff01);
return;
}
template< class TS, CH chSrc, DispatchType disp >
static FwStatus My_FW_Rotate_8u_SSE2(const TS* pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
TS* pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
int interpolation_E = interpolation ^ FWI_SMOOTH_EDGE;
if (interpolation != FWI_INTER_NN && interpolation != FWI_INTER_LINEAR
&& interpolation != FWI_INTER_CUBIC) {
if ( interpolation_E != FWI_INTER_NN && interpolation_E != FWI_INTER_LINEAR
&& interpolation_E != FWI_INTER_CUBIC)
return fwStsInterpolationErr;
interpolation = interpolation_E;
interpolation_E = FWI_SMOOTH_EDGE;
}
int channel=ChannelCount(chSrc);
FwStatus status = My_FW_ParaCheck2<TS>(pSrc, srcSize, srcStep, srcRoi, pDst, dstStep,
dstRoi, channel);
if (status !=fwStsNoErr) return status;
float theta;
float coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = (float)(0.0174532925199 * angle);//(3.14159265359/180.0)
//cos and sin value need to be fixed
coeffs[0][0] = (float)((int)(cos(theta)*32768))/32768;
coeffs[0][1] = (float)((int)(sin(theta)*32768))/32768;
coeffs[0][2] = (float)xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = (float)yShift;
//return My_FW_WarpAffine <TS, chSrc, disp> (pSrc, srcSize, srcStep, srcRoi,
// pDst, dstStep, dstRoi, coeffs, interpolation);
int channel1;
// Will not change 4th channel element in AC4
if (chSrc == AC4) channel1=5;
else channel1=channel;
Fw32f round;
// 32f is supported, but not 32u and 32s
// No rounding is needed for 32f type
if (sizeof(TS) == 4) round=0;
else round=0.5;
float sortX[4], sortY[4];
float mapX[4], mapY[4], tempx;
float temp1, temp2;
//srcROI mapped area
//Force to be floating data
mapX[0]=(float)(coeffs[0][0] * srcRoi.x + coeffs[0][1] * srcRoi.y + coeffs[0][2]);
mapY[0]=(float)(coeffs[1][0] * srcRoi.x + coeffs[1][1] * srcRoi.y + coeffs[1][2]);
mapX[1]=(float)(mapX[0]+coeffs[0][0]*(srcRoi.width-1));
mapY[1]=(float)(mapY[0]+coeffs[1][0]*(srcRoi.width-1));
temp1 = (float)(coeffs[0][1] * (srcRoi.height-1));
temp2 = (float)(coeffs[1][1] * (srcRoi.height-1));
mapX[2]=mapX[1] + (float)temp1;
mapY[2]=mapY[1] + (float)temp2;
mapX[3]=mapX[0] + (float)temp1;
mapY[3]=mapY[0] + (float)temp2;
//Sort X,Y coordinator according to Y value
//Before any pexchange, possible orders
//Angle [0, 90) 1<=0<=2<=3 or 1<=2<=0<=3
//Angle [90, 180)2<=3<=1<=0 or 2<=1<=3<=0
//Angle [180, 270) 3<=2<=0<=1 or 3<=0<=2<=1
//Angle [270, 360) 0<=1<=3<=2 or 0<=3<=1<=2
if (mapY[0] > mapY[2]){
sortX[0]=mapX[2];
sortY[0]=mapY[2];
sortX[2]=mapX[0];
sortY[2]=mapY[0];
} else {
sortX[0]=mapX[0];
sortY[0]=mapY[0];
sortX[2]=mapX[2];
sortY[2]=mapY[2];
}
if (mapY[1] > mapY[3]) {
sortX[1]=mapX[3];
sortY[1]=mapY[3];
sortX[3]=mapX[1];
sortY[3]=mapY[1];
} else {
sortX[1]=mapX[1];
sortY[1]=mapY[1];
sortX[3]=mapX[3];
sortY[3]=mapY[3];
}
//After two exchanges, we have 1<=0<=2<=3 or 0<=1<=3<=2
if (sortY[0]>sortY[1]) {
FW_SWAP(sortY[0], sortY[1], tempx);
FW_SWAP(sortX[0], sortX[1], tempx);
FW_SWAP(sortY[2], sortY[3], tempx);
FW_SWAP(sortX[2], sortX[3], tempx);
}
//We have 0<=1<=3<=2 after sorting
int xstart, xend, ystart, yend;
int x, y, flag=0;
float cy, tx, ty;
//float xmap, ymap;
//dstStep and srcStep are byte size
//we need to change it with data array size
dstStep = dstStep / (sizeof(TS));
srcStep = srcStep / (sizeof(TS));
if (FW_ZERO(sortY[0]-sortY[1])) {//sortY[0]==sortY[1], sortY[2]=sortY[3]
// In this case, the rotation angle must be 0, 90, 180, 270
// We should seperate the case for best performance
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
if (sortX[0] < sortX[1]) {
xstart = (int) (FW_MAX(sortX[0], dstRoi.x));
xend = (int) (FW_MIN(sortX[1], (dstRoi.x + dstRoi.width -1)));
} else {
xstart = (int) (FW_MAX(sortX[1], dstRoi.x));
xend = (int) (FW_MIN(sortX[0], (dstRoi.x + dstRoi.width -1)));
}
float* cx = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff00 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff01 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
for (x=dstRoi.x; x<(dstRoi.x+dstRoi.width); x++)
{
cx[x - dstRoi.x] = x - coeffs[0][2];
cx_coeff00[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][0];
cx_coeff01[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][1];
}
for (y=ystart;y<=yend;y++) {
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
__m128 txXMM = _mm_set1_ps(tx);
__m128 tyXMM = _mm_set1_ps(ty);
XMM128 cxCoeff00 = {0}, cxCoeff01 = {0};
XMM128 dst = {0};
int y_dstStep = y * dstStep;
if(chSrc == C1)
{
for (x=xstart; x<=xend-16; x+=16) {
for(int xx = 0 ; xx < 16; xx = xx + 4)
{
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x+xx-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x+xx-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
dst.u8[xx + xxx] = *(pSrc+ ymap*srcStep+xmap);
flag = 1;
}
}
_mm_storeu_si128((__m128i *)(pDst+y_dstStep+x), dst.i);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
*(pDst+y_dstStep+x) = *(pSrc+ ymap*srcStep+xmap);
flag = 1;
}
}//end of C1
else
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
else
{
*((Fw16u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw16u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+(x+xxx) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel);
}
flag = 1;
}
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
*((Fw32u*)(pDst+y_dstStep+x * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
else
{
*((Fw16u*)(pDst+y_dstStep+x * channel)) = *((Fw16u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+x * channel +2) = *(pSrc+ ymap*srcStep+xmap * channel);
}
flag = 1;
}
}//end of C4, AC4
}
fwFree (cx);
fwFree (cx_coeff00);
fwFree (cx_coeff01);
} else if (FW_ZERO(sortY[1]-sortY[3])) {//sortY[1]==sortY[3]
if (sortX[1] < sortX[3]) {
FW_SWAP(sortX[1], sortX[3], tempx);
}
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else { //general case
if (sortX[1] < sortX[3]) {
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[0], sortY[0], sortX[1], sortY[1],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[3], sortY[3], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else {//sortX[1] >= sortX[3]
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_8u_SSE2 <TS, disp> (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
}
}
//if no point is handled, return warning
if (flag==0) return fwStsWrongIntersectROI;
return fwStsNoErr;
}
void My_FW_Rotate_Region_16u_SSE2(float xltop, float yltop, float xlbot, float ylbot,
float xrtop, float yrtop, float xrbot, float yrbot,
int ystart, int yend, float coeffs[2][3],
const Fw16u* pSrc, int srcStep, FwiRect srcRoi,
Fw16u* pDst, int dstStep, FwiRect dstRoi,
int /*interpolation*/, int* flag,
int channel, int chSrc, Fw32f /*round*/)
{
float ratel, rater, coeffl, coeffr, xleft, xright;
float tx, ty,cy;//, xmap, ymap;
int x, y, xstart, xend;
ratel = (xlbot-xltop)/(ylbot-yltop);
coeffl = xltop - yltop * ratel;
rater = (xrbot-xrtop)/(yrbot-yrtop);
coeffr = xrtop - yrtop * rater;
float* cx = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff00 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff01 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
for (x=dstRoi.x; x<(dstRoi.x+dstRoi.width); x++)
{
cx[x - dstRoi.x] = x - coeffs[0][2];
cx_coeff00[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][0];
cx_coeff01[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][1];
}
for (y=ystart;y<=yend;y++) {
xleft = ratel * y + coeffl;
xright = rater * y + coeffr;
xstart = (int) (FW_MAX(xleft, dstRoi.x));
xend = (int) (FW_MIN(xright, (dstRoi.x + dstRoi.width -1)));
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
__m128 txXMM = _mm_set1_ps(tx);
__m128 tyXMM = _mm_set1_ps(ty);
XMM128 cxCoeff00 = {0}, cxCoeff01 = {0};
XMM128 dst = {0};
int y_dstStep = y * dstStep;
if(chSrc == C1)
{
for (x=xstart; x<=xend-8; x+=8) {
for(int xx = 0 ; xx < 8; xx = xx + 4)
{
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x+xx-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x+xx-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
dst.u16[xx + xxx] = *(pSrc+ ymap*srcStep+xmap);
*flag = 1;
}
}
_mm_storeu_si128((__m128i *)(pDst+y_dstStep+x), dst.i);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
*(pDst+y_dstStep+x) = *(pSrc+ ymap*srcStep+xmap);
*flag = 1;
}
}//end of C1
else
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel + 2)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel + 2));
}
else
{
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+(x+xxx) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
*flag = 1;
}
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
*((Fw32u*)(pDst+y_dstStep+(x) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*((Fw32u*)(pDst+y_dstStep+(x) * channel + 2)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel + 2));
}
else
{
*((Fw32u*)(pDst+y_dstStep+(x) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+(x) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
*flag = 1;
}
}//end of C4, AC4
}
fwFree (cx);
fwFree (cx_coeff00);
fwFree (cx_coeff01);
return;
}
template< CH chSrc >
static FwStatus My_FW_Rotate_16u_SSE2(const Fw16u* pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw16u* pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
int interpolation_E = interpolation ^ FWI_SMOOTH_EDGE;
if (interpolation != FWI_INTER_NN && interpolation != FWI_INTER_LINEAR
&& interpolation != FWI_INTER_CUBIC) {
if ( interpolation_E != FWI_INTER_NN && interpolation_E != FWI_INTER_LINEAR
&& interpolation_E != FWI_INTER_CUBIC)
return fwStsInterpolationErr;
interpolation = interpolation_E;
interpolation_E = FWI_SMOOTH_EDGE;
}
int channel=ChannelCount(chSrc);
FwStatus status = My_FW_ParaCheck2<Fw16u>(pSrc, srcSize, srcStep, srcRoi, pDst, dstStep,
dstRoi, channel);
if (status !=fwStsNoErr) return status;
float theta;
float coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = (float)(0.0174532925199 * angle);//(3.14159265359/180.0)
//cos and sin value need to be fixed
coeffs[0][0] = (float)((int)(cos(theta)*32768))/32768;
coeffs[0][1] = (float)((int)(sin(theta)*32768))/32768;
coeffs[0][2] = (float)xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = (float)yShift;
//return My_FW_WarpAffine <TS, chSrc, disp> (pSrc, srcSize, srcStep, srcRoi,
// pDst, dstStep, dstRoi, coeffs, interpolation);
int channel1;
// Will not change 4th channel element in AC4
if (chSrc == AC4) channel1=5;
else channel1=channel;
Fw32f round;
// 32f is supported, but not 32u and 32s
// No rounding is needed for 32f type
//if (sizeof(TS) == 4) round=0;
//else
round=0.5;
float sortX[4], sortY[4];
float mapX[4], mapY[4], tempx;
float temp1, temp2;
//srcROI mapped area
//Force to be floating data
mapX[0]=(float)(coeffs[0][0] * srcRoi.x + coeffs[0][1] * srcRoi.y + coeffs[0][2]);
mapY[0]=(float)(coeffs[1][0] * srcRoi.x + coeffs[1][1] * srcRoi.y + coeffs[1][2]);
mapX[1]=(float)(mapX[0]+coeffs[0][0]*(srcRoi.width-1));
mapY[1]=(float)(mapY[0]+coeffs[1][0]*(srcRoi.width-1));
temp1 = (float)(coeffs[0][1] * (srcRoi.height-1));
temp2 = (float)(coeffs[1][1] * (srcRoi.height-1));
mapX[2]=mapX[1] + (float)temp1;
mapY[2]=mapY[1] + (float)temp2;
mapX[3]=mapX[0] + (float)temp1;
mapY[3]=mapY[0] + (float)temp2;
//Sort X,Y coordinator according to Y value
//Before any pexchange, possible orders
//Angle [0, 90) 1<=0<=2<=3 or 1<=2<=0<=3
//Angle [90, 180)2<=3<=1<=0 or 2<=1<=3<=0
//Angle [180, 270) 3<=2<=0<=1 or 3<=0<=2<=1
//Angle [270, 360) 0<=1<=3<=2 or 0<=3<=1<=2
if (mapY[0] > mapY[2]){
sortX[0]=mapX[2];
sortY[0]=mapY[2];
sortX[2]=mapX[0];
sortY[2]=mapY[0];
} else {
sortX[0]=mapX[0];
sortY[0]=mapY[0];
sortX[2]=mapX[2];
sortY[2]=mapY[2];
}
if (mapY[1] > mapY[3]) {
sortX[1]=mapX[3];
sortY[1]=mapY[3];
sortX[3]=mapX[1];
sortY[3]=mapY[1];
} else {
sortX[1]=mapX[1];
sortY[1]=mapY[1];
sortX[3]=mapX[3];
sortY[3]=mapY[3];
}
//After two exchanges, we have 1<=0<=2<=3 or 0<=1<=3<=2
if (sortY[0]>sortY[1]) {
FW_SWAP(sortY[0], sortY[1], tempx);
FW_SWAP(sortX[0], sortX[1], tempx);
FW_SWAP(sortY[2], sortY[3], tempx);
FW_SWAP(sortX[2], sortX[3], tempx);
}
//We have 0<=1<=3<=2 after sorting
int xstart, xend, ystart, yend;
int x, y, flag=0;
float cy, tx, ty;
//float xmap, ymap;
//dstStep and srcStep are byte size
//we need to change it with data array size
dstStep = dstStep / (sizeof(Fw16u));
srcStep = srcStep / (sizeof(Fw16u));
if (FW_ZERO(sortY[0]-sortY[1])) {//sortY[0]==sortY[1], sortY[2]=sortY[3]
// In this case, the rotation angle must be 0, 90, 180, 270
// We should seperate the case for best performance
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
if (sortX[0] < sortX[1]) {
xstart = (int) (FW_MAX(sortX[0], dstRoi.x));
xend = (int) (FW_MIN(sortX[1], (dstRoi.x + dstRoi.width -1)));
} else {
xstart = (int) (FW_MAX(sortX[1], dstRoi.x));
xend = (int) (FW_MIN(sortX[0], (dstRoi.x + dstRoi.width -1)));
}
float* cx = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff00 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff01 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
for (x=dstRoi.x; x<(dstRoi.x+dstRoi.width); x++)
{
cx[x - dstRoi.x] = x - coeffs[0][2];
cx_coeff00[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][0];
cx_coeff01[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][1];
}
for (y=ystart;y<=yend;y++) {
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
__m128 txXMM = _mm_set1_ps(tx);
__m128 tyXMM = _mm_set1_ps(ty);
XMM128 cxCoeff00 = {0}, cxCoeff01 = {0};
XMM128 dst = {0};
int y_dstStep = y * dstStep;
if(chSrc == C1)
{
for (x=xstart; x<=xend-8; x+=8) {
for(int xx = 0 ; xx < 8; xx = xx + 4)
{
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x+xx-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x+xx-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
dst.u16[xx + xxx] = *(pSrc+ ymap*srcStep+xmap);
flag = 1;
}
}
_mm_storeu_si128((__m128i *)(pDst+y_dstStep+x), dst.i);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
*(pDst+y_dstStep+x) = *(pSrc+ ymap*srcStep+xmap);
flag = 1;
}
}//end of C1
else
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel + 2)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel + 2));
}
else
{
*((Fw32u*)(pDst+y_dstStep+(x+xxx) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+(x+xxx) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
flag = 1;
}
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
*((Fw32u*)(pDst+y_dstStep+(x) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*((Fw32u*)(pDst+y_dstStep+(x) * channel + 2)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel + 2));
}
else
{
*((Fw32u*)(pDst+y_dstStep+(x) * channel)) = *((Fw32u*)(pSrc+ ymap*srcStep+xmap * channel));
*(pDst+y_dstStep+(x) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
flag = 1;
}
}//end of C4, AC4
}
fwFree (cx);
fwFree (cx_coeff00);
fwFree (cx_coeff01);
} else if (FW_ZERO(sortY[1]-sortY[3])) {//sortY[1]==sortY[3]
if (sortX[1] < sortX[3]) {
FW_SWAP(sortX[1], sortX[3], tempx);
}
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else { //general case
if (sortX[1] < sortX[3]) {
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[0], sortY[0], sortX[1], sortY[1],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[3], sortY[3], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else {//sortX[1] >= sortX[3]
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_16u_SSE2 (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
}
}
//if no point is handled, return warning
if (flag==0) return fwStsWrongIntersectROI;
return fwStsNoErr;
}
void My_FW_Rotate_Region_32f_SSE2(float xltop, float yltop, float xlbot, float ylbot,
float xrtop, float yrtop, float xrbot, float yrbot,
int ystart, int yend, float coeffs[2][3],
const Fw32f* pSrc, int srcStep, FwiRect srcRoi,
Fw32f* pDst, int dstStep, FwiRect dstRoi,
int /*interpolation*/, int* flag,
int channel, int chSrc, Fw32f /*round*/)
{
float ratel, rater, coeffl, coeffr, xleft, xright;
float tx, ty,cy;//, xmap, ymap;
int x, y, xstart, xend;
ratel = (xlbot-xltop)/(ylbot-yltop);
coeffl = xltop - yltop * ratel;
rater = (xrbot-xrtop)/(yrbot-yrtop);
coeffr = xrtop - yrtop * rater;
float* cx = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff00 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff01 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
for (x=dstRoi.x; x<(dstRoi.x+dstRoi.width); x++)
{
cx[x - dstRoi.x] = x - coeffs[0][2];
cx_coeff00[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][0];
cx_coeff01[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][1];
}
for (y=ystart;y<=yend;y++) {
xleft = ratel * y + coeffl;
xright = rater * y + coeffr;
xstart = (int) (FW_MAX(xleft, dstRoi.x));
xend = (int) (FW_MIN(xright, (dstRoi.x + dstRoi.width -1)));
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
__m128 txXMM = _mm_set1_ps(tx);
__m128 tyXMM = _mm_set1_ps(ty);
XMM128 cxCoeff00 = {0}, cxCoeff01 = {0};
XMM128 dst = {0};
int y_dstStep = y * dstStep;
if(chSrc == C1)
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
dst.f32[xxx] = *(pSrc+ ymap*srcStep+xmap);
*flag = 1;
}
_mm_storeu_ps((pDst+y_dstStep+x), dst.f);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
*(pDst+y_dstStep+x) = *(pSrc+ ymap*srcStep+xmap);
*flag = 1;
}
}//end of C1
else
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
dst.f = _mm_loadu_ps(pSrc+ ymap*srcStep+xmap * channel);
_mm_storeu_ps((pDst+y_dstStep+(x+xxx) * channel), dst.f);
}
else
{
*(pDst+y_dstStep+(x+xxx) * channel) = *(pSrc+ ymap*srcStep+xmap * channel);
*(pDst+y_dstStep+(x+xxx) * channel + 1) = *(pSrc+ ymap*srcStep+xmap * channel + 1);
*(pDst+y_dstStep+(x+xxx) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
*flag = 1;
}
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
dst.f = _mm_loadu_ps(pSrc+ ymap*srcStep+xmap * channel);
_mm_storeu_ps((pDst+y_dstStep+(x) * channel), dst.f);
}
else
{
*(pDst+y_dstStep+(x) * channel) = *(pSrc+ ymap*srcStep+xmap * channel);
*(pDst+y_dstStep+(x) * channel + 1) = *(pSrc+ ymap*srcStep+xmap * channel + 1);
*(pDst+y_dstStep+(x) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
*flag = 1;
}
}//end of C4, AC4
}
fwFree (cx);
fwFree (cx_coeff00);
fwFree (cx_coeff01);
return;
}
template< CH chSrc >
static FwStatus My_FW_Rotate_32f_SSE2(const Fw32f* pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw32f* pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
int interpolation_E = interpolation ^ FWI_SMOOTH_EDGE;
if (interpolation != FWI_INTER_NN && interpolation != FWI_INTER_LINEAR
&& interpolation != FWI_INTER_CUBIC) {
if ( interpolation_E != FWI_INTER_NN && interpolation_E != FWI_INTER_LINEAR
&& interpolation_E != FWI_INTER_CUBIC)
return fwStsInterpolationErr;
interpolation = interpolation_E;
interpolation_E = FWI_SMOOTH_EDGE;
}
int channel=ChannelCount(chSrc);
FwStatus status = My_FW_ParaCheck2<Fw32f>(pSrc, srcSize, srcStep, srcRoi, pDst, dstStep,
dstRoi, channel);
if (status !=fwStsNoErr) return status;
float theta;
float coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = (float)(0.0174532925199 * angle);//(3.14159265359/180.0)
//cos and sin value need to be fixed
coeffs[0][0] = (float)((int)(cos(theta)*32768))/32768;
coeffs[0][1] = (float)((int)(sin(theta)*32768))/32768;
coeffs[0][2] = (float)xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = (float)yShift;
//return My_FW_WarpAffine <TS, chSrc, disp> (pSrc, srcSize, srcStep, srcRoi,
// pDst, dstStep, dstRoi, coeffs, interpolation);
int channel1;
// Will not change 4th channel element in AC4
if (chSrc == AC4) channel1=5;
else channel1=channel;
Fw32f round;
// 32f is supported, but not 32u and 32s
// No rounding is needed for 32f type
//if (sizeof(TS) == 4) round=0;
//else
round=0.5;
float sortX[4], sortY[4];
float mapX[4], mapY[4], tempx;
float temp1, temp2;
//srcROI mapped area
//Force to be floating data
mapX[0]=(float)(coeffs[0][0] * srcRoi.x + coeffs[0][1] * srcRoi.y + coeffs[0][2]);
mapY[0]=(float)(coeffs[1][0] * srcRoi.x + coeffs[1][1] * srcRoi.y + coeffs[1][2]);
mapX[1]=(float)(mapX[0]+coeffs[0][0]*(srcRoi.width-1));
mapY[1]=(float)(mapY[0]+coeffs[1][0]*(srcRoi.width-1));
temp1 = (float)(coeffs[0][1] * (srcRoi.height-1));
temp2 = (float)(coeffs[1][1] * (srcRoi.height-1));
mapX[2]=mapX[1] + (float)temp1;
mapY[2]=mapY[1] + (float)temp2;
mapX[3]=mapX[0] + (float)temp1;
mapY[3]=mapY[0] + (float)temp2;
//Sort X,Y coordinator according to Y value
//Before any pexchange, possible orders
//Angle [0, 90) 1<=0<=2<=3 or 1<=2<=0<=3
//Angle [90, 180)2<=3<=1<=0 or 2<=1<=3<=0
//Angle [180, 270) 3<=2<=0<=1 or 3<=0<=2<=1
//Angle [270, 360) 0<=1<=3<=2 or 0<=3<=1<=2
if (mapY[0] > mapY[2]){
sortX[0]=mapX[2];
sortY[0]=mapY[2];
sortX[2]=mapX[0];
sortY[2]=mapY[0];
} else {
sortX[0]=mapX[0];
sortY[0]=mapY[0];
sortX[2]=mapX[2];
sortY[2]=mapY[2];
}
if (mapY[1] > mapY[3]) {
sortX[1]=mapX[3];
sortY[1]=mapY[3];
sortX[3]=mapX[1];
sortY[3]=mapY[1];
} else {
sortX[1]=mapX[1];
sortY[1]=mapY[1];
sortX[3]=mapX[3];
sortY[3]=mapY[3];
}
//After two exchanges, we have 1<=0<=2<=3 or 0<=1<=3<=2
if (sortY[0]>sortY[1]) {
FW_SWAP(sortY[0], sortY[1], tempx);
FW_SWAP(sortX[0], sortX[1], tempx);
FW_SWAP(sortY[2], sortY[3], tempx);
FW_SWAP(sortX[2], sortX[3], tempx);
}
//We have 0<=1<=3<=2 after sorting
int xstart, xend, ystart, yend;
int x, y, flag=0;
float cy, tx, ty;
//float xmap, ymap;
//dstStep and srcStep are byte size
//we need to change it with data array size
dstStep = dstStep / (sizeof(Fw32f));
srcStep = srcStep / (sizeof(Fw32f));
if (FW_ZERO(sortY[0]-sortY[1])) {//sortY[0]==sortY[1], sortY[2]=sortY[3]
// In this case, the rotation angle must be 0, 90, 180, 270
// We should seperate the case for best performance
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
if (sortX[0] < sortX[1]) {
xstart = (int) (FW_MAX(sortX[0], dstRoi.x));
xend = (int) (FW_MIN(sortX[1], (dstRoi.x + dstRoi.width -1)));
} else {
xstart = (int) (FW_MAX(sortX[1], dstRoi.x));
xend = (int) (FW_MIN(sortX[0], (dstRoi.x + dstRoi.width -1)));
}
float* cx = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff00 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
float* cx_coeff01 = (float*)fwMalloc((dstRoi.width) * sizeof(float));
for (x=dstRoi.x; x<(dstRoi.x+dstRoi.width); x++)
{
cx[x - dstRoi.x] = x - coeffs[0][2];
cx_coeff00[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][0];
cx_coeff01[x - dstRoi.x] = cx[x - dstRoi.x] * coeffs[0][1];
}
for (y=ystart;y<=yend;y++) {
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
__m128 txXMM = _mm_set1_ps(tx);
__m128 tyXMM = _mm_set1_ps(ty);
XMM128 cxCoeff00 = {0}, cxCoeff01 = {0};
XMM128 dst = {0};
int y_dstStep = y * dstStep;
if(chSrc == C1)
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
dst.f32[xxx] = *(pSrc+ ymap*srcStep+xmap);
flag = 1;
}
_mm_storeu_ps((pDst+y_dstStep+x), dst.f);
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
*(pDst+y_dstStep+x) = *(pSrc+ ymap*srcStep+xmap);
flag = 1;
}
}//end of C1
else
{
for (x=xstart; x<=xend-4; x+=4) {
cxCoeff00.f = _mm_loadu_ps(cx_coeff00+(x-dstRoi.x));
cxCoeff01.f = _mm_loadu_ps(cx_coeff01+(x-dstRoi.x));
cxCoeff00.f = _mm_add_ps(cxCoeff00.f, txXMM);
cxCoeff01.f = _mm_add_ps(cxCoeff01.f, tyXMM);
cxCoeff00.i = _mm_cvttps_epi32 (cxCoeff00.f);
cxCoeff01.i = _mm_cvttps_epi32 (cxCoeff01.f);
for(int xxx = 0; xxx < 4; xxx++)
{
int &xmap = cxCoeff00.s32[xxx];
int &ymap = cxCoeff01.s32[xxx];
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
dst.f = _mm_loadu_ps(pSrc+ ymap*srcStep+xmap * channel);
_mm_storeu_ps(pDst+y_dstStep+(x+xxx) * channel, dst.f);
}
else //if(chSrc == AC4)
{
*(pDst+y_dstStep+(x+xxx) * channel) = *(pSrc+ ymap*srcStep+xmap * channel);
*(pDst+y_dstStep+(x+xxx) * channel + 1) = *(pSrc+ ymap*srcStep+xmap * channel + 1);
*(pDst+y_dstStep+(x+xxx) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
flag = 1;
}
}
for (; x<=xend; x++) {
int xmap = (int)(cx_coeff00[ x - dstRoi.x] + tx);
int ymap = (int)(cx_coeff01[ x - dstRoi.x] + ty);
if (xmap < 0 || xmap > srcRoi.width - 1 ||
ymap < 0 || ymap > srcRoi.height- 1) {
continue;
}
xmap += srcRoi.x;
ymap += srcRoi.y;
if(chSrc == C4)
{
dst.f = _mm_loadu_ps(pSrc+ ymap*srcStep+xmap * channel);
_mm_storeu_ps(pDst+y_dstStep+x * channel, dst.f);
}
else
{
*(pDst+y_dstStep+(x) * channel) = *(pSrc+ ymap*srcStep+xmap * channel);
*(pDst+y_dstStep+(x) * channel + 1) = *(pSrc+ ymap*srcStep+xmap * channel + 1);
*(pDst+y_dstStep+(x) * channel + 2) = *(pSrc+ ymap*srcStep+xmap * channel + 2);
}
flag = 1;
}
}//end of C4, AC4
}
fwFree (cx);
fwFree (cx_coeff00);
fwFree (cx_coeff01);
} else if (FW_ZERO(sortY[1]-sortY[3])) {//sortY[1]==sortY[3]
if (sortX[1] < sortX[3]) {
FW_SWAP(sortX[1], sortX[3], tempx);
}
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else { //general case
if (sortX[1] < sortX[3]) {
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[0], sortY[0], sortX[1], sortY[1],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[3], sortY[3], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else {//sortX[1] >= sortX[3]
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region_32f_SSE2 (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
}
}
//if no point is handled, return warning
if (flag==0) return fwStsWrongIntersectROI;
return fwStsNoErr;
}
template< class TS, CH chSrc, DispatchType disp >
static FwStatus My_FW_Rotate(const TS* pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
TS* pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
int interpolation_E = interpolation ^ FWI_SMOOTH_EDGE;
if (interpolation != FWI_INTER_NN && interpolation != FWI_INTER_LINEAR
&& interpolation != FWI_INTER_CUBIC) {
if ( interpolation_E != FWI_INTER_NN && interpolation_E != FWI_INTER_LINEAR
&& interpolation_E != FWI_INTER_CUBIC)
return fwStsInterpolationErr;
interpolation = interpolation_E;
interpolation_E = FWI_SMOOTH_EDGE;
}
int channel=ChannelCount(chSrc);
FwStatus status = My_FW_ParaCheck2<TS>(pSrc, srcSize, srcStep, srcRoi, pDst, dstStep,
dstRoi, channel);
if (status !=fwStsNoErr) return status;
float theta;
float coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = (float)(0.0174532925199 * angle);//(3.14159265359/180.0)
//cos and sin value need to be fixed
coeffs[0][0] = (float)((int)(cos(theta)*32768))/32768;
coeffs[0][1] = (float)((int)(sin(theta)*32768))/32768;
coeffs[0][2] = (float)xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = (float)yShift;
//return My_FW_WarpAffine <TS, chSrc, disp> (pSrc, srcSize, srcStep, srcRoi,
// pDst, dstStep, dstRoi, coeffs, interpolation);
int channel1;
// Will not change 4th channel element in AC4
if (chSrc == AC4) channel1=3;
else channel1=channel;
Fw32f round;
// 32f is supported, but not 32u and 32s
// No rounding is needed for 32f type
if (sizeof(TS) == 4) round=0;
else round=0.5;
float sortX[4], sortY[4];
float mapX[4], mapY[4], tempx;
float temp1, temp2;
//srcROI mapped area
//Force to be floating data
mapX[0]=(float)(coeffs[0][0] * srcRoi.x + coeffs[0][1] * srcRoi.y + coeffs[0][2]);
mapY[0]=(float)(coeffs[1][0] * srcRoi.x + coeffs[1][1] * srcRoi.y + coeffs[1][2]);
mapX[1]=(float)(mapX[0]+coeffs[0][0]*(srcRoi.width-1));
mapY[1]=(float)(mapY[0]+coeffs[1][0]*(srcRoi.width-1));
temp1 = (float)(coeffs[0][1] * (srcRoi.height-1));
temp2 = (float)(coeffs[1][1] * (srcRoi.height-1));
mapX[2]=mapX[1] + (float)temp1;
mapY[2]=mapY[1] + (float)temp2;
mapX[3]=mapX[0] + (float)temp1;
mapY[3]=mapY[0] + (float)temp2;
//Sort X,Y coordinator according to Y value
//Before any pexchange, possible orders
//Angle [0, 90) 1<=0<=2<=3 or 1<=2<=0<=3
//Angle [90, 180)2<=3<=1<=0 or 2<=1<=3<=0
//Angle [180, 270) 3<=2<=0<=1 or 3<=0<=2<=1
//Angle [270, 360) 0<=1<=3<=2 or 0<=3<=1<=2
if (mapY[0] > mapY[2]){
sortX[0]=mapX[2];
sortY[0]=mapY[2];
sortX[2]=mapX[0];
sortY[2]=mapY[0];
} else {
sortX[0]=mapX[0];
sortY[0]=mapY[0];
sortX[2]=mapX[2];
sortY[2]=mapY[2];
}
if (mapY[1] > mapY[3]) {
sortX[1]=mapX[3];
sortY[1]=mapY[3];
sortX[3]=mapX[1];
sortY[3]=mapY[1];
} else {
sortX[1]=mapX[1];
sortY[1]=mapY[1];
sortX[3]=mapX[3];
sortY[3]=mapY[3];
}
//After two exchanges, we have 1<=0<=2<=3 or 0<=1<=3<=2
if (sortY[0]>sortY[1]) {
FW_SWAP(sortY[0], sortY[1], tempx);
FW_SWAP(sortX[0], sortX[1], tempx);
FW_SWAP(sortY[2], sortY[3], tempx);
FW_SWAP(sortX[2], sortX[3], tempx);
}
//We have 0<=1<=3<=2 after sorting
int xstart, xend, ystart, yend;
int x, y, flag=0;
float cx, cy, tx, ty;
float xmap, ymap;
//dstStep and srcStep are byte size
//we need to change it with data array size
dstStep = dstStep / (sizeof(TS));
srcStep = srcStep / (sizeof(TS));
if (FW_ZERO(sortY[0]-sortY[1])) {//sortY[0]==sortY[1], sortY[2]=sortY[3]
// In this case, the rotation angle must be 0, 90, 180, 270
// We should seperate the case for best performance
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
if (sortX[0] < sortX[1]) {
xstart = (int) (FW_MAX(sortX[0], dstRoi.x));
xend = (int) (FW_MIN(sortX[1], (dstRoi.x + dstRoi.width -1)));
} else {
xstart = (int) (FW_MAX(sortX[1], dstRoi.x));
xend = (int) (FW_MIN(sortX[0], (dstRoi.x + dstRoi.width -1)));
}
for (y=ystart;y<=yend;y++) {
cy = y - coeffs[1][2];
tx = coeffs[1][0] * cy; //-sin(theta)*cy
ty = coeffs[1][1] * cy; //cos(theta)*cy
for (x=xstart; x<=xend; x++) {
cx = x - coeffs[0][2];
xmap = coeffs[0][0] * cx + tx;
ymap = coeffs[0][1] * cx + ty;
My_FW_PointHandle<TS, disp> (xmap, ymap, x, y, pSrc, srcStep, srcRoi,
pDst, dstStep, interpolation, &flag, channel, channel1, round);
}
}
} else if (FW_ZERO(sortY[1]-sortY[3])) {//sortY[1]==sortY[3]
if (sortX[1] < sortX[3]) {
FW_SWAP(sortX[1], sortX[3], tempx);
}
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else { //general case
if (sortX[1] < sortX[3]) {
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[0], sortY[0], sortX[1], sortY[1],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[0], sortY[0], sortX[3], sortY[3], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[1], sortY[1], sortX[2], sortY[2],
sortX[3], sortY[3], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
} else {//sortX[1] >= sortX[3]
//First part
ystart = (int) (FW_MAX(sortY[0], dstRoi.y));
yend = (int) (FW_MIN(sortY[1], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[0], sortY[0], sortX[1], sortY[1], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Second part
ystart = (int) (FW_MAX(sortY[1], dstRoi.y));
yend = (int) (FW_MIN(sortY[3], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[0], sortY[0], sortX[3], sortY[3],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
//Third part
ystart = (int) (FW_MAX(sortY[3], dstRoi.y));
yend = (int) (FW_MIN(sortY[2], (dstRoi.y + dstRoi.height -1)));
My_FW_Rotate_Region <TS, disp> (sortX[3], sortY[3], sortX[2], sortY[2],
sortX[1], sortY[1], sortX[2], sortY[2], ystart, yend, coeffs,
pSrc, srcStep, srcRoi, pDst, dstStep, dstRoi, interpolation, &flag,
channel, channel1, round);
}
}
//if no point is handled, return warning
if (flag==0) return fwStsWrongIntersectROI;
return fwStsNoErr;
}
//Description
//The function fwiRotateCenter is declared in the fwi.h file. This function rotates the ROI of
//the source image by angle degrees (counterclockwise for positive angle values) around the point
//with coordinates xCenter, yCenter. The origin of the source image is implied to be in the top
//left corner. The result is resampled using the interpolation method specified by the
//interpolation parameter, and written to the destination image ROI.
template< class TS, CH chSrc, DispatchType disp >
FwStatus My_FW_RotateCenter(const TS* pSrc,FwiSize srcSize, int srcStep, FwiRect srcRoi,
TS* pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return My_FW_Rotate<TS, chSrc, disp>(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
} // namespace OPT_LEVEL
using namespace OPT_LEVEL;
// 8u data type with 1 channel
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_8u_C1R)(const Fw8u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_8u_SSE2 <Fw8u, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw8u, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
// 8u data type with 3 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_8u_C3R)(const Fw8u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_8u_SSE2 <Fw8u, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw8u, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
// 8u data type with 4 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_8u_C4R)(const Fw8u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_8u_SSE2 <Fw8u, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw8u, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
//8u data type with 4 channels (alpha channel will not be changed in the destination buffer during transformation)
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_8u_AC4R)(const Fw8u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_8u_SSE2 <Fw8u, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw8u, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_16u_C1R)(const Fw16u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_16u_SSE2 <C1> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw16u, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_16u_C3R)(const Fw16u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_16u_SSE2 <C3> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw16u, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_16u_C4R)(const Fw16u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_16u_SSE2 <C4> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw16u, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_16u_AC4R)(const Fw16u *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_16u_SSE2 <AC4> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw16u, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
//float data with 1 channel
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_32f_C1R)(const Fw32f *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_32f_SSE2 <C1> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw32f, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
//float data with 3 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_32f_C3R)(const Fw32f *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_32f_SSE2 <C3> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw32f, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
//float data with 4 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_32f_C4R)(const Fw32f *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_32f_SSE2 <C4> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw32f, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
//float data with 3+ alpha channels, destination alpha channel data will not be changed.
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_32f_AC4R)(const Fw32f *pSrc, FwiSize srcSize, int srcStep, FwiRect srcRoi,
Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
switch( Dispatch::Type<DT_SSE2>() )
{
case DT_SSE3:
case DT_SSE2:
if (interpolation==FWI_INTER_NN)
return My_FW_Rotate_32f_SSE2 <AC4> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
default:
return My_FW_Rotate <Fw32f, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
}
//8u data with 3 planars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_8u_P3R)(const Fw8u *const pSrc[3], FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *const pDst[3], int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
double theta;
double coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
coeffs[0][0] = cos(theta);
coeffs[0][1] = sin(theta);
coeffs[0][2] = xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = yShift;
FwStatus status;
int i;
for (i=0;i<3;i++) {
status = My_FW_WarpAffine <Fw8u, C1, DT_REFR> (pSrc[i], srcSize, srcStep, srcRoi,
pDst[i], dstStep, dstRoi, coeffs, interpolation);
if (status!=fwStsNoErr) return status;
}
return fwStsNoErr;
}
//8u data with 4 planars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_8u_P4R)(const Fw8u *const pSrc[4], FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *const pDst[4], int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
double theta;
double coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
coeffs[0][0] = cos(theta);
coeffs[0][1] = sin(theta);
coeffs[0][2] = xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = yShift;
FwStatus status;
int i;
for (i=0;i<4;i++) {
status = My_FW_WarpAffine <Fw8u, C1, DT_REFR> (pSrc[i], srcSize, srcStep, srcRoi,
pDst[i], dstStep, dstRoi, coeffs, interpolation);
if (status!=fwStsNoErr) return status;
}
return fwStsNoErr;
}
//unsigned short data with 3 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_16u_P3R)(const Fw16u *const pSrc[3], FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *const pDst[3], int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
double theta;
double coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
coeffs[0][0] = cos(theta);
coeffs[0][1] = sin(theta);
coeffs[0][2] = xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = yShift;
FwStatus status;
int i;
for (i=0;i<3;i++) {
status = My_FW_WarpAffine <Fw16u, C1, DT_REFR> (pSrc[i], srcSize, srcStep, srcRoi,
pDst[i], dstStep, dstRoi, coeffs, interpolation);
if (status!=fwStsNoErr) return status;
}
return fwStsNoErr;
}
//unsigned short data with 4 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_16u_P4R)(const Fw16u *const pSrc[4], FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *const pDst[4], int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
double theta;
double coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
coeffs[0][0] = cos(theta);
coeffs[0][1] = sin(theta);
coeffs[0][2] = xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = yShift;
FwStatus status;
int i;
for (i=0;i<4;i++) {
status = My_FW_WarpAffine <Fw16u, C1, DT_REFR> (pSrc[i], srcSize, srcStep, srcRoi,
pDst[i], dstStep, dstRoi, coeffs, interpolation);
if (status!=fwStsNoErr) return status;
}
return fwStsNoErr;
}
//float data with 3 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_32f_P3R)(const Fw32f *const pSrc[3], FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *const pDst[3], int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
double theta;
double coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
coeffs[0][0] = cos(theta);
coeffs[0][1] = sin(theta);
coeffs[0][2] = xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = yShift;
FwStatus status;
int i;
for (i=0;i<3;i++) {
status = My_FW_WarpAffine <Fw32f, C1, DT_REFR> (pSrc[i], srcSize, srcStep, srcRoi,
pDst[i], dstStep, dstRoi, coeffs, interpolation);
if (status!=fwStsNoErr) return status;
}
return fwStsNoErr;
}
//float data with 4 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotate_32f_P4R)(const Fw32f *const pSrc[4], FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *const pDst[4], int dstStep, FwiRect dstRoi,
double angle, double xShift, double yShift, int interpolation)
{
double theta;
double coeffs[2][3];
// [ cos (theta) sin(theta) ]
// [-sin (theta) cos(theta) ]
// theta is in the counter-clockwise, but y axis is down direction
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
coeffs[0][0] = cos(theta);
coeffs[0][1] = sin(theta);
coeffs[0][2] = xShift;
coeffs[1][0] =-coeffs[0][1];//-sin(theta)
coeffs[1][1] = coeffs[0][0];//cos(theta)
coeffs[1][2] = yShift;
FwStatus status;
int i;
for (i=0;i<4;i++) {
status = My_FW_WarpAffine <Fw32f, C1, DT_REFR> (pSrc[i], srcSize, srcStep, srcRoi,
pDst[i], dstStep, dstRoi, coeffs, interpolation);
if (status!=fwStsNoErr) return status;
}
return fwStsNoErr;
}
//Description
//The function fwiGetRotateShift is declared in the fwi.h file. Use this function if you need
//to rotate an image about an arbitrary center (xCenter, yCenter) rather than the origin (0,0).
//The function helps compute shift values xShift, yShift that should be passed to fwiRotate
//function for the rotation around (xCenter, yCenter) to take place.
FwStatus PREFIX_OPT(OPT_PREFIX, fwiGetRotateShift)(double xCenter, double yCenter,
double angle, double *xShift, double *yShift)
{
if (xShift == 0 || yShift == 0 )
return fwStsNullPtrErr;
double theta, c00, c01, c10, c11;
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
c00 = cos(theta);
c01 = sin(theta);
c10 =-c01;//-sin(theta)
c11 = c00;//cos(theta)
double newCenterx = xCenter * c00 + yCenter * c01;
double newCentery = xCenter * c10 + yCenter * c11;
*xShift= xCenter-newCenterx;
*yShift= yCenter-newCentery;
return fwStsNoErr;
}
//Description
//The function fwiAddRotateShift is declared in the fwi.h file. Use this function if you
//need to rotate an image about an arbitrary center (xCenter, yCenter) rather than the origin
//(0,0) with required shifts. The function helps compute shift values xShift, yShift that should
//be passed to fwiRotate function to perform the rotation around (xCenter, yCenter) and
//desired shifting. The shift values should be initialized. For example, to rotate an image around a
//point (xCenter, yCenter) by the angle with shift values (30.3, 26.2) the following code must be
//written:
//xShift = 30.3
//yShift = 26.2
//fwiAddRotateShift(xCenter,yCenter,angle,&xShift,&yShift);
//fwiRotate(angle,xShift,yShift);
FwStatus PREFIX_OPT(OPT_PREFIX, fwiAddRotateShift)(double xCenter, double yCenter,
double angle, double *xShift, double *yShift)
{
if (xShift == 0 || yShift == 0 )
return fwStsNullPtrErr;
double theta, c00, c01, c10, c11;
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
c00 = cos(theta);
c01 = sin(theta);
c10 = -c01;//-sin(theta)
c11 = c00;//cos(theta)
double newCenterx = xCenter * c00 + yCenter * c01;
double newCentery = xCenter * c10 + yCenter * c11;
*xShift += xCenter-newCenterx;
*yShift += yCenter-newCentery;
return fwStsNoErr;
}
//Description
//The function fwiGetRotateQuad is declared in the fwi.h file. This function is used as a
//support function for fwiRotate. It computes vertex coordinates of the quadrangle, to which the
//source rectangular ROI would be mapped by the fwiRotate function that rotates an image by
//angle degrees and shifts it by xShift, yShift.
//The first dimension [4] of the array quad[4][2] is equal to the number of vertices, and the
//second dimension [2] means x and y coordinates of the vertex. Quadrangle vertices have the
//following meaning:
//quad[0] corresponds to the transformed top-left corner of the source ROI,
//quad[1] corresponds to the transformed top-right corner of the source ROI,
//quad[2] corresponds to the transformed bottom-right corner of the source ROI,
//quad[3] corresponds to the transformed bottom-left corner of the source ROI.
FwStatus PREFIX_OPT(OPT_PREFIX, fwiGetRotateQuad)(FwiRect srcRoi, double quad[4][2],
double angle, double xShift, double yShift)
{
double theta, c[2][3];
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
c[0][0] = cos(theta);
c[0][1] = sin(theta);
c[1][0] = -c[0][1];//-sin(theta)
c[1][1] = c[0][0];//cos(theta)
c[0][2] = xShift;
c[1][2] = yShift;
return fwiGetAffineQuad(srcRoi, quad, c);
}
//Description
//The function fwiGetRotateBound is declared in the fwi.h file. This function is used as a
//support function for fwiRotate. It computes vertex coordinates of the smallest bounding
//rectangle for the quadrangle quad, to which the source ROI would be mapped by the
//fwiRotate function that rotates an image by angle degrees and shifts it by xShift,
//yShift.
//bound[0] specifies x, y coordinates of the top-left corner, bound[1] specifies x, y coordinates
//of the bottom-right corner.
FwStatus PREFIX_OPT(OPT_PREFIX, fwiGetRotateBound)(FwiRect srcRoi, double bound[2][2],
double angle, double xShift, double yShift)
{
double theta, c[2][3];
theta = 0.0174532925199 * angle;//(3.14159265359/180.0)
c[0][0] = cos(theta);
c[0][1] = sin(theta);
c[1][0] =-c[0][1];//-sin(theta)
c[1][1] = c[0][0];//cos(theta)
c[0][2] = xShift;
c[1][2] = yShift;
return fwiGetAffineBound(srcRoi, bound, c);
}
// 8u data type with 1 channel
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_8u_C1R)(const Fw8u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw8u, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
// 8u data type with 3 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_8u_C3R)(const Fw8u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw8u, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
// 8u data type with 4 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_8u_C4R)(const Fw8u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw8u, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
//8u data type with 4 channels (alpha channel will not be changed in the destination buffer during transformation)
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_8u_AC4R)(const Fw8u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw8u, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_16u_C1R)(const Fw16u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw16u, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_16u_C3R)(const Fw16u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw16u, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_16u_C4R)(const Fw16u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw16u, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_16u_AC4R)(const Fw16u *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw16u, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
//float data with 1 channel
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_32f_C1R)(const Fw32f *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw32f, C1, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
//float data with 3 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_32f_C3R)(const Fw32f *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw32f, C3, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
//float data with 4 channels
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_32f_C4R)(const Fw32f *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw32f, C4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
//float data with 3+ alpha channels, destination alpha channel data will not be changed.
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_32f_AC4R)(const Fw32f *pSrc,FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *pDst, int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
return My_FW_RotateCenter <Fw32f, AC4, DT_REFR> (pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xCenter, yCenter, interpolation);
}
//8u data with 3 planars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_8u_P3R)(const Fw8u *const pSrc[3],FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *const pDst[3], int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return fwiRotate_8u_P3R(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
//8u data with 4 planars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_8u_P4R)(const Fw8u *const pSrc[4],FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw8u *const pDst[4], int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return fwiRotate_8u_P4R(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
//unsigned short data with 3 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_16u_P3R)(const Fw16u *const pSrc[3],FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *const pDst[3], int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return fwiRotate_16u_P3R(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
//unsigned short data with 4 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_16u_P4R)(const Fw16u *const pSrc[4],FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw16u *const pDst[4], int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return fwiRotate_16u_P4R(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
//float data with 3 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_32f_P3R)(const Fw32f *const pSrc[3],FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *const pDst[3], int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return fwiRotate_32f_P3R(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
//float data with 4 plannars
FwStatus PREFIX_OPT(OPT_PREFIX, fwiRotateCenter_32f_P4R)(const Fw32f *const pSrc[4],FwiSize srcSize, int srcStep,
FwiRect srcRoi, Fw32f *const pDst[4], int dstStep, FwiRect dstRoi,
double angle, double xCenter, double yCenter, int interpolation)
{
double xShift, yShift;
fwiGetRotateShift(xCenter, yCenter, angle, &xShift, &yShift);
return fwiRotate_32f_P4R(pSrc, srcSize, srcStep, srcRoi,
pDst, dstStep, dstRoi, angle, xShift, yShift, interpolation);
}
// Please do NOT remove the above line for CPP files that need to be multipass compiled
// OREFR OSSE2
| 38.396747 | 136 | 0.553541 | dbremner |
165ad9fe7c8ceb9a0406830421b10ae345b2078d | 694 | cpp | C++ | examples/file_upload_cpp/fs_remove.cpp | SammyEnigma/QuickStreams | 999b517cf6c9321dee61ea80d9b51adf1e32aeec | [
"MIT"
] | 48 | 2017-05-20T22:17:58.000Z | 2021-05-06T13:27:04.000Z | examples/file_upload_cpp/fs_remove.cpp | SammyEnigma/QuickStreams | 999b517cf6c9321dee61ea80d9b51adf1e32aeec | [
"MIT"
] | 1 | 2018-04-23T11:10:57.000Z | 2018-04-23T16:04:14.000Z | examples/file_upload_cpp/fs_remove.cpp | SammyEnigma/QuickStreams | 999b517cf6c9321dee61ea80d9b51adf1e32aeec | [
"MIT"
] | 11 | 2017-05-20T22:18:01.000Z | 2019-08-28T23:30:53.000Z | #include "Filesystem.hpp"
#include <QuickStreams>
#include <QVariant>
#include <QString>
#include <QTimer>
#include <QDebug>
using namespace quickstreams;
Stream::Reference Filesystem::remove(const QString& fileId) {
qDebug() << "FS::remove > removing file: " << fileId;
// Create and return an atomic stream representing the removal operation
return _streamProvider->create([this, fileId](
const StreamHandle& stream,
const QVariant& data
) {
Q_UNUSED(data)
// Close the returned stream after a random amount of time
QTimer::singleShot(randomLatency(), [stream, fileId]() {
qDebug() << "FS::remove > file " << fileId << " has been removed";
stream.close();
});
});
}
| 26.692308 | 73 | 0.700288 | SammyEnigma |
165c9c36fecf26eb96f48dd52b60ba8a4be84c9e | 3,098 | cpp | C++ | src/parser.cpp | samcoppini/xrfc | 34055b3f8673dac17f9b59de90d2eb17163f25f1 | [
"BSL-1.0"
] | null | null | null | src/parser.cpp | samcoppini/xrfc | 34055b3f8673dac17f9b59de90d2eb17163f25f1 | [
"BSL-1.0"
] | null | null | null | src/parser.cpp | samcoppini/xrfc | 34055b3f8673dac17f9b59de90d2eb17163f25f1 | [
"BSL-1.0"
] | null | null | null | #include "parser.hpp"
using namespace std::string_literals;
namespace xrf {
namespace {
/**
* @brief Attempts to parse a XRF chunk, which will result in either a new,
* valid, chunk being added to the passed-in list of chunks, or new error
* messages being added to the list of errors
*
* @param file
* The file reader to read the next characters of the chunk from
* @param chunkChar
* The first character in the chunk that was read already
* @param chunks
* The existing list of chunks, which may be added to
* @param errors
* The existing list of parser errors, which may be added to
*/
void parseChunk(FileReader &file, char chunkChar, std::vector<Chunk> &chunks, ParserErrorList &errors) {
Chunk chunk;
chunk.line = file.curLine();
chunk.col = file.curColumn();
for (std::optional<char> c = chunkChar; c && !std::isspace(*c); c = file.read()) {
switch (*c) {
case '0': chunk.commands.push_back(CommandType::Input); break;
case '1': chunk.commands.push_back(CommandType::Output); break;
case '2': chunk.commands.push_back(CommandType::Pop); break;
case '3': chunk.commands.push_back(CommandType::Dup); break;
case '4': chunk.commands.push_back(CommandType::Swap); break;
case '5': chunk.commands.push_back(CommandType::Inc); break;
case '6': chunk.commands.push_back(CommandType::Dec); break;
case '7': chunk.commands.push_back(CommandType::Add); break;
case '8': chunk.commands.push_back(CommandType::IgnoreFirst); break;
case '9': chunk.commands.push_back(CommandType::Bottom); break;
case 'A': chunk.commands.push_back(CommandType::Jump); break;
case 'B': chunk.commands.push_back(CommandType::Exit); break;
case 'C': chunk.commands.push_back(CommandType::IgnoreVisited); break;
case 'D': chunk.commands.push_back(CommandType::Randomize); break;
case 'E': chunk.commands.push_back(CommandType::Sub); break;
case 'F': chunk.commands.push_back(CommandType::Nop); break;
default:
errors.emplace_back("Found invalid command character: "s + *c, file.curLine(), file.curColumn());
break;
}
}
if (chunk.commands.size() < COMMANDS_PER_CHUNK) {
errors.emplace_back("Chunk doesn't have enough commands.", chunk.line, chunk.col);
}
else if (chunk.commands.size() > COMMANDS_PER_CHUNK) {
errors.emplace_back("Chunk has too many commands.", chunk.line, chunk.col);
}
else {
chunks.push_back(std::move(chunk));
}
}
} // anonymous namespace
std::variant<ParserErrorList, std::vector<Chunk>> parseXrf(FileReader &file) {
std::vector<Chunk> chunks;
ParserErrorList errors;
for (auto c = file.read(); c; c = file.read()) {
if (!std::isspace(*c)) {
parseChunk(file, *c, chunks, errors);
}
}
if (errors.empty()) {
return chunks;
}
else {
return errors;
}
}
} // namespace xrf
| 36.880952 | 113 | 0.631052 | samcoppini |
165e1d9c106c370b141dcf62bc6db45a84154fc2 | 14,930 | cpp | C++ | src/libtsduck/plugin/tsInputSwitcherArgs.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | src/libtsduck/plugin/tsInputSwitcherArgs.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | src/libtsduck/plugin/tsInputSwitcherArgs.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "tsInputSwitcherArgs.h"
#include "tsArgsWithPlugins.h"
TSDUCK_SOURCE;
#if defined(TS_NEED_STATIC_CONST_DEFINITIONS)
constexpr size_t ts::InputSwitcherArgs::DEFAULT_MAX_INPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::MIN_INPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::DEFAULT_MAX_OUTPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::MIN_OUTPUT_PACKETS;
constexpr size_t ts::InputSwitcherArgs::DEFAULT_BUFFERED_PACKETS;
constexpr size_t ts::InputSwitcherArgs::MIN_BUFFERED_PACKETS;
constexpr ts::MilliSecond ts::InputSwitcherArgs::DEFAULT_RECEIVE_TIMEOUT;
#endif
//----------------------------------------------------------------------------
// Constructors.
//----------------------------------------------------------------------------
ts::InputSwitcherArgs::InputSwitcherArgs() :
appName(),
fastSwitch(false),
delayedSwitch(false),
terminate(false),
reusePort(false),
firstInput(0),
primaryInput(NPOS),
cycleCount(1),
bufferedPackets(0),
maxInputPackets(0),
maxOutputPackets(0),
eventCommand(),
eventUDP(),
eventLocalAddress(),
eventTTL(0),
sockBuffer(0),
remoteServer(),
allowedRemote(),
receiveTimeout(0),
inputs(),
output()
{
}
//----------------------------------------------------------------------------
// Enforce default or minimum values.
//----------------------------------------------------------------------------
void ts::InputSwitcherArgs::enforceDefaults()
{
if (inputs.empty()) {
// If no input plugin is used, used only standard input.
inputs.push_back(PluginOptions(u"file"));
}
if (output.name.empty()) {
output.set(u"file");
}
if (receiveTimeout <= 0 && primaryInput != NPOS) {
receiveTimeout = DEFAULT_RECEIVE_TIMEOUT;
}
firstInput = std::min(firstInput, inputs.size() - 1);
bufferedPackets = std::max(bufferedPackets, MIN_BUFFERED_PACKETS);
maxInputPackets = std::max(maxInputPackets, MIN_INPUT_PACKETS);
maxOutputPackets = std::max(maxOutputPackets, MIN_OUTPUT_PACKETS);
}
//----------------------------------------------------------------------------
// Define command line options in an Args.
//----------------------------------------------------------------------------
void ts::InputSwitcherArgs::defineArgs(Args& args) const
{
args.option(u"allow", 'a', Args::STRING);
args.help(u"allow",
u"Specify an IP address or host name which is allowed to send remote commands. "
u"Several --allow options are allowed. By default, all remote commands are accepted.");
args.option(u"buffer-packets", 'b', Args::POSITIVE);
args.help(u"buffer-packets",
u"Specify the size in TS packets of each input plugin buffer. "
u"The default is " + UString::Decimal(DEFAULT_BUFFERED_PACKETS) + u" packets.");
args.option(u"cycle", 'c', Args::POSITIVE);
args.help(u"cycle",
u"Specify how many times to repeat the cycle through all input plugins in sequence. "
u"By default, all input plugins are executed in sequence only once (--cycle 1). "
u"The options --cycle, --infinite and --terminate are mutually exclusive.");
args.option(u"delayed-switch", 'd');
args.help(u"delayed-switch",
u"Perform delayed input switching. When switching from one input plugin to another one, "
u"the second plugin is started first. Packets from the first plugin continue to be "
u"output while the second plugin is starting. Then, after the second plugin starts to "
u"receive packets, the switch occurs: packets are now fetched from the second plugin. "
u"Finally, after the switch, the first plugin is stopped.");
args.option(u"event-command", 0, Args::STRING);
args.help(u"event-command", u"'command'",
u"When a switch event occurs, run this external shell command. "
u"This can be used to notify some external system of the event. "
u"The command receives additional parameters:\n\n"
u"1. Event name, currently only \"newinput\" is defined.\n"
u"2. The input index before the event.\n"
u"3. The input index after the event.");
args.option(u"event-udp", 0, Args::STRING);
args.help(u"event-udp", u"address:port",
u"When a switch event occurs, send a short JSON description over UDP/IP to the specified destination. "
u"This can be used to notify some external system of the event. "
u"The 'address' specifies an IP address which can be either unicast or multicast. "
u"It can be also a host name that translates to an IP address. "
u"The 'port' specifies the destination UDP port.");
args.option(u"event-local-address", 0, Args::STRING);
args.help(u"event-local-address", u"address",
u"With --event-udp, when the destination is a multicast address, specify "
u"the IP address of the outgoing local interface. It can be also a host "
u"name that translates to a local address.");
args.option(u"event-ttl", 0, Args::POSITIVE);
args.help(u"event-ttl",
u"With --event-udp, specifies the TTL (Time-To-Live) socket option. "
u"The actual option is either \"Unicast TTL\" or \"Multicast TTL\", "
u"depending on the destination address. Remember that the default "
u"Multicast TTL is 1 on most systems.");
args.option(u"fast-switch", 'f');
args.help(u"fast-switch",
u"Perform fast input switching. All input plugins are started at once and they "
u"continuously receive packets in parallel. Packets are dropped, except for the "
u"current input plugin. This option is typically used when all inputs are live "
u"streams on distinct devices (not the same DVB tuner for instance).\n\n"
u"By default, only one input plugin is started at a time. When switching, "
u"the current input is first stopped and then the next one is started.");
args.option(u"first-input", 0, Args::UNSIGNED);
args.help(u"first-input",
u"Specify the index of the first input plugin to start. "
u"By default, the first plugin (index 0) is used.");
args.option(u"infinite", 'i');
args.help(u"infinite", u"Infinitely repeat the cycle through all input plugins in sequence.");
args.option(u"max-input-packets", 0, Args::POSITIVE);
args.help(u"max-input-packets",
u"Specify the maximum number of TS packets to read at a time. "
u"This value may impact the switch response time. "
u"The default is " + UString::Decimal(DEFAULT_MAX_INPUT_PACKETS) + u" packets. "
u"The actual value is never more than half the --buffer-packets value.");
args.option(u"max-output-packets", 0, Args::POSITIVE);
args.help(u"max-output-packets",
u"Specify the maximum number of TS packets to write at a time. "
u"The default is " + UString::Decimal(DEFAULT_MAX_OUTPUT_PACKETS) + u" packets.");
args.option(u"primary-input", 'p', Args::UNSIGNED);
args.help(u"primary-input",
u"Specify the index of the input plugin which is considered as primary "
u"or preferred. This input plugin is always started, never stopped, even "
u"without --fast-switch. When no packet is received on this plugin, the "
u"normal switching rules apply. However, as soon as packets are back on "
u"the primary input, the reception is immediately switched back to it. "
u"By default, there is no primary input, all input plugins are equal.");
args.option(u"no-reuse-port");
args.help(u"no-reuse-port",
u"Disable the reuse port socket option for the remote control. "
u"Do not use unless completely necessary.");
args.option(u"receive-timeout", 0, Args::UNSIGNED);
args.help(u"receive-timeout",
u"Specify a receive timeout in milliseconds. "
u"When the current input plugin has received no packet within "
u"this timeout, automatically switch to the next plugin. "
u"By default, without --primary-input, there is no automatic switch "
u"when the current input plugin is waiting for packets. With "
u"--primary-input, the default is " + UString::Decimal(DEFAULT_RECEIVE_TIMEOUT) + u" ms.");
args.option(u"remote", 'r', Args::STRING);
args.help(u"remote", u"[address:]port",
u"Specify the local UDP port which is used to receive remote commands. "
u"If an optional address is specified, it must be a local IP address of the system. "
u"By default, there is no remote control.");
args.option(u"terminate", 't');
args.help(u"terminate", u"Terminate execution when the current input plugin terminates.");
args.option(u"udp-buffer-size", 0, Args::UNSIGNED);
args.help(u"udp-buffer-size",
u"Specifies the UDP socket receive buffer size (socket option).");
}
//----------------------------------------------------------------------------
// Load arguments from command line.
//----------------------------------------------------------------------------
bool ts::InputSwitcherArgs::loadArgs(DuckContext& duck, Args& args)
{
appName = args.appName();
fastSwitch = args.present(u"fast-switch");
delayedSwitch = args.present(u"delayed-switch");
terminate = args.present(u"terminate");
args.getIntValue(cycleCount, u"cycle", args.present(u"infinite") ? 0 : 1);
args.getIntValue(bufferedPackets, u"buffer-packets", DEFAULT_BUFFERED_PACKETS);
maxInputPackets = std::min(args.intValue<size_t>(u"max-input-packets", DEFAULT_MAX_INPUT_PACKETS), bufferedPackets / 2);
args.getIntValue(maxOutputPackets, u"max-output-packets", DEFAULT_MAX_OUTPUT_PACKETS);
const UString remoteName(args.value(u"remote"));
reusePort = !args.present(u"no-reuse-port");
args.getIntValue(sockBuffer, u"udp-buffer-size");
args.getIntValue(firstInput, u"first-input", 0);
args.getIntValue(primaryInput, u"primary-input", NPOS);
args.getIntValue(receiveTimeout, u"receive-timeout", primaryInput >= inputs.size() ? 0 : DEFAULT_RECEIVE_TIMEOUT);
// Event reporting.
args.getValue(eventCommand, u"event-command");
setEventUDP(args.value(u"event-udp"), args.value(u"event-local-address"), args);
args.getIntValue(eventTTL, u"event-ttl", 0);
// Check conflicting modes.
if (args.present(u"cycle") + args.present(u"infinite") + args.present(u"terminate") > 1) {
args.error(u"options --cycle, --infinite and --terminate are mutually exclusive");
}
if (fastSwitch && delayedSwitch) {
args.error(u"options --delayed-switch and --fast-switch are mutually exclusive");
}
// Resolve network names. The resolve() method reports error and set the args error state.
if (!remoteName.empty() && remoteServer.resolve(remoteName, args) && !remoteServer.hasPort()) {
args.error(u"missing UDP port number in --remote");
}
// Resolve all allowed remote.
UStringVector remotes;
args.getValues(remotes, u"allow");
allowedRemote.clear();
for (auto it = remotes.begin(); it != remotes.end(); ++it) {
const IPv4Address addr(*it, args);
if (addr.hasAddress()) {
allowedRemote.insert(addr);
}
}
// Load all plugin descriptions. Default output is the standard output file.
ArgsWithPlugins* pargs = dynamic_cast<ArgsWithPlugins*>(&args);
if (pargs != nullptr) {
pargs->getPlugins(inputs, PluginType::INPUT);
pargs->getPlugin(output, PluginType::OUTPUT, u"file");
}
else {
inputs.clear();
output.set(u"file");
}
if (inputs.empty()) {
// If no input plugin is used, used only standard input.
inputs.push_back(PluginOptions(u"file"));
}
// Check validity of input indexes.
if (firstInput >= inputs.size()) {
args.error(u"invalid input index for --first-input %d", {firstInput});
}
if (primaryInput != NPOS && primaryInput >= inputs.size()) {
args.error(u"invalid input index for --primary-input %d", {primaryInput});
}
return args.valid();
}
//----------------------------------------------------------------------------
// Set the UDP destination for event reporting using strings.
//----------------------------------------------------------------------------
bool ts::InputSwitcherArgs::setEventUDP(const UString& destination, const UString& local, Report& report)
{
if (destination.empty()) {
eventUDP.clear();
}
else if (!eventUDP.resolve(destination, report)) {
return false;
}
else if (!eventUDP.hasAddress() || !eventUDP.hasPort()) {
report.error(u"event reporting through UDP requires an IP address and a UDP port");
return false;
}
if (local.empty()) {
eventLocalAddress.clear();
}
else if (!eventLocalAddress.resolve(local, report)) {
return false;
}
return true;
}
| 45.242424 | 124 | 0.624313 | cedinu |
1660317546a7a152a90f506404d000dc585c4677 | 5,030 | cpp | C++ | Graphics/Mesh.cpp | KrasnovPavel/DSD_GameEngine | 0e22d6adcf26a9d47a7a950d448c959648b5a56d | [
"MIT"
] | null | null | null | Graphics/Mesh.cpp | KrasnovPavel/DSD_GameEngine | 0e22d6adcf26a9d47a7a950d448c959648b5a56d | [
"MIT"
] | null | null | null | Graphics/Mesh.cpp | KrasnovPavel/DSD_GameEngine | 0e22d6adcf26a9d47a7a950d448c959648b5a56d | [
"MIT"
] | null | null | null | //
// Created by Pavel Krasnov (krasnovpavel0@gmail.com) on 11.12.17.
//
#include <GL/gl.h>
#include <GL/glut.h>
#include "Mesh.h"
#include "MeshParser.h"
using namespace DSD;
INIT_REFLECTION(Mesh)
Mesh::Mesh(const std::string& meshFileName, const Vector3 &position, const Quaternion &rotation, const Vector3 &scale)
{
this->position = position;
this->rotation = rotation;
this->scale = scale;
setMesh(meshFileName);
}
Mesh::Mesh(Mesh &&rhl) noexcept : DSDBaseObject(rhl)
{
position = rhl.position;
rotation = rhl.rotation;
scale = rhl.scale;
copyVertices(rhl.m_vertices, rhl.m_normals, rhl.m_amountOfVertices, rhl.m_gridVertices);
memcpy(m_color, rhl.m_color, 4*sizeof(float));
}
Mesh::Mesh(const Mesh &rhl) : DSDBaseObject(rhl)
{
position = rhl.position;
rotation = rhl.rotation;
scale = rhl.scale;
copyVertices(rhl.m_vertices, rhl.m_normals, rhl.m_amountOfVertices, rhl.m_gridVertices);
memcpy(m_color, rhl.m_color, 4*sizeof(float));
}
void Mesh::setMesh(const std::string &meshFileName)
{
m_meshFileName = meshFileName;
auto tmp = MeshParser::parse(meshFileName);
copyVertices(tmp.first.data(), tmp.second.data(), tmp.first.size()/3);
setColor(1.f, 1.f, 1.f, 1.f);
}
Mesh &Mesh::operator=(const Mesh &rhs)
{
position = rhs.position;
rotation = rhs.rotation;
scale = rhs.scale;
copyVertices(rhs.m_vertices, rhs.m_normals, rhs.m_amountOfVertices, rhs.m_gridVertices);
memcpy(m_color, rhs.m_color, 4 * sizeof(float));
static_cast<DSDBaseObject *>(this)->operator=(rhs);
return *this;
}
void Mesh::copyVertices(double *vertices,
double *normals,
const std::size_t& amountOfVertices,
double* gridVertices)
{
delete[] m_vertices;
delete[] m_normals;
m_amountOfVertices = amountOfVertices;
m_amountOfData = m_amountOfVertices * 3;
m_amountOfGridData = m_amountOfVertices * 6;
m_vertices = new double[m_amountOfData];
m_normals = new double[m_amountOfData];
memcpy(m_vertices, vertices, m_amountOfData * sizeof(double));
memcpy(m_normals, normals, m_amountOfData * sizeof(double));
delete[] m_gridVertices;
m_gridVertices = new double[m_amountOfGridData];
if (gridVertices) memcpy(m_gridVertices, gridVertices, m_amountOfGridData*sizeof(double));
else generateGrid();
}
void Mesh::draw() const
{
if (solid) drawSolid();
else drawGrid();
}
void Mesh::setColor(float r, float g, float b, float a)
{
m_color[0] = r;
m_color[1] = g;
m_color[2] = b;
m_color[3] = a;
}
Mesh::~Mesh()
{
delete[] m_vertices;
delete[] m_normals;
delete[] m_gridVertices;
}
void Mesh::generateGrid()
{
for (int i = 0; i < m_amountOfVertices/3; ++i)
{
memcpy(m_gridVertices+i*6*3, m_vertices+i*3*3, 3*sizeof(double));
memcpy(m_gridVertices+i*6*3+3*1, m_vertices+i*3*3+3*1, 3*sizeof(double));
memcpy(m_gridVertices+i*6*3+3*2, m_vertices+i*3*3+3*1, 3*sizeof(double));
memcpy(m_gridVertices+i*6*3+3*3, m_vertices+i*3*3+3*2, 3*sizeof(double));
memcpy(m_gridVertices+i*6*3+3*4, m_vertices+i*3*3+3*2, 3*sizeof(double));
memcpy(m_gridVertices+i*6*3+3*5, m_vertices+i*3*3, 3*sizeof(double));
}
}
void Mesh::drawSolid() const
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
auto tmp = rotation.toAxisAngle();
glTranslated(position.x, position.y, position.z);
glRotated(tmp.second * 180. * M_1_PI, tmp.first.x, tmp.first.y, tmp.first.z);
glScaled(scale.x, scale.y, scale.z);
glPushMatrix();
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3, GL_DOUBLE, 0, m_vertices);
glNormalPointer(GL_DOUBLE, 0, m_normals);
glMaterialfv(GL_FRONT, GL_SPECULAR, m_color);
glDrawArrays(GL_TRIANGLES, 0, m_amountOfVertices);
glPopMatrix();
}
void Mesh::drawGrid() const
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
auto tmp = rotation.toAxisAngle();
glTranslated(position.x, position.y, position.z);
glRotated(tmp.second * 180. * M_1_PI, tmp.first.x, tmp.first.y, tmp.first.z);
glPushMatrix();
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3, GL_DOUBLE, 0, m_gridVertices);
glMaterialfv(GL_FRONT, GL_EMISSION, m_color);
float noMaterial[] = {0,0,0,1};
glLightfv(GL_LIGHT0, GL_AMBIENT, noMaterial);
glLightfv(GL_LIGHT0, GL_DIFFUSE, noMaterial);
glLightfv(GL_LIGHT0, GL_SPECULAR, noMaterial);
glDrawArrays(GL_LINES, 0, m_amountOfVertices*2);
glMaterialfv(GL_FRONT, GL_EMISSION, noMaterial);
GLfloat lightAmbient[] = {0.0, 0.0, 0.0, 1.0};
GLfloat lightDiffuse[] = {0.7, 0.7, 0.7, 1.0};
GLfloat lightSpecular[] = {1.0, 1.0, 1.0, 1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, lightSpecular);
glPopMatrix();
}
| 30.301205 | 118 | 0.67833 | KrasnovPavel |
166846b6ee5a616929638ff6570411fe764d5a03 | 7,166 | hpp | C++ | ivarp/include/ivarp/math_fn/n_ary_ops.hpp | phillip-keldenich/squares-in-disk | 501ebeb00b909b9264a9611fd63e082026cdd262 | [
"MIT"
] | null | null | null | ivarp/include/ivarp/math_fn/n_ary_ops.hpp | phillip-keldenich/squares-in-disk | 501ebeb00b909b9264a9611fd63e082026cdd262 | [
"MIT"
] | null | null | null | ivarp/include/ivarp/math_fn/n_ary_ops.hpp | phillip-keldenich/squares-in-disk | 501ebeb00b909b9264a9611fd63e082026cdd262 | [
"MIT"
] | null | null | null | // The code is open source under the MIT license.
// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group
// https://ibr.cs.tu-bs.de/alg
//
// 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.
//
// Created by Phillip Keldenich on 06.11.19.
//
#pragma once
namespace ivarp {
struct MathNAryMinTag {
struct EvalBounds {
template<typename B1, typename... Bs> struct Eval {
static constexpr std::int64_t lb = fixed_point_bounds::minimum(B1::lb, Bs::lb...);
static constexpr std::int64_t ub = fixed_point_bounds::minimum(B1::ub, Bs::ub...);
};
};
static const char* name() noexcept {
return "min";
}
template<typename Context> IVARP_HD static EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1) noexcept {
return a1;
}
template<typename Context, typename A1> IVARP_H static DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1) {
return ivarp::forward<A1>(a1);
}
template<typename Context> static IVARP_HD
EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1, typename Context::NumberType a2) noexcept
{
return minimum(a1, a2);
}
template<typename Context, typename A1, typename A2> static IVARP_H DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1, A2&& a2)
{
return minimum(ivarp::forward<A1>(a1), ivarp::forward<A2>(a2));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_HD EnableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args) noexcept
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_H DisableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args)
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
};
struct MathNAryMaxTag {
struct EvalBounds {
template<typename B1, typename... Bs> struct Eval {
static constexpr std::int64_t lb = fixed_point_bounds::maximum(B1::lb, Bs::lb...);
static constexpr std::int64_t ub = fixed_point_bounds::maximum(B1::ub, Bs::ub...);
};
};
static const char* name() noexcept {
return "max";
}
template<typename Context> IVARP_HD static EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1) noexcept {
return a1;
}
template<typename Context, typename A1> IVARP_H static DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1) {
return ivarp::forward<A1>(a1);
}
template<typename Context> static IVARP_HD
EnableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(typename Context::NumberType a1, typename Context::NumberType a2) noexcept
{
return maximum(a1, a2);
}
template<typename Context, typename A1, typename A2> static IVARP_H DisableForCUDANT<typename Context::NumberType, typename Context::NumberType> eval(A1&& a1, A2&& a2)
{
return maximum(ivarp::forward<A1>(a1), ivarp::forward<A2>(a2));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_HD EnableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args) noexcept
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
template<typename Context, typename A1, typename A2, typename A3, typename... Args>
static IVARP_H DisableForCUDANT<typename Context::NumberType,typename Context::NumberType> eval(A1&& a1, A2&& a2, A3&& a3, Args&&... args)
{
return eval<Context>(ivarp::forward<A1>(a1), eval<Context>(ivarp::forward<A2>(a2), ivarp::forward<A3>(a3), ivarp::forward<Args>(args)...));
}
};
/// The MathExpression type of an n-ary operator, if at least one argument is a math expression and all
/// arguments are math expressions, numbers or integers.
template<typename Tag, bool Ok, typename... Args> struct NAryOpResult;
template<typename Tag, typename... Args> struct NAryOpResult<Tag, true, Args...> {
using Type = MathNAry<Tag, EnsureExpr<Args>...>;
};
/// Shorthand for NAryOpResult; also applies decay and checks arguments.
template<typename Tag, typename... Args> using NAryOpResultType =
typename NAryOpResult<Tag,
OneOf<IsMathExpr<Args>::value...>::value &&
AllOf<IsExprOrConstant<Args>::value...>::value,
BareType<Args>...>::Type;
/// MathExpression for minimum of k >= 1 arguments.
template<typename A1, typename... Args> static inline NAryOpResultType<MathNAryMinTag, A1, Args...>
minimum(A1&& a1, Args&&... args)
{
return {ivarp::forward<A1>(a1), ivarp::forward<Args>(args)...};
}
/// MathExpression for maximum of k >= 1 arguments.
template<typename A1, typename... Args> static inline NAryOpResultType<MathNAryMaxTag, A1, Args...>
maximum(A1&& a1, Args&&... args)
{
return {ivarp::forward<A1>(a1), ivarp::forward<Args>(args)...};
}
}
| 50.111888 | 175 | 0.653224 | phillip-keldenich |
166abc748343e25fc7c514e4c84f20b5fda8a8d6 | 226 | cpp | C++ | lib/OpNet/TypeChain.cpp | LLNL/typeforge | e91c0447140040a9ae02f3a58af3621a00a5e242 | [
"BSD-3-Clause"
] | 2 | 2021-05-17T19:22:37.000Z | 2021-09-01T15:10:38.000Z | lib/OpNet/TypeChain.cpp | LLNL/typeforge | e91c0447140040a9ae02f3a58af3621a00a5e242 | [
"BSD-3-Clause"
] | null | null | null | lib/OpNet/TypeChain.cpp | LLNL/typeforge | e91c0447140040a9ae02f3a58af3621a00a5e242 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright 2020 Lawrence Livermore National Security, LLC and other Typeforge developers.
* See the top-level NOTICE file for details.
*
* SPDX-License-Identifier: BSD-3
*/
#include "Typeforge/OpNet/TypeChain.hpp"
| 22.6 | 91 | 0.743363 | LLNL |
166b26b731e353a281563a5e98335000d00974e1 | 34,851 | cpp | C++ | src/devices/cpu/pic16c62x/pic16c62x.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/cpu/pic16c62x/pic16c62x.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/cpu/pic16c62x/pic16c62x.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Tony La Porta
/**************************************************************************\
* Microchip PIC16C62X Emulator *
* *
* Based On *
* Microchip PIC16C5X Emulator *
* Copyright Tony La Porta *
* Originally written for the MAME project. *
* *
* *
* Addressing architecture is based on the Harvard addressing scheme. *
* *
* *
* **** Change Log **** *
* SZ (22-Oct-2009) *
* - Improvements and tests *
* SZ (2-Oct-2009) *
* - Internal ram and registers *
* SZ (12-Sep-2009) *
* - Started working on it. *
* *
* *
* **** TODO **** *
* - Finish checking opcodes/instructions *
* - Internal devices *
* - Interrupts *
* - Everything ! *
* *
* **** DONE **** *
* - I/O ports *
* - Savestates *
* - Internal memory *
* - New opcodes *
* - Opcode disassembly *
* *
* **** Notes (from PIC16C5X): **** *
* PIC WatchDog Timer has a separate internal clock. For the moment, we're *
* basing the count on a 4MHz input clock, since 4MHz is the typical *
* input frequency (but by no means always). *
* A single scaler is available for the Counter/Timer or WatchDog Timer. *
* When connected to the Counter/Timer, it functions as a Prescaler, *
* hence prescale overflows, tick the Counter/Timer. *
* When connected to the WatchDog Timer, it functions as a Postscaler *
* hence WatchDog Timer overflows, tick the Postscaler. This scenario *
* means that the WatchDog timeout occurs when the Postscaler has *
* reached the scaler rate value, not when the WatchDog reaches zero. *
* CLRWDT should prevent the WatchDog Timer from timing out and generating *
* a device reset, but how is not known. The manual also mentions that *
* the WatchDog Timer can only be disabled during ROM programming, and *
* no other means seem to exist??? *
* *
\**************************************************************************/
#include "emu.h"
#include "pic16c62x.h"
#include "16c62xdsm.h"
#include "debugger.h"
DEFINE_DEVICE_TYPE(PIC16C620, pic16c620_device, "pic16c620", "Microchip PIC16C620")
DEFINE_DEVICE_TYPE(PIC16C620A, pic16c620a_device, "pic16c620a", "Microchip PIC16C620A")
DEFINE_DEVICE_TYPE(PIC16C621, pic16c621_device, "pic16c621", "Microchip PIC16C621")
DEFINE_DEVICE_TYPE(PIC16C621A, pic16c621a_device, "pic16c621a", "Microchip PIC16C621A")
DEFINE_DEVICE_TYPE(PIC16C622, pic16c622_device, "pic16c622", "Microchip PIC16C622")
DEFINE_DEVICE_TYPE(PIC16C622A, pic16c622a_device, "pic16c622a", "Microchip PIC16C622A")
/****************************************************************************
* Internal Memory Map
****************************************************************************/
void pic16c62x_device::pic16c62x_rom_9(address_map &map)
{
map(0x000, 0x1ff).rom();
}
void pic16c62x_device::pic16c62x_rom_10(address_map &map)
{
map(0x000, 0x3ff).rom();
}
void pic16c62x_device::pic16c62x_rom_11(address_map &map)
{
map(0x000, 0x7ff).rom();
}
void pic16c62x_device::pic16c620_ram(address_map &map)
{
map(0x00, 0x06).ram();
map(0x0a, 0x0c).ram();
map(0x1f, 0x6f).ram();
map(0x80, 0x86).ram();
map(0x8a, 0x8e).ram();
map(0x9f, 0x9f).ram();
}
void pic16c62x_device::pic16c622_ram(address_map &map)
{
map(0x00, 0x06).ram();
map(0x0a, 0x0c).ram();
map(0x1f, 0x7f).ram();
map(0x80, 0x86).ram();
map(0x8a, 0x8e).ram();
map(0x9f, 0xbf).ram();
}
// pic16c620a, pic16c621a and pic16c622a
void pic16c62x_device::pic16c62xa_ram(address_map &map)
{
map(0x00, 0x06).ram();
map(0x0a, 0x0c).ram();
map(0x1f, 0x6f).ram();
map(0x70, 0x7f).ram().share(nullptr);
map(0x80, 0x86).ram();
map(0x8a, 0x8e).ram();
map(0x9f, 0xbf).ram();
map(0xf0, 0xff).ram().share(nullptr);
}
pic16c62x_device::pic16c62x_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock, int program_width, int picmodel)
: cpu_device(mconfig, type, tag, owner, clock)
, m_program_config("program", ENDIANNESS_LITTLE, 16, program_width, -1
, ( ( program_width == 9 ) ? address_map_constructor(FUNC(pic16c62x_device::pic16c62x_rom_9), this) :
( ( program_width == 10 ) ? address_map_constructor(FUNC(pic16c62x_device::pic16c62x_rom_10), this) :
address_map_constructor(FUNC(pic16c62x_device::pic16c62x_rom_11), this) )))
, m_data_config("data", ENDIANNESS_LITTLE, 8, 8, 0
, ( ( picmodel == 0x16C620 || picmodel == 0x16C621 ) ? address_map_constructor(FUNC(pic16c62x_device::pic16c620_ram), this) :
( ( picmodel == 0x16C622 ) ? address_map_constructor(FUNC(pic16c62x_device::pic16c622_ram), this) :
address_map_constructor(FUNC(pic16c62x_device::pic16c62xa_ram), this) ) ) )
, m_io_config("io", ENDIANNESS_LITTLE, 8, 5, 0)
, m_CONFIG(0x3fff)
, m_reset_vector(0x0)
, m_picmodel(picmodel)
, m_picRAMmask(0xff)
{
}
pic16c620_device::pic16c620_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: pic16c62x_device(mconfig, PIC16C620, tag, owner, clock, 9, 0x16C620)
{
}
pic16c620a_device::pic16c620a_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: pic16c62x_device(mconfig, PIC16C620A, tag, owner, clock, 9, 0x16C620A)
{
}
pic16c621_device::pic16c621_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: pic16c62x_device(mconfig, PIC16C621, tag, owner, clock, 10, 0x16C621)
{
}
pic16c621a_device::pic16c621a_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: pic16c62x_device(mconfig, PIC16C621A, tag, owner, clock, 10, 0x16C621A)
{
}
pic16c622_device::pic16c622_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: pic16c62x_device(mconfig, PIC16C622, tag, owner, clock, 11, 0x16C622)
{
}
pic16c622a_device::pic16c622a_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: pic16c62x_device(mconfig, PIC16C622A, tag, owner, clock, 11, 0x16C622A)
{
}
device_memory_interface::space_config_vector pic16c62x_device::memory_space_config() const
{
return space_config_vector{
std::make_pair(AS_PROGRAM, &m_program_config),
std::make_pair(AS_DATA, &m_data_config),
std::make_pair(AS_IO, &m_io_config)
};
}
std::unique_ptr<util::disasm_interface> pic16c62x_device::create_disassembler()
{
return std::make_unique<pic16c62x_disassembler>();
}
void pic16c62x_device::update_internalram_ptr()
{
m_internalram = (uint8_t *)m_data.space().get_write_ptr(0x00);
}
#define PIC16C62x_RDOP(A) (m_cache.read_word(A))
#define PIC16C62x_RAM_RDMEM(A) ((uint8_t)m_data.read_byte(A))
#define PIC16C62x_RAM_WRMEM(A,V) (m_data.write_byte(A,V))
#define PIC16C62x_In(Port) ((uint8_t)m_io.read_byte((Port)))
#define PIC16C62x_Out(Port,Value) (m_io.write_byte((Port),Value))
/************ Read the state of the T0 Clock input signal ************/
#define PIC16C62x_T0_In (m_io.read_byte(PIC16C62x_T0) >> 4)
#define M_RDRAM(A) (((A) == 0) ? m_internalram[0] : PIC16C62x_RAM_RDMEM(A))
#define M_WRTRAM(A,V) do { if ((A) == 0) m_internalram[0] = (V); else PIC16C62x_RAM_WRMEM(A,V); } while (0)
#define M_RDOP(A) PIC16C62x_RDOP(A)
#define P_IN(A) PIC16C62x_In(A)
#define P_OUT(A,V) PIC16C62x_Out(A,V)
#define S_T0_IN PIC16C62x_T0_In
#define ADDR_MASK 0x1fff
#define TMR0 m_internalram[1]
#define PCL m_internalram[2]
#define STATUS m_internalram[3]
#define FSR m_internalram[4]
#define PORTA m_internalram[5]
#define PORTB m_internalram[6]
#define INDF M_RDRAM(FSR)
#define RISING_EDGE_T0 (( (int)(T0_in - m_old_T0) > 0) ? 1 : 0)
#define FALLING_EDGE_T0 (( (int)(T0_in - m_old_T0) < 0) ? 1 : 0)
/******** The following is the Status Flag register definition. *********/
/* | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | */
/* |IRP|RP1|RP0| TO | PD | Z | DC | C | */
#define IRP_FLAG 0x80 /* IRP Register Bank Select bit (used for indirect addressing) */
#define RP1_FLAG 0x40 /* RP1 Register Bank Select bits (used for direct addressing) */
#define RP0_FLAG 0x20 /* RP0 Register Bank Select bits (used for direct addressing) */
#define TO_FLAG 0x10 /* TO Time Out flag (WatchDog) */
#define PD_FLAG 0x08 /* PD Power Down flag */
#define Z_FLAG 0x04 /* Z Zero Flag */
#define DC_FLAG 0x02 /* DC Digit Carry/Borrow flag (Nibble) */
#define C_FLAG 0x01 /* C Carry/Borrow Flag (Byte) */
#define IRP (STATUS & IRP_FLAG)
#define RP1 (STATUS & RP1_FLAG)
#define RP0 (STATUS & RP0_FLAG)
#define TO (STATUS & TO_FLAG)
#define PD (STATUS & PD_FLAG)
#define ZERO (STATUS & Z_FLAG)
#define DC (STATUS & DC_FLAG)
#define CARRY (STATUS & C_FLAG)
#define ADDR ((m_opcode.b.l & 0x7f) | (RP0 << 2))
/******** The following is the Option Flag register definition. *********/
/* | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | */
/* | RBPU | INTEDG | TOCS | TOSE | PSA | PS | */
#define RBPU_FLAG 0x80 /* RBPU Pull-up Enable */
#define INTEDG_FLAG 0x40 /* INTEDG Interrupt Edge Select */
#define T0CS_FLAG 0x20 /* TOCS Timer 0 clock source select */
#define T0SE_FLAG 0x10 /* TOSE Timer 0 clock source edge select */
#define PSA_FLAG 0x08 /* PSA Prescaler Assignment bit */
#define PS_REG 0x07 /* PS Prescaler Rate select */
#define T0CS (m_OPTION & T0CS_FLAG)
#define T0SE (m_OPTION & T0SE_FLAG)
#define PSA (m_OPTION & PSA_FLAG)
#define PS (m_OPTION & PS_REG)
/******** The following is the Config Flag register definition. *********/
/* | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | */
/* | CP | | BODEN | CP | PWRTE | WDTE | FOSC | */
/* CP Code Protect (ROM read protect) */
#define BODEN_FLAG 0x40 /* BODEN Brown-out Reset Enable */
#define PWRTE_FLAG 0x08 /* PWRTE Power-up Timer Enable */
#define WDTE_FLAG 0x04 /* WDTE WatchDog Timer enable */
#define FOSC_FLAG 0x03 /* FOSC Oscillator source select */
#define WDTE (m_CONFIG & WDTE_FLAG)
#define FOSC (m_CONFIG & FOSC_FLAG)
/************************************************************************
* Shortcuts
************************************************************************/
#define CLR(flagreg, flag) ( flagreg &= (uint8_t)(~flag) )
#define SET(flagreg, flag) ( flagreg |= flag )
/* Easy bit position selectors */
#define POS ((m_opcode.w.l >> 7) & 7)
static const unsigned int bit_clr[8] = { 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f };
static const unsigned int bit_set[8] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
void pic16c62x_device::CALCULATE_Z_FLAG()
{
if (m_ALU == 0) SET(STATUS, Z_FLAG);
else CLR(STATUS, Z_FLAG);
}
void pic16c62x_device::CALCULATE_ADD_CARRY()
{
if ((uint8_t)(m_old_data) > (uint8_t)(m_ALU)) {
SET(STATUS, C_FLAG);
}
else {
CLR(STATUS, C_FLAG);
}
}
void pic16c62x_device::CALCULATE_ADD_DIGITCARRY()
{
if (((uint8_t)(m_old_data) & 0x0f) > ((uint8_t)(m_ALU) & 0x0f)) {
SET(STATUS, DC_FLAG);
}
else {
CLR(STATUS, DC_FLAG);
}
}
void pic16c62x_device::CALCULATE_SUB_CARRY()
{
if ((uint8_t)(m_old_data) < (uint8_t)(m_ALU)) {
CLR(STATUS, C_FLAG);
}
else {
SET(STATUS, C_FLAG);
}
}
void pic16c62x_device::CALCULATE_SUB_DIGITCARRY()
{
if (((uint8_t)(m_old_data) & 0x0f) < ((uint8_t)(m_ALU) & 0x0f)) {
CLR(STATUS, DC_FLAG);
}
else {
SET(STATUS, DC_FLAG);
}
}
uint16_t pic16c62x_device::POP_STACK()
{
uint16_t data = m_STACK[7];
m_STACK[7] = m_STACK[6];
m_STACK[6] = m_STACK[5];
m_STACK[5] = m_STACK[4];
m_STACK[4] = m_STACK[3];
m_STACK[3] = m_STACK[2];
m_STACK[2] = m_STACK[1];
m_STACK[1] = m_STACK[0];
return (data & ADDR_MASK);
}
void pic16c62x_device::PUSH_STACK(uint16_t data)
{
m_STACK[0] = m_STACK[1];
m_STACK[1] = m_STACK[2];
m_STACK[2] = m_STACK[3];
m_STACK[3] = m_STACK[4];
m_STACK[4] = m_STACK[5];
m_STACK[5] = m_STACK[6];
m_STACK[6] = m_STACK[7];
m_STACK[7] = (data & ADDR_MASK);
}
uint8_t pic16c62x_device::GET_REGFILE(offs_t addr) /* Read from internal memory */
{
uint8_t data;
if (addr == 0) { /* Indirect addressing */
addr = (FSR & m_picRAMmask);
}
switch(addr)
{
case 0x00: /* Not an actual register, so return 0 */
case 0x80:
data = 0;
break;
case 0x02:
case 0x03:
case 0x0b:
case 0x82:
case 0x83:
case 0x8b:
data = M_RDRAM(addr & 0x7f);
break;
case 0x84:
case 0x04: data = (FSR | (uint8_t)(~m_picRAMmask));
break;
case 0x05: data = P_IN(0);
data &= m_TRISA;
data |= ((uint8_t)(~m_TRISA) & PORTA);
data &= 0x1f; /* 5-bit port (only lower 5 bits used) */
break;
case 0x06: data = P_IN(1);
data &= m_TRISB;
data |= ((uint8_t)(~m_TRISB) & PORTB);
break;
case 0x8a:
case 0x0a: data = m_PCLATH;
break;
case 0x81: data = m_OPTION;
break;
case 0x85: data = m_TRISA;
break;
case 0x86: data = m_TRISB;
break;
default: data = M_RDRAM(addr);
break;
}
return data;
}
void pic16c62x_device::STORE_REGFILE(offs_t addr, uint8_t data) /* Write to internal memory */
{
if (addr == 0) { /* Indirect addressing */
addr = (FSR & m_picRAMmask);
}
switch(addr)
{
case 0x80:
case 0x00: /* Not an actual register, nothing to save */
break;
case 0x01: m_delay_timer = 2; /* Timer starts after next two instructions */
if (PSA == 0) m_prescaler = 0; /* Must clear the Prescaler */
TMR0 = data;
break;
case 0x82:
case 0x02: PCL = data;
m_PC = (m_PCLATH << 8) | data;
break;
case 0x83:
case 0x03: STATUS &= (uint8_t)(~(IRP_FLAG|RP1_FLAG|RP0_FLAG)); STATUS |= (data & (IRP_FLAG|RP1_FLAG|RP0_FLAG));
break;
case 0x84:
case 0x04: FSR = (data | (uint8_t)(~m_picRAMmask));
break;
case 0x05: data &= 0x1f; /* 5-bit port (only lower 5 bits used) */
P_OUT(0,data & (uint8_t)(~m_TRISA)); PORTA = data;
break;
case 0x06: P_OUT(1,data & (uint8_t)(~m_TRISB)); PORTB = data;
break;
case 0x8a:
case 0x0a:
m_PCLATH = data & 0x1f;
M_WRTRAM(0x0a, m_PCLATH);
break;
case 0x8b:
case 0x0b: M_WRTRAM(0x0b, data);
break;
case 0x81: m_OPTION = data;
M_WRTRAM(0x81, data);
break;
case 0x85: if (m_TRISA != data)
{
m_TRISA = data | 0xf0;
P_OUT(2,m_TRISA);
P_OUT(0,PORTA & (uint8_t)(~m_TRISA) & 0x0f);
M_WRTRAM(addr, data);
}
break;
case 0x86: if (m_TRISB != data)
{
m_TRISB = data;
P_OUT(3,m_TRISB);
P_OUT(1,PORTB & (uint8_t)(~m_TRISB));
M_WRTRAM(addr, data);
}
break;
default: M_WRTRAM(addr, data);
break;
}
}
void pic16c62x_device::STORE_RESULT(offs_t addr, uint8_t data)
{
if (m_opcode.b.l & 0x80)
{
STORE_REGFILE(addr, data);
}
else
{
m_W = data;
}
}
/************************************************************************
* Emulate the Instructions
************************************************************************/
/* This following function is here to fill in the void for */
/* the opcode call function. This function is never called. */
void pic16c62x_device::illegal()
{
logerror("PIC16C62x: PC=%03x, Illegal opcode = %04x\n", (m_PC-1), m_opcode.w.l);
}
void pic16c62x_device::addwf()
{
m_old_data = GET_REGFILE(ADDR);
m_ALU = m_old_data + m_W;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
CALCULATE_ADD_CARRY();
CALCULATE_ADD_DIGITCARRY();
}
void pic16c62x_device::addlw()
{
m_ALU = (m_opcode.b.l & 0xff) + m_W;
m_W = m_ALU;
CALCULATE_Z_FLAG();
CALCULATE_ADD_CARRY();
CALCULATE_ADD_DIGITCARRY();
}
void pic16c62x_device::andwf()
{
m_ALU = GET_REGFILE(ADDR) & m_W;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
void pic16c62x_device::andlw()
{
m_ALU = m_opcode.b.l & m_W;
m_W = m_ALU;
CALCULATE_Z_FLAG();
}
void pic16c62x_device::bcf()
{
m_ALU = GET_REGFILE(ADDR);
m_ALU &= bit_clr[POS];
STORE_REGFILE(ADDR, m_ALU);
}
void pic16c62x_device::bsf()
{
m_ALU = GET_REGFILE(ADDR);
m_ALU |= bit_set[POS];
STORE_REGFILE(ADDR, m_ALU);
}
void pic16c62x_device::btfss()
{
if ((GET_REGFILE(ADDR) & bit_set[POS]) == bit_set[POS])
{
m_PC++;
PCL = m_PC & 0xff;
m_inst_cycles += 1; /* Add NOP cycles */
}
}
void pic16c62x_device::btfsc()
{
if ((GET_REGFILE(ADDR) & bit_set[POS]) == 0)
{
m_PC++;
PCL = m_PC & 0xff;
m_inst_cycles += 1; /* Add NOP cycles */
}
}
void pic16c62x_device::call()
{
PUSH_STACK(m_PC);
m_PC = ((m_PCLATH & 0x18) << 8) | (m_opcode.w.l & 0x7ff);
m_PC &= ADDR_MASK;
PCL = m_PC & 0xff;
}
void pic16c62x_device::clrw()
{
m_W = 0;
SET(STATUS, Z_FLAG);
}
void pic16c62x_device::clrf()
{
STORE_REGFILE(ADDR, 0);
SET(STATUS, Z_FLAG);
}
void pic16c62x_device::clrwdt()
{
m_WDT = 0;
if (PSA) m_prescaler = 0;
SET(STATUS, TO_FLAG);
SET(STATUS, PD_FLAG);
}
void pic16c62x_device::comf()
{
m_ALU = (uint8_t)(~(GET_REGFILE(ADDR)));
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
void pic16c62x_device::decf()
{
m_ALU = GET_REGFILE(ADDR) - 1;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
void pic16c62x_device::decfsz()
{
m_ALU = GET_REGFILE(ADDR) - 1;
STORE_RESULT(ADDR, m_ALU);
if (m_ALU == 0)
{
m_PC++;
PCL = m_PC & 0xff;
m_inst_cycles += 1; /* Add NOP cycles */
}
}
void pic16c62x_device::goto_op()
{
m_PC = ((m_PCLATH & 0x18) << 8) | (m_opcode.w.l & 0x7ff);
m_PC &= ADDR_MASK;
PCL = m_PC & 0xff;
}
void pic16c62x_device::incf()
{
m_ALU = GET_REGFILE(ADDR) + 1;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
void pic16c62x_device::incfsz()
{
m_ALU = GET_REGFILE(ADDR) + 1;
STORE_RESULT(ADDR, m_ALU);
if (m_ALU == 0)
{
m_PC++;
PCL = m_PC & 0xff;
m_inst_cycles += 1; /* Add NOP cycles */
}
}
void pic16c62x_device::iorlw()
{
m_ALU = m_opcode.b.l | m_W;
m_W = m_ALU;
CALCULATE_Z_FLAG();
}
void pic16c62x_device::iorwf()
{
m_ALU = GET_REGFILE(ADDR) | m_W;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
void pic16c62x_device::movf()
{
m_ALU = GET_REGFILE(ADDR);
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
void pic16c62x_device::movlw()
{
m_W = m_opcode.b.l;
}
void pic16c62x_device::movwf()
{
STORE_REGFILE(ADDR, m_W);
}
void pic16c62x_device::nop()
{
/* Do nothing */
}
void pic16c62x_device::option()
{
m_OPTION = m_W;
}
void pic16c62x_device::retlw()
{
m_W = m_opcode.b.l;
m_PC = POP_STACK();
PCL = m_PC & 0xff;
}
void pic16c62x_device::returns()
{
m_PC = POP_STACK();
PCL = m_PC & 0xff;
}
void pic16c62x_device::retfie()
{
m_PC = POP_STACK();
PCL = m_PC & 0xff;
//INTCON(7)=1;
}
void pic16c62x_device::rlf()
{
m_ALU = GET_REGFILE(ADDR);
m_ALU <<= 1;
if (STATUS & C_FLAG) m_ALU |= 1;
if (GET_REGFILE(ADDR) & 0x80) SET(STATUS, C_FLAG);
else CLR(STATUS, C_FLAG);
STORE_RESULT(ADDR, m_ALU);
}
void pic16c62x_device::rrf()
{
m_ALU = GET_REGFILE(ADDR);
m_ALU >>= 1;
if (STATUS & C_FLAG) m_ALU |= 0x80;
if (GET_REGFILE(ADDR) & 1) SET(STATUS, C_FLAG);
else CLR(STATUS, C_FLAG);
STORE_RESULT(ADDR, m_ALU);
}
void pic16c62x_device::sleepic()
{
if (WDTE) m_WDT = 0;
if (PSA) m_prescaler = 0;
SET(STATUS, TO_FLAG);
CLR(STATUS, PD_FLAG);
}
void pic16c62x_device::subwf()
{
m_old_data = GET_REGFILE(ADDR);
m_ALU = m_old_data - m_W;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
CALCULATE_SUB_CARRY();
CALCULATE_SUB_DIGITCARRY();
}
void pic16c62x_device::sublw()
{
m_ALU = (m_opcode.b.l & 0xff) - m_W;
m_W = m_ALU;
CALCULATE_Z_FLAG();
CALCULATE_SUB_CARRY();
CALCULATE_SUB_DIGITCARRY();
}
void pic16c62x_device::swapf()
{
m_ALU = ((GET_REGFILE(ADDR) << 4) & 0xf0);
m_ALU |= ((GET_REGFILE(ADDR) >> 4) & 0x0f);
STORE_RESULT(ADDR, m_ALU);
}
void pic16c62x_device::tris()
{
switch(m_opcode.b.l & 0x7)
{
case 5: STORE_REGFILE(0x85, m_W); break;
case 6: STORE_REGFILE(0x86, m_W); break;
default: illegal(); break;
}
}
void pic16c62x_device::xorlw()
{
m_ALU = m_W ^ m_opcode.b.l;
m_W = m_ALU;
CALCULATE_Z_FLAG();
}
void pic16c62x_device::xorwf()
{
m_ALU = GET_REGFILE(ADDR) ^ m_W;
STORE_RESULT(ADDR, m_ALU);
CALCULATE_Z_FLAG();
}
/***********************************************************************
* Instruction Table (Format, Instruction, Cycles)
***********************************************************************/
const pic16c62x_device::pic16c62x_instruction pic16c62x_device::s_instructiontable[]=
{
{(char *)"000111dfffffff", &pic16c62x_device::addwf, 1},
{(char *)"000101dfffffff", &pic16c62x_device::andwf, 1},
{(char *)"0000011fffffff", &pic16c62x_device::clrf, 1},
{(char *)"00000100000011", &pic16c62x_device::clrw, 1},
{(char *)"001001dfffffff", &pic16c62x_device::comf, 1},
{(char *)"000011dfffffff", &pic16c62x_device::decf, 1},
{(char *)"001011dfffffff", &pic16c62x_device::decfsz, 1},
{(char *)"001010dfffffff", &pic16c62x_device::incf, 1},
{(char *)"001111dfffffff", &pic16c62x_device::incfsz, 1},
{(char *)"000100dfffffff", &pic16c62x_device::iorwf, 1},
{(char *)"001000dfffffff", &pic16c62x_device::movf, 1},
{(char *)"0000001fffffff", &pic16c62x_device::movwf, 1},
{(char *)"0000000xx00000", &pic16c62x_device::nop, 1},
{(char *)"001101dfffffff", &pic16c62x_device::rlf, 1},
{(char *)"001100dfffffff", &pic16c62x_device::rrf, 1},
{(char *)"000010dfffffff", &pic16c62x_device::subwf, 1},
{(char *)"001110dfffffff", &pic16c62x_device::swapf, 1},
{(char *)"000110dfffffff", &pic16c62x_device::xorwf, 1},
{(char *)"0100bbbfffffff", &pic16c62x_device::bcf, 1},
{(char *)"0101bbbfffffff", &pic16c62x_device::bsf, 1},
{(char *)"0110bbbfffffff", &pic16c62x_device::btfsc, 1},
{(char *)"0111bbbfffffff", &pic16c62x_device::btfss, 1},
{(char *)"11111xkkkkkkkk", &pic16c62x_device::addlw, 1},
{(char *)"111001kkkkkkkk", &pic16c62x_device::andlw, 1},
{(char *)"100aaaaaaaaaaa", &pic16c62x_device::call, 2},
{(char *)"101aaaaaaaaaaa", &pic16c62x_device::goto_op, 2},
{(char *)"111000kkkkkkkk", &pic16c62x_device::iorlw, 1},
{(char *)"1100xxkkkkkkkk", &pic16c62x_device::movlw, 1},
{(char *)"00000000001001", &pic16c62x_device::retfie, 2},
{(char *)"1101xxkkkkkkkk", &pic16c62x_device::retlw, 2},
{(char *)"00000000001000", &pic16c62x_device::returns, 2},
{(char *)"00000001100011", &pic16c62x_device::sleepic, 1},
{(char *)"11110xkkkkkkkk", &pic16c62x_device::sublw, 1},
{(char *)"111010kkkkkkkk", &pic16c62x_device::xorlw, 1},
{(char *)"00000001100100", &pic16c62x_device::clrwdt, 1},
{(char *)"00000001100010", &pic16c62x_device::option, 1}, // deprecated
{(char *)"00000001100fff", &pic16c62x_device::tris, 1}, // deprecated
{nullptr, nullptr, 0}
};
/***********************************************************************
* Opcode Table build function
***********************************************************************/
void pic16c62x_device::build_opcode_table(void)
{
int instr,mask,bits;
int a;
// defaults
for ( a = 0; a < 0x4000; a++)
{
m_opcode_table[a].cycles = 0;
m_opcode_table[a].function = &pic16c62x_device::illegal;
}
// build table
for( instr = 0; s_instructiontable[instr].cycles != 0; instr++)
{
bits=0;
mask=0;
for ( a = 0; a < 14; a++)
{
switch (s_instructiontable[instr].format[a])
{
case '0':
bits = bits << 1;
mask = (mask << 1) | 1;
break;
case '1':
bits = (bits << 1) | 1;
mask = (mask << 1) | 1;
break;
default:
bits = bits << 1;
mask = mask << 1;
break;
}
}
for ( a = 0; a < 0x4000; a++)
{
if (((a & mask) == bits) && (m_opcode_table[a].cycles == 0))
{
m_opcode_table[a].cycles = s_instructiontable[instr].cycles;
m_opcode_table[a].function = s_instructiontable[instr].function;
}
}
}
}
/****************************************************************************
* Inits CPU emulation
****************************************************************************/
void pic16c62x_device::device_start()
{
space(AS_PROGRAM).cache(m_cache);
space(AS_PROGRAM).specific(m_program);
space(AS_DATA).specific(m_data);
space(AS_IO).specific(m_io);
/* ensure the internal ram pointers are set before get_info is called */
update_internalram_ptr();
build_opcode_table();
save_item(NAME(m_W));
save_item(NAME(m_ALU));
save_item(NAME(m_OPTION));
save_item(NAME(m_PCLATH));
save_item(NAME(m_TRISA));
save_item(NAME(m_TRISB));
save_item(NAME(m_old_T0));
save_item(NAME(m_old_data));
save_item(NAME(m_picRAMmask));
save_item(NAME(m_WDT));
save_item(NAME(m_prescaler));
save_item(NAME(m_STACK));
save_item(NAME(m_PC));
save_item(NAME(m_PREVPC));
save_item(NAME(m_CONFIG));
save_item(NAME(m_opcode.d));
save_item(NAME(m_delay_timer));
save_item(NAME(m_picmodel));
save_item(NAME(m_reset_vector));
save_item(NAME(m_temp_config));
save_item(NAME(m_inst_cycles));
state_add( PIC16C62x_PC, "PC", m_PC).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_W, "W", m_W).formatstr("%02X");
state_add( PIC16C62x_ALU, "ALU", m_ALU).formatstr("%02X");
state_add( PIC16C62x_STR, "STR", m_debugger_temp).mask(0xff).callimport().callexport().formatstr("%02X");
state_add( PIC16C62x_TMR0, "TMR", m_debugger_temp).mask(0xff).callimport().callexport().formatstr("%02X");
state_add( PIC16C62x_WDT, "WDT", m_WDT).formatstr("%04X");
state_add( PIC16C62x_OPT, "OPT", m_OPTION).formatstr("%02X");
state_add( PIC16C62x_STK0, "STK0", m_STACK[0]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK1, "STK1", m_STACK[1]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK2, "STK2", m_STACK[2]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK3, "STK3", m_STACK[3]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK4, "STK4", m_STACK[4]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK5, "STK5", m_STACK[5]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK6, "STK6", m_STACK[6]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_STK7, "STK7", m_STACK[7]).mask(0xfff).formatstr("%03X");
state_add( PIC16C62x_PRTA, "PRTA", m_debugger_temp).mask(0x1f).callimport().callexport().formatstr("%02X");
state_add( PIC16C62x_PRTB, "PRTB", m_debugger_temp).mask(0xff).callimport().callexport().formatstr("%02X");
state_add( PIC16C62x_TRSA, "TRSA", m_TRISA).mask(0x1f).formatstr("%02X");
state_add( PIC16C62x_TRSB, "TRSB", m_TRISB).formatstr("%02X");
state_add( PIC16C62x_FSR, "FSR", m_debugger_temp).mask(0xff).callimport().callexport().formatstr("%02X");
state_add( PIC16C62x_PSCL, "PSCL", m_debugger_temp).callimport().formatstr("%3s");
state_add( STATE_GENPC, "GENPC", m_PC).noshow();
state_add( STATE_GENPCBASE, "CURPC", m_PREVPC).noshow();
state_add( STATE_GENFLAGS, "GENFLAGS", m_OPTION).formatstr("%13s").noshow();
set_icountptr(m_icount);
}
void pic16c62x_device::state_import(const device_state_entry &entry)
{
switch (entry.index())
{
case PIC16C62x_STR:
STATUS = m_debugger_temp;
break;
case PIC16C62x_TMR0:
TMR0 = m_debugger_temp;
break;
case PIC16C62x_PRTA:
PORTA = m_debugger_temp;
break;
case PIC16C62x_PRTB:
PORTB = m_debugger_temp;
break;
case PIC16C62x_FSR:
FSR = ((m_debugger_temp & m_picRAMmask) | (uint8_t)(~m_picRAMmask));
break;
case PIC16C62x_PSCL:
m_prescaler = m_debugger_temp;
break;
}
}
void pic16c62x_device::state_export(const device_state_entry &entry)
{
switch (entry.index())
{
case PIC16C62x_STR:
m_debugger_temp = STATUS;
break;
case PIC16C62x_TMR0:
m_debugger_temp = TMR0;
break;
case PIC16C62x_PRTA:
m_debugger_temp = PORTA & 0x1f;
break;
case PIC16C62x_PRTB:
m_debugger_temp = PORTB;
break;
case PIC16C62x_FSR:
m_debugger_temp = ((FSR) & m_picRAMmask) | (uint8_t)(~m_picRAMmask);
break;
}
}
void pic16c62x_device::state_string_export(const device_state_entry &entry, std::string &str) const
{
switch (entry.index())
{
case PIC16C62x_PSCL:
str = string_format("%c%02X", ((m_OPTION & 0x08) ? 'W' : 'T'), m_prescaler);
break;
case STATE_GENFLAGS:
str = string_format("%01x%c%c%c%c%c %c%c%c%03x",
(STATUS & 0xe0) >> 5,
STATUS & 0x10 ? '.':'O', /* WDT Overflow */
STATUS & 0x08 ? 'P':'D', /* Power/Down */
STATUS & 0x04 ? 'Z':'.', /* Zero */
STATUS & 0x02 ? 'c':'b', /* Nibble Carry/Borrow */
STATUS & 0x01 ? 'C':'B', /* Carry/Borrow */
m_OPTION & 0x20 ? 'C':'T', /* Counter/Timer */
m_OPTION & 0x10 ? 'N':'P', /* Negative/Positive */
m_OPTION & 0x08 ? 'W':'T', /* WatchDog/Timer */
m_OPTION & 0x08 ? (1<<(m_OPTION&7)) : (2<<(m_OPTION&7)) );
break;
}
}
/****************************************************************************
* Reset registers to their initial values
****************************************************************************/
void pic16c62x_device::pic16c62x_reset_regs()
{
m_PC = m_reset_vector;
m_TRISA = 0x1f;
m_TRISB = 0xff;
m_OPTION = 0xff;
STATUS = 0x18;
PCL = 0;
FSR |= (uint8_t)(~m_picRAMmask);
PORTA = 0;
m_prescaler = 0;
m_delay_timer = 0;
m_old_T0 = 0;
m_inst_cycles = 0;
PIC16C62x_RAM_WRMEM(0x85,m_TRISA);
PIC16C62x_RAM_WRMEM(0x86,m_TRISB);
PIC16C62x_RAM_WRMEM(0x81,m_OPTION);
}
void pic16c62x_device::pic16c62x_soft_reset()
{
SET(STATUS, (TO_FLAG | PD_FLAG | Z_FLAG | DC_FLAG | C_FLAG));
pic16c62x_reset_regs();
}
void pic16c62x_device::set_config(int data)
{
logerror("Writing %04x to the PIC16C62x configuration bits\n",data);
m_CONFIG = (data & 0x3fff);
}
/****************************************************************************
* WatchDog
****************************************************************************/
void pic16c62x_device::pic16c62x_update_watchdog(int counts)
{
/* TODO: needs updating */
/* WatchDog is set up to count 18,000 (0x464f hex) ticks to provide */
/* the timeout period of 0.018ms based on a 4MHz input clock. */
/* Note: the 4MHz clock should be divided by the PIC16C5x_CLOCK_DIVIDER */
/* which effectively makes the PIC run at 1MHz internally. */
/* If the current instruction is CLRWDT or SLEEP, don't update the WDT */
if ((m_opcode.w.l != 0x64) && (m_opcode.w.l != 0x63))
{
uint16_t old_WDT = m_WDT;
m_WDT -= counts;
if (m_WDT > 0x464f) {
m_WDT = 0x464f - (0xffff - m_WDT);
}
if (((old_WDT != 0) && (old_WDT < m_WDT)) || (m_WDT == 0))
{
if (PSA) {
m_prescaler++;
if (m_prescaler >= (1 << PS)) { /* Prescale values from 1 to 128 */
m_prescaler = 0;
CLR(STATUS, TO_FLAG);
pic16c62x_soft_reset();
}
}
else {
CLR(STATUS, TO_FLAG);
pic16c62x_soft_reset();
}
}
}
}
/****************************************************************************
* Update Timer
****************************************************************************/
void pic16c62x_device::pic16c62x_update_timer(int counts)
{
if (PSA == 0) {
m_prescaler += counts;
if (m_prescaler >= (2 << PS)) { /* Prescale values from 2 to 256 */
TMR0 += (m_prescaler / (2 << PS));
m_prescaler %= (2 << PS); /* Overflow prescaler */
}
}
else {
TMR0 += counts;
}
}
/****************************************************************************
* Execute IPeriod. Return 0 if emulation should be stopped
****************************************************************************/
void pic16c62x_device::execute_run()
{
uint8_t T0_in;
update_internalram_ptr();
do
{
if (PD == 0) /* Sleep Mode */
{
m_inst_cycles = 1;
debugger_instruction_hook(m_PC);
if (WDTE) {
pic16c62x_update_watchdog(1);
}
}
else
{
m_PREVPC = m_PC;
debugger_instruction_hook(m_PC);
m_opcode.d = M_RDOP(m_PC);
m_PC++;
PCL++;
m_inst_cycles = m_opcode_table[m_opcode.w.l & 0x3fff].cycles;
(this->*m_opcode_table[m_opcode.w.l & 0x3fff].function)();
if (T0CS) { /* Count mode */
T0_in = S_T0_IN;
if (T0_in) T0_in = 1;
if (T0SE) { /* Count falling edge T0 input */
if (FALLING_EDGE_T0) {
pic16c62x_update_timer(1);
}
}
else { /* Count rising edge T0 input */
if (RISING_EDGE_T0) {
pic16c62x_update_timer(1);
}
}
m_old_T0 = T0_in;
}
else { /* Timer mode */
if (m_delay_timer) {
m_delay_timer--;
}
else {
pic16c62x_update_timer(m_inst_cycles);
}
}
if (WDTE) {
pic16c62x_update_watchdog(m_inst_cycles);
}
}
m_icount -= m_inst_cycles;
} while (m_icount > 0);
}
void pic16c62x_device::device_reset()
{
update_internalram_ptr();
pic16c62x_reset_regs();
SET(STATUS, (TO_FLAG | PD_FLAG));
}
| 29.139632 | 166 | 0.584373 | Robbbert |
166f731e972767a615d1cb43a5d44ba04fd18b70 | 5,061 | cpp | C++ | src/REPL/Command/Match.cpp | nccgroup/xendbg | 74ce0c1ad6398b14e5702d0f58832d40088cea23 | [
"MIT"
] | 67 | 2019-01-27T01:49:40.000Z | 2022-02-18T16:01:09.000Z | src/REPL/Command/Match.cpp | SpencerMichaels/xendbg | e0290847eb0c345a9db681514c1adcf9269396c8 | [
"MIT"
] | 3 | 2019-06-30T14:51:56.000Z | 2020-02-14T19:17:23.000Z | src/REPL/Command/Match.cpp | SpencerMichaels/xendbg | e0290847eb0c345a9db681514c1adcf9269396c8 | [
"MIT"
] | 14 | 2019-01-28T07:11:23.000Z | 2021-06-14T13:33:12.000Z | //
// Copyright (C) 2018-2019 NCC Group
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#include <iostream>
#include "Match.hpp"
#include <Util/string.hpp>
using xd::repl::cmd::Argument;
using xd::repl::cmd::Flag;
using xd::repl::cmd::ArgsHandle;
using xd::repl::cmd::FlagsHandle;
using xd::util::string::is_prefix;
using xd::util::string::next_char;
using xd::util::string::next_not_char;
using xd::util::string::next_whitespace;
using xd::util::string::skip_whitespace;
using xd::util::string::StrConstIt ;
void xd::repl::cmd::validate_args(const std::vector<Argument> &args) {
bool prev_arg_has_default = false;
for (const auto& arg : args) {
if (arg.get_default_value().empty()) {
if (prev_arg_has_default) {
throw DefaultArgPositionException();
}
} else {
prev_arg_has_default = true;
}
}
}
void xd::repl::cmd::validate_new_arg(const std::vector<Argument> &args,
const Argument &new_arg)
{
if (!args.empty() &&
!args.back().get_default_value().empty() &&
new_arg.get_default_value().empty())
{
throw DefaultArgPositionException();
}
}
std::pair<StrConstIt, ArgsHandle> xd::repl::cmd::match_args(
StrConstIt begin, StrConstIt end, const std::vector<Argument> &args)
{
ArgsHandle args_handle;
auto it = begin;
for (const auto& arg : args) {
it = skip_whitespace(it, end);
const auto arg_end = arg.match(it, end);
if (arg_end == it) {
if (!arg.is_optional()) {
throw ArgMatchFailedException(it, arg);
} else {
args_handle.put(arg, arg.get_default_value());
}
} else {
args_handle.put(arg, std::string(it, arg_end));
}
it = arg_end;
}
return std::make_pair(it, args_handle);
}
std::pair<StrConstIt, FlagsHandle> xd::repl::cmd::match_flags(
StrConstIt begin, StrConstIt end, const std::vector<Flag> &flags,
bool ignore_unknown_flags)
{
FlagsHandle flags_handle;
auto it = begin;
while (it != end && *it == '-') {
const auto flag_it = std::find_if(flags.begin(), flags.end(),
[it, end](const auto &flag) {
return flag.match_name(it, end) != it;
});
if (flag_it != flags.end()) {
const auto [args_end, args] = flag_it->match(it, end);
flags_handle.put(*flag_it, args);
it = skip_whitespace(args_end, end);
} else {
if (ignore_unknown_flags) {
// Find the next potential flag
// If this is the last potential flag, skip beyond it and bail out
const auto prev_it = it;
it = next_char(it, end, '-');
if (it == prev_it) {
return std::make_pair(next_whitespace(it+1, end), flags_handle);
} else if (it == prev_it+1 && it == next_char(it, end, '-')) {
return std::make_pair(next_whitespace(it+2, end), flags_handle);
}
} else {
throw UnknownFlagException(it);
}
}
}
return std::make_pair(it, flags_handle);
}
std::optional<std::pair<std::string::const_iterator, Argument>>
xd::repl::cmd::get_next_arg(StrConstIt begin, StrConstIt end,
const std::vector<Argument> &args)
{
auto it = begin;
for (const auto& arg : args) {
// If the arg fails to match, it is the next expected arg.
const auto arg_end = arg.match(it, end);
if (arg_end == it)
return std::make_pair(it, arg);
/*
* If the arg has completion options AND the current string is a strict
* prefix of at least one of its options, then it is the next expected.
*/
const auto options = arg.complete(it, end);
if (options) {
const auto has_partial_match = std::any_of(
options.value().begin(), options.value().end(),
[it, arg_end](const auto &opt) {
return ((unsigned long)(arg_end - it) < opt.size()) &&
is_prefix(it, arg_end, opt.begin(), opt.end());
});
if (has_partial_match)
return std::make_pair(it, arg);
}
it = skip_whitespace(arg_end, end);
}
// All args accounted for!
return std::nullopt;
}
| 31.830189 | 83 | 0.653626 | nccgroup |
16703495a18512431801766b039c37972da543e0 | 2,774 | cc | C++ | server/db_slice.cc | romange/midi-redis | 35e7bce4ce6246716464fb78445babc0317b5000 | [
"Apache-2.0"
] | 12 | 2021-12-09T18:50:47.000Z | 2022-03-11T17:47:04.000Z | server/db_slice.cc | romange/midi-redis | 35e7bce4ce6246716464fb78445babc0317b5000 | [
"Apache-2.0"
] | null | null | null | server/db_slice.cc | romange/midi-redis | 35e7bce4ce6246716464fb78445babc0317b5000 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021, Roman Gershman. All rights reserved.
// See LICENSE for licensing terms.
//
#include "server/db_slice.h"
#include <boost/fiber/fiber.hpp>
#include <boost/fiber/operations.hpp>
#include "base/logging.h"
#include "server/engine_shard_set.h"
#include "util/fiber_sched_algo.h"
#include "util/proactor_base.h"
namespace dfly {
using namespace boost;
using namespace std;
using namespace util;
DbSlice::DbSlice(uint32_t index, EngineShard* owner) : shard_id_(index), owner_(owner) {
db_arr_.emplace_back();
CreateDbRedis(0);
}
DbSlice::~DbSlice() {
for (auto& db : db_arr_) {
if (!db.main_table)
continue;
db.main_table.reset();
}
}
void DbSlice::Reserve(DbIndex db_ind, size_t key_size) {
ActivateDb(db_ind);
auto& db = db_arr_[db_ind];
DCHECK(db.main_table);
db.main_table->reserve(key_size);
}
auto DbSlice::Find(DbIndex db_index, std::string_view key) const -> OpResult<MainIterator> {
DCHECK_LT(db_index, db_arr_.size());
DCHECK(db_arr_[db_index].main_table);
auto& db = db_arr_[db_index];
MainIterator it = db.main_table->find(key);
if (it == db.main_table->end()) {
return OpStatus::KEY_NOTFOUND;
}
return it;
}
auto DbSlice::AddOrFind(DbIndex db_index, std::string_view key) -> pair<MainIterator, bool> {
DCHECK_LT(db_index, db_arr_.size());
DCHECK(db_arr_[db_index].main_table);
auto& db = db_arr_[db_index];
pair<MainIterator, bool> res = db.main_table->emplace(key, MainValue{});
if (res.second) { // new entry
db.stats.obj_memory_usage += res.first->first.capacity();
return make_pair(res.first, true);
}
return res;
}
void DbSlice::ActivateDb(DbIndex db_ind) {
if (db_arr_.size() <= db_ind)
db_arr_.resize(db_ind + 1);
CreateDbRedis(db_ind);
}
void DbSlice::CreateDbRedis(unsigned index) {
auto& db = db_arr_[index];
if (!db.main_table) {
db.main_table.reset(new MainTable);
}
}
void DbSlice::AddNew(DbIndex db_ind, std::string_view key, MainValue obj, uint64_t expire_at_ms) {
CHECK(AddIfNotExist(db_ind, key, std::move(obj), expire_at_ms));
}
bool DbSlice::AddIfNotExist(DbIndex db_ind, std::string_view key, MainValue obj,
uint64_t expire_at_ms) {
auto& db = db_arr_[db_ind];
auto [new_entry, success] = db.main_table->emplace(key, obj);
if (!success)
return false; // in this case obj won't be moved and will be destroyed during unwinding.
db.stats.obj_memory_usage += (new_entry->first.capacity() + new_entry->second.capacity());
if (expire_at_ms) {
// TODO
}
return true;
}
size_t DbSlice::DbSize(DbIndex db_ind) const {
DCHECK_LT(db_ind, db_array_size());
if (IsDbValid(db_ind)) {
return db_arr_[db_ind].main_table->size();
}
return 0;
}
} // namespace dfly
| 23.709402 | 98 | 0.695746 | romange |
1672231aec6c72c0744fc02d1906f9a9f9e9297f | 316 | cpp | C++ | runtime/pass/ContextAnalysis.cpp | Wheest/atJIT | 7e29862db7b5eb9cee470edeb165380f881903c9 | [
"BSD-3-Clause"
] | 47 | 2018-08-03T09:15:08.000Z | 2022-02-14T07:06:12.000Z | runtime/pass/ContextAnalysis.cpp | Wheest/atJIT | 7e29862db7b5eb9cee470edeb165380f881903c9 | [
"BSD-3-Clause"
] | 15 | 2018-06-18T19:50:50.000Z | 2019-08-29T16:52:11.000Z | runtime/pass/ContextAnalysis.cpp | Wheest/atJIT | 7e29862db7b5eb9cee470edeb165380f881903c9 | [
"BSD-3-Clause"
] | 5 | 2018-08-28T02:35:44.000Z | 2021-11-01T06:54:51.000Z | #include <easy/runtime/RuntimePasses.h>
using namespace llvm;
using namespace easy;
char easy::ContextAnalysis::ID = 0;
llvm::Pass* easy::createContextAnalysisPass(std::shared_ptr<easy::Context> C) {
return new ContextAnalysis(std::move(C));
}
static RegisterPass<easy::ContextAnalysis> X("", "", true, true);
| 24.307692 | 79 | 0.740506 | Wheest |
167617b29e0a47bd7fa225320f67a6ac0effe74f | 9,027 | cpp | C++ | vnext/Microsoft.ReactNative.IntegrationTests/TurboModuleTests.cpp | harinikmsft/react-native-windows | c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21 | [
"MIT"
] | 2 | 2020-12-19T17:37:56.000Z | 2021-10-18T03:28:11.000Z | vnext/Microsoft.ReactNative.IntegrationTests/TurboModuleTests.cpp | sjalim/react-native-windows | 04e766ef7304d0852a06e772cbfc1982897a3808 | [
"MIT"
] | 2 | 2020-11-04T17:36:33.000Z | 2020-11-16T10:12:46.000Z | vnext/Microsoft.ReactNative.IntegrationTests/TurboModuleTests.cpp | sjalim/react-native-windows | 04e766ef7304d0852a06e772cbfc1982897a3808 | [
"MIT"
] | 1 | 2019-10-17T20:48:17.000Z | 2019-10-17T20:48:17.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include <NativeModules.h>
#include <sstream>
#include <string>
using namespace React;
using namespace winrt::Microsoft::ReactNative;
namespace ReactNativeIntegrationTests {
REACT_MODULE(SampleTurboModule)
struct SampleTurboModule {
REACT_INIT(Initialize)
void Initialize(ReactContext const & /*reactContext*/) noexcept {}
REACT_CONSTANT(m_constantString, L"constantString")
const std::string m_constantString{"constantString"};
REACT_CONSTANT(m_constantInt, L"constantInt")
const int m_constantInt{3};
REACT_CONSTANT_PROVIDER(GetConstants)
void GetConstants(React::ReactConstantProvider &provider) noexcept {
provider.Add(L"constantString2", L"Hello");
provider.Add(L"constantInt2", 10);
}
REACT_METHOD(Succeeded, L"succeeded")
void Succeeded() noexcept {
succeededSignal.set_value(true);
}
REACT_METHOD(OnError, L"onError")
void OnError(std::string errorMessage) noexcept {
// intended to keep the parameter name for debug purpose
succeededSignal.set_value(false);
}
REACT_METHOD(PromiseFunction, L"promiseFunction")
void PromiseFunction(std::string a, int b, bool c, ReactPromise<React::JSValue> result) noexcept {
auto resultString = (std::stringstream() << a << ", " << b << ", " << (c ? "true" : "false")).str();
result.Resolve({resultString});
// TODO:
// calling ".then" in the bundle fails, figure out why
// it could be an issue about environment setup
// since the issue doesn't happen in Playground.sln
PromiseFunctionResult(resultString);
}
REACT_METHOD(PromiseFunctionResult, L"promiseFunctionResult")
void PromiseFunctionResult(std::string a) noexcept {
promiseFunctionSignal.set_value(a);
}
REACT_SYNC_METHOD(SyncFunction, L"syncFunction")
std::string SyncFunction(std::string a, int b, bool c) noexcept {
auto resultString = (std::stringstream() << a << ", " << b << ", " << (c ? "true" : "false")).str();
return resultString;
}
REACT_METHOD(SyncFunctionResult, L"syncFunctionResult")
void SyncFunctionResult(std::string a) noexcept {
syncFunctionSignal.set_value(a);
}
REACT_METHOD(Constants, L"constants")
void Constants(std::string a, int b, std::string c, int d) noexcept {
auto resultString = (std::stringstream() << a << ", " << b << ", " << c << ", " << d).str();
constantsSignal.set_value(resultString);
}
REACT_METHOD(OneCallback, L"oneCallback")
void OneCallback(int a, int b, const std::function<void(int)> &resolve) noexcept {
resolve(a + b);
}
REACT_METHOD(OneCallbackResult, L"oneCallbackResult")
void OneCallbackResult(int r) noexcept {
oneCallbackSignal.set_value(r);
}
REACT_METHOD(TwoCallbacks, L"twoCallbacks")
void TwoCallbacks(
bool succeeded,
int a,
std::string b,
const std::function<void(int)> &resolve,
const std::function<void(std::string)> &reject) noexcept {
if (succeeded) {
resolve(a);
} else {
reject(b);
}
}
REACT_METHOD(TwoCallbacksResolved, L"twoCallbacksResolved")
void TwoCallbacksResolved(int r) noexcept {
twoCallbacksResolvedSignal.set_value(r);
}
REACT_METHOD(TwoCallbacksRejected, L"twoCallbacksRejected")
void TwoCallbacksRejected(std::string r) noexcept {
twoCallbacksRejectedSignal.set_value(r);
}
static std::promise<bool> succeededSignal;
static std::promise<std::string> promiseFunctionSignal;
static std::promise<std::string> syncFunctionSignal;
static std::promise<std::string> constantsSignal;
static std::promise<int> oneCallbackSignal;
static std::promise<int> twoCallbacksResolvedSignal;
static std::promise<std::string> twoCallbacksRejectedSignal;
};
std::promise<bool> SampleTurboModule::succeededSignal;
std::promise<std::string> SampleTurboModule::promiseFunctionSignal;
std::promise<std::string> SampleTurboModule::syncFunctionSignal;
std::promise<std::string> SampleTurboModule::constantsSignal;
std::promise<int> SampleTurboModule::oneCallbackSignal;
std::promise<int> SampleTurboModule::twoCallbacksResolvedSignal;
std::promise<std::string> SampleTurboModule::twoCallbacksRejectedSignal;
struct SampleTurboModuleSpec : TurboModuleSpec {
static constexpr auto methods = std::tuple{
Method<void() noexcept>{0, L"succeeded"},
Method<void(std::string) noexcept>{0, L"onError"},
Method<void(std::string, int, bool, ReactPromise<React::JSValue>) noexcept>{2, L"promiseFunction"},
Method<void(std::string) noexcept>{3, L"promiseFunctionResult"},
SyncMethod<std::string(std::string, int, bool) noexcept>{4, L"syncFunction"},
Method<void(std::string) noexcept>{5, L"syncFunctionResult"},
Method<void(std::string, int, std::string, int) noexcept>{6, L"constants"},
Method<void(int, int, const std::function<void(int)> &) noexcept>{7, L"oneCallback"},
Method<void(int) noexcept>{8, L"oneCallbackResult"},
Method<void(
bool,
int,
std::string,
const std::function<void(int)> &,
const std::function<void(std::string)> &) noexcept>{9, L"twoCallbacks"},
Method<void(int) noexcept>{10, L"twoCallbacksResolved"},
Method<void(std::string) noexcept>{11, L"twoCallbacksRejected"},
};
template <class TModule>
static constexpr void ValidateModule() noexcept {
constexpr auto methodCheckResults = CheckMethods<TModule, SampleTurboModuleSpec>();
REACT_SHOW_METHOD_SPEC_ERRORS(0, "succeeded", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(1, "onError", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(2, "promiseFunction", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(3, "promiseFunctionResult", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(4, "syncFunction", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(5, "syncFunctionResult", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(6, "constants", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(7, "oneCallback", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(8, "oneCallbackResult", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(9, "twoCallbacks", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(10, "twoCallbacksResolved", "I don't care error message");
REACT_SHOW_METHOD_SPEC_ERRORS(11, "twoCallbacksRejected", "I don't care error message");
}
};
struct SampleTurboModulePackageProvider : winrt::implements<SampleTurboModulePackageProvider, IReactPackageProvider> {
void CreatePackage(IReactPackageBuilder const &packageBuilder) noexcept {
auto experimental = packageBuilder.as<IReactPackageBuilderExperimental>();
experimental.AddTurboModule(
L"SampleTurboModule", MakeTurboModuleProvider<SampleTurboModule, SampleTurboModuleSpec>());
}
};
TEST_CLASS (TurboModuleTests) {
TEST_METHOD(ExecuteSampleTurboModule) {
ReactNativeHost host{};
auto queueController = winrt::Windows::System::DispatcherQueueController::CreateOnDedicatedThread();
queueController.DispatcherQueue().TryEnqueue([&]() noexcept {
host.PackageProviders().Append(winrt::make<SampleTurboModulePackageProvider>());
// bundle is assumed to be co-located with the test binary
wchar_t testBinaryPath[MAX_PATH];
TestCheck(GetModuleFileNameW(NULL, testBinaryPath, MAX_PATH) < MAX_PATH);
testBinaryPath[std::wstring_view{testBinaryPath}.rfind(L"\\")] = 0;
host.InstanceSettings().BundleRootPath(testBinaryPath);
host.InstanceSettings().JavaScriptBundleFile(L"TurboModuleTests");
host.InstanceSettings().UseDeveloperSupport(false);
host.InstanceSettings().UseWebDebugger(false);
host.InstanceSettings().UseFastRefresh(false);
host.InstanceSettings().UseLiveReload(false);
host.InstanceSettings().EnableDeveloperMenu(false);
host.LoadInstance();
});
TestCheckEqual(true, SampleTurboModule::succeededSignal.get_future().get());
TestCheckEqual("something, 1, true", SampleTurboModule::promiseFunctionSignal.get_future().get());
TestCheckEqual("something, 2, false", SampleTurboModule::syncFunctionSignal.get_future().get());
TestCheckEqual("constantString, 3, Hello, 10", SampleTurboModule::constantsSignal.get_future().get());
TestCheckEqual(3, SampleTurboModule::oneCallbackSignal.get_future().get());
TestCheckEqual(123, SampleTurboModule::twoCallbacksResolvedSignal.get_future().get());
TestCheckEqual("Failed", SampleTurboModule::twoCallbacksRejectedSignal.get_future().get());
host.UnloadInstance().get();
queueController.ShutdownQueueAsync().get();
}
};
} // namespace ReactNativeIntegrationTests
| 42.580189 | 119 | 0.713305 | harinikmsft |
16767a771591a5d8a76020a00e589ef65359e441 | 33,346 | cpp | C++ | s32v234_sdk/libs/apexcv_pro/orb/src/apexcv_pro_orb.cpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/apexcv_pro/orb/src/apexcv_pro_orb.cpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/apexcv_pro/orb/src/apexcv_pro_orb.cpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | 2 | 2021-01-21T02:06:16.000Z | 2021-01-28T10:47:37.000Z | /*******************************************************************************
*
* NXP Confidential Proprietary
*
* Copyright (c) 2016-2017 NXP Semiconductor;
* All Rights Reserved
*
*******************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP OR ITS 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 <oal.h>
#include <algorithm>
#include <vector>
#include "apexcv_pro_orb.h"
#include "apexcv_pro_fast.h"
#include <APU_ORB_RBRIEF.hpp>
#include <APU_ORB_ORIENTATION.hpp>
/* This is the standardized sampling pattern for Orb, this will work with descriptor
* sizes of a maximum 256 bits
* If bigger descriptors are needed plese generate a new sampling pattern and plug-it into
* APEX.
* https://github.com/opencv/opencv/blob/master/modules/features2d/src/orb.cpp :: line 375
*/
static int8_t samplingPattern[1024] =
{
8, -3, 9, 5, 4, 2, 7, -12, -11, 9, -8, 2, 7, -12, 12, -13,
2, -13, 2, 12, 1, -7, 1, 6, -2, -10, -2, -4, -13, -13, -11, -8,
-13, -3, -12, -9, 10, 4, 11, 9, -13, -8, -8, -9, -11, 7, -9, 12,
7, 7, 12, 6, -4, -5, -3, 0, -13, 2, -12, -3, -9, 0, -7, 5,
12, -6, 12, -1, -3, 6, -2, 12, -6, -13, -4, -8, 11, -13, 12, -8,
4, 7, 5, 1, 5, -3, 10, -3, 3, -7, 6, 12, -8, -7, -6, -2,
-2, 11, -1, -10, -13, 12, -8, 10, -7, 3, -5, -3, -4, 2, -3, 7,
-10, -12, -6, 11, 5, -12, 6, -7, 5, -6, 7, -1, 1, 0, 4, -5,
9, 11, 11, -13, 4, 7, 4, 12, 2, -1, 4, 4, -4, -12, -2, 7,
-8, -5, -7, -10, 4, 11, 9, 12, 0, -8, 1, -13, -13, -2, -8, 2,
-3, -2, -2, 3, -6, 9, -4, -9, 8, 12, 10, 7, 0, 9, 1, 3,
7, -5, 11, -10, -13, -6, -11, 0, 10, 7, 12, 1, -6, -3, -6, 12,
10, -9, 12, -4, -13, 8, -8, -12, -13, 0, -8, -4, 3, 3, 7, 8,
5, 7, 10, -7, -1, 7, 1, -12, 3, -10, 5, 6, 2, -4, 3, -10,
-13, 0, -13, 5, -13, -7, -12, 12, -13, 3, -11, 8, -7, 12, -4, 7,
6, -10, 12, 8, -9, -1, -7, -6, -2, -5, 0, 12, -12, 5, -7, 5,
3, -10, 8, -13, -7, -7, -4, 5, -3, -2, -1, -7, 2, 9, 5, -11,
-11, -13, -5, -13, -1, 6, 0, -1, 5, -3, 5, 2, -4, -13, -4, 12,
-9, -6, -9, 6, -12, -10, -8, -4, 10, 2, 12, -3, 7, 12, 12, 12,
-7, -13, -6, 5, -4, 9, -3, 4, 7, -1, 12, 2, -7, 6, -5, 1,
-13, 11, -12, 5, -3, 7, -2, -6, 7, -8, 12, -7, -13, -7, -11, -12,
1, -3, 12, 12, 2, -6, 3, 0, -4, 3, -2, -13, -1, -13, 1, 9,
7, 1, 8, -6, 1, -1, 3, 12, 9, 1, 12, 6, -1, -9, -1, 3,
-13, -13, -10, 5, 7, 7, 10, 12, 12, -5, 12, 9, 6, 3, 7, 11,
5, -13, 6, 10, 2, -12, 2, 3, 3, 8, 4, -6, 2, 6, 12, -13,
9, -12, 10, 3, -8, 4, -7, 9, -11, 12, -4, -6, 1, 12, 2, -8,
6, -9, 7, -4, 2, 3, 3, -2, 6, 3, 11, 0, 3, -3, 8, -8,
7, 8, 9, 3, -11, -5, -6, -4, -10, 11, -5, 10, -5, -8, -3, 12,
-10, 5, -9, 0, 8, -1, 12, -6, 4, -6, 6, -11, -10, 12, -8, 7,
4, -2, 6, 7, -2, 0, -2, 12, -5, -8, -5, 2, 7, -6, 10, 12,
-9, -13, -8, -8, -5, -13, -5, -2, 8, -8, 9, -13, -9, -11, -9, 0,
1, -8, 1, -2, 7, -4, 9, 1, -2, 1, -1, -4, 11, -6, 12, -11,
-12, -9, -6, 4, 3, 7, 7, 12, 5, 5, 10, 8, 0, -4, 2, 8,
-9, 12, -5, -13, 0, 7, 2, 12, -1, 2, 1, 7, 5, 11, 7, -9,
3, 5, 6, -8, -13, -4, -8, 9, -5, 9, -3, -3, -4, -7, -3, -12,
6, 5, 8, 0, -7, 6, -6, 12, -13, 6, -5, -2, 1, -10, 3, 10,
4, 1, 8, -4, -2, -2, 2, -13, 2, -12, 12, 12, -2, -13, 0, -6,
4, 1, 9, 3, -6, -10, -3, -5, -3, -13, -1, 1, 7, 5, 12, -11,
4, -2, 5, -7, -13, 9, -9, -5, 7, 1, 8, 6, 7, -8, 7, 6,
-7, -4, -7, 1, -8, 11, -7, -8, -13, 6, -12, -8, 2, 4, 3, 9,
10, -5, 12, 3, -6, -5, -6, 7, 8, -3, 9, -8, 2, -12, 2, 8,
-11, -2, -10, 3, -12, -13, -7, -9, -11, 0, -10, -5, 5, -3, 11, 8,
-2, -13, -1, 12, -1, -8, 0, 9, -13, -11, -12, -5, -10, -2, -10, 11,
-3, 9, -2, -13, 2, -3, 3, 2, -9, -13, -4, 0, -4, 6, -3, -10,
-4, 12, -2, -7, -6, -11, -4, 9, 6, -3, 6, 11, -13, 11, -5, 5,
11, 11, 12, 6, 7, -5, 12, -2, -1, 12, 0, 7, -4, -8, -3, -2,
-7, 1, -6, 7, -13, -12, -8, -13, -7, -2, -6, -8, -8, 5, -6, -9,
-5, -1, -4, 5, -13, 7, -8, 10, 1, 5, 5, -13, 1, 0, 10, -13,
9, 12, 10, -1, 5, -8, 10, -9, -1, 11, 1, -13, -9, -3, -6, 2,
-1, -10, 1, 12, -13, 1, -8, -10, 8, -11, 10, -6, 2, -13, 3, -6,
7, -13, 12, -9, -10, -10, -5, -7, -10, -8, -8, -13, 4, -6, 8, 5,
3, 12, 8, -13, -4, 2, -3, -3, 5, -13, 10, -12, 4, -13, 5, -1,
-9, 9, -4, 3, 0, 3, 3, -9, -12, 1, -6, 1, 3, 2, 4, -8,
-10, -10, -10, 9, 8, -13, 12, 12, -8, -12, -6, -5, 2, 2, 3, 7,
10, 6, 11, -8, 6, 8, 8, -12, -7, 10, -6, 5, -3, -9, -3, 9,
-1, -13, -1, 5, -3, -7, -3, 4, -8, -2, -8, 3, 4, 2, 12, 12,
2, -5, 3, 11, 6, -9, 11, -13, 3, -1, 7, 12, 11, -1, 12, 4,
-3, 0, -3, 6, 4, -11, 4, 12, 2, -4, 2, 1, -10, -6, -8, 1,
-13, 7, -11, 1, -13, 12, -11, -13, 6, 0, 11, -13, 0, -1, 1, 4,
-13, 3, -9, -2, -9, 8, -6, -3, -13, -6, -8, -2, 5, -9, 8, 10,
2, 7, 3, -9, -1, -6, -1, -1, 9, 5, 11, -2, 11, -3, 12, -8,
3, 0, 3, 5, -1, 4, 0, 10, 3, -6, 4, 5, -13, 0, -10, 5,
5, 8, 12, 11, 8, 9, 9, -6, 7, -4, 8, -12, -10, 4, -10, 9,
7, 3, 12, 4, 9, -7, 10, -2, 7, 0, 12, -2, -1, -6, 0, -11};
namespace apexcv
{
// Helper function used to sort the keypoints
static bool CmpGreaterFeature(Orb::Corner aLeft, Orb::Corner aRight)
{
return(aLeft.strength > aRight.strength);
}
static inline void flushUMat(vsdk::SUMat& aTarget)
{
// Helper function used to flush the cache data into the DDR
uint8_t * pData = (uint8_t *)aTarget.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
int size = (int)(aTarget.total() * aTarget.elemSize());
OAL_MemoryFlushAndInvalidate((void *)pData, size);
return;
}
// Helper function that calculates Harris corner metric
float
HarrisScore(uint8_t *__restrict__ apCenter,
int aStep,
const int acBlockSize,
const float acHarrisK)
{
const int radius = (acBlockSize >> 1);
const float scale = 1.0f / ((1 << 2) * acBlockSize * 255.f);
const float sclPow2 = scale * scale;
const float sclPow4 = (sclPow2 * sclPow2);
register int a = 0, b = 0, c = 0;
for(int y = -radius; y < radius; y++)
{
// Point to the center of the image row
const uint8_t *__restrict__ pStartRow = (uint8_t * __restrict__) & apCenter[y * aStep];
for(int x = -radius; x < radius; x++)
{
// Row access
const uint8_t *__restrict__ ptr = (const uint8_t * __restrict__) & pStartRow[x];
// Compute dx and dy
// Data from first line
int mat00 = ptr[-aStep - 1];
int mat01 = ptr[-aStep + 0];
int mat02 = ptr[-aStep + 1];
// Data from the second line
int mat10 = ptr[-1];
int mat12 = ptr[+1];
// Data from the third line
int mat20 = ptr[aStep - 1];
int mat21 = ptr[aStep + 0];
int mat22 = ptr[aStep + 1];
// Image derivative for both x and y
int dx = (mat02 - mat00) + 2 * (mat12 - mat10) + (mat22 - mat20);
int dy = (mat20 - mat00) + 2 * (mat21 - mat01) + (mat22 - mat02);
// Compute the products of the derivation at each pixel
a += (dx * dx);
b += (dy * dy);
c += (dx * dy);
}
}
// H(x, y) = | Sx*x(x, y) Sx*y(x, y) | in our code = | a c |
// | Sy*x(x, y) Sy*y(x, y) | | c b |
// Harris Cornerness = Det(H) - k * trace(H) ^ 2
float score = ((float)a * b - (float)c * c - acHarrisK * ((float)a + b) * ((float)a + b)) * sclPow4;
// Return the Harris Corner Metric
return score;
}
APEXCV_LIB_RESULT CalcChunkOffsets(vsdk::SUMat &aInputImg, std::vector<Orb::Corner> &aKeypoints, int aNrOfkeypoints, int aPatchSize, vsdk::SUMat &aChunkOffsets)
{
// Each keypoint is place inside a chunk
// This helper function calculate the offset in bytes inside the image for each chunk
uint16_t span = aInputImg.step[0];
uint16_t halfPatch = aPatchSize >> 1;
int32_t *pChunkOffset = (int32_t *)aChunkOffsets.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
int32_t sizeBytes = aChunkOffsets.total() * aChunkOffsets.elemSize();
// Clear the buffer
memset((uint8_t *)pChunkOffset, 0, sizeBytes);
// Basic error checks
if(aPatchSize <= 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aNrOfkeypoints <= 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aKeypoints.size() == 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
// Loop all the keypoints
for(int kpntId = 0; kpntId < aNrOfkeypoints; kpntId++)
{
// Read the <x, y> coordinates of the keypoints
Orb::Corner data = aKeypoints[kpntId];
// Calculate the offset in bytes for the keypoint
uint16_t x = data.x;
uint16_t y = data.y;
uint16_t newX = (x - halfPatch);
uint16_t newY = (y - halfPatch);
int32_t offset = newX + newY * span;
pChunkOffset[kpntId] = offset;
}
OAL_MemoryFlushAndInvalidate((void *)pChunkOffset, sizeBytes);
return APEXCV_SUCCESS;
}
Orb::Orb() :
mpChunkOffsets(nullptr),
mpAngles(nullptr),
mpDescriptorCount(nullptr),
mpBinPatternOut(nullptr),
mInit(false),
mpProcessCalcOrientation(nullptr),
mpProcessCalcRbrief(nullptr)
{
}
Orb::~Orb()
{
// Class destructor
if(NULL != mpProcessCalcRbrief)
{
delete[] (APU_ORB_RBRIEF *) mpProcessCalcRbrief;
}
if (NULL != mpProcessCalcOrientation)
{
delete[](APU_ORB_ORIENTATION *) mpProcessCalcOrientation;
}
if (NULL != mpBinPatternOut)
{
delete[] mpBinPatternOut;
}
if (NULL != mpDescriptorCount)
{
delete[] mpDescriptorCount;
}
if (NULL != mpAngles)
{
delete[] mpAngles;
}
if (NULL != mpChunkOffsets)
{
delete[] mpChunkOffsets;
}
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
APEXCV_LIB_RESULT Orb::Create(unsigned char aApexId,
unsigned char aNrOfThreads,
unsigned int aBorderSize,
unsigned int aPatchSize,
unsigned int aRadius,
unsigned int aDescriptorSizeInBytes,
unsigned int aFastCircumference,
unsigned int aFastThreshold,
float aHarrisK,
unsigned int aNrOfKeypoints)
{
// Basic error checks
if(mInit != false)
{
return APEXCV_ERROR_OBJECT_ALREADY_INITIALIZED;
}
if(aBorderSize < aRadius)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aPatchSize < (2 * aRadius))
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aDescriptorSizeInBytes == 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aNrOfKeypoints == 0)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aNrOfThreads > 2)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(aApexId >= 2)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
APEXCV_LIB_RESULT status;
const int pairXY = 2;
const int nrOfPairsForComparison = 2;
const int smpltPtrnApexDmaBytes = 2048;
const int maxNrOfKeypoints = FAST_MAX_LIST_ELEMENTS;
// Class parameters
mApexId = aApexId;
mNrOfThreads = aNrOfThreads;
mDistanceFromBorder = aBorderSize;
mFastCirc = aFastCircumference;
mFastTh = aFastThreshold;
mHarrisK = aHarrisK;
mNrOfFeatures = aNrOfKeypoints;
int descriptorSizeInBits = aDescriptorSizeInBytes * 8;
int samplingPoints = descriptorSizeInBits * nrOfPairsForComparison * pairXY;
// Allocate the buffer to maximum
// The sampling buffer is tagged as static_fixed inside the ACF
msmplBitPattern = vsdk::SUMat(1, smpltPtrnApexDmaBytes, VSDK_CV_8SC1);
if (!msmplBitPattern.empty())
{
// Fill-in the buffer that APEX will "see" as the sampling bit pattern
int8_t * pData = (int8_t *)msmplBitPattern.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
// Clear the buffer
memset(pData, 0, smpltPtrnApexDmaBytes);
for (int idx = 0; idx < samplingPoints; idx++)
{
pData[idx] = samplingPattern[idx];
}
}
// Dynamic allocation of APU processes
APU_ORB_ORIENTATION * pProcessCalcOrientation = new APU_ORB_ORIENTATION[mNrOfThreads];
if(NULL == pProcessCalcOrientation)
{
return APEXCV_ERROR_MEMORY_ALLOCATION_FAILED;
}
// Store to the class variables
mpProcessCalcOrientation = (void *) pProcessCalcOrientation;
{
for(int32_t i=0;i<mNrOfThreads;i++)
{
ApexcvHostBaseBaseClass::InfoCluster lInfo;
char lTemp[50];
sprintf(lTemp, "%s_THREAD[%d]","APU_ORB_ORIENTATION",i);
lInfo.set_ACF(lTemp, (void*) &pProcessCalcOrientation[i]);
lInfo.push_PortName("INPUT");
mvInfoClusters.push_back(lInfo);
}
}
APU_ORB_RBRIEF * pProcessCalcRbrief = new APU_ORB_RBRIEF[mNrOfThreads];
if(NULL == pProcessCalcRbrief)
{
return APEXCV_ERROR_MEMORY_ALLOCATION_FAILED;
}
// Store to the class variables
mpProcessCalcRbrief = (void *) pProcessCalcRbrief;
{
for(int32_t i=0;i<mNrOfThreads;i++)
{
ApexcvHostBaseBaseClass::InfoCluster lInfo;
char lTemp[50];
sprintf(lTemp, "%s_THREAD[%d]","APU_ORB_RBRIEF",i);
lInfo.set_ACF(lTemp, (void *) &pProcessCalcRbrief[i]);
lInfo.push_PortName("INPUT");
mvInfoClusters.push_back(lInfo);
}
}
// Dynamic allocation of the data structures linked to the parallel processes
mpChunkOffsets = new vsdk::SUMat[mNrOfThreads];
mpAngles = new vsdk::SUMat[mNrOfThreads];
mpDescriptorCount = new vsdk::SUMat[mNrOfThreads];
mpBinPatternOut = new vsdk::SUMat[mNrOfThreads];
// Allocating memory and filling in the parameters that will be sent to APEX
mPatchSizeInPixels = vsdk::SUMat(1, 1, VSDK_CV_8SC1);
mRadiusInPixels = vsdk::SUMat(1, 1, VSDK_CV_8SC1);
mDescrSizeBytes = vsdk::SUMat(1, 1, VSDK_CV_8SC1);
mFastCornerList = vsdk::SUMat(1, maxNrOfKeypoints, VSDK_CV_32SC1);
mDescrSizeBytes.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u) = (int8_t)aDescriptorSizeInBytes;
flushUMat(mDescrSizeBytes);
mRadiusInPixels.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u) = (int8_t)aRadius;
flushUMat(mRadiusInPixels);
mPatchSizeInPixels.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u) = (int8_t)aPatchSize;
flushUMat(mPatchSizeInPixels);
// Splitting the work between the APEXes
int nrOfElements = mNrOfFeatures / mNrOfThreads;
int descrSizeInBytes = (int)(mDescrSizeBytes.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u));
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
mpChunkOffsets[threadId] = vsdk::SUMat(1, nrOfElements, VSDK_CV_32SC1);
mpAngles[threadId] = vsdk::SUMat(1, nrOfElements, VSDK_CV_16UC1);
mpDescriptorCount[threadId] = vsdk::SUMat(1, 1, VSDK_CV_32SC1);
mpBinPatternOut[threadId] = vsdk::SUMat(1, nrOfElements * descrSizeInBytes, VSDK_CV_8UC1);
// IC Orientation Initialization
status = pProcessCalcOrientation[threadId].Initialize();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// Connecting the external buffers to the kernel graphs
status = pProcessCalcOrientation[threadId].ConnectIO("PATCH_SIZE", mPatchSizeInPixels);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Connecting the external buffers to the kernel graphs
status = pProcessCalcOrientation[threadId].ConnectIO("RADIUS", mRadiusInPixels);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Connecting the external buffers to the kernel graphs
status = pProcessCalcOrientation[threadId].ConnectIO("OUTPUT", mpAngles[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Initializing the Rotated Brief for APEX
status = pProcessCalcRbrief[threadId].Initialize();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// BIT_PATTERN - Connecting the sampling pattern to the APEX
// This buffer will indicate to the hw what samples to pick from the input chunk
status = pProcessCalcRbrief[threadId].ConnectIO("BIT_PATTERN", msmplBitPattern);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// ORIENTATION - Connecting the orientation of each chunk to the APEX
status = pProcessCalcRbrief[threadId].ConnectIO("ORIENTATION", mpAngles[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// PATCH_SIZE - Connecting the dimension of the patch
status = pProcessCalcRbrief[threadId].ConnectIO("PATCH_SIZE", mPatchSizeInPixels);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// PATCH_SIZE - Connecting the size of the descriptor in bytes
status = pProcessCalcRbrief[threadId].ConnectIO("DESCR_SIZE_B", mDescrSizeBytes);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// COUNT_DESCR - Connecting the number of output descriptors
status = pProcessCalcRbrief[threadId].ConnectIO("COUNT_DESCR", mpDescriptorCount[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
}
// Class is initialized correctly only if the code arrives at this point
mInit = true;
// Everythig is fine until this point
return APEXCV_SUCCESS;
}
APEXCV_LIB_RESULT Orb::Detect(vsdk::SUMat &aInImg)
{
APEXCV_LIB_RESULT status = EXIT_FAILURE;
mInGrayScale = aInImg;
mImgW = aInImg.cols;
mImgH = aInImg.rows;
mImgSpan = aInImg.step[0];
unsigned char *lpBaseImg = aInImg.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
int patchSize;
if(!mPatchSizeInPixels.empty())
{
patchSize = (int)(*((int8_t *)mPatchSizeInPixels.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data));
}
else
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
if(mDistanceFromBorder >= (unsigned int)aInImg.cols)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
if(mDistanceFromBorder >= (unsigned int)aInImg.rows)
{
return APEXCV_ERROR_INVALID_ARGUMENT;
}
// Initializing Fast9 detector
status = mFast9.Initialize(mFastCornerList,
aInImg,
mFastTh,
false,
mFastCirc,
true);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// Configure APEX to run with 64 CUs
status = mFast9.SelectApuConfiguration(ACF_APU_CFG__APU_0_CU_0_63_SMEM_0_3, mApexId);
if(status != APEXCV_SUCCESS)
{
return status;
}
// Start crunching the data in the APEX
status = mFast9.Process();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
// Return the number of detected keypoints
mDetectedKeypoints = mFast9.GetNrOfFeatures();
// mDetectedKeypoints is to allocate intermediate buffers so it needs to exit
if(mDetectedKeypoints == 0)
{
return APEXCV_SUCCESS;
}
if(mDetectedKeypoints < 0)
{
// This is the special case when FAST9 has an internal error when running in serialize mode!
// Check FAST9 APU kernel code to see the status!
printf("Fast9 went crazy !\n Status is: %d\n", mDetectedKeypoints);
return APEXCV_ERROR_FAILURE;
}
APU_ORB_ORIENTATION * pProcessCalcOrientation = (APU_ORB_ORIENTATION *) mpProcessCalcOrientation;
// FAST9 outputs a list of coordinates in the form of <x, y>
uint16_t *pOutPackedList = (uint16_t *)(mFastCornerList.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data);
// Constant value
const int harrisWindowSize = 7;
const int pair = 2;
// The keypoint array is not sorted at the beginning
bool isSorted = false;
for(int idx = 0; idx < mDetectedKeypoints; idx++)
{
// Read the keypoint coordinates
unsigned int x = pOutPackedList[pair * idx + 0];
unsigned int y = pOutPackedList[pair * idx + 1];
// Filter out the keypoints that are outside of the borderline
if((x > mDistanceFromBorder) &&
(y > mDistanceFromBorder) &&
(x < (mImgW - mDistanceFromBorder)) &&
(y < (mImgH - mDistanceFromBorder)))
{
// Place the pointer to the center of the keypoint
uint8_t *__restrict__ pCenter = (uint8_t * __restrict__) & lpBaseImg[y * mImgSpan + x];
// This variable will be inserted in the keypoint array
Orb::Corner keypoint;
keypoint.x = x;
keypoint.y = y;
keypoint.strength = HarrisScore(pCenter, mImgSpan, harrisWindowSize, mHarrisK);
// Don't keep more keypoints than you need
if(mKeypoints.size() < mNrOfFeatures)
{
// Place the values into the vector in no particular order
mKeypoints.push_back(keypoint);
}
else
{
// "mKeypoints" is sorted only once when its size is equal to the desired nr of mKeypoints
if(isSorted == false)
{
// Sort the mKeypoints
std::sort(mKeypoints.begin(), mKeypoints.end(), CmpGreaterFeature);
isSorted = true;
}
// The new keypoint is compared to the last element in the vector which is also the smallest
// It's insert in the queue only if CmpGreaterFeature() returns bool true
if(CmpGreaterFeature(keypoint, mKeypoints.back()))
{
// Remove the last element
mKeypoints.pop_back();
// Place the new element in the vector
mKeypoints.insert(std::lower_bound(mKeypoints.begin(), mKeypoints.end(), keypoint, CmpGreaterFeature), keypoint);
}
}
}
}
// If fast detects a keypoint, find it's corresponding "cornerness" from Harris
// Orb needs the best FAST points based on the Harris score
// Sort only if fast did not find enough mKeypoints
if(isSorted == false)
{
std::sort(mKeypoints.begin(), mKeypoints.end(), CmpGreaterFeature);
}
// After detection update the number of keypoints
mNrOfFeatures = mKeypoints.size();
if(0 == mNrOfFeatures)
{
return APEXCV_SUCCESS;
}
// Calculate chunk offsets
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
ACF_APU_CFG apuConfig = ACF_APU_CFG__APU_0_CU_0_31_SMEM_0_1;
if(threadId)
{
apuConfig = ACF_APU_CFG__APU_1_CU_32_63_SMEM_2_3;
}
// Creating a subvector of keypoints for each APU
int nrOfElem = (mNrOfFeatures / mNrOfThreads);
int start = threadId * nrOfElem;
int stop = start + nrOfElem;
std::vector<Orb::Corner> keypointSubVector(mKeypoints.begin() + start, mKeypoints.begin() + stop);
// Calculating the chunk offsets for each of the detected keypoints
status = CalcChunkOffsets(mInGrayScale, keypointSubVector, nrOfElem, patchSize, mpChunkOffsets[threadId]);
// Exit with error
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_INTERNAL_ERROR;
}
// APUs must run only with 32 active CUs because of DMA size
status = pProcessCalcOrientation[threadId].SelectApuConfiguration(apuConfig, (int32_t) mApexId);
// Exit with error
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_SELECTAPUCONFIG;
}
status = pProcessCalcOrientation[threadId].ConnectIndirectInput("INPUT", aInImg, mpChunkOffsets[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
// Start all processes
status = pProcessCalcOrientation[threadId].Start();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Wait for the APU processes to finish
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
status = pProcessCalcOrientation[threadId].Wait();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Exit the function
return APEXCV_SUCCESS;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
APEXCV_LIB_RESULT Orb::SetBriefSamplingPattern(vsdk::SUMat &aInBitPattern)
{
// Helper function used to connect the sampling pattern to the apex graph
if(mInit == true)
{
APEXCV_LIB_RESULT status;
APU_ORB_RBRIEF * pProcessCalcRbrief = (APU_ORB_RBRIEF *) mpProcessCalcRbrief;
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
status = pProcessCalcRbrief[threadId].ConnectIO("BIT_PATTERN", aInBitPattern);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
}
}
else
{
// Exit with error
return APEXCV_ERROR_OBJECT_ISNOT_INITIALIZED;
}
// Exit the function
return APEXCV_SUCCESS;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
APEXCV_LIB_RESULT Orb::Compute(vsdk::SUMat &aInSmoothedImg,
vsdk::SUMat &aOutDescriptors)
{
APEXCV_LIB_RESULT status;
APU_ORB_RBRIEF * pProcessCalcRbrief = (APU_ORB_RBRIEF *) mpProcessCalcRbrief;
if ((0 == mNrOfFeatures) || (0 == mDetectedKeypoints))
{
return APEXCV_SUCCESS;
}
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
ACF_APU_CFG apuConfig = ACF_APU_CFG__APU_0_CU_0_31_SMEM_0_1;
if(threadId)
{
apuConfig = ACF_APU_CFG__APU_1_CU_32_63_SMEM_2_3;
}
status = pProcessCalcRbrief[threadId].ConnectIndirectInput("INPUT", aInSmoothedImg, mpChunkOffsets[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
status = pProcessCalcRbrief[threadId].ConnectIO("OUTPUT", mpBinPatternOut[threadId]);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_CONNECTIO;
}
status = pProcessCalcRbrief[threadId].SelectApuConfiguration(apuConfig, (int32_t)mApexId);
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_SELECTAPUCONFIG;
}
status = pProcessCalcRbrief[threadId].Start();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Wait for the APU processes to finish
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
status = pProcessCalcRbrief[threadId].Wait();
if(status != APEXCV_SUCCESS)
{
return APEXCV_ERROR_ACF_PROC_EXEC;
}
}
// Pointing to the base of the output container
uint8_t *pBase = (uint8_t *)aOutDescriptors.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
// Calculating the necessary offset to jump between thread output clusters
int descrSizeB = (int)(mDescrSizeBytes.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).at<int8_t>(0u));
int nrDescrToCopy = (mNrOfFeatures / mNrOfThreads);
int clusterSizeB = (descrSizeB * nrDescrToCopy);
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
uint8_t *pDst = (uint8_t *)(pBase + threadId * clusterSizeB);
uint8_t *pSrc = (uint8_t *)mpBinPatternOut[threadId].getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
memcpy(pDst, pSrc, clusterSizeB);
}
// Everything is fine until here
return APEXCV_SUCCESS;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetPatchSize()
{
return mPatchSizeInPixels;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetRadius()
{
return mRadiusInPixels;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetFastOut()
{
return mFastCornerList;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
int Orb::GetNrOfDetectedKeypoints()
{
return mDetectedKeypoints;
}
int Orb::GetNrOfValidKeypoints()
{
return mNrOfFeatures;
}
bool Orb::DataIsValid()
{
return ((mNrOfFeatures != 0) && (mDetectedKeypoints != 0));
}
vsdk::SUMat &Orb::GetChunkOffsets()
{
if(DataIsValid() == true)
{
// Allocating the container
mAllChunkOffsets = vsdk::SUMat(1, mNrOfFeatures, VSDK_CV_32S);
// Pointing to the base of the container
uint8_t *pBaseDst = (uint8_t *)mAllChunkOffsets.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
// Size of the cluster
int clusterSizeB = (int)(mpChunkOffsets[threadId].total() * mpChunkOffsets[threadId].elemSize());
uint8_t *pSrc = (uint8_t *)mpChunkOffsets[threadId].getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
uint8_t *pDst = (uint8_t *)(pBaseDst + threadId * clusterSizeB);
memcpy(pDst, pSrc, clusterSizeB);
}
}
return mAllChunkOffsets;
}
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
vsdk::SUMat &Orb::GetIcoAngles()
{
if(DataIsValid() == true)
{
// Allocating the container
mAllAngles = vsdk::SUMat(1, mNrOfFeatures, VSDK_CV_16U);
// Pointing to the base of the container
uint8_t *pBaseDst = (uint8_t *)mAllAngles.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
for(int threadId = 0; threadId < mNrOfThreads; threadId++)
{
// Size of the cluster
int clusterSizeB = (int)(mpAngles[threadId].total() * mpAngles[threadId].elemSize());
uint8_t *pSrc = (uint8_t *)mpAngles[threadId].getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED).data;
OAL_MemoryFlushAndInvalidate((void *)pSrc, clusterSizeB);
uint8_t *pDst = (uint8_t *)(pBaseDst + threadId * clusterSizeB);
memcpy(pDst, pSrc, clusterSizeB);
}
}
return mAllAngles;
}
std::vector<Orb::Corner> &Orb::GetKeypoints()
{
return mKeypoints;
}
} /* namespace apexcv */
| 34.735417 | 162 | 0.55314 | intesight |
16782b280ef5d9a2ade28b1763bfa3d83086b2bd | 15,704 | cpp | C++ | src/main.cpp | HTLife/Logger2 | 0810e72b3b94eaf164ad98a70feae9ad80d61b79 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | HTLife/Logger2 | 0810e72b3b94eaf164ad98a70feae9ad80d61b79 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | HTLife/Logger2 | 0810e72b3b94eaf164ad98a70feae9ad80d61b79 | [
"BSD-2-Clause"
] | null | null | null | #include "main.h"
int find_argument(int argc, char** argv, const char* argument_name)
{
for(int i = 1; i < argc; ++i)
{
if(strcmp(argv[i], argument_name) == 0)
{
return (i);
}
}
return (-1);
}
int parse_argument(int argc, char** argv, const char* str, int &val)
{
int index = find_argument(argc, argv, str) + 1;
if(index > 0 && index < argc)
{
val = atoi(argv[index]);
}
return (index - 1);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
int width = 640;
int height = 480;
int fps = 30;
int tcp = 0;
parse_argument(argc, argv, "-w", width);
parse_argument(argc, argv, "-h", height);
parse_argument(argc, argv, "-f", fps);
tcp = find_argument(argc, argv, "-t") != -1;
MainWindow * window = new MainWindow(width, height, fps, tcp);
window->show();
return app.exec();
}
MainWindow::MainWindow(int width, int height, int fps, bool tcp)
: logger(0),
depthImage(width, height, QImage::Format_RGB888),
rgbImage(width, height, QImage::Format_RGB888),
recording(false),
lastDrawn(-1),
width(width),
height(height),
fps(fps),
tcp(tcp),
comms(tcp ? new Communicator : 0)
{
this->setMaximumSize(width * 2, height + 160);
this->setMinimumSize(width * 2, height + 160);
QVBoxLayout * wrapperLayout = new QVBoxLayout;
QHBoxLayout * mainLayout = new QHBoxLayout;
QHBoxLayout * fileLayout = new QHBoxLayout;
QHBoxLayout * optionLayout = new QHBoxLayout;
QHBoxLayout * buttonLayout = new QHBoxLayout;
wrapperLayout->addLayout(mainLayout);
depthLabel = new QLabel(this);
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
mainLayout->addWidget(depthLabel);
imageLabel = new QLabel(this);
imageLabel->setPixmap(QPixmap::fromImage(rgbImage));
mainLayout->addWidget(imageLabel);
wrapperLayout->addLayout(fileLayout);
wrapperLayout->addLayout(optionLayout);
QLabel * logLabel = new QLabel("Log file: ", this);
logLabel->setMaximumWidth(logLabel->fontMetrics().boundingRect(logLabel->text()).width());
fileLayout->addWidget(logLabel);
logFile = new QLabel(this);
logFile->setTextInteractionFlags(Qt::TextSelectableByMouse);
logFile->setStyleSheet("border: 1px solid grey");
fileLayout->addWidget(logFile);
#ifdef __APPLE__
int cushion = 25;
#else
int cushion = 10;
#endif
browseButton = new QPushButton("Browse", this);
browseButton->setMaximumWidth(browseButton->fontMetrics().boundingRect(browseButton->text()).width() + cushion);
connect(browseButton, SIGNAL(clicked()), this, SLOT(fileBrowse()));
fileLayout->addWidget(browseButton);
dateNameButton = new QPushButton("Date filename", this);
dateNameButton->setMaximumWidth(dateNameButton->fontMetrics().boundingRect(dateNameButton->text()).width() + cushion);
connect(dateNameButton, SIGNAL(clicked()), this, SLOT(dateFilename()));
fileLayout->addWidget(dateNameButton);
autoExposure = new QCheckBox("Auto Exposure");
autoExposure->setChecked(false);
autoWhiteBalance = new QCheckBox("Auto White Balance");
autoWhiteBalance->setChecked(false);
compressed = new QCheckBox("Compressed");
compressed->setChecked(true);
memoryRecord = new QCheckBox("Record to RAM");
memoryRecord->setChecked(false);
memoryStatus = new QLabel("");
connect(autoExposure, SIGNAL(stateChanged(int)), this, SLOT(setExposure()));
connect(autoWhiteBalance, SIGNAL(stateChanged(int)), this, SLOT(setWhiteBalance()));
connect(compressed, SIGNAL(released()), this, SLOT(setCompressed()));
connect(memoryRecord, SIGNAL(stateChanged(int)), this, SLOT(setMemoryRecord()));
optionLayout->addWidget(autoExposure);
optionLayout->addWidget(autoWhiteBalance);
optionLayout->addWidget(compressed);
optionLayout->addWidget(memoryRecord);
optionLayout->addWidget(memoryStatus);
wrapperLayout->addLayout(buttonLayout);
startStop = new QPushButton(tcp ? "Stream && Record" : "Record", this);
connect(startStop, SIGNAL(clicked()), this, SLOT(recordToggle()));
buttonLayout->addWidget(startStop);
QPushButton * quitButton = new QPushButton("Quit", this);
connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));
buttonLayout->addWidget(quitButton);
setLayout(wrapperLayout);
startStop->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
quitButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QFont currentFont = startStop->font();
currentFont.setPointSize(currentFont.pointSize() + 8);
startStop->setFont(currentFont);
quitButton->setFont(currentFont);
painter = new QPainter(&depthImage);
painter->setPen(Qt::green);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, "Attempting to start OpenNI2...");
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
#ifndef OS_WINDOWS
char * homeDir = getenv("HOME");
logFolder.append(homeDir);
logFolder.append("/");
#else
char * homeDrive = getenv("HOMEDRIVE");
char * homeDir = getenv("HOMEPATH");
logFolder.append(homeDrive);
logFolder.append("\\");
logFolder.append(homeDir);
logFolder.append("\\");
#endif
logFolder.append("Kinect_Logs");
boost::filesystem::path p(logFolder.c_str());
boost::filesystem::create_directory(p);
logFile->setText(QString::fromStdString(getNextFilename()));
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timerCallback()));
timer->start(15);
}
MainWindow::~MainWindow()
{
timer->stop();
delete logger;
}
std::string MainWindow::getNextFilename()
{
static char const* const fmt = "%Y-%m-%d";
std::ostringstream ss;
ss.imbue(std::locale(std::cout.getloc(), new boost::gregorian::date_facet(fmt)));
ss << boost::gregorian::day_clock::universal_day();
std::string dateFilename;
if(!lastFilename.length())
{
dateFilename = ss.str();
}
else
{
dateFilename = lastFilename;
}
std::string currentFile;
int currentNum = 0;
while(true)
{
std::stringstream strs;
strs << logFolder;
#ifndef OS_WINDOWS
strs << "/";
#else
strs << "\\";
#endif
strs << dateFilename << ".";
strs << std::setfill('0') << std::setw(2) << currentNum;
strs << ".klg";
if(!boost::filesystem::exists(strs.str().c_str()))
{
return strs.str();
}
currentNum++;
}
return "";
}
void MainWindow::dateFilename()
{
lastFilename.clear();
logFile->setText(QString::fromStdString(getNextFilename()));
}
void MainWindow::fileBrowse()
{
QString message = "Log file selection";
QString types = "All files (*)";
QString fileName = QFileDialog::getSaveFileName(this, message, ".", types);
if(!fileName.isEmpty())
{
if(!fileName.contains(".klg", Qt::CaseInsensitive))
{
fileName.append(".klg");
}
#ifndef OS_WINDOWS
logFolder = fileName.toStdString().substr(0, fileName.toStdString().rfind("/"));
lastFilename = fileName.toStdString().substr(fileName.toStdString().rfind("/") + 1, fileName.toStdString().rfind(".klg"));
#else
logFolder = fileName.toStdString().substr(0, fileName.toStdString().rfind("\\"));
lastFilename = fileName.toStdString().substr(fileName.toStdString().rfind("\\") + 1, fileName.toStdString().rfind(".klg"));
#endif
lastFilename = lastFilename.substr(0, lastFilename.size() - 4);
logFile->setText(QString::fromStdString(getNextFilename()));
}
}
void MainWindow::recordToggle()
{
if(!recording)
{
if(logFile->text().length() == 0)
{
QMessageBox::information(this, "Information", "You have not selected an output log file");
}
else
{
memoryRecord->setEnabled(false);
compressed->setEnabled(false);
logger->startWriting(logFile->text().toStdString());
startStop->setText("Stop");
recording = true;
}
}
else
{
logger->stopWriting(this);
memoryRecord->setEnabled(true);
compressed->setEnabled(true);
startStop->setText(tcp ? "Stream && Record" : "Record");
recording = false;
logFile->setText(QString::fromStdString(getNextFilename()));
}
}
void MainWindow::setExposure()
{
logger->getOpenNI2Interface()->setAutoExposure(autoExposure->isChecked());
}
void MainWindow::setWhiteBalance()
{
logger->getOpenNI2Interface()->setAutoWhiteBalance(autoWhiteBalance->isChecked());
}
void MainWindow::setCompressed()
{
if(compressed->isChecked())
{
logger->setCompressed(compressed->isChecked());
}
else if(!compressed->isChecked())
{
if(QMessageBox::question(this, "Compression?", "If you don't have a fast machine or an SSD hard drive you might drop frames, are you sure?", "&No", "&Yes", QString::null, 0, 1 ))
{
logger->setCompressed(compressed->isChecked());
}
else
{
compressed->setChecked(true);
logger->setCompressed(compressed->isChecked());
}
}
}
void MainWindow::setMemoryRecord()
{
logger->setMemoryRecord(memoryRecord->isChecked());
}
void MainWindow::quit()
{
if(QMessageBox::question(this, "Quit?", "Are you sure you want to quit?", "&No", "&Yes", QString::null, 0, 1 ))
{
if(recording)
{
recordToggle();
}
this->close();
}
}
void MainWindow::timerCallback()
{
int64_t usedMemory = MemoryBuffer::getUsedSystemMemory();
int64_t totalMemory = MemoryBuffer::getTotalSystemMemory();
int64_t processMemory = MemoryBuffer::getProcessMemory();
float usedGB = (usedMemory / (float)1073741824);
float totalGB = (totalMemory / (float)1073741824);
#ifdef __APPLE__
float processGB = (processMemory / (float)1073741824);
#else
float processGB = (processMemory / (float)1048576);
#endif
QString memoryInfo = QString::number(usedGB, 'f', 2) + "/" + QString::number(totalGB, 'f', 2) + "GB memory used, " + QString::number(processGB, 'f', 2) + "GB by Logger2";
memoryStatus->setText(memoryInfo);
if(!logger)
{
if(frameStats.size() >= 15)
{
logger = new Logger2(width, height, fps, tcp, this->logFolder);
if(!logger->getOpenNI2Interface()->ok())
{
memset(depthImage.bits(), 0, width * height * 3);
painter->setPen(Qt::red);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, "Attempting to start OpenNI2... failed!");
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
QMessageBox msgBox;
msgBox.setText("Sorry, OpenNI2 is having trouble (it's still in beta). Please try running Logger2 again.");
msgBox.setDetailedText(QString::fromStdString(logger->getOpenNI2Interface()->error()));
msgBox.exec();
exit(-1);
}
else
{
memset(depthImage.bits(), 0, width * height * 3);
painter->setPen(Qt::green);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, "Starting stream...");
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
}
return;
}
else
{
frameStats.push_back(0);
return;
}
}
int lastDepth = logger->getOpenNI2Interface()->latestDepthIndex.getValue();
if(lastDepth == -1)
{
return;
}
int bufferIndex = lastDepth % OpenNI2Interface::numBuffers;
if(bufferIndex == lastDrawn)
{
return;
}
if(lastFrameTime == logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second)
{
return;
}
memcpy(&depthBuffer[0], logger->getOpenNI2Interface()->frameBuffers[bufferIndex].first.first, width * height * 2);
if(!(tcp && recording))
{
memcpy(rgbImage.bits(), logger->getOpenNI2Interface()->frameBuffers[bufferIndex].first.second, width * height * 3);
}
cv::Mat1w depth(height, width, (unsigned short *)&depthBuffer[0]);
normalize(depth, tmp, 0, 255, cv::NORM_MINMAX, 0);
cv::Mat3b depthImg(height, width, (cv::Vec<unsigned char, 3> *)depthImage.bits());
cv::cvtColor(tmp, depthImg, CV_GRAY2RGB);
painter->setPen(recording ? Qt::red : Qt::green);
painter->setFont(QFont("Arial", 30));
painter->drawText(10, 50, recording ? (tcp ? "Streaming & Recording" : "Recording") : "Viewing");
frameStats.push_back(abs(logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second - lastFrameTime));
if(frameStats.size() > 15)
{
frameStats.erase(frameStats.begin());
}
int64_t speedSum = 0;
for(unsigned int i = 0; i < frameStats.size(); i++)
{
speedSum += frameStats[i];
}
int64_t avgSpeed = (float)speedSum / (float)frameStats.size();
float fps = 1.0f / ((float)avgSpeed / 1000000.0f);
fps = floor(fps * 10.0f);
fps /= 10.0f;
std::stringstream str;
str << (int)ceil(fps) << "fps";
lastFrameTime = logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second;
painter->setFont(QFont("Arial", 24));
#ifdef __APPLE__
int offset = 20;
#else
int offset = 10;
#endif
painter->drawText(10, height - offset, QString::fromStdString(str.str()));
if(tcp)
{
cv::Mat3b modelImg(height / 4, width / 4);
cv::Mat3b modelImgBig(height, width, (cv::Vec<unsigned char, 3> *)rgbImage.bits());
std::string dataStr = comms->tryRecv();
if(dataStr.length())
{
std::vector<char> data(dataStr.begin(), dataStr.end());
modelImg = cv::imdecode(cv::Mat(data), 1);
cv::Size bigSize(width, height);
cv::resize(modelImg, modelImgBig, bigSize, 0, 0);
}
}
depthLabel->setPixmap(QPixmap::fromImage(depthImage));
imageLabel->setPixmap(QPixmap::fromImage(rgbImage));
if(logger->getMemoryBuffer().memoryFull.getValue())
{
assert(recording);
recordToggle();
QMessageBox msgBox;
msgBox.setText("Recording has been automatically stopped to prevent running out of system memory.");
msgBox.exec();
}
std::pair<bool, int64_t> dropping = logger->dropping.getValue();
if(!tcp && dropping.first)
{
assert(recording);
recordToggle();
std::stringstream strs;
strs << "Recording has been automatically stopped. Logging experienced a jump of " << dropping.second / 1000
<< "ms, indicating a drop below 10fps. Please try enabling compression or recording to RAM to prevent this.";
QMessageBox msgBox;
msgBox.setText(QString::fromStdString(strs.str()));
msgBox.exec();
}
}
| 29.969466 | 187 | 0.604687 | HTLife |
167b87db97246dbaeb9eb96becfa5211c30e744f | 16,137 | cpp | C++ | src/gui/color.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | 1 | 2020-12-28T01:41:35.000Z | 2020-12-28T01:41:35.000Z | src/gui/color.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | src/gui/color.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | // Copyright (C) 2018 Vincent Chambrin
// This file is part of the Yasl project
// For conditions of distribution and use, see copyright notice in LICENSE
#include "yasl/gui/color.h"
#include "yasl/common/binding/class.h"
#include "yasl/common/binding/default_arguments.h"
#include "yasl/common/binding/namespace.h"
#include "yasl/common/enums.h"
#include "yasl/common/genericvarianthandler.h"
#include "yasl/core/datastream.h"
#include "yasl/core/enums.h"
#include "yasl/core/string.h"
#include "yasl/gui/color.h"
#include <script/classbuilder.h>
#include <script/enumbuilder.h>
static void register_color_spec_enum(script::Class color)
{
using namespace script;
Enum spec = color.newEnum("Spec").setId(script::Type::QColorSpec).get();
spec.addValue("Invalid", QColor::Invalid);
spec.addValue("Rgb", QColor::Rgb);
spec.addValue("Hsv", QColor::Hsv);
spec.addValue("Cmyk", QColor::Cmyk);
spec.addValue("Hsl", QColor::Hsl);
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
static void register_color_name_format_enum(script::Class color)
{
using namespace script;
Enum name_format = color.newEnum("NameFormat").setId(script::Type::QColorNameFormat).get();
name_format.addValue("HexRgb", QColor::HexRgb);
name_format.addValue("HexArgb", QColor::HexArgb);
}
#endif
static void register_color_class(script::Namespace ns)
{
using namespace script;
Class color = ns.newClass("Color").setId(script::Type::QColor).get();
register_color_spec_enum(color);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
register_color_name_format_enum(color);
#endif
// QColor();
bind::default_constructor<QColor>(color).create();
// ~QColor();
bind::destructor<QColor>(color).create();
// QColor(Qt::GlobalColor);
bind::constructor<QColor, Qt::GlobalColor>(color).create();
// QColor(int, int, int, int = 255);
bind::constructor<QColor, int, int, int, int>(color)
.apply(bind::default_arguments(255)).create();
// QColor(QRgb);
/// TODO: QColor(QRgb);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// QColor(QRgba64);
/// TODO: QColor(QRgba64);
#endif
// QColor(const QString &);
bind::constructor<QColor, const QString &>(color).create();
// QColor(QStringView);
/// TODO: QColor(QStringView);
// QColor(const char *);
/// TODO: QColor(const char *);
// QColor(QLatin1String);
/// TODO: QColor(QLatin1String);
// QColor(QColor::Spec);
bind::constructor<QColor, QColor::Spec>(color).create();
// QColor(const QColor &);
bind::constructor<QColor, const QColor &>(color).create();
// QColor(QColor &&);
bind::constructor<QColor, QColor &&>(color).create();
// QColor & operator=(QColor &&);
bind::memop_assign<QColor, QColor &&>(color);
// QColor & operator=(const QColor &);
bind::memop_assign<QColor, const QColor &>(color);
// QColor & operator=(Qt::GlobalColor);
bind::memop_assign<QColor, Qt::GlobalColor>(color);
// bool isValid() const;
bind::member_function<QColor, bool, &QColor::isValid>(color, "isValid").create();
// QString name() const;
bind::member_function<QColor, QString, &QColor::name>(color, "name").create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
// QString name(QColor::NameFormat) const;
bind::member_function<QColor, QString, QColor::NameFormat, &QColor::name>(color, "name").create();
#endif
// void setNamedColor(const QString &);
bind::void_member_function<QColor, const QString &, &QColor::setNamedColor>(color, "setNamedColor").create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
// void setNamedColor(QStringView);
/// TODO: void setNamedColor(QStringView);
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
// void setNamedColor(QLatin1String);
/// TODO: void setNamedColor(QLatin1String);
#endif
// static QStringList colorNames();
bind::static_member_function<QColor, QStringList, &QColor::colorNames>(color, "colorNames").create();
// QColor::Spec spec() const;
bind::member_function<QColor, QColor::Spec, &QColor::spec>(color, "spec").create();
// int alpha() const;
bind::member_function<QColor, int, &QColor::alpha>(color, "alpha").create();
// void setAlpha(int);
bind::void_member_function<QColor, int, &QColor::setAlpha>(color, "setAlpha").create();
// qreal alphaF() const;
bind::member_function<QColor, qreal, &QColor::alphaF>(color, "alphaF").create();
// void setAlphaF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setAlphaF>(color, "setAlphaF").create();
// int red() const;
bind::member_function<QColor, int, &QColor::red>(color, "red").create();
// int green() const;
bind::member_function<QColor, int, &QColor::green>(color, "green").create();
// int blue() const;
bind::member_function<QColor, int, &QColor::blue>(color, "blue").create();
// void setRed(int);
bind::void_member_function<QColor, int, &QColor::setRed>(color, "setRed").create();
// void setGreen(int);
bind::void_member_function<QColor, int, &QColor::setGreen>(color, "setGreen").create();
// void setBlue(int);
bind::void_member_function<QColor, int, &QColor::setBlue>(color, "setBlue").create();
// qreal redF() const;
bind::member_function<QColor, qreal, &QColor::redF>(color, "redF").create();
// qreal greenF() const;
bind::member_function<QColor, qreal, &QColor::greenF>(color, "greenF").create();
// qreal blueF() const;
bind::member_function<QColor, qreal, &QColor::blueF>(color, "blueF").create();
// void setRedF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setRedF>(color, "setRedF").create();
// void setGreenF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setGreenF>(color, "setGreenF").create();
// void setBlueF(qreal);
bind::void_member_function<QColor, qreal, &QColor::setBlueF>(color, "setBlueF").create();
// void getRgb(int *, int *, int *, int *) const;
/// TODO: void getRgb(int *, int *, int *, int *) const;
// void setRgb(int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, &QColor::setRgb>(color, "setRgb")
.apply(bind::default_arguments(255)).create();
// void getRgbF(qreal *, qreal *, qreal *, qreal *) const;
/// TODO: void getRgbF(qreal *, qreal *, qreal *, qreal *) const;
// void setRgbF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, &QColor::setRgbF>(color, "setRgbF")
.apply(bind::default_arguments(qreal(1.0))).create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// QRgba64 rgba64() const;
/// TODO: QRgba64 rgba64() const;
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// void setRgba64(QRgba64);
/// TODO: void setRgba64(QRgba64);
#endif
// QRgb rgba() const;
/// TODO: QRgb rgba() const;
// void setRgba(QRgb);
/// TODO: void setRgba(QRgb);
// QRgb rgb() const;
/// TODO: QRgb rgb() const;
// void setRgb(QRgb);
/// TODO: void setRgb(QRgb);
// int hue() const;
bind::member_function<QColor, int, &QColor::hue>(color, "hue").create();
// int saturation() const;
bind::member_function<QColor, int, &QColor::saturation>(color, "saturation").create();
// int hsvHue() const;
bind::member_function<QColor, int, &QColor::hsvHue>(color, "hsvHue").create();
// int hsvSaturation() const;
bind::member_function<QColor, int, &QColor::hsvSaturation>(color, "hsvSaturation").create();
// int value() const;
bind::member_function<QColor, int, &QColor::value>(color, "value").create();
// qreal hueF() const;
bind::member_function<QColor, qreal, &QColor::hueF>(color, "hueF").create();
// qreal saturationF() const;
bind::member_function<QColor, qreal, &QColor::saturationF>(color, "saturationF").create();
// qreal hsvHueF() const;
bind::member_function<QColor, qreal, &QColor::hsvHueF>(color, "hsvHueF").create();
// qreal hsvSaturationF() const;
bind::member_function<QColor, qreal, &QColor::hsvSaturationF>(color, "hsvSaturationF").create();
// qreal valueF() const;
bind::member_function<QColor, qreal, &QColor::valueF>(color, "valueF").create();
// void getHsv(int *, int *, int *, int *) const;
/// TODO: void getHsv(int *, int *, int *, int *) const;
// void setHsv(int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, &QColor::setHsv>(color, "setHsv")
.apply(bind::default_arguments(255)).create();
// void getHsvF(qreal *, qreal *, qreal *, qreal *) const;
/// TODO: void getHsvF(qreal *, qreal *, qreal *, qreal *) const;
// void setHsvF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, &QColor::setHsvF>(color, "setHsvF")
.apply(bind::default_arguments(qreal(1.0))).create();
// int cyan() const;
bind::member_function<QColor, int, &QColor::cyan>(color, "cyan").create();
// int magenta() const;
bind::member_function<QColor, int, &QColor::magenta>(color, "magenta").create();
// int yellow() const;
bind::member_function<QColor, int, &QColor::yellow>(color, "yellow").create();
// int black() const;
bind::member_function<QColor, int, &QColor::black>(color, "black").create();
// qreal cyanF() const;
bind::member_function<QColor, qreal, &QColor::cyanF>(color, "cyanF").create();
// qreal magentaF() const;
bind::member_function<QColor, qreal, &QColor::magentaF>(color, "magentaF").create();
// qreal yellowF() const;
bind::member_function<QColor, qreal, &QColor::yellowF>(color, "yellowF").create();
// qreal blackF() const;
bind::member_function<QColor, qreal, &QColor::blackF>(color, "blackF").create();
// void getCmyk(int *, int *, int *, int *, int *);
/// TODO: void getCmyk(int *, int *, int *, int *, int *);
// void setCmyk(int, int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, int, &QColor::setCmyk>(color, "setCmyk")
.apply(bind::default_arguments(255)).create();
// void getCmykF(qreal *, qreal *, qreal *, qreal *, qreal *);
/// TODO: void getCmykF(qreal *, qreal *, qreal *, qreal *, qreal *);
// void setCmykF(qreal, qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, qreal, &QColor::setCmykF>(color, "setCmykF")
.apply(bind::default_arguments(qreal(1.0))).create();
// int hslHue() const;
bind::member_function<QColor, int, &QColor::hslHue>(color, "hslHue").create();
// int hslSaturation() const;
bind::member_function<QColor, int, &QColor::hslSaturation>(color, "hslSaturation").create();
// int lightness() const;
bind::member_function<QColor, int, &QColor::lightness>(color, "lightness").create();
// qreal hslHueF() const;
bind::member_function<QColor, qreal, &QColor::hslHueF>(color, "hslHueF").create();
// qreal hslSaturationF() const;
bind::member_function<QColor, qreal, &QColor::hslSaturationF>(color, "hslSaturationF").create();
// qreal lightnessF() const;
bind::member_function<QColor, qreal, &QColor::lightnessF>(color, "lightnessF").create();
// void getHsl(int *, int *, int *, int *) const;
/// TODO: void getHsl(int *, int *, int *, int *) const;
// void setHsl(int, int, int, int = 255);
bind::void_member_function<QColor, int, int, int, int, &QColor::setHsl>(color, "setHsl")
.apply(bind::default_arguments(255)).create();
// void getHslF(qreal *, qreal *, qreal *, qreal *) const;
/// TODO: void getHslF(qreal *, qreal *, qreal *, qreal *) const;
// void setHslF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::void_member_function<QColor, qreal, qreal, qreal, qreal, &QColor::setHslF>(color, "setHslF")
.apply(bind::default_arguments(qreal(1.0))).create();
// QColor toRgb() const;
bind::member_function<QColor, QColor, &QColor::toRgb>(color, "toRgb").create();
// QColor toHsv() const;
bind::member_function<QColor, QColor, &QColor::toHsv>(color, "toHsv").create();
// QColor toCmyk() const;
bind::member_function<QColor, QColor, &QColor::toCmyk>(color, "toCmyk").create();
// QColor toHsl() const;
bind::member_function<QColor, QColor, &QColor::toHsl>(color, "toHsl").create();
// QColor convertTo(QColor::Spec) const;
bind::member_function<QColor, QColor, QColor::Spec, &QColor::convertTo>(color, "convertTo").create();
// static QColor fromRgb(QRgb);
/// TODO: static QColor fromRgb(QRgb);
// static QColor fromRgba(QRgb);
/// TODO: static QColor fromRgba(QRgb);
// static QColor fromRgb(int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, &QColor::fromRgb>(color, "fromRgb")
.apply(bind::default_arguments(255)).create();
// static QColor fromRgbF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, &QColor::fromRgbF>(color, "fromRgbF")
.apply(bind::default_arguments(qreal(1.0))).create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// static QColor fromRgba64(ushort, ushort, ushort, ushort);
/// TODO: static QColor fromRgba64(ushort, ushort, ushort, ushort);
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
// static QColor fromRgba64(QRgba64);
/// TODO: static QColor fromRgba64(QRgba64);
#endif
// static QColor fromHsv(int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, &QColor::fromHsv>(color, "fromHsv")
.apply(bind::default_arguments(255)).create();
// static QColor fromHsvF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, &QColor::fromHsvF>(color, "fromHsvF")
.apply(bind::default_arguments(qreal(1.0))).create();
// static QColor fromCmyk(int, int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, int, &QColor::fromCmyk>(color, "fromCmyk")
.apply(bind::default_arguments(255)).create();
// static QColor fromCmykF(qreal, qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, qreal, &QColor::fromCmykF>(color, "fromCmykF")
.apply(bind::default_arguments(qreal(1.0))).create();
// static QColor fromHsl(int, int, int, int = 255);
bind::static_member_function<QColor, QColor, int, int, int, int, &QColor::fromHsl>(color, "fromHsl")
.apply(bind::default_arguments(255)).create();
// static QColor fromHslF(qreal, qreal, qreal, qreal = qreal(1.0));
bind::static_member_function<QColor, QColor, qreal, qreal, qreal, qreal, &QColor::fromHslF>(color, "fromHslF")
.apply(bind::default_arguments(qreal(1.0))).create();
// QColor light(int) const;
bind::member_function<QColor, QColor, int, &QColor::light>(color, "light").create();
// QColor lighter(int = 150) const;
bind::member_function<QColor, QColor, int, &QColor::lighter>(color, "lighter")
.apply(bind::default_arguments(150)).create();
// QColor dark(int) const;
bind::member_function<QColor, QColor, int, &QColor::dark>(color, "dark").create();
// QColor darker(int) const;
bind::member_function<QColor, QColor, int, &QColor::darker>(color, "darker").create();
// bool operator==(const QColor &) const;
bind::memop_eq<QColor, const QColor &>(color);
// bool operator!=(const QColor &) const;
bind::memop_neq<QColor, const QColor &>(color);
// static bool isValidColor(const QString &);
bind::static_member_function<QColor, bool, const QString &, &QColor::isValidColor>(color, "isValidColor").create();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
// static bool isValidColor(QStringView);
/// TODO: static bool isValidColor(QStringView);
#endif
// static bool isValidColor(QLatin1String);
/// TODO: static bool isValidColor(QLatin1String);
yasl::registerVariantHandler<yasl::GenericVariantHandler<QColor, QMetaType::QColor>>();
}
void register_color_file(script::Namespace gui)
{
using namespace script;
Namespace ns = gui;
register_color_class(ns);
// QDebug operator<<(QDebug, const QColor &);
/// TODO: QDebug operator<<(QDebug, const QColor &);
// QDataStream & operator<<(QDataStream &, const QColor &);
bind::op_put_to<QDataStream &, const QColor &>(ns);
// QDataStream & operator>>(QDataStream &, QColor &);
bind::op_read_from<QDataStream &, QColor &>(ns);
}
| 47.60177 | 121 | 0.684576 | strandfield |
167c5dcbe25c27afb0aecd3c5dda990f34d22f29 | 45,499 | cc | C++ | apps/phone-call/phonecall_func.cc | zhiqiang-hu/cell-phone-ux-demo | 80df27f47bdf3318b60fe327890f868c3fe28969 | [
"Apache-2.0"
] | 13 | 2017-12-17T16:18:44.000Z | 2022-01-07T15:40:36.000Z | apps/phone-call/phonecall_func.cc | zhiqiang-hu/cell-phone-ux-demo | 80df27f47bdf3318b60fe327890f868c3fe28969 | [
"Apache-2.0"
] | null | null | null | apps/phone-call/phonecall_func.cc | zhiqiang-hu/cell-phone-ux-demo | 80df27f47bdf3318b60fe327890f868c3fe28969 | [
"Apache-2.0"
] | 8 | 2018-07-07T03:08:33.000Z | 2022-01-27T09:25:08.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT NOTICE
//
// The following open source license statement does not apply to any
// entity in the Exception List published by FMSoft.
//
// For more information, please visit:
//
// https://www.fmsoft.cn/exception-list
//
//////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "global.h"
#include "ActivityStack.hh"
#include "PhoneCallActivity.hh"
#define SEPARATOR_DARKER_COLOR 0xffb3b7a5
#define SEPARATOR_LIGHTER_COLOR 0xffffffff
#define PHONE_PNG_INDEX 3
const char* bmpfiles[] = {
"res/phone-call/mute.png",
"res/phone-call/keyboard.png",
"res/phone-call/handsfree.png",
"res/phone-call/phone.png",
"res/phone-call/mute_32.png",
"res/phone-call/keyboard_32.png",
"res/phone-call/handsfree_32.png",
};
const char *main_text[] = {
"1", "2", "3",
"4", "5", "6",
"7", "8", "9",
"*", "0", "#"
};
const char *sub_text[] = {
"", "ABC", "DEF",
"GHI", "JKL", "MNO",
"PQRS", "TUV", "WXYZ",
"", "+", ""
};
static ARGB func_gradient_color[] = {0xFFFFFFFF, 0xffc1af4c};
static float func_gradient_pos[] = {0.0, 1.0};
static ARGB bk_gradient_color[] = {BACK_ARGB_BKCOLOR, BACK_ARGB_BKCOLOR};
static float bk_gradient_pos[] = {0.0, 1.0};
static ARGB func_bk_gradient_color[] = {0xccfcfcfc, 0xcce5e5e5, 0xccb2b2b2};
static float func_bk_gradient_pos[] = {0.0, 0.98, 1.0};
static ARGB endcall_gradient_color[] = {0xFFfdc972, 0xFFfcb848, 0xffba3305, 0xffd25e39};
static float endcall_gradient_pos[] = {0.0, 0.03, 0.8, 1.0};
static ARGB hidekeypad_gradient_color[] = {0xFF868686, 0xFF616161, 0xff1c1c1c, 0xff393939, 0xff393939};
static float hidekeypad_gradient_pos[] = {0.0, 0.02, 0.94, 0.99, 1.0};
static ARGB title_gradient_color[] = {0xffcfd571, 0xff7c9731, 0xff354605};
static float title_gradient_pos[] = {0.0, 0.98, 1.0};
static ARGB btndown_gradient_color[] = {0xa0d0e4fb, 0xa0167cef, 0xa0d0e4fb};
static float btndown_gradient_pos[] = {0.0, 0.5, 1.0};
#if 0
static gradient_data func_gradient_color[] = {
{0.0,0xFFFFFFFF},
{1.0,0xffc1af4c}
};
static gradient_data bk_gradient_color[] = {
{0.0,BACK_ARGB_BKCOLOR},
{1.0,BACK_ARGB_BKCOLOR}
};
static gradient_data func_bk_gradient_color[] = {
{0.0,0xccfcfcfc},
{0.98,0xcce5e5e5},
{1.0,0xccb2b2b2}
};
static gradient_data endcall_gradient_color[] = {
{0.0,0xFFfdc972},
{0.03,0xFFfcb848},
{0.98,0xffba3305},
{1.0,0xffd25e39}
};
static gradient_data hidekeypad_gradient_color[] = {
{0.0,0xFF868686},
{0.02,0xFF616161},
{0.94,0xff1c1c1c},
{0.99,0xff393939},
{1.0,0xff393939}
};
static gradient_data title_gradient_color[] = {
{0.0,0xffcfd571},
{0.98,0xff7c9731},
{1.0,0xff354605}
};
static gradient_data btndown_gradient_color[] = {
{0.0,0xa0d0e4fb},
{0.5,0xa0167cef},
{1.0,0xa0d0e4fb}
};
#endif
static BOOL first_click_status = FALSE;
static void set_gradient_color(mShapeTransRoundPiece *piece,
ARGB *colors, float *pos, int num)
{
HBRUSH brush;
_c(piece)->setProperty (piece, NCSP_TRANROUND_FILLMODE, NCSP_TRANROUND_GRADIENT_FILL);
brush = _c(piece)->getBrush(piece);
MGPlusSetLinearGradientBrushColorsEx(brush,colors,num,pos);
return;
}
static const char* get_key_str_from_piece(mHotPiece *self, PhoneCallActivity *act)
{
int i, j;
for (i = 0; i < N_FUNC_BTN_Y_NUM; ++i) {
for (j = 0; j < N_FUNC_BTN_X_NUM; ++j) {
if (self == (mHotPiece*)act->getKeyPiece(j, i)) {
return main_text[i * N_FUNC_BTN_X_NUM + j];
}
}
}
return NULL;
}
static BOOL onClickKeypad(mWidget *self, mHotPiece *piece,
int event_id, DWORD param)
{
if(event_id == NCSN_ABP_PUSHED)
{
mAnimationEditPiece *editpiece;
HWND main_hwnd = GetMainWindowHandle(self->hwnd);
PhoneCallActivity* act = (PhoneCallActivity*)
Activity::getActivityFromHWND (main_hwnd);
mContainerCtrl *edit = (mContainerCtrl *)ncsGetChildObj(
main_hwnd, ID_ANIMATION_EDIT);
if (act == NULL||edit == NULL)
return FALSE;
const char *str = get_key_str_from_piece(piece, act);
editpiece = act->getTitleEditPiece();
if (editpiece == NULL)
return FALSE;
if (strlen(act->getPhoneNumber())>=(PHONE_NUMBER_LEN-1)||
first_click_status == TRUE)
{
memset(act->getPhoneNumber(),0x00,PHONE_NUMBER_LEN);
_c(editpiece)->setContent (edit->hwnd,editpiece,"",TEXT_ALIGN_CENTER);
}
strcat(act->getPhoneNumber(),str);
_c(editpiece)->append(edit->hwnd,editpiece, str);
first_click_status = FALSE;
return TRUE;
}
return FALSE;
}
void PhoneCallActivity::initResource(void)
{
int i;
for (i=0;i<(signed)(sizeof(bmpfiles)/sizeof(char *));i++)
{
if (Load32Resource(bmpfiles[i],RES_TYPE_IMAGE,0) == NULL)
{
printf("bmp load failure!%s\n",bmpfiles[i]);
}
}
m_mainFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
KEYPAD_TEXT_FONT_H, 0);
m_starFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
KEYPAD_STARTEXT_FONT_H, 0);
m_subFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
KEYPAD_SUBTEXT_FONT_H, 0);
m_infoFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
CALL_INFO_FONT_H, 0);
m_funcFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
FUNC_TEXT_FONT_H, 0);
m_endcallFont = m_infoFont;
m_hideFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
CALL_HIDEKEYPAD_FONT_H, 0);
m_titleFont = CreateLogFontEx ("ttf", "helvetica", "UTF-8",
FONT_WEIGHT_REGULAR,
FONT_SLANT_ROMAN,
FONT_FLIP_NONE,
FONT_OTHER_NONE,
FONT_DECORATE_NONE, FONT_RENDER_SUBPIXEL,
TITLE_TEXT_FONT_H, 0);
}
void PhoneCallActivity::releaseResource(void)
{
int i;
for (i=0;i<(signed)(sizeof(bmpfiles)/sizeof(char *));i++)
{
UnregisterRes(bmpfiles[i]);
}
DestroyLogFont(m_mainFont);
DestroyLogFont(m_subFont);
DestroyLogFont(m_infoFont);
DestroyLogFont(m_funcFont);
DestroyLogFont(m_titleFont);
DestroyLogFont(m_starFont);
DestroyLogFont(m_hideFont);
}
static void imageAnimationPauseResume(PhoneCallActivity* act,BOOL isPause)
{
int i;
func_contain_piece *contain_piece_temp = NULL;
ANIMATION_INDEX record;
static BOOL contain_status[ANIMATION_MAX];
assert(act);
for (i=0;i<ANIMATION_MAX;i++)
{
record = (ANIMATION_INDEX)i;
contain_piece_temp = act->getFuncContainPiece(NULL,&record);
assert(contain_piece_temp);
if (isPause)
{
contain_status[record] = FALSE;
if (contain_piece_temp->animation_handle != NULL&&
mGEffAnimationGetProperty(contain_piece_temp->animation_handle,
MGEFF_PROP_STATE) == MGEFF_STATE_RUNNING)
{
act->stopImageMoveAnimation(NULL,(ANIMATION_INDEX)i);
contain_status[record] = TRUE;
}
}
else
{
if (contain_status[record] && contain_piece_temp->animation_handle != NULL&&
mGEffAnimationGetProperty(contain_piece_temp->animation_handle,
MGEFF_PROP_STATE) == MGEFF_STATE_PAUSED)
{
RECT rc = {0, 0, FUNC_BTN_W, FUNC_BTN_H};
PanelPiece_invalidatePiece((mHotPiece*)contain_piece_temp->func_subgradient_piece, &rc);
set_gradient_color(contain_piece_temp->func_subgradient_piece,
func_gradient_color,func_gradient_pos,TABLESIZE(func_gradient_color));
act->startImageMoveAnimation(NULL,(ANIMATION_INDEX)i,
JUMP_ANIMATION_DURATION,InQuad,ANIMATION_OFFSET);
}
}
}
}
static int func_event_handler(mHotPiece *_self,
int message, WPARAM wParam, LPARAM lParam, mObject *owner)
{
assert(owner != NULL);
mContainerCtrl *ctnr = (mContainerCtrl *)owner;
HWND main_hwnd = GetMainWindowHandle(ctnr->hwnd);
PhoneCallActivity* act = (PhoneCallActivity*)
Activity::getActivityFromHWND (main_hwnd);
mPanelPiece *self = (mPanelPiece *)_self;
func_contain_piece *contain_piece = NULL;
ANIMATION_INDEX idx;
contain_piece = act->getFuncContainPiece(self,&idx);
if (contain_piece == NULL)
return -1;
if (idx == ANIMATION_KEYPAD)
{
if (message == MSG_LBUTTONUP)
{
set_gradient_color(contain_piece->func_subgradient_piece,
func_bk_gradient_color,func_bk_gradient_pos,TABLESIZE(func_bk_gradient_color));
act->startFlipPushAnimation(ctnr,FLIP_ANIMATION_DURATION,OutQuad,0);
imageAnimationPauseResume(act,TRUE);
first_click_status = TRUE;
}
else if (message == MSG_LBUTTONDOWN)
{
set_gradient_color(contain_piece->func_subgradient_piece,
func_gradient_color,func_gradient_pos,TABLESIZE(func_gradient_color));
PanelPiece_invalidatePiece((mHotPiece*)contain_piece->func_subgradient_piece,NULL);
}
return 0;
}
if (message == MSG_LBUTTONUP)
return 0;
if (contain_piece->animation_handle != NULL&&
mGEffAnimationGetProperty(contain_piece->animation_handle,
MGEFF_PROP_STATE) == MGEFF_STATE_RUNNING)
{
act->stopImageMoveAnimation(ctnr,(ANIMATION_INDEX)idx);
}
else
{
RECT rc = {0, 0, FUNC_BTN_W, FUNC_BTN_H};
PanelPiece_invalidatePiece((mHotPiece*)contain_piece->func_subgradient_piece, &rc);
set_gradient_color(contain_piece->func_subgradient_piece,
func_gradient_color,func_gradient_pos,TABLESIZE(func_gradient_color));
act->startImageMoveAnimation(ctnr,(ANIMATION_INDEX)idx,
JUMP_ANIMATION_DURATION,InQuad,ANIMATION_OFFSET);
}
return 0;
}
func_contain_piece *PhoneCallActivity::getFuncContainPiece(
mPanelPiece *self,ANIMATION_INDEX *idx)
{
int i;
if ((self == NULL) && (idx != NULL)) {
ANIMATION_INDEX index = *idx;
if ((index >= ANIMATION_MUTE) && (index < ANIMATION_MAX)) {
return &m_funcContainPiece[index];
}
return NULL;
}
else if (self != NULL) {
for (i = 0; i < ANIMATION_MAX; i++) {
if (m_funcContainPiece[i].func_subcontain_piece == self) {
if (idx != NULL) {
*idx = (ANIMATION_INDEX)i;
}
return &m_funcContainPiece[i];
}
}
}
return NULL;
}
static BOOL endcall_event_handler(mWidget *self, mHotPiece *piece,
int event_id, DWORD param)
{
mContainerCtrl *ctnr = (mContainerCtrl *)self;
HWND main_hwnd;
PhoneCallActivity* act;
mButtonPanelPiece *hidepadpiece;
if (ctnr == NULL||event_id != NCSN_ABP_CLICKED)
return FALSE;
main_hwnd = GetMainWindowHandle(ctnr->hwnd);
act = (PhoneCallActivity*)
Activity::getActivityFromHWND (main_hwnd);
if (act == NULL)
return FALSE;
hidepadpiece = act->getBtnPiece(BTN_HIDEPAD);
if (piece == (mHotPiece*)hidepadpiece) {
imageAnimationPauseResume(act,FALSE);
act->startFlipPushAnimation(ctnr,FLIP_ANIMATION_DURATION,OutQuad,0);
}
else {
ACTIVITYSTACK->pop();
//ActivityStack::singleton()->pop();
}
return TRUE;
}
mPanelPiece* PhoneCallActivity::titleCreate(mContainerCtrl *ctnr)
{
mContainerCtrl *containerctrl = ctnr;
mPanelPiece *toppiece;
mPanelPiece *containerpiece;
mHotPiece *backpiece;
mHotPiece *manimationeditpiece;
RECT contentrc;
SetRect(&contentrc,0,0,CALL_TITLE_W, CALL_TITLE_H);
if (ctnr == NULL)
return NULL;
toppiece = (mPanelPiece*)NEWPIECE(mPanelPiece);
_c(toppiece)->setRect (toppiece, &contentrc);
containerpiece = (mPanelPiece*)NEWPIECE(mPanelPiece);
_c(containerpiece)->setRect (containerpiece, &contentrc);
//_c(containerctrl)->setBody(containerctrl, (mHotPiece*)containerpiece);
_c(containerctrl)->setBody(containerctrl, (mHotPiece*)toppiece);
_c(toppiece)->addContent(toppiece, (mHotPiece*)containerpiece, 0, 0);
backpiece = (mHotPiece*)NEWPIECE(mShapeTransRoundPiece);
_c(backpiece)->setRect (backpiece, &contentrc);
_c(backpiece)->setProperty (backpiece, NCSP_TRANROUND_CORNERFLAG,0);
set_gradient_color((mShapeTransRoundPiece *)backpiece,
title_gradient_color,title_gradient_pos,TABLESIZE(title_gradient_color));
_c(containerpiece)->addContent(containerpiece, backpiece, 0, 0);
manimationeditpiece = (mHotPiece*)NEWPIECE(mAnimationEditPiece);
_c(manimationeditpiece)->setRect (manimationeditpiece, &contentrc);
_c(manimationeditpiece)->setProperty (
manimationeditpiece, NCSP_ANIMATIONEDITPIECE_FONT,(DWORD)m_titleFont);
_c(manimationeditpiece)->setProperty (
manimationeditpiece, NCSP_ANIMATIONEDITPIECE_TEXTCOLOR,CALL_TITLE_COLOR);
_c(manimationeditpiece)->setProperty (
manimationeditpiece, NCSP_ANIMATIONEDITPIECE_TEXTSHADOWCOLOR,CALL_TITLE_SHADOW_COLOR);
_c(containerpiece)->addContent(containerpiece, manimationeditpiece, 0, 0);
m_animationEditPiece = (mAnimationEditPiece *)manimationeditpiece;
#if 0
_c((mAnimationEditPiece *)manimationeditpiece)->setContent(
containerctrl->hwnd,(mAnimationEditPiece *)manimationeditpiece,m_phoneNumber,TEXT_ALIGN_CENTER);
#endif
return containerpiece;
}
static BOOL add_func_content(mContainerCtrl *ctnr,
mPanelPiece *body,PLOGFONT text_font)
{
int idx;
int contain_x,contain_y;
HWND main_hwnd;
PhoneCallActivity* act;
mPanelPiece *content[N_FUNC_BTN_NUM];
mHotPiece *image[N_FUNC_BTN_NUM];
mHotPiece *backpiece[N_FUNC_BTN_NUM];
mHotPiece *label;
PBITMAP pbitmap;
func_contain_piece *contain_piece = NULL;
ANIMATION_INDEX index;
int conerflag[N_FUNC_BTN_NUM] = {
TRANROUND_CORNERFLAG_LEFTBOTTOM,
0,
TRANROUND_CORNERFLAG_RIGHTBOTTOM
};
const char *text_str[N_FUNC_BTN_NUM] = {
"Mute",
"Keypad",
"Handsfree"
};
RECT rc = { 0, 0, FUNC_BTN_W, FUNC_BTN_H };
RECT image_rc;
RECT inforc;
if (ctnr == NULL||body == NULL)
return FALSE;
main_hwnd = GetMainWindowHandle(ctnr->hwnd);
act = (PhoneCallActivity*)Activity::getActivityFromHWND (main_hwnd);
if (act == NULL)
return FALSE;
for (idx = 0; idx < N_FUNC_BTN_NUM; idx++)
{
contain_x = (FUNC_BTN_W + HSEP_W) * idx;
contain_y = VSEP_H;
content[idx] = (mPanelPiece*)NEWPIECE(mPanelPiece);
_c(content[idx])->setRect (content[idx], &rc);
backpiece[idx] = (mHotPiece*)NEWPIECE(mShapeTransRoundPiece);
_c(backpiece[idx])->setRect (backpiece[idx], &rc);
_c(backpiece[idx])->setProperty (backpiece[idx], NCSP_TRANROUND_RADIUS, 2);
_c(backpiece[idx])->setProperty (backpiece[idx], NCSP_TRANROUND_CORNERFLAG,
conerflag[idx]);
set_gradient_color((mShapeTransRoundPiece *)backpiece[idx],
func_bk_gradient_color,func_bk_gradient_pos,TABLESIZE(func_bk_gradient_color));
pbitmap = (PBITMAP)RetrieveRes(bmpfiles[idx]);
SetRect(&image_rc,0,0,pbitmap->bmWidth,pbitmap->bmHeight);
image[idx] = (mHotPiece*)NEWPIECE(mImagePiece);
_c(image[idx])->setRect (image[idx], &image_rc);
_c(image[idx])->setProperty (image[idx],NCSP_IMAGEPIECE_IMAGE, (DWORD)pbitmap);
_c(content[idx])->addContent(content[idx], backpiece[idx], 0, 0);
_c(content[idx])->addContent(content[idx], image[idx],
(FUNC_BTN_W-pbitmap->bmWidth)>>1, (FUNC_BTN_H-pbitmap->bmHeight)>>1);
SetRect(&inforc,0,0,FUNC_BTN_W,FUNC_TEXT_FONT_H+4);
label = (mHotPiece*)NEWPIECE(mTextPiece);
_c(label)->setRect (label, &inforc);
if (text_font != NULL)
{
_c(label)->setProperty (label,NCSP_TEXTPIECE_LOGFONT, (DWORD)text_font);
}
_c(label)->setProperty(label, NCSP_TEXTPIECE_TEXTCOLOR,(DWORD)FUNC_TEXT_COLOR);
_c(label)->setProperty (label,NCSP_LABELPIECE_LABEL, (DWORD)text_str[idx]);
_c(content[idx])->addContent(content[idx], label, 0,FUNC_TEXT_Y);
_c(body)->addContent(body, (mHotPiece*)content[idx], contain_x,contain_y);
_c(content[idx])->appendEventHandler(content[idx], MSG_LBUTTONDOWN, func_event_handler);
_c(content[idx])->appendEventHandler(content[idx], MSG_LBUTTONUP, func_event_handler);
index = (ANIMATION_INDEX)idx;
contain_piece = act->getFuncContainPiece(NULL,&index);
contain_piece->func_subcontain_piece = content[idx];
contain_piece->func_subimage_piece = (mImagePiece *)image[idx];
contain_piece->func_subgradient_piece = (mShapeTransRoundPiece *)backpiece[idx];
}
return TRUE;
}
mContainerCtrl* PhoneCallActivity::functionCreate(HWND hwnd,RECT rect)
{
int j;
mContainerCtrl *containerctrl;
mPanelPiece *containerpiece;
mPanelPiece *content;
mPanelPiece *labelcontent;
mHotPiece *labelbackpiece;
mHotPiece *separatorx[N_FUNC_BTN_X_NUM - 1];
mHotPiece *separatory;
mHotPiece *label;
RECT inforc = {0, 0, CALL_INFO_W, CALL_INFO_H};
RECT vseprc = {0, 0, VSEP_W, VSEP_H};
RECT hseprc = {0, 0, HSEP_W, HSEP_H};
RECT containrc;
RECT contentrc;
containerctrl = (mContainerCtrl*)ncsCreateWindow(
NCSCTRL_CONTAINERCTRL,
"ContainerCtrl",
WS_VISIBLE, WS_EX_TRANSPARENT, ID_CTRN_FUNC,
rect.left, rect.top,
RECTW(rect), RECTH(rect),
hwnd,
NULL, NULL, NULL, 0);
/* start set contain */
containerpiece = (mPanelPiece*)NEWPIECE(mPanelPiece);
SetRect(&containrc,0,0,RECTW(rect),RECTH(rect));
_c(containerpiece)->setRect (containerpiece, &containrc);
_c(containerctrl)->setBody(containerctrl, (mHotPiece*)containerpiece);
/* end set contain */
/* start set label content piece */
labelcontent = (mPanelPiece*)NEWPIECE(mPanelPiece);
_c(labelcontent)->setRect (labelcontent, &inforc);
_c(containerpiece)->addContent(containerpiece, (mHotPiece*)labelcontent, 0, 0);
labelbackpiece = (mHotPiece*)NEWPIECE(mShapeTransRoundPiece);
_c(labelbackpiece)->setRect (labelbackpiece, &inforc);
_c(labelbackpiece)->setProperty (labelbackpiece, NCSP_TRANROUND_BKCOLOR, BACK_ARGB_BKCOLOR);
_c(labelbackpiece)->setProperty (labelbackpiece, NCSP_TRANROUND_RADIUS, 2);
_c(labelbackpiece)->setProperty (labelbackpiece, NCSP_TRANROUND_CORNERFLAG,
TRANROUND_CORNERFLAG_RIGHTTOP|TRANROUND_CORNERFLAG_LEFTTOP);
_c(labelcontent)->addContent(labelcontent, labelbackpiece, 0, 0);
label = (mHotPiece*)NEWPIECE(mTextPiece);
_c(label)->setRect (label, &inforc);
_c(label)->setProperty(label, NCSP_LABELPIECE_LABEL,(DWORD)"Calling...");
_c(label)->setProperty(label, NCSP_TEXTPIECE_LOGFONT,(DWORD)m_infoFont);
_c(label)->setProperty(label, NCSP_TEXTPIECE_TEXTCOLOR,(DWORD)CALL_INFO_COLOR);
_c(labelcontent)->addContent(labelcontent, label, 0, 0);
/* end set label content piece */
/* start set content piece */
content = (mPanelPiece*)NEWPIECE(mPanelPiece);
SetRect(&contentrc,0,0,RECTW(rect),RECTH(rect)- CALL_INFO_H);
_c(content)->setRect (content, &contentrc);
_c(containerpiece)->addContent(containerpiece, (mHotPiece*)content, 0, CALL_INFO_H);
/* end set content piece */
/* start set separator piece */
for (j = 0; j < (N_FUNC_BTN_X_NUM - 1); j++)
{
separatorx[j] = (mHotPiece*)NEWPIECE(mPhoneSeparatorPiece);
_c(separatorx[j])->setRect (separatorx[j], &hseprc);
_c(separatorx[j])->setProperty (separatorx[j],
NCSP_PHONESEPARATORPIECE_DARKER_COLOR, (DWORD)SEPARATOR_DARKER_COLOR);
_c(separatorx[j])->setProperty (separatorx[j],
NCSP_PHONESEPARATORPIECE_LIGHTER_COLOR, (DWORD)SEPARATOR_LIGHTER_COLOR);
_c(separatorx[j])->setProperty (separatorx[j],
NCSP_PHONESEPARATORPIECE_DIRECT_MODE, (DWORD)PHONESEPARATORPIECE_VERT);
_c(content)->addContent(content, separatorx[j],
KEYPAD_BTN_W + (KEYPAD_BTN_W + HSEP_W) * j, 0);
}
separatory = (mHotPiece*)NEWPIECE(mPhoneSeparatorPiece);
_c(separatory)->setRect (separatory, &vseprc);
_c(separatory)->setProperty (separatory,
NCSP_PHONESEPARATORPIECE_DARKER_COLOR, (DWORD)SEPARATOR_DARKER_COLOR);
_c(separatory)->setProperty (separatory,
NCSP_PHONESEPARATORPIECE_LIGHTER_COLOR, (DWORD)SEPARATOR_LIGHTER_COLOR);
_c(separatory)->setProperty (separatory,
NCSP_PHONESEPARATORPIECE_DIRECT_MODE, (DWORD)PHONESEPARATORPIECE_HERT);
_c(content)->addContent(content, separatory,0, 0);
/* end set separator piece */
/* start set control piece */
add_func_content(containerctrl,content,m_funcFont);
/* end set control piece */
m_ctrnPiece[CNTR_FUNC] = content;
_c(containerpiece)->enableChildCache(containerpiece, (mHotPiece*)m_ctrnPiece[CNTR_FUNC], TRUE);
return containerctrl;
}
mPanelPiece* PhoneCallActivity::keypadCreate(mContainerCtrl *ctnr, RECT rect)
{
int i,j;
mPanelPiece *containerpiece = (mPanelPiece *)ctnr->body;
mPanelPiece *content;
mHotPiece *keyboard;
mButtonPanelPiece *key;
mShapeTransRoundPiece *keyBackground;
mHotPiece *separatorx[N_FUNC_BTN_X_NUM - 1];
mHotPiece *separatory[N_FUNC_BTN_Y_NUM];
RECT vseprc = {0, 0, VSEP_W, VSEP_H};
RECT hseprc = {0, 0, HSEP_W, HSEP_H - VSEP_H};
RECT btnrc = {0, 0, KEYPAD_BTN_W, KEYPAD_BTN_H};
RECT contentrc;
/* start set content piece */
content = (mPanelPiece*)NEWPIECE(mPanelPiece);
SetRect(&contentrc,0,0,RECTW(rect),RECTH(rect)-CALL_INFO_H);
_c(content)->setRect (content, &contentrc);
_c(containerpiece)->addContent(containerpiece, (mHotPiece*)content, 400, CALL_INFO_H);
/* end set content piece */
/* start set separator piece */
for (j = 0; j < (N_FUNC_BTN_X_NUM - 1); j++)
{
separatorx[j] = (mHotPiece*)NEWPIECE(mPhoneSeparatorPiece);
_c(separatorx[j])->setRect (separatorx[j], &hseprc);
_c(separatorx[j])->setProperty (separatorx[j],
NCSP_PHONESEPARATORPIECE_DARKER_COLOR, (DWORD)SEPARATOR_DARKER_COLOR);
_c(separatorx[j])->setProperty (separatorx[j],
NCSP_PHONESEPARATORPIECE_LIGHTER_COLOR, (DWORD)SEPARATOR_LIGHTER_COLOR);
_c(separatorx[j])->setProperty (separatorx[j],
NCSP_PHONESEPARATORPIECE_DIRECT_MODE, (DWORD)PHONESEPARATORPIECE_VERT);
_c(content)->addContent(content, separatorx[j],
KEYPAD_BTN_W + (KEYPAD_BTN_W + HSEP_W) * j, 0);
}
for (i=0;i<N_FUNC_BTN_Y_NUM;i++)
{
separatory[i] = (mHotPiece*)NEWPIECE(mPhoneSeparatorPiece);
_c(separatory[i])->setRect (separatory[i], &vseprc);
_c(separatory[i])->setProperty (separatory[i],
NCSP_PHONESEPARATORPIECE_DARKER_COLOR, (DWORD)SEPARATOR_DARKER_COLOR);
_c(separatory[i])->setProperty (separatory[i],
NCSP_PHONESEPARATORPIECE_LIGHTER_COLOR, (DWORD)SEPARATOR_LIGHTER_COLOR);
_c(separatory[i])->setProperty (separatory[i],
NCSP_PHONESEPARATORPIECE_DIRECT_MODE, (DWORD)PHONESEPARATORPIECE_HERT);
_c(content)->addContent(content, separatory[i],
0, (KEYPAD_BTN_H + VSEP_H) * i);
}
/* end set separator piece */
/* start set keypad piece */
for (j=0;j<N_FUNC_BTN_Y_NUM;j++)
{
for (i=0;i<N_FUNC_BTN_X_NUM;i++)
{
key = NEWPIECE(mButtonPanelPiece);
keyBackground = _c(key)->getBkgndPiece(key);
_c(key)->setRect (key, &btnrc);
if (j == N_FUNC_BTN_Y_NUM - 1&&i == 0)
{
_c(keyBackground)->setProperty (keyBackground,
NCSP_TRANROUND_CORNERFLAG, TRANROUND_CORNERFLAG_LEFTBOTTOM);
}
else if (j == N_FUNC_BTN_Y_NUM - 1&&i == N_FUNC_BTN_X_NUM - 1)
{
_c(keyBackground)->setProperty (keyBackground,
NCSP_TRANROUND_CORNERFLAG, TRANROUND_CORNERFLAG_RIGHTBOTTOM);
}
else
{
_c(keyBackground)->setProperty (keyBackground, NCSP_TRANROUND_CORNERFLAG, 0);
}
_c(keyBackground)->setProperty (keyBackground, NCSP_TRANROUND_RADIUS, 2);
_c(key)->setGradientBackgroundColor(key,
bk_gradient_color,bk_gradient_pos,TABLESIZE(bk_gradient_color),
btndown_gradient_color,btndown_gradient_pos,TABLESIZE(btndown_gradient_color));
_c(key)->setStates(key);
ncsAddEventListener((mObject*)key, (mObject*)ctnr,
(NCS_CB_ONPIECEEVENT)onClickKeypad, NCSN_ABP_PUSHED);
_c(content)->addContent(content, (mHotPiece*)key,
(KEYPAD_BTN_W+VSEP_H) * i, (KEYPAD_BTN_H + HSEP_W) * j+HSEP_W);
keyboard = (mHotPiece*)NEWPIECE(mPhoneStaticRDRPiece);
_c(keyboard)->setRect (keyboard, &btnrc);
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_MAIN_TEXT, (DWORD)main_text[j*N_FUNC_BTN_X_NUM + i]);
if (strcmp(main_text[j*N_FUNC_BTN_X_NUM + i],"*") == 0)
{
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_MAIN_FONT, (DWORD)m_starFont);
}
else
{
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_MAIN_FONT, (DWORD)m_mainFont);
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_SUB_TEXT, (DWORD)sub_text[j*N_FUNC_BTN_X_NUM + i]);
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_SUB_FONT, (DWORD)m_subFont);
}
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_MAIN_COLOR, (DWORD)CALL_KEYPAD_MAINCOLOR);
_c(keyboard)->setProperty(keyboard,
NCSP_PHONESTATICRDRPIECE_SUB_COLOR, (DWORD)CALL_KEYPAD_SUBCOLOR);
_c(key)->addContentToLayout(key, keyboard);
m_keyPiece[i][j] = (mButtonPanelPiece *)key;
}
}
/* end set keypad piece */
m_ctrnPiece[CNTR_KEYPAD] = (mPanelPiece *)content;
_c(containerpiece)->enableChildCache(containerpiece, (mHotPiece*)m_ctrnPiece[CNTR_KEYPAD], TRUE);
return content;
}
mContainerCtrl* PhoneCallActivity::endCallButtonCreate(HWND hwnd,RECT rect)
{
mContainerCtrl *containerctrl;
mPanelPiece *containerpiece;
mButtonPanelPiece *endcallcontainpiece;
mButtonPanelPiece *hidepadcontainpiece;
mShapeTransRoundPiece *background;
mHotPiece *backpiece;
RECT containrc;
RECT backrc;
RECT labelrc;
RECT image_rc;
mHotPiece *endcallLabel;
mHotPiece *endcallimage;
mHotPiece *hidepadLabel;
PBITMAP pbitmap;
containerctrl = (mContainerCtrl*)ncsCreateWindow(
NCSCTRL_CONTAINERCTRL,
"ContainerCtrl",
WS_VISIBLE, WS_EX_TRANSPARENT, ID_BTN_ENDCALL,
rect.left, rect.top,
RECTW(rect), RECTH(rect),
hwnd,
NULL, NULL, NULL, 0);
/* start set main contain */
containerpiece = (mPanelPiece*)NEWPIECE(mPanelPiece);
SetRect(&containrc,0,0,RECTW(rect),RECTH(rect));
_c(containerpiece)->setRect (containerpiece, &containrc);
_c(containerctrl)->setBody(containerctrl, (mHotPiece*)containerpiece);
/*end set main contain*/
/* start set main backpiece */
backrc = containrc;
backpiece = (mHotPiece*)NEWPIECE(mShapeTransRoundPiece);
_c(backpiece)->setRect (backpiece, &backrc);
_c(backpiece)->setProperty (backpiece, NCSP_TRANROUND_BKCOLOR, ENDCALL_BK_COLOR);
_c(backpiece)->setProperty (backpiece, NCSP_TRANROUND_CORNERFLAG, 0);
_c(containerpiece)->addContent(containerpiece, backpiece, 0, 0);
/* end set main backpiece */
/* start set endcall contain */
endcallcontainpiece = (mButtonPanelPiece*)NEWPIECE(mButtonPanelPiece);
containrc.right -= ENDCALL_X<<1;
containrc.bottom -= ENDCALL_Y<<1;
_c(containerpiece)->addContent(containerpiece,
(mHotPiece*)endcallcontainpiece, ENDCALL_X, ENDCALL_Y);
/*end set endcall contain*/
/*start set endcall image piece*/
pbitmap = (PBITMAP)RetrieveRes(bmpfiles[PHONE_PNG_INDEX]);
if (pbitmap != NULL)
{
SetRect(&image_rc,0,0,pbitmap->bmWidth,containrc.bottom);
endcallimage = (mHotPiece*)NEWPIECE(mImagePiece);
_c(endcallimage)->setRect (endcallimage, &image_rc);
_c(endcallimage)->setProperty (endcallimage,NCSP_IMAGEPIECE_IMAGE, (DWORD)pbitmap);
_c(endcallcontainpiece)->addContentToLayout(endcallcontainpiece, endcallimage);
}
/*end set endcall image piece*/
/* start set endcall label piece */
SetRect(&labelrc,0,0,ENDCALL_TEXT_W,containrc.bottom);
endcallLabel = (mHotPiece*)NEWPIECE(mTextPiece);
_c(endcallLabel)->setRect (endcallLabel, &labelrc);
_c(endcallLabel)->setProperty(endcallLabel, NCSP_LABELPIECE_LABEL,(DWORD)"End call");
_c(endcallLabel)->setProperty(endcallLabel, NCSP_TEXTPIECE_LOGFONT,(DWORD)m_endcallFont);
_c(endcallLabel)->setProperty(endcallLabel, NCSP_TEXTPIECE_TEXTCOLOR,ENDCALL_TEXT_COLOR);
_c(endcallLabel)->setProperty(endcallLabel, NCSP_TEXTPIECE_TEXTSHADOWCOLOR,ENDCALL_TEXT_SHADOWCOLOR);
_c(endcallcontainpiece)->addContentToLayout(endcallcontainpiece,endcallLabel);
ncsAddEventListener((mObject*)endcallcontainpiece, (mObject*)containerctrl,
(NCS_CB_ONPIECEEVENT)endcall_event_handler, NCSN_ABP_CLICKED);
background = _c(endcallcontainpiece)->getBkgndPiece(endcallcontainpiece);
_c(background)->setProperty (background, NCSP_TRANROUND_RADIUS,4);
set_gradient_color(background,
endcall_gradient_color,endcall_gradient_pos,TABLESIZE(endcall_gradient_color));
_c(background)->setProperty(background,NCSP_TRANROUND_FILLENGINE,TRANROUND_FILLENGINE_NORMAL);
_c(endcallcontainpiece)->setRect (endcallcontainpiece, &containrc);
m_btnPiece[BTN_ENDCALL] = endcallcontainpiece;
/* end set endcall label piece */
/* start set hidepad contain */
containrc.right = HIDEPAD_W;
hidepadcontainpiece = (mButtonPanelPiece*)NEWPIECE(mButtonPanelPiece);
_c(hidepadcontainpiece)->setRect (hidepadcontainpiece, &containrc);
_c(containerpiece)->addContent(containerpiece,
(mHotPiece*)hidepadcontainpiece, HIDEPAD_X, ENDCALL_Y);
_c(containerpiece)->movePiece(containerpiece,
(mHotPiece *)hidepadcontainpiece,200,300);
/*end set hidepad contain*/
/* start set hidepad label piece */
SetRect(&labelrc,0,0,containrc.right,containrc.bottom);
hidepadLabel = (mHotPiece*)NEWPIECE(mTextPiece);
_c(hidepadLabel)->setRect (hidepadLabel, &labelrc);
_c(hidepadLabel)->setProperty(hidepadLabel, NCSP_LABELPIECE_LABEL,(DWORD)"Hide Keypad");
_c(hidepadLabel)->setProperty(hidepadLabel, NCSP_TEXTPIECE_LOGFONT,(DWORD)m_hideFont);
_c(hidepadLabel)->setProperty(hidepadLabel, NCSP_TEXTPIECE_TEXTCOLOR,ENDCALL_TEXT_COLOR);
_c(hidepadLabel)->setProperty(hidepadLabel, NCSP_TEXTPIECE_TEXTSHADOWCOLOR,ENDCALL_TEXT_SHADOWCOLOR);
_c(hidepadcontainpiece)->addContentToLayout(hidepadcontainpiece, hidepadLabel);
ncsAddEventListener((mObject*)hidepadcontainpiece, (mObject*)containerctrl,
(NCS_CB_ONPIECEEVENT)endcall_event_handler, NCSN_ABP_CLICKED);
background = _c(hidepadcontainpiece)->getBkgndPiece(hidepadcontainpiece);
_c(background)->setProperty(background,NCSP_TRANROUND_RADIUS,4);
_c(hidepadcontainpiece)->setGradientBackgroundColor(hidepadcontainpiece,
hidekeypad_gradient_color,hidekeypad_gradient_pos,TABLESIZE(hidekeypad_gradient_color),
btndown_gradient_color,btndown_gradient_pos,TABLESIZE(btndown_gradient_color));
_c(background)->setProperty(background,NCSP_TRANROUND_FILLENGINE,TRANROUND_FILLENGINE_NORMAL);
_c(hidepadcontainpiece)->setStates(hidepadcontainpiece);
m_btnPiece[BTN_HIDEPAD] = hidepadcontainpiece;
/* end set hidepad label piece */
return containerctrl;
}
static void act_onDraw (MGEFF_ANIMATION handle, void* target, intptr_t id, void* value)
{
ANIMATION_INDEX index;
mPanelPiece *self = (mPanelPiece *)target;
PhoneCallActivity* act;
HWND main_hwnd = GetMainWindowHandle(_c(self)->getOwner(self)->hwnd);
act = (PhoneCallActivity*)
Activity::getActivityFromHWND (main_hwnd);
if (act == NULL)
return;
func_contain_piece *contain_piece = NULL;
contain_piece = act->getFuncContainPiece(self,&index);
if (contain_piece == NULL)
return;
if (id == 1) {
POINT *pt = (POINT*)value;
_c(self)->movePiece(self,
(mHotPiece *)contain_piece->func_subimage_piece,pt->x,pt->y);
}else{
int alpha = *((int *)value);
_c(self)->setPieceAlpha(self,
(mHotPiece *)contain_piece->func_subimage_piece,alpha);
}
return;
}
static void my_finish_cb(MGEFF_ANIMATION handle)
{
return;
}
MGEFF_ANIMATION PhoneCallActivity::startImageMoveAnimation(mContainerCtrl *ctnr,
ANIMATION_INDEX idx,int duration,enum EffMotionType type,
int offset)
{
POINT pts = {0, 0};
POINT pte = {0, 0};
MGEFF_ANIMATION animation;
MGEFF_ANIMATION animation1;
MGEFF_ANIMATION animation2;
//HWND main_hwnd;
mPanelPiece *self;
func_contain_piece *contain_piece = NULL;
ANIMATION_INDEX index = idx;
int id;
if (offset == 0||idx<ANIMATION_MUTE||idx >= ANIMATION_MAX)
{
return NULL;
}
if (index == ANIMATION_MUTE)
id = 0;
else if (index == ANIMATION_HANDSFREE)
id = 2;
else
return NULL;
PBITMAP pbitmap = (PBITMAP)RetrieveRes(bmpfiles[id]);
pts.x = (FUNC_BTN_W-pbitmap->bmWidth)>>1;
pts.y = ((FUNC_BTN_H-pbitmap->bmHeight)>>1)-offset;
pte.x = (FUNC_BTN_W-pbitmap->bmWidth)>>1;
pte.y = ((FUNC_BTN_H-pbitmap->bmHeight)>>1)+offset;
contain_piece = getFuncContainPiece(NULL,&index);
if (contain_piece == NULL)
return NULL;
self = contain_piece->func_subcontain_piece;
if (self == NULL)
return NULL;
if (contain_piece->animation_handle != NULL)
{
mGEffAnimationResume(contain_piece->animation_handle);
return contain_piece->animation_handle;
}
assert(ctnr);
//main_hwnd = GetMainWindowHandle(ctnr->hwnd);
animation = mGEffAnimationCreateGroup(MGEFF_SEQUENTIAL);
if (animation == NULL)
return NULL;
if (idx) {
animation1 = mGEffAnimationCreate (self, act_onDraw, 1, MGEFF_POINT);
mGEffAnimationSetStartValue (animation1, &pts);
mGEffAnimationSetEndValue (animation1, &pte);
mGEffAnimationSetCurve (animation1,InQuad);
mGEffAnimationSetDuration (animation1, duration);
animation2 = mGEffAnimationCreate (self, act_onDraw,
1, MGEFF_POINT);
mGEffAnimationSetStartValue (animation2, &pte);
mGEffAnimationSetEndValue (animation2, &pts);
mGEffAnimationSetCurve (animation2,OutQuad);
mGEffAnimationSetDuration (animation2, duration);
}else{
int alphaStart = 0xff, alphaEnd = 0x00;
duration = 800;
EffMotionType curve = InQuad;
animation1 = mGEffAnimationCreate (self, act_onDraw,
2, MGEFF_INT);
mGEffAnimationSetStartValue (animation1, &alphaStart);
mGEffAnimationSetEndValue (animation1, &alphaEnd);
mGEffAnimationSetCurve (animation1,curve);
mGEffAnimationSetDuration (animation1, duration);
animation2 = mGEffAnimationCreate (self, act_onDraw,
2, MGEFF_INT);
mGEffAnimationSetStartValue (animation2, &alphaEnd);
mGEffAnimationSetEndValue (animation2, &alphaStart);
mGEffAnimationSetCurve (animation2,curve);
mGEffAnimationSetDuration (animation2, duration);
}
mGEffAnimationAddToGroup(animation,animation1);
mGEffAnimationAddToGroup(animation,animation2);
mGEffAnimationSetProperty(animation, MGEFF_PROP_LOOPCOUNT,LOOP_COUNT);
mGEffAnimationSetFinishedCb(animation, my_finish_cb);
_c((mPanelPiece*)ctnr->body)->animationAsyncRun ((mPanelPiece*)ctnr->body, animation, 0);
contain_piece->animation_handle = animation;
return animation;
}
void PhoneCallActivity::stopImageMoveAnimation(mContainerCtrl *ctnr,ANIMATION_INDEX idx)
{
mPanelPiece *self;
func_contain_piece *contain_piece = NULL;
ANIMATION_INDEX index = idx;
int id;
if (index == ANIMATION_MUTE)
id = 0;
else if (index == ANIMATION_HANDSFREE)
id = 2;
else
return;
PBITMAP pbitmap = (PBITMAP)RetrieveRes(bmpfiles[id]);
if (idx<ANIMATION_MUTE||idx >= ANIMATION_MAX)
{
return ;
}
contain_piece = getFuncContainPiece(NULL,&index);
if (contain_piece == NULL)
return ;
self = contain_piece->func_subcontain_piece;
if (self == NULL)
return ;
set_gradient_color(contain_piece->func_subgradient_piece,
func_bk_gradient_color,func_bk_gradient_pos,TABLESIZE(func_bk_gradient_color));
self = contain_piece->func_subcontain_piece;
if (id == 2)
{
_c(self)->movePiece(self,
(mHotPiece *)contain_piece->func_subimage_piece,
(FUNC_BTN_W-pbitmap->bmWidth)>>1, (FUNC_BTN_H-pbitmap->bmHeight)>>1);
}
else if (id == 0)
{
_c(self)->setPieceAlpha(self,
(mHotPiece *)contain_piece->func_subimage_piece,255);
}
mGEffAnimationPause(contain_piece->animation_handle);
PanelPiece_invalidatePiece((mHotPiece*)self, NULL);
return;
}
static void act_push(mContainerCtrl *ctnr,PhoneCallActivity* act,int id,int pt)
{
int hidepadx,hidepady;
float temp;
RECT rc;
mButtonPanelPiece *endcallcontainpiece;
mButtonPanelPiece *hidepadcontainpiece;
mPanelPiece *self = (mPanelPiece *)ctnr->body;
endcallcontainpiece = act->getBtnPiece(BTN_ENDCALL);
hidepadcontainpiece = act->getBtnPiece(BTN_HIDEPAD);
if (id == 1)
{
hidepadx = HIDEPAD_X+(HIDEPAD_W - pt);
hidepady = ENDCALL_Y;
temp = (float)HIDEPAD_W*(2.0-(float)pt/HIDEPAD_W);
SetRect(&rc, 0, 0, hidepadx, CALL_END_CALL_H - (ENDCALL_Y<<1));
PanelPiece_invalidatePiece((mHotPiece*)endcallcontainpiece, &rc);
SetRect(&rc,0,0,(int)temp,CALL_END_CALL_H-(ENDCALL_Y<<1));
}
else
{
hidepadx = HIDEPAD_X+pt;
hidepady = ENDCALL_Y;
if (pt == HIDEPAD_W)
hidepadx = 400;
temp = (float)HIDEPAD_W*(1.0+(float)pt/HIDEPAD_W);
if (pt == HIDEPAD_W)
temp += ENDCALL_HIDEPAD_SPACE;
SetRect(&rc,0,0,(int)temp,CALL_END_CALL_H-(ENDCALL_Y<<1));
PanelPiece_invalidatePiece((mHotPiece*)endcallcontainpiece, &rc);
}
_c(self)->movePiece(self,
(mHotPiece *)hidepadcontainpiece,hidepadx,hidepady);
_c(endcallcontainpiece)->setRect(endcallcontainpiece,&rc);
return;
}
static void act_flip(mContainerCtrl *ctnr,PhoneCallActivity* act,int id,int pt)
{
float angle;
mPanelPiece *func_self;
func_self = (mPanelPiece *)ctnr->body;
if (id == 1)
{
angle = 180.0*((float)pt/HIDEPAD_W);
/* this just for 32bit pixel format bitmap show */
if (angle == 0)
angle = 1;
if (angle <=90)
{
_c(func_self)->rotatePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_FUNC),angle,0,1,0);
}
else
{
_c(func_self)->movePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_FUNC),400,CALL_INFO_H);
_c(func_self)->movePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_KEYPAD),0,CALL_INFO_H);
_c(func_self)->rotatePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_KEYPAD),angle,0,1,0);
}
}
else
{
angle = 180.0-180.0*((float)pt/HIDEPAD_W);
if (angle > 90)
{
_c(func_self)->rotatePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_KEYPAD),angle,0,1,0);
}
else
{
_c(func_self)->movePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_KEYPAD),400,CALL_INFO_H);
_c(func_self)->movePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_FUNC),0,CALL_INFO_H);
_c(func_self)->rotatePiece(func_self,
(mHotPiece *)act->getCntrPiece(CNTR_FUNC),angle,0,1,0);
}
}
}
static void act_pushflipCB (MGEFF_ANIMATION handle, void* target, intptr_t id, void* value)
{
HWND main_hwnd;
mContainerCtrl *ctnr = (mContainerCtrl *)target;
PhoneCallActivity* act;
mContainerCtrl *function_ctrl;
int pt = *(int*)value;
if (ctnr == NULL)
return;
main_hwnd = GetMainWindowHandle(ctnr->hwnd);
act = (PhoneCallActivity*)Activity::getActivityFromHWND(main_hwnd);
if (act == NULL)
return;
function_ctrl = (mContainerCtrl *)ncsGetChildObj(main_hwnd, ID_CTRN_FUNC);
if (function_ctrl == NULL)
return;
act_push(ctnr,act,id,pt);
act_flip(function_ctrl,act,id,pt);
return;
}
MGEFF_ANIMATION PhoneCallActivity::startFlipPushAnimation(mContainerCtrl *ctnr,
int duration,enum EffMotionType type,DWORD add_data)
{
int i;
int pte = 0;
int pts = HIDEPAD_W;
MGEFF_ANIMATION animation;
HWND main_hwnd = GetMainWindowHandle(ctnr->hwnd);
mContainerCtrl *btn = (mContainerCtrl *)ncsGetChildObj(main_hwnd, ID_BTN_ENDCALL);
mContainerCtrl *pad_ctrl = (mContainerCtrl *)ncsGetChildObj(main_hwnd, ID_CTRN_FUNC);
mPanelPiece* cntr = (mPanelPiece*)pad_ctrl->body;
PBITMAP pbitmap;
mImagePiece* image;
func_contain_piece *contain_piece = NULL;
PhoneCallActivity* act = (PhoneCallActivity*)Activity::getActivityFromHWND (main_hwnd);
if (btn == ctnr)
{
animation = mGEffAnimationCreate (ctnr, act_pushflipCB, 0, MGEFF_INT);
}
else
{
/* if is func container must change bitmap pixel format to match the cache dc */
for ( i = 0; i < ANIMATION_MAX; i++ ) {
pbitmap = (PBITMAP)RetrieveRes(bmpfiles[i+4]);
contain_piece = act->getFuncContainPiece(NULL, (ANIMATION_INDEX*)&i);
image = contain_piece->func_subimage_piece;
_c(image)->setProperty(image, NCSP_IMAGEPIECE_IMAGE, (DWORD)pbitmap);
}
/* update the cache */
_c(cntr)->updateChildCache(cntr, (mHotPiece*)m_ctrnPiece[CNTR_FUNC]);
animation = mGEffAnimationCreate (btn, act_pushflipCB, 1, MGEFF_INT);
}
mGEffAnimationSetStartValue (animation, &pte);
mGEffAnimationSetEndValue (animation, &pts);
mGEffAnimationSetCurve (animation,type);
mGEffAnimationSetDuration (animation, duration);
_c((mPanelPiece*)ctnr->body)->animationSyncRunAndDelete ((mPanelPiece*)ctnr->body, animation);
/* if is func container must restore bitmap pixel format to match the real dc */
if (btn != ctnr) {
for ( i = 0; i < ANIMATION_MAX; i++ ) {
pbitmap = (PBITMAP)RetrieveRes(bmpfiles[i]);
contain_piece = act->getFuncContainPiece(NULL, (ANIMATION_INDEX*)&i);
image = contain_piece->func_subimage_piece;
_c(image)->setProperty(image, NCSP_IMAGEPIECE_IMAGE, (DWORD)pbitmap);
}
InvalidateRect(pad_ctrl->hwnd, NULL, TRUE);
}
return NULL;
}
int PhoneCallActivity::onStop()
{
imageAnimationPauseResume(this,TRUE);
return 0;
}
| 35.518345 | 105 | 0.660608 | zhiqiang-hu |
167d1a6a38f47e1add1967c79c3dcb161c3cf94f | 2,821 | cpp | C++ | src/Common/TokenType.cpp | Morphlng/cploxplox | f7f64c535b76bdaab90d7ea7fd0377bf44595c71 | [
"MIT"
] | null | null | null | src/Common/TokenType.cpp | Morphlng/cploxplox | f7f64c535b76bdaab90d7ea7fd0377bf44595c71 | [
"MIT"
] | null | null | null | src/Common/TokenType.cpp | Morphlng/cploxplox | f7f64c535b76bdaab90d7ea7fd0377bf44595c71 | [
"MIT"
] | null | null | null | #include "Common/TokenType.h"
namespace CXX {
const char* TypeName(TokenType type)
{
switch (type)
{
case TokenType::PLUS: // +
return "PLUS";
case TokenType::MINUS: // -
return "MINUS";
case TokenType::MUL: // *
return "MUL";
case TokenType::DIV: // /
return "DIV";
case TokenType::MOD: // %
return "MOD";
case TokenType::LPAREN: // (
return "LPAREN";
case TokenType::RPAREN: // )
return "RPAREN";
case TokenType::LBRACE: // [
return "LBRACE";
case TokenType::RBRACE: // ]
return "RBRACE";
case TokenType::LBRACKET: // {
return "LBRACKET";
case TokenType::RBRACKET: // }
return "RBRACKET";
case TokenType::COMMA: // ,
return "COMMA";
case TokenType::DOT: // .
return "DOT";
case TokenType::COLON: //:
return "PLUS";
case TokenType::SEMICOLON: // ;
return "SEMICOLON";
case TokenType::PLUS_PLUS:
return "PLUS_PLUS";
case TokenType::MINUS_MINUS:
return "MINUS_MINUS";
case TokenType::PLUS_EQUAL:
return "PLUS_EQUAL";
case TokenType::MINUS_EQUAL:
return "MINUS_EQUAL";
case TokenType::MUL_EQUAL:
return "MUL_EQUAL";
case TokenType::DIV_EQUAL:
return "DIV_EQUAL";
case TokenType::QUESTION_MARK: // ?
return "QUESTION_MARK";
// bool
case TokenType::BANG: // !
return "BANG";
case TokenType::BANGEQ: // !=
return "BANGEQ";
case TokenType::EQ: // =
return "EQ";
case TokenType::EQEQ: // ==
return "EQEQ";
case TokenType::GT: // >
return "GT";
case TokenType::GTE: // >=
return "GTE";
case TokenType::LT: // LT
return "LT";
case TokenType::LTE: // <=
return "LTE";
// primary
case TokenType::NUMBER: // number
return "NUMBER";
case TokenType::STRING: // string
return "STRING";
case TokenType::IDENTIFIER: // identifier
return "IDENTIFIER";
// keyword
case TokenType::NIL: // nil, represent undefined variable
return "NIL";
case TokenType::TRUE: // true
return "TRUE";
case TokenType::FALSE: // false
return "FALSE";
case TokenType::VAR:
return "VAR";
case TokenType::CLASS:
return "CLASS";
case TokenType::THIS:
return "THIS";
case TokenType::SUPER:
return "IDENTIFIER";
case TokenType::IF:
return "IF";
case TokenType::ELSE:
return "ELSE";
case TokenType::FOR:
return "FOR";
case TokenType::WHILE:
return "WHILE";
case TokenType::BREAK:
return "BREAK";
case TokenType::CONTINUE:
return "CONTINUE";
case TokenType::FUNC:
return "FUNC";
case TokenType::RETURN:
return "RETURN";
case TokenType::AND:
return "AND";
case TokenType::OR:
return "OR";
case TokenType::IMPORT:
return "IMPORT";
case TokenType::AS:
return "AS";
case TokenType::FROM:
return "FROM";
case TokenType::END_OF_FILE:
return "EOF";
}
return "unreachable";
}
} | 21.371212 | 59 | 0.631691 | Morphlng |
167e531f1fabb80e12c24ac291623b3e2646b1ce | 304 | cpp | C++ | Main/P1615.cpp | qinyihao/Luogu_Problem_Solver | bb4675f045affe513613023394027c3359bb0876 | [
"MIT"
] | null | null | null | Main/P1615.cpp | qinyihao/Luogu_Problem_Solver | bb4675f045affe513613023394027c3359bb0876 | [
"MIT"
] | null | null | null | Main/P1615.cpp | qinyihao/Luogu_Problem_Solver | bb4675f045affe513613023394027c3359bb0876 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long long a2,b2,c2,s2;
long long a1,b1,c1,s1;
long long k,ans;
int main()
{
scanf("%lld:%lld:%lld\n%lld:%lld:%lld",&a1,&b1,&c1,&a2,&b2,&c2);
s1=a1*3600+b1*60+c1;
s2=a2*3600+b2*60+c2;
scanf("%lld",&k);
ans=k*(s2-s1);
printf("%lld",ans);
return 0;
}
| 16.888889 | 65 | 0.605263 | qinyihao |
168098d4959918324edb9474d337f02c97e1b905 | 2,148 | cpp | C++ | src/Utils.cpp | lyftt/WebServer | adc2ef7f999e6c6e75cea46087161fe21116bd40 | [
"MIT"
] | null | null | null | src/Utils.cpp | lyftt/WebServer | adc2ef7f999e6c6e75cea46087161fe21116bd40 | [
"MIT"
] | null | null | null | src/Utils.cpp | lyftt/WebServer | adc2ef7f999e6c6e75cea46087161fe21116bd40 | [
"MIT"
] | null | null | null | #include "Utils.h"
#include <fcntl.h>
#include <sys/epoll.h>
#include "config.h"
#include "http_conn.h"
#include "TimerSortList.h"
#include "webserver.h"
/*静态遍历定义*/
int Utils::u_epollfd = -1;
/*
*
* 设置fd为非阻塞
*
*/
int Utils::setnonblocking(int fd)
{
int old_opt = fcntl(fd,F_GETFL);
int new_opt = old_opt | O_NONBLOCK;
fcntl(fd,F_SETFL,new_opt);
return old_opt;
}
/*
*
*重置文件描述的epolloneshot事件
*
*/
bool Utils::modfd(int epollfd, int fd, int ev, int trig_mode)
{
epoll_event event;
event.data.fd = fd;
if (ET == trig_mode)
{
event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP; //ET 触发模式
}
else
{
event.events = ev | EPOLLONESHOT | EPOLLRDHUP; //LT 触发模式
}
epoll_ctl(u_epollfd,EPOLL_CTL_MOD,fd,&event); //重置epolloneshot事件
}
/*
*将文件描述符注册到epoll内核事件表
*
*/
bool Utils::addfd(int epollfd, int fd, bool one_shot, int trig_mode)
{
epoll_event event;
event.data.fd = fd;
if (ET == trig_mode)
{
event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; //高效ET模式,监听可读事件和连接断开事件
}
else
{
event.events = EPOLLIN | EPOLLRDHUP; //普通LT模式,监听可读事件和连接断开事件
}
if (one_shot)
event.events |= EPOLLONESHOT;
epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event);
setnonblocking(fd);
return true;
}
/*
*
* 设置epollfd
*
**/
int Utils::set_epollfd(int epollfd)
{
int old_value = u_epollfd;
u_epollfd = epollfd;
return old_value;
}
/*
*
* 获取epollfd
*
**/
int Utils::get_epollfd()
{
return u_epollfd;
}
/*
*
* 定时器的回调函数
*
*/
void Utils::cb_func(client_data* user_data)
{
if (!user_data)
return;
epoll_ctl(u_epollfd,EPOLL_CTL_DEL,user_data->sockfd,0); //从监听的红黑树中删除这个连接
close(user_data->sockfd); //关闭连接
http_conn::m_user_count--; //连接数量减一
}
/*
*
* 还没绑定到定时器时,直接调用close关闭连接即可
*
*/
void Utils::show_error(int connfd,const char *info)
{
send(connfd,info,strlen(info),0);
close(connfd);
}
/*
*
* 超时的处理函数
*
*/
void Utils::timer_handler(TimerSortList* list)
{
list->tick();
alarm(TIMESLOT);
}
| 15.565217 | 77 | 0.604749 | lyftt |
1682841d20ba5c157c575c46c93dbb99c6bb5b30 | 2,972 | cpp | C++ | Ilya Bondarenko/EditedFinance.cpp | soomrack/MR2020 | 2de7289665dcdac4a436eb512f283780aa78cb76 | [
"MIT"
] | 4 | 2020-09-22T12:04:07.000Z | 2020-10-03T22:28:00.000Z | Ilya Bondarenko/EditedFinance.cpp | soomrack/MR2020 | 2de7289665dcdac4a436eb512f283780aa78cb76 | [
"MIT"
] | null | null | null | Ilya Bondarenko/EditedFinance.cpp | soomrack/MR2020 | 2de7289665dcdac4a436eb512f283780aa78cb76 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
// Edited by Panteleev M. D.
int main()
{
setlocale(LC_ALL, "Rus");
float d1=0;
float x, y,z, t, n;
n = 0;
// программа для подсчета выполаты по ипотеке
//начало
float stavka, ttt, mstavka, os, emp, od, pch, och, x2, sk, pow1, time, total,total1;
int n1, n2;
cout << "Введите процентную ставку годовых: ";
cin >> stavka;
cout << "Введите количество лет ипотеки: ";
cin >> ttt;
cout << "Введите сумму кредита: ";
cin >> sk;
cout << endl << "Введите ежемесячный доход: ";
cin >> x2;
n1 = 0;
n2 = 0;
mstavka = stavka / 12 / 100; // находим ежемесячную ставку
ttt = ttt * 12; // срок ипотеки в месяцах
pow1 = 1 + mstavka;
os = pow(pow1, ttt); //находим общую ставку
emp = sk * mstavka * os / (os - 1);// находим ежемесячный платеж
od = sk;// приравниваем остаток долка к сумме кредита
total = emp * ttt;
total1 = total;
cout << "Ежемесячный платеж : " << emp << endl;
cout << "Количество долга : " << total << endl;
n1 = 0;
while (total >= 0 )
{
total = total - emp-x2;
n1 = n1 + 1;
n2 = n2 + 1;
}
n1 = n1/12;
n2 = n2 ;
n2 = n2 % 12;
cout << "Количество времени, через которое будет выплачена вся сумма: " << n1 <<" лет" << endl <<n2 <<" месяцев"<< endl;
cout << "остаток: " << (total1 - n1 * 12 * (emp + x2) - (n2) * (emp + x2)) * (-1) << endl << endl;
//конец
// программа для подсчета стоимости квартиры после инфляции
// начало
float ct, tt, a = 0, prozent;
cout << "Введите процент инфляции: ";
cin >> prozent;
cout << "Введите стоимость квартиры: ";
cin >> ct;
cout << "Введите количество лет: ";
cin >> tt;
int month = rand() % (int)tt+1;
while (a < tt)
{
if (a==month) //В один из месяцев недвижимость растет в цене (открыли рядом метро)
{
cout << "Wow! Your property greatly increased in price!" << '\n';
ct += 300000;
}
ct = ct * (1 + prozent / 100);
a = a + 1;
}
cout << "Стоимость квартиры через " << tt << " лет (года)" << ct << endl << endl;
//конец
// программа для подсчета средств при депозите
//начало
cout << "Введите начальный капитал: ";
cin >> d1;
cout << "Введите доход: ";
cin >> x;
cout << "Введите процент годовых депозита: ";
cin >> z;
cout << "Введите срок депозита: ";
cin >> t;
int probability = rand()%100+1;
int year = rand() % (int)t +1;
while (n<t)
{
if (probability >= 92 && year == n) //С определенной вероятностью в один из годов может обанкротиться банк
{
cout << "Bank went buckrupt! You lost some of your money" << '\n';
d1 -= 600000;
}
d1 = d1* (1 + z / 100);
d1 = d1 + x * 12;
n = n + 1;
}
cout << d1 << endl;
//конец
if (d1>=ct)
{
cout << endl << "Сумма,находящаяся в банке позволяет купить квартиру.";
}
else {
cout << "Сумма,находящаяся в банке не позволяет купить квартиру.";
}
}
| 24.97479 | 122 | 0.564266 | soomrack |
168340b0962936f89e2b4371955683ee49c3f378 | 3,871 | cpp | C++ | pgadmin/dlg/dlgSchema.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 111 | 2015-01-02T15:39:46.000Z | 2022-01-08T05:08:20.000Z | pgadmin/dlg/dlgSchema.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 13 | 2015-07-08T20:26:20.000Z | 2019-06-17T12:45:35.000Z | pgadmin/dlg/dlgSchema.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 96 | 2015-03-11T14:06:44.000Z | 2022-02-07T10:04:45.000Z | //////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2016, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// dlgSchema.cpp - PostgreSQL Schema Property
//
//////////////////////////////////////////////////////////////////////////
// wxWindows headers
#include <wx/wx.h>
// App headers
#include "pgAdmin3.h"
#include "utils/misc.h"
#include "dlg/dlgSchema.h"
#include "schema/pgSchema.h"
#include "ctl/ctlSeclabelPanel.h"
// pointer to controls
BEGIN_EVENT_TABLE(dlgSchema, dlgDefaultSecurityProperty)
END_EVENT_TABLE();
dlgProperty *pgSchemaBaseFactory::CreateDialog(frmMain *frame, pgObject *node, pgObject *parent)
{
return new dlgSchema(this, frame, (pgSchema *)node, parent);
}
dlgSchema::dlgSchema(pgaFactory *f, frmMain *frame, pgSchema *node, pgObject *parent)
: dlgDefaultSecurityProperty(f, frame, node, wxT("dlgSchema"), wxT("USAGE,CREATE"), "UC", node != NULL ? true : false)
{
schema = node;
seclabelPage = new ctlSeclabelPanel(nbNotebook);
}
pgObject *dlgSchema::GetObject()
{
return schema;
}
int dlgSchema::Go(bool modal)
{
wxString strDefPrivsOnTables, strDefPrivsOnSeqs, strDefPrivsOnFuncs, strDefPrivsOnTypes;
if (connection->BackendMinimumVersion(9, 1))
{
seclabelPage->SetConnection(connection);
seclabelPage->SetObject(schema);
this->Connect(EVT_SECLABELPANEL_CHANGE, wxCommandEventHandler(dlgSchema::OnChange));
}
else
seclabelPage->Disable();
if (schema)
{
if (connection->BackendMinimumVersion(9, 0))
{
strDefPrivsOnTables = schema->GetDefPrivsOnTables();
strDefPrivsOnSeqs = schema->GetDefPrivsOnSequences();
strDefPrivsOnFuncs = schema->GetDefPrivsOnFunctions();
}
if (connection->BackendMinimumVersion(9, 2))
strDefPrivsOnTypes = schema->GetDefPrivsOnTypes();
// edit mode
if (!connection->BackendMinimumVersion(7, 5))
cbOwner->Disable();
if (schema->GetMetaType() == PGM_CATALOG)
{
cbOwner->Disable();
txtName->Disable();
}
}
else
{
// create mode
}
return dlgDefaultSecurityProperty::Go(modal, true, strDefPrivsOnTables, strDefPrivsOnSeqs, strDefPrivsOnFuncs, strDefPrivsOnTypes);
}
pgObject *dlgSchema::CreateObject(pgCollection *collection)
{
wxString name = GetName();
pgObject *obj = schemaFactory.CreateObjects(collection, 0, wxT(" WHERE nspname=") + qtDbString(name) + wxT("\n"));
return obj;
}
#ifdef __WXMAC__
void dlgSchema::OnChangeSize(wxSizeEvent &ev)
{
SetPrivilegesLayout();
if (GetAutoLayout())
{
Layout();
}
}
#endif
void dlgSchema::CheckChange()
{
bool enable = true;
wxString name = GetName();
if (schema)
{
enable = name != schema->GetName()
|| txtComment->GetValue() != schema->GetComment()
|| cbOwner->GetValue() != schema->GetOwner();
if (seclabelPage && connection->BackendMinimumVersion(9, 1))
enable = enable || !(seclabelPage->GetSqlForSecLabels().IsEmpty());
}
else
{
CheckValid(enable, !name.IsEmpty(), _("Please specify name."));
}
EnableOK(enable);
}
wxString dlgSchema::GetSql()
{
wxString sql, name;
name = qtIdent(GetName());
if (schema)
{
// edit mode
AppendNameChange(sql);
AppendOwnerChange(sql, wxT("SCHEMA ") + name);
}
else
{
// create mode
sql = wxT("CREATE SCHEMA ") + name;
AppendIfFilled(sql, wxT("\n AUTHORIZATION "), qtIdent(cbOwner->GetValue()));
sql += wxT(";\n");
}
AppendComment(sql, wxT("SCHEMA"), 0, schema);
sql += GetGrant(wxT("UC"), wxT("SCHEMA ") + name);
if (connection->BackendMinimumVersion(9, 0) && defaultSecurityChanged)
sql += GetDefaultPrivileges(name);
if (seclabelPage && connection->BackendMinimumVersion(9, 1))
sql += seclabelPage->GetSqlForSecLabels(wxT("SCHEMA"), name);
return sql;
}
void dlgSchema::OnChange(wxCommandEvent &event)
{
CheckChange();
}
| 22.637427 | 132 | 0.676828 | cjayho |
1683814c6cc41a6ceed66a8ca49dc183f55e68c5 | 886 | cpp | C++ | elasticfusionpublic/GUI/src/Main.cpp | beichendexiatian/InstanceFusion | cd48e3f477595a48d845ce01302f564b6b3fc6f6 | [
"Apache-2.0"
] | 27 | 2016-03-02T09:43:59.000Z | 2021-12-01T06:30:31.000Z | elasticfusionpublic/GUI/src/Main.cpp | beichendexiatian/InstanceFusion | cd48e3f477595a48d845ce01302f564b6b3fc6f6 | [
"Apache-2.0"
] | 1 | 2022-03-27T13:09:39.000Z | 2022-03-27T13:09:39.000Z | GUI/src/Main.cpp | YabinXuTUD/HRBFFusion3D | 20dbff99782f31844791b09824bbfd9370d4a0c4 | [
"BSD-3-Clause"
] | 4 | 2016-03-02T05:52:59.000Z | 2018-04-29T00:37:30.000Z | /*
* This file is part of ElasticFusion.
*
* Copyright (C) 2015 Imperial College London
*
* The use of the code within this file and all code within files that
* make up the software that is ElasticFusion is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.imperial.ac.uk/dyson-robotics-lab/downloads/elastic-fusion/elastic-fusion-license/>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email researchcontracts.engineering@imperial.ac.uk.
*
*/
#include "MainController.h"
int main(int argc, char * argv[])
{
MainController mainController(argc, argv);
mainController.launch();
return 0;
}
| 30.551724 | 111 | 0.732506 | beichendexiatian |
16859bae680005ef9c5b767174458121a17b3063 | 3,820 | cc | C++ | src/converter/converter_regression_test.cc | google-admin/mozc | d0efe11cc6232c4e99371c19d2e02303ba889233 | [
"BSD-3-Clause"
] | null | null | null | src/converter/converter_regression_test.cc | google-admin/mozc | d0efe11cc6232c4e99371c19d2e02303ba889233 | [
"BSD-3-Clause"
] | null | null | null | src/converter/converter_regression_test.cc | google-admin/mozc | d0efe11cc6232c4e99371c19d2e02303ba889233 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2010-2021, 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 <memory>
#include <string>
#include "base/file_util.h"
#include "base/system_util.h"
#include "composer/composer.h"
#include "composer/table.h"
#include "config/config_handler.h"
#include "converter/converter_interface.h"
#include "converter/segments.h"
#include "engine/engine_factory.h"
#include "engine/engine_interface.h"
#include "protocol/commands.pb.h"
#include "protocol/config.pb.h"
#include "request/conversion_request.h"
#include "testing/base/public/gunit.h"
#include "testing/base/public/mozctest.h"
namespace mozc {
namespace {
using composer::Table;
class ConverterRegressionTest : public ::testing::Test {
private:
const testing::ScopedTmpUserProfileDirectory scoped_profile_dir_;
};
TEST_F(ConverterRegressionTest, QueryOfDeathTest) {
std::unique_ptr<EngineInterface> engine = EngineFactory::Create().value();
ConverterInterface *converter = engine->GetConverter();
CHECK(converter);
{
Segments segments;
EXPECT_TRUE(converter->StartConversion(&segments, "りゅきゅけmぽ"));
}
{
Segments segments;
EXPECT_TRUE(converter->StartConversion(&segments, "5.1,||t:1"));
}
{
Segments segments;
// Converter returns false, but not crash.
EXPECT_FALSE(converter->StartConversion(&segments, ""));
}
{
Segments segments;
ConversionRequest conv_request;
// Create an empty composer.
const Table table;
const commands::Request request;
composer::Composer composer(&table, &request, nullptr);
conv_request.set_composer(&composer);
// Converter returns false, but not crash.
EXPECT_FALSE(converter->StartConversionForRequest(conv_request, &segments));
}
}
TEST_F(ConverterRegressionTest, Regression3323108) {
std::unique_ptr<EngineInterface> engine = EngineFactory::Create().value();
ConverterInterface *converter = engine->GetConverter();
Segments segments;
EXPECT_TRUE(converter->StartConversion(&segments, "ここではきものをぬぐ"));
EXPECT_EQ(3, segments.conversion_segments_size());
const ConversionRequest default_request;
EXPECT_TRUE(converter->ResizeSegment(&segments, default_request, 1, 2));
EXPECT_EQ(2, segments.conversion_segments_size());
EXPECT_EQ("きものをぬぐ", segments.conversion_segment(1).key());
}
} // namespace
} // namespace mozc
| 36.730769 | 80 | 0.756021 | google-admin |
168a0040034c92b44f4d34d6c41c4f370d3ff330 | 587 | cpp | C++ | zoom/canonical.cpp | indexgeo/yazpp | e2de35b08a9cb2aeca511bfe39e61c3c5b67b9d0 | [
"BSD-3-Clause"
] | 3 | 2018-09-14T11:02:44.000Z | 2020-10-07T21:48:21.000Z | zoom/canonical.cpp | indexgeo/yazpp | e2de35b08a9cb2aeca511bfe39e61c3c5b67b9d0 | [
"BSD-3-Clause"
] | null | null | null | zoom/canonical.cpp | indexgeo/yazpp | e2de35b08a9cb2aeca511bfe39e61c3c5b67b9d0 | [
"BSD-3-Clause"
] | 3 | 2016-01-29T08:02:22.000Z | 2017-02-14T10:23:23.000Z | /* g++ -g -o canonical canonical.cpp -lyaz++ -lyaz -lxml2 */
#include <iostream>
#include <yaz++/zoom.h>
using namespace ZOOM;
int main(int argc, char **argv)
{
connection conn("lx2.loc.gov", 210);
conn.option("databaseName", "LCDB");
conn.option("preferredRecordSyntax", "USMARC");
resultSet rs(conn, prefixQuery("@attr 1=7 0253333490"));
const record rec(rs, 0);
std::cout << rec.render() << std::endl;
}
/*
* Local variables:
* c-basic-offset: 4
* c-file-style: "Stroustrup"
* indent-tabs-mode: nil
* End:
* vim: shiftwidth=4 tabstop=8 expandtab
*/
| 22.576923 | 60 | 0.640545 | indexgeo |
168a35a894b7e48f5b34bc5d0054435015ddd494 | 6,773 | hpp | C++ | SGXDNN/layers/maxpool2d.hpp | LukeZheZhu/slalom | 96ff15977b7058b96d2a00a51c6aabbe729cc6d5 | [
"MIT"
] | 128 | 2018-06-11T06:07:21.000Z | 2022-03-30T19:33:29.000Z | SGXDNN/layers/maxpool2d.hpp | LukeZheZhu/slalom | 96ff15977b7058b96d2a00a51c6aabbe729cc6d5 | [
"MIT"
] | 41 | 2018-09-03T15:33:35.000Z | 2022-02-09T23:40:03.000Z | SGXDNN/layers/maxpool2d.hpp | LukeZheZhu/slalom | 96ff15977b7058b96d2a00a51c6aabbe729cc6d5 | [
"MIT"
] | 46 | 2018-11-23T09:11:20.000Z | 2022-03-21T08:38:39.000Z | #ifndef SGXDNN_MAXPOOL2D_H_
#define SGXDNN_MAXPOOL2D_H_
#include <iostream>
#include <string>
#include "../mempool.hpp"
#include "layer.hpp"
#include "eigen_maxpool.h"
using namespace tensorflow;
namespace SGXDNN
{
template<typename T>
void fast_maxpool(T* input, T* output,
int batch, int input_rows_, int input_cols_, int input_depth_, int out_rows_, int out_cols_,
int window_rows_, int window_cols_, int pad_rows_, int pad_cols_, int row_stride_, int col_stride_,
bool avg_pool = false)
{
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> ConstEigenMatrixMap;
typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> EigenMatrixMap;
ConstEigenMatrixMap in_mat(input, input_depth_,
input_cols_ * input_rows_ * batch);
EigenMatrixMap out_mat(output, input_depth_, out_rows_ * out_cols_ * batch);
// The following code basically does the following:
// 1. Flattens the input and output tensors into two dimensional arrays.
// tensor_in_as_matrix:
// depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)
// output_as_matrix:
// depth by (out_width * out_height * tensor_in_batch)
//
// 2. Walks through the set of columns in the flattened
// tensor_in_as_matrix,
// and updates the corresponding column(s) in output_as_matrix with the
// max value.
auto shard = [&in_mat, &out_mat, input_rows_, input_cols_, input_depth_, out_rows_, out_cols_,
window_rows_, window_cols_, pad_rows_, pad_cols_, row_stride_, col_stride_, avg_pool](long start, long limit) {
const int in_rows = input_rows_;
const int in_cols = input_cols_;
const int window_rows = window_rows_;
const int window_cols = window_cols_;
const int pad_rows = pad_rows_;
const int pad_cols = pad_cols_;
const int row_stride = row_stride_;
const int col_stride = col_stride_;
const int out_height = out_rows_;
const int out_width = out_cols_;
const int input_depth = input_depth_;
{
// Initializes the output tensor with MIN<T>.
const int output_image_size = out_height * out_width * input_depth;
EigenMatrixMap out_shard(out_mat.data() + start * output_image_size,
1, (limit - start) * output_image_size);
if (avg_pool) {
out_shard.setConstant((T) 0.0);
} else {
out_shard.setConstant(Eigen::NumTraits<T>::lowest());
}
}
for (int b = start; b < limit; ++b) {
const int out_offset_batch = b * out_height;
for (int h = 0; h < in_rows; ++h) {
for (int w = 0; w < in_cols; ++w) {
// (h_start, h_end) * (w_start, w_end) is the range that the input
// vector projects to.
const int hpad = h + pad_rows;
const int wpad = w + pad_cols;
const int h_start = (hpad < window_rows)
? 0
: (hpad - window_rows) / row_stride + 1;
const int h_end = std::min(hpad / row_stride + 1, out_height);
const int w_start = (wpad < window_cols)
? 0
: (wpad - window_cols) / col_stride + 1;
const int w_end = std::min(wpad / col_stride + 1, out_width);
// compute elementwise max
const int in_offset = (b * in_rows + h) * in_cols + w;
for (int ph = h_start; ph < h_end; ++ph) {
const int out_offset_base =
(out_offset_batch + ph) * out_width;
for (int pw = w_start; pw < w_end; ++pw) {
const int out_offset = out_offset_base + pw;
if (avg_pool) {
out_mat.col(out_offset) += in_mat.col(in_offset) / ((T)(window_rows * window_cols));
} else {
out_mat.col(out_offset) = out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));
}
}
}
}
}
}
};
shard(0, batch);
}
template <typename T> class MaxPool2D : public Layer<T>
{
public:
explicit MaxPool2D(
const std::string& name,
const array4d input_shape,
const int window_rows,
const int window_cols,
const int row_stride,
const int col_stride,
const Eigen::PaddingType& padding,
const bool avg_pool,
MemPool* mem_pool
): Layer<T>(name, input_shape),
window_rows_(window_rows),
window_cols_(window_cols),
row_stride_(row_stride),
col_stride_(col_stride),
padding_(padding),
avg_pool_(avg_pool),
mem_pool_(mem_pool)
{
input_rows_ = input_shape[1];
input_cols_ = input_shape[2];
input_depth_ = input_shape[3];
GetWindowedOutputSize(input_rows_, window_rows_, row_stride_,
padding_, &out_rows_, &pad_rows_);
GetWindowedOutputSize(input_cols_, window_cols_, col_stride_,
padding_, &out_cols_, &pad_cols_);
output_shape_ = {0, out_rows_, out_cols_, input_depth_};
output_size_ = out_rows_ * out_cols_ * input_depth_;
printf("in Pool2D with window = (%d, %d), stride = (%d, %d), padding = %d, out_shape = (%d, %d, %d), pad = (%d, %d)\n",
window_rows_, window_cols_, row_stride_, col_stride_, padding_, out_rows_, out_cols_, input_depth_, pad_rows_, pad_cols_);
}
array4d output_shape() override
{
return output_shape_;
}
int output_size() override
{
return output_size_;
}
protected:
TensorMap<T, 4> apply_impl(TensorMap<T, 4> input, void* device_ptr = NULL, bool release_input = true) override
{
int batch = input.dimension(0);
output_shape_[0] = batch;
T* output_mem_ = mem_pool_->alloc<T>(batch * output_size_);
auto output_map = TensorMap<T, 4>(output_mem_, output_shape_);
fast_maxpool(input.data(), output_map.data(),
batch, input_rows_, input_cols_, input_depth_, out_rows_, out_cols_,
window_rows_, window_cols_, pad_rows_, pad_cols_, row_stride_, col_stride_, avg_pool_);
mem_pool_->release(input.data());
return output_map;
}
TensorMap<T, 4> fwd_verify_impl(TensorMap<T, 4> input, float** aux_data, int linear_idx, void* device_ptr = NULL, bool release_input = true) override
{
auto output_map = apply_impl(input, device_ptr, release_input);
if (avg_pool_) {
output_map = output_map.round();
}
return output_map;
}
int input_rows_;
int input_cols_;
int input_depth_;
int out_rows_;
int out_cols_;
int pad_rows_;
int pad_cols_;
const Eigen::PaddingType padding_;
const int window_rows_;
const int window_cols_;
const int row_stride_;
const int col_stride_;
const bool avg_pool_;
MemPool* mem_pool_;
array4d output_shape_;
int output_size_;
};
}
#endif
| 32.878641 | 151 | 0.643142 | LukeZheZhu |
168c5e0c9c9aefd0d15b3bdd7d521e1917a5f2fc | 1,585 | cpp | C++ | src/numeric_overflow.cpp | prasertcbs/C_plus_plus | d2ad3665506e861e7664710971b361ed0e023a8c | [
"MIT"
] | null | null | null | src/numeric_overflow.cpp | prasertcbs/C_plus_plus | d2ad3665506e861e7664710971b361ed0e023a8c | [
"MIT"
] | null | null | null | src/numeric_overflow.cpp | prasertcbs/C_plus_plus | d2ad3665506e861e7664710971b361ed0e023a8c | [
"MIT"
] | null | null | null | // numeric overflow
// ex. https://arstechnica.com/information-technology/2014/12/gangnam-style-overflows-int_max-forces-youtube-to-go-64-bit/
#include <iostream>
#include <limits> // to find min, max values of data types
#include <cmath> // to use pow() function
#include <bitset> // to print binary number
using namespace std;
int main() {
int i; // signed integer (store both positive and negative numbers)
cout << sizeof(i) << endl;
int imax = numeric_limits<int>::max(); // 2,147,483,647
int imin = numeric_limits<int>::min();
cout << "max int = " << imax << endl;
cout << "min int = " << imin << endl;
cout << "imax + 1 = " << imax + 1 << endl; // numeric overflow happens
cout << "imax + 10 = " << imax + 10 << endl;
// cout << pow(2, 31) - 1 << endl;
cout << (int) pow(2, 31) - 1 << endl;
cout << "imax = " << bitset<32>(imax) << endl;
unsigned int ui; // store only positive integer number (take 4 bytes)
unsigned int uimax = numeric_limits<unsigned int>::max(); //
unsigned int uimin = numeric_limits<unsigned int>::min(); //
cout << "max uint = " << uimax << endl;
cout << "min uint = " << uimin << endl;
unsigned long int uli; // take 8 bytes to store value
cout << "sizeof unsigned long int = " << sizeof(uli) << " bytes" << endl;
unsigned long int ulimax = numeric_limits<unsigned long int>::max(); //
unsigned long int ulimin = numeric_limits<unsigned long int>::min(); //
cout << "max ulint = " << ulimax << endl;
cout << "min ulint = " << ulimin << endl;
return 0;
} | 37.738095 | 122 | 0.605047 | prasertcbs |
168f66ea15283d8a72bc9c195b260f907bb4b951 | 2,439 | cpp | C++ | src/day09/day09.cpp | alikoptan/adventofcode2020 | 2d1cb40dcbc35cfc24ba22e20fdb6df127b7a318 | [
"Unlicense"
] | null | null | null | src/day09/day09.cpp | alikoptan/adventofcode2020 | 2d1cb40dcbc35cfc24ba22e20fdb6df127b7a318 | [
"Unlicense"
] | null | null | null | src/day09/day09.cpp | alikoptan/adventofcode2020 | 2d1cb40dcbc35cfc24ba22e20fdb6df127b7a318 | [
"Unlicense"
] | null | null | null | #include "string"
#include "deque"
#include "vector"
#include "iostream"
#include "climits"
#include "unordered_map"
using namespace std;
class day9 {
private:
const int PERMABLE = 25;
long long anomaly = 0;
vector <long long> numberList, prefixSum;
deque <long long> window;
void readFile() {
freopen("input.txt", "r", stdin);
string line;
while (getline(cin, line)) {
numberList.push_back(stol(line));
}
}
bool exists(deque<long long> currentWindow, long long target) {
unordered_map <long long, bool> table;
while (!currentWindow.empty()) {
if (table[target - currentWindow.front()])
return true;
table[currentWindow.front()] = true;
currentWindow.pop_front();
}
return false;
}
void initSum() {
long long currentSum = 0;
for (auto element : numberList) {
currentSum += element;
prefixSum.push_back(currentSum);
}
}
long long getSum(int& i, int& j) {
if (!j)
return prefixSum[j];
return prefixSum[j] - prefixSum[i - 1];
}
public:
day9() {
readFile();
}
void part1() {
for (int i = 0; i < PERMABLE; i++)
window.push_back(numberList[i]);
for (int i = PERMABLE; i < numberList.size(); i++) {
if (exists(window, numberList[i])) {
window.pop_front();
window.push_back(numberList[i]);
}else {
this->anomaly = numberList[i];
break;
}
}
cout << "Part 1: " << this->anomaly << '\n';
}
void part2() {
initSum();
long long borderSum = 0, minimum = LONG_MAX, maximum = 0;
for (int i = 0; i < numberList.size(); i++) {
for (int j = i + 1; j < numberList.size(); j++) {
if (getSum(i, j) == anomaly) {
for (int k = i; k <= j; k++) {
minimum = min(minimum, numberList[k]);
maximum = max(maximum, numberList[k]);
}
borderSum = minimum + maximum;
break;
}
}
}
cout << "Part 2: " << borderSum << '\n';
}
};
int main() {
day9 solution;
solution.part1();
solution.part2();
return 0;
}
| 27.404494 | 67 | 0.481755 | alikoptan |
169229f94fc636e7c4b8b51c519734346a41cf4a | 2,911 | cpp | C++ | Terminal/Source/LoadJPEG.cpp | Gravecat/BearLibTerminal | 64fec04101350a99a71db872c513e17bdd2cc94d | [
"MIT"
] | 80 | 2020-06-17T15:26:27.000Z | 2022-03-29T11:17:01.000Z | Terminal/Source/LoadJPEG.cpp | Gravecat/BearLibTerminal | 64fec04101350a99a71db872c513e17bdd2cc94d | [
"MIT"
] | 11 | 2020-07-19T15:22:06.000Z | 2022-03-31T03:33:13.000Z | Terminal/Source/LoadJPEG.cpp | Gravecat/BearLibTerminal | 64fec04101350a99a71db872c513e17bdd2cc94d | [
"MIT"
] | 18 | 2020-09-16T01:29:46.000Z | 2022-03-27T18:48:09.000Z | /*
* BearLibTerminal
* Copyright (C) 2013-2014 Cfyz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <NanoJPEG.h>
#include <functional>
#include <algorithm>
#include <stdexcept>
#include <istream>
#include <vector>
#include <memory>
#include "Geometry.hpp"
#include "Utility.hpp"
#include "Bitmap.hpp"
#include "Log.hpp"
namespace BearLibTerminal
{
std::string to_string(const Jpeg::Decoder::DecodeResult& value)
{
switch (value)
{
case Jpeg::Decoder::OK: return "OK";
case Jpeg::Decoder::NotAJpeg: return "not a JPEG";
case Jpeg::Decoder::Unsupported: return "unsupported format";
case Jpeg::Decoder::OutOfMemory: return "out of memory";
case Jpeg::Decoder::InternalError: return "internal error";
case Jpeg::Decoder::SyntaxError: return "syntax error";
default: return "unknown error";
}
}
Bitmap LoadJPEG(std::istream& stream)
{
std::istreambuf_iterator<char> eos;
std::string contents(std::istreambuf_iterator<char>(stream), eos);
std::unique_ptr<Jpeg::Decoder> decoder(new Jpeg::Decoder((const unsigned char*)contents.data(), contents.size()));
if (decoder->GetResult() != Jpeg::Decoder::OK)
{
throw std::runtime_error(std::string("Failed to load JPEG resource: ") + to_string(decoder->GetResult()));
}
Size size(decoder->GetWidth(), decoder->GetHeight());
if (size.width <= 0 || size.height <= 0)
{
throw std::runtime_error(std::string("Failed to load JPEG resource: internal loader error"));
}
Bitmap result(size, Color());
uint8_t* data = decoder->GetImage();
bool is_color = decoder->IsColor();
for (int y = 0; y < size.height; y++)
{
for (int x = 0; x < size.width; x++)
{
if (is_color)
{
result(x, y) = Color(0xFF, data[0], data[1], data[2]);
data += 3;
}
else
{
result(x, y) = Color(0xFF, data[0], data[0], data[0]);
data += 1;
}
}
}
return result;
}
}
| 31.301075 | 116 | 0.701134 | Gravecat |
169379be3d546912001d578df643de860221fa4b | 335 | hpp | C++ | src/rsm/options.hpp | Nadrin/rsm | 7cdeb4a17a4b01bfd135d81a97b6f9690f8700d9 | [
"MIT"
] | 5 | 2019-01-29T03:56:56.000Z | 2019-08-13T15:17:26.000Z | src/rsm/options.hpp | Nadrin/rsm | 7cdeb4a17a4b01bfd135d81a97b6f9690f8700d9 | [
"MIT"
] | null | null | null | src/rsm/options.hpp | Nadrin/rsm | 7cdeb4a17a4b01bfd135d81a97b6f9690f8700d9 | [
"MIT"
] | 1 | 2019-03-28T08:48:31.000Z | 2019-03-28T08:48:31.000Z | /*
* rsm :: Random Sampling Mathematics
* Copyright (c) 2018 Michał Siejak
* Released under the MIT license; see LICENSE file for details.
*/
#pragma once
#include <cstdint>
namespace rsm {
using options_t = uint8_t;
namespace opt {
enum option_bits {
none = 0,
jitter = 1,
shuffle = 2,
};
} // opt
} // rsm
| 13.4 | 64 | 0.638806 | Nadrin |
169725ec4d220cbd21892f14e6b98bce36409e80 | 30,147 | cpp | C++ | Samples/Win7Samples/netds/peertopeer/DRT/CAPIWrappers.cpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/netds/peertopeer/DRT/CAPIWrappers.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/netds/peertopeer/DRT/CAPIWrappers.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | // CAPIWrappers.cpp - Functions for dealing with certificates.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#endif
#include "CAPIWrappers.h"
#pragma comment(lib, "crypt32")
#pragma comment(lib, "rpcrt4")
#ifndef USES
#define USES(x) (x = x)
#endif
#define HRESULT_FROM_RPCSTATUS(x) \
(((x < 0) || (x == RPC_S_OK)) ? \
(HRESULT)x : \
(HRESULT) (((x) & 0x0000FFFF) | (FACILITY_RPC<< 16) | 0x80000000))
#define SECOND_IN_FILETIME (10i64 * 1000 * 1000)
const DWORD SIXTYFOUR_K = 64 * 1024;
const DWORD SIXTEEN_K = 16 * 1024;
const DWORD ONE_K = 1024;
BYTE s_keyDataBuf[SIXTEEN_K] = {0};
BYTE s_certBuf[SIXTEEN_K] = {0};
BYTE s_fileBuf[SIXTYFOUR_K] = {0};
/****************************************************************************++
Description :
This function creates a well known sid using User domain. CreateWellKnownSid requires
domain sid to be provided to generate such sids. This function first gets the domain sid
out of the user information in the token and then generate a well known sid.
Arguments:
hToken - [supplies] The token for which sid has to be generated
sidType - [supplies] The type of well known sid
pSid - [receives] The newly create sid
pdwSidSize - [Supplies/Receives] The size of the memory allocated for ppSid
Returns:
Errors returned by GetTokenInformation
Errors returned by CreateWellKnownSid
E_OUTOFMEMORY In case there is not enough memory
Errors returned by GetWindowsAccountDomainSid
--***************************************************************************/
HRESULT
CreateWellKnownSidForAccount(
__in_opt HANDLE hToken,
__in WELL_KNOWN_SID_TYPE sidType,
__out PSID pSid,
__inout DWORD * pdwSidSize)
{
HRESULT hr = S_OK;
TOKEN_USER * pUserToken = NULL;
DWORD dwTokenLen = 0;
PBYTE pDomainSid[SECURITY_MAX_SID_SIZE];
DWORD dwSidSize = SECURITY_MAX_SID_SIZE;
//
// Get the TokenUser, use this TokenUser to generate a well-known sid that requires a domain
//
if (!GetTokenInformation(
hToken,
TokenUser,
NULL,
dwTokenLen,
&dwTokenLen))
{
DWORD err = GetLastError();
if (err != ERROR_INSUFFICIENT_BUFFER)
{
hr = HRESULT_FROM_WIN32(err);
goto cleanup;
}
}
pUserToken = (TOKEN_USER *) new BYTE[dwTokenLen];
if (pUserToken == NULL)
{
hr = E_OUTOFMEMORY;
goto cleanup;
}
if (!GetTokenInformation(
hToken,
TokenUser,
pUserToken,
dwTokenLen,
&dwTokenLen))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanup;
}
//
// Now get the domain sid from the TokenUser
//
if (!GetWindowsAccountDomainSid(
pUserToken->User.Sid,
(PSID) pDomainSid,
&dwSidSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanup;
}
if(!CreateWellKnownSid(
sidType,
pDomainSid,
pSid,
pdwSidSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto cleanup;
}
cleanup:
delete [] pUserToken;
return hr;
}
/****************************************************************************++
Routine Description:
Verifies whether specified well-known SID is in the current user token
Arguments:
sid - one of the WELL_KNOWN_SID_TYPE consts
hToken - Optional the token for which we want to test membership
pfMember - [Receives] TRUE if specified sid is a member of the user token, FALSE otherwise
Notes:
-
Return Value:
Errors returned by CreateWellKnownSid
Errors returned by CheckTokenMembership
--*****************************************************************************/
HRESULT
IsMemberOf(
__in WELL_KNOWN_SID_TYPE sid,
__in_opt HANDLE hToken,
__out BOOL * pfMember)
{
HRESULT hr = S_OK;
BOOL fMember = FALSE;
BYTE pSID[SECURITY_MAX_SID_SIZE] = {0};
DWORD dwSIDSize = sizeof(pSID);
//
// create SID for the authenticated users
//
if (!CreateWellKnownSid(
sid,
NULL, // not a domain sid
(SID*)pSID,
&dwSIDSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
if (FAILED(hr) && (hr != E_INVALIDARG))
{
goto Cleanup;
}
//
// In case of invalid-arg we might need to provide the domain, so create well known sid for domain
//
hr = CreateWellKnownSidForAccount(hToken, sid, pSID, &dwSIDSize);
if (hr == HRESULT_FROM_WIN32(ERROR_NON_ACCOUNT_SID))
{
//
// If it is a non account sid (for example Local Service). Ignore the error.
//
hr = S_OK;
fMember = FALSE;
goto Cleanup;
}
else if (FAILED(hr))
{
goto Cleanup;
}
}
//
// check whether token has this sid
//
if (!CheckTokenMembership(hToken,
(SID*)pSID, // sid for the authenticated user
&fMember))
{
hr = HRESULT_FROM_WIN32(GetLastError());
// just to be on the safe side (as we don't know that CheckTokenMembership
// does not modify fAuthenticated in case of error)
fMember = FALSE;
if (hr == E_ACCESSDENIED && hToken == NULL)
{
// unable to query the thread token. Open as self and try again
if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken))
{
if (CheckTokenMembership(hToken, (SID*)pSID, &fMember))
{
hr = S_OK;
}
else
{
// stick with the original error code, but ensure that fMember is correct
fMember = FALSE;
}
CloseHandle(hToken);
}
}
goto Cleanup;
}
Cleanup:
*pfMember = fMember;
return hr;
}
// helper used by CreateCryptProv
HRESULT
IsServiceAccount(
OUT BOOL * pfMember)
{
HRESULT hr = S_OK;
BOOL fMember = FALSE;
hr = IsMemberOf(WinLocalServiceSid, NULL, &fMember);
if (FAILED(hr) || fMember)
{
goto Cleanup;
}
hr = IsMemberOf(WinLocalSystemSid, NULL, &fMember);
if (FAILED(hr) || fMember)
{
goto Cleanup;
}
hr = IsMemberOf(WinNetworkServiceSid, NULL, &fMember);
if (FAILED(hr) || fMember)
{
goto Cleanup;
}
Cleanup:
*pfMember = fMember;
return hr;
}
/****************************************************************************++
Routine Description:
Deletes the key container and the keys
Arguments:
pwzContainer -
Notes:
-
Return Value:
- S_OK
- or -
- no other errors are expected
--*****************************************************************************/
HRESULT
DeleteKeys(
IN PCWSTR pwzContainer)
{
HRESULT hr = S_OK;
HCRYPTPROV hCryptProv = NULL;
BOOL fServiceAccount = FALSE;
hr = IsServiceAccount(&fServiceAccount);
if (FAILED(hr))
{
goto Cleanup;
}
//
// this is the most counter-intuitive API that i have seen in my life
// in order to delete the contanier and all the keys in it, i have to call CryptAcquireContext
//
if (!CryptAcquireContextW(&hCryptProv,
pwzContainer,
NULL,
DEFAULT_PROV_TYPE,
fServiceAccount ?
(CRYPT_DELETEKEYSET | CRYPT_MACHINE_KEYSET) :
(CRYPT_DELETEKEYSET)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
Cleanup:
return hr;
}
/****************************************************************************++
Routine Description:
Wrapper fro CryptDestroyKey
Arguments:
hKey - handle to the key to destroy
Notes:
-
Return Value:
- VOID
--*****************************************************************************/
VOID
DestroyKey(
IN HCRYPTKEY hKey)
{
if (NULL != hKey)
{
//
// this is quite counter-intuitive API
// CryptDestroyKey just releases the handle to the key, but only in case of
// private/public key pairs.
//
if (!CryptDestroyKey(hKey))
{
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
USES(hr);
//
// should never happen, unless handle is invalid
//
}
}
}
/****************************************************************************++
Routine Description:
Releases the handle to the CSP
Arguments:
hCryptProv - handle to the CSP
Notes:
- handles the NULL CSP gracefully
Return Value:
- VOID
--*****************************************************************************/
VOID
ReleaseCryptProv(
IN HCRYPTPROV hCryptProv)
{
if (NULL != hCryptProv)
{
if (!CryptReleaseContext(hCryptProv, 0))
{
//
// one reason why this could fail (at least it failed a couple of times already) i s
// that some certifcate store was opened using this CSP, but
// CERT_STORE_NO_CRYPT_RELEASE_FLAG was not specified, so that
// when cert store is released the provider is released as well.
//
// verify that all stores that were ever used, specify this flag
//
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
USES(hr);
}
}
}
/****************************************************************************++
Routine Description:
Creates a handle to the CSP
Arguments:
pwzContainerName - name of the container to be created. if NULL, GUID is generated
for the name of the container
fCreateNewKeys - forces new keys to be created
phCryptProv - pointer to the location, where handle should be returned
Notes:
-
Return Value:
- S_OK
- or -
- CAPI error returned by CryptAcquireContextW
--*****************************************************************************/
HRESULT
CreateCryptProv(
IN PCWSTR pwzContainerName,
IN BOOL fCreateNewKeys,
OUT HCRYPTPROV* phCryptProv)
{
HRESULT hr = S_OK;
HCRYPTKEY hKey = NULL;
RPC_STATUS status = RPC_S_OK;
BOOL fCreatedContainer = FALSE;
WCHAR* pwzNewContainerName = NULL;
*phCryptProv = NULL;
if (NULL == pwzContainerName)
{
UUID uuid;
BOOL fServiceAccount = FALSE;
//
// generate container name from the UUID
//
status = UuidCreate(&uuid);
hr = HRESULT_FROM_RPCSTATUS(status);
if (FAILED(hr))
{
goto Cleanup;
}
status = UuidToStringW(&uuid, (unsigned short**)&pwzNewContainerName);
hr = HRESULT_FROM_RPCSTATUS(status);
if (FAILED(hr))
{
goto Cleanup;
}
pwzContainerName = pwzNewContainerName;
hr = IsServiceAccount(&fServiceAccount);
if (FAILED(hr))
{
goto Cleanup;
}
//
// open the clean key container
//
// note: CRYPT_NEW_KEYSET is not creating new keys, it just
// creates new key container. duh.
//
if (!CryptAcquireContextW(phCryptProv,
pwzNewContainerName,
NULL, // default provider name
DEFAULT_PROV_TYPE,
fServiceAccount ?
(CRYPT_SILENT | CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET) :
(CRYPT_SILENT | CRYPT_NEWKEYSET)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
//
// we are seeing that CryptAcquireContextW returns NTE_FAIL under low
// memory condition, so we just mask the error
//
if (NTE_FAIL == hr)
{
hr = E_OUTOFMEMORY;
}
goto Cleanup;
}
fCreatedContainer = TRUE;
}
else
{
BOOL fServiceAccount = FALSE;
hr = IsServiceAccount(&fServiceAccount);
if (FAILED(hr))
{
goto Cleanup;
}
//
// open the provider first, create the keys too
//
if (!CryptAcquireContextW(phCryptProv,
pwzContainerName,
NULL, // default provider name
DEFAULT_PROV_TYPE,
fServiceAccount ?
(CRYPT_SILENT | CRYPT_MACHINE_KEYSET) :
(CRYPT_SILENT)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
//
// we are seeing that CryptAcquireContextW returns NTE_FAIL under low
// memory condition, so we just mask the error
//
if (NTE_FAIL == hr)
{
hr = E_OUTOFMEMORY;
}
goto Cleanup;
}
}
if (fCreateNewKeys)
{
//
// make sure keys exist
//
if (!CryptGetUserKey(*phCryptProv,
DEFAULT_KEY_SPEC,
&hKey))
{
hr = HRESULT_FROM_WIN32(GetLastError());
// if key does not exist, create it
if (HRESULT_FROM_WIN32((unsigned long)NTE_NO_KEY) == hr)
{
hr = S_OK;
if (!CryptGenKey(*phCryptProv,
DEFAULT_KEY_SPEC,
CRYPT_EXPORTABLE,
&hKey))
{
hr = HRESULT_FROM_WIN32(GetLastError());
//
// we are seeing that CryptGenKey returns ERROR_CANTOPEN under low
// memory condition, so we just mask the error
//
if (HRESULT_FROM_WIN32(ERROR_CANTOPEN) == hr)
{
hr = E_OUTOFMEMORY;
}
goto Cleanup;
}
}
else
{
// failed to get user key by some misterious reason, so bail out
goto Cleanup;
}
}
}
Cleanup:
DestroyKey(hKey);
if (FAILED(hr))
{
//
// release the context
//
ReleaseCryptProv(*phCryptProv);
*phCryptProv = NULL;
//
// delete the keys, if we created them
//
if (fCreatedContainer)
{
DeleteKeys(pwzContainerName);
}
}
if (NULL != pwzNewContainerName)
{
// this always returns RPC_S_OK
status = RpcStringFreeW((unsigned short**)&pwzNewContainerName);
USES(status);
}
return hr;
}
/****************************************************************************++
Routine Description:
Retrieves the name of the CSP container.
Arguments:
hCryptProv - handle to the CSP
pcChars - count of chars in the buffer on input. count of chars used on return
pwzContainerName - pointer to output buffer
Notes:
-
Return Value:
- S_OK
- or -
- NTE_BAD_UID, if hCryptProv handle is not valid
--*****************************************************************************/
HRESULT
GetContainerName(
IN HCRYPTPROV hCryptProv,
__inout ULONG* pcChars,
__out_ecount_opt(*pcChars) LPWSTR pwzContainerName)
{
HRESULT hr = S_OK;
CHAR * pszBuf = new CHAR[*pcChars];
ULONG cbBufSize = sizeof(CHAR) *(*pcChars);
if (NULL == pszBuf)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
//
// get the name of the key container
//
if (!CryptGetProvParam(hCryptProv,
PP_CONTAINER,
(BYTE*)pszBuf,
&cbBufSize,
0))
{
hr = HRESULT_FROM_WIN32(GetLastError());
// if buffer is not sufficiently large, just return with this error
if (HRESULT_FROM_WIN32(ERROR_MORE_DATA) == hr)
{
// if buffer was not sufficiently large return the number of characters needed
*pcChars = cbBufSize / sizeof(CHAR);
goto Cleanup;
}
else
{
goto Cleanup;
}
}
//
// convert the string to the wide character, since that's what needed for the key info
//
if (0 == MultiByteToWideChar(CP_ACP,
0, // dwFlags
pszBuf,
-1, // calculate the length
pwzContainerName,
*pcChars))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
Cleanup:
if (NULL != pszBuf)
{
delete [] pszBuf;
}
return hr;
}
// Read a single cert from a file
HRESULT ReadCertFromFile(LPCWSTR pwzFileName, CERT_CONTEXT** ppCert, HCRYPTPROV* phCryptProv)
{
BOOL bRet = FALSE;
FILE* pFile = NULL;
errno_t err;
// open cert file for local cert
err = _wfopen_s(&pFile, pwzFileName, L"rb");
if (err)
{
return CRYPT_E_FILE_ERROR;
}
// read local cert into *ppLocalCert, allocating memory
fread(s_fileBuf, sizeof(s_fileBuf), 1, pFile);
fclose(pFile);
CRYPT_DATA_BLOB blob;
blob.cbData = sizeof(s_fileBuf);
blob.pbData = s_fileBuf;
HCERTSTORE hCertStore = PFXImportCertStore(&blob, L"DRT Rocks!", CRYPT_EXPORTABLE);
if (NULL == hCertStore)
return HRESULT_FROM_WIN32(GetLastError());
// TODO: does this have to be a c style cast? I get compile errors if I try reinterpret or static cast
// the first cert is always the leaf cert (since we encoded it that way)
CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)CertEnumCertificatesInStore(hCertStore, NULL);
if (NULL == pCertContext)
return HRESULT_FROM_WIN32(GetLastError());
// retreive the crypt provider which has the private key for this certificate
DWORD dwKeySpec = 0;
HCRYPTPROV hCryptProv = NULL;
bRet = CryptAcquireCertificatePrivateKey(pCertContext,
CRYPT_ACQUIRE_SILENT_FLAG | CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
NULL, &hCryptProv, &dwKeySpec, NULL);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// make sure provider stays around for duration of the test run. We need hCryptProv of root cert to sign local certs
CryptContextAddRef(hCryptProv, NULL, 0);
// everything succeeded, safe to set outparam
*ppCert = pCertContext;
if (NULL != phCryptProv)
*phCryptProv = hCryptProv;
return S_OK;
}
// helper function to write the cert store out to a file
HRESULT WriteStoreToFile(__in HCERTSTORE hCertStore, __in PCWSTR pwzFileName)
{
BOOL bRet = FALSE;
FILE* pFile = NULL;
errno_t err;
CRYPT_DATA_BLOB blob = { sizeof(s_fileBuf), s_fileBuf};
bRet = PFXExportCertStore(hCertStore, &blob, L"DRT Rocks!", EXPORT_PRIVATE_KEYS);
if (!bRet)
{
return HRESULT_FROM_WIN32(GetLastError());
}
err = _wfopen_s(&pFile, pwzFileName, L"wb");
if (err)
{
return CRYPT_E_FILE_ERROR;
}
fwrite(blob.pbData, blob.cbData, 1, pFile);
fclose(pFile);
return S_OK;
}
// helper function used by make certs to encode a name for storage in a cert (modified from drt\test\drtcert\main.cpp)
HRESULT EncodeName(__in PCWSTR pwzName, DWORD* pcbEncodedName, BYTE* pbEncodedName)
{
CERT_NAME_INFO nameInfo = {0};
CERT_RDN rdn = {0};
CERT_RDN_ATTR rdnAttr = {0};
nameInfo.cRDN = 1;
nameInfo.rgRDN = &rdn;
rdn.cRDNAttr = 1;
rdn.rgRDNAttr = &rdnAttr;
rdnAttr.dwValueType = CERT_RDN_UNICODE_STRING;
rdnAttr.pszObjId = szOID_COMMON_NAME;
rdnAttr.Value.pbData = (BYTE*)pwzName;
rdnAttr.Value.cbData = sizeof(WCHAR) * (DWORD)(wcslen(pwzName) + 1);
if (!CryptEncodeObject(DEFAULT_ENCODING, X509_NAME, &nameInfo, pbEncodedName, pcbEncodedName))
{
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
// manufacture a single cert and export it to a file
HRESULT MakeAndExportACert(PCWSTR pwzSignerName, PCWSTR pwzCertName, PCWSTR pwzFileName, HCERTSTORE hCertStore,
HCRYPTPROV hCryptProvSigner, HCRYPTPROV hCryptProvThisCert,
CERT_CONTEXT* pIssuerCertContext)
{
HRESULT hr = S_OK;
BOOL bRet = FALSE;
BYTE byteBuf1[ONE_K] = {0};
BYTE byteBuf2[ONE_K] = {0};
DWORD cSignerName = sizeof(byteBuf1);
BYTE* pbSignerName = byteBuf1;
DWORD cCertName = sizeof(byteBuf2);
BYTE* pbCertName = byteBuf2;
CERT_INFO certInfo = {0};
BYTE serialNumberBuf[16];
ULONGLONG ullTime = 0;
XCERT_CONTEXT pCertContext;
ULONG cchContainer = 512;
WCHAR wzContainer[512];
CRYPT_KEY_PROV_INFO keyInfo = {0};
// encode the names for use in a cert
hr = EncodeName(pwzSignerName, &cSignerName, pbSignerName);
if (FAILED(hr))
return hr;
hr = EncodeName(pwzCertName, &cCertName, pbCertName);
if (FAILED(hr))
return hr;
// first retrieve the public key from the hCryptProv (which abstracts the key pair)
DWORD dwSize = sizeof(s_keyDataBuf);
bRet = CryptExportPublicKeyInfo(hCryptProvThisCert, DEFAULT_KEY_SPEC, DEFAULT_ENCODING,
reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(s_keyDataBuf), &dwSize);
if (FALSE == bRet)
return HRESULT_FROM_WIN32(GetLastError());
// set the cert properties
certInfo.dwVersion = CERT_V3;
certInfo.SerialNumber.cbData = sizeof(serialNumberBuf);
certInfo.SerialNumber.pbData = serialNumberBuf;
certInfo.SignatureAlgorithm.pszObjId = DEFAULT_ALGORITHM;
GetSystemTimeAsFileTime((FILETIME*)&ullTime);
ullTime -= SECOND_IN_FILETIME * 60 * 60 * 24;
CopyMemory(&certInfo.NotBefore, &ullTime, sizeof(FILETIME));
ullTime += SECOND_IN_FILETIME * 60 * 60 * 24 * 365;
CopyMemory(&certInfo.NotAfter, &ullTime, sizeof(FILETIME));
certInfo.Issuer.cbData = cSignerName;
certInfo.Issuer.pbData = pbSignerName;
certInfo.Subject.cbData = cCertName;
certInfo.Subject.pbData = pbCertName;
certInfo.SubjectPublicKeyInfo = *(reinterpret_cast<CERT_PUBLIC_KEY_INFO*>(s_keyDataBuf));
// create the cert
DWORD cCertBuf = sizeof(s_certBuf);
bRet = CryptSignAndEncodeCertificate(hCryptProvSigner, // Crypto provider
DEFAULT_KEY_SPEC, // Key spec, we always use the same
DEFAULT_ENCODING, // Encoding type, default
X509_CERT_TO_BE_SIGNED, // Structure type - certificate
&certInfo, // Structure information
&certInfo.SignatureAlgorithm, // Signature algorithm
NULL, // reserved, must be NULL
s_certBuf, // hopefully it will fit in 1K
&cCertBuf);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// retrieve the cert context. pCertContext gets a pointer into the crypto api heap, we must treat it as read only.
// pCertContext must be freed with CertFreeCertificateContext(p); we use a smart pointer to do the free
pCertContext = (CERT_CONTEXT*)CertCreateCertificateContext(DEFAULT_ENCODING, s_certBuf, cCertBuf);
if (NULL == pCertContext)
return HRESULT_FROM_WIN32(GetLastError());
// next attach the private key
// =================
// retrieve container name
hr = GetContainerName(hCryptProvThisCert, &cchContainer, wzContainer);
if (FAILED(hr))
return hr;
// set up key info struct for CAPI call
keyInfo.pwszContainerName = wzContainer;
keyInfo.pwszProvName = NULL;
keyInfo.dwProvType = DEFAULT_PROV_TYPE;
keyInfo.dwKeySpec = DEFAULT_KEY_SPEC;
// attach private key
bRet = CertSetCertificateContextProperty(pCertContext, CERT_KEY_PROV_INFO_PROP_ID, 0, &keyInfo);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// put the cert into the store
bRet = CertAddCertificateContextToStore(hCertStore, pCertContext, CERT_STORE_ADD_NEW, NULL);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
// make sure the issuer cert is also in the store, if we have an issuer for the cert (ie, the non self signed case)
if (pIssuerCertContext)
{
bRet = CertAddCertificateContextToStore(hCertStore, pIssuerCertContext, CERT_STORE_ADD_NEW, NULL);
if (!bRet)
return HRESULT_FROM_WIN32(GetLastError());
}
// now export the cert to a file
hr = WriteStoreToFile(hCertStore, pwzFileName);
return hr;
}
// using cryptoApi, make a cert and export it. If there is an existing root cert, this will
// use the existing root cert to sign the local cert.
// export a local cert to the file <currentdir>\LocalCert.cer
// export a root cert to the file <currentDir>\RootCert.cer (if one does not already exist)
HRESULT MakeCert(LPCWSTR pwzLocalCertFileName, LPCWSTR pwzLocalCertName,
LPCWSTR pwzIssuerCertFileName, LPCWSTR pwzIssuerCertName)
{
HRESULT hr = S_OK;
XHCERTSTORE hSelfCertStore;
XHCERTSTORE hSignedCertStore;
XHCRYPTPROV hCryptProvIssuer;
XHCRYPTPROV hCryptProvThis;
XCERT_CONTEXT pIssuerCert;
// If there is an issuer cert, make sure it exists
if (pwzIssuerCertFileName)
{
hr = ReadCertFromFile(pwzIssuerCertFileName, &pIssuerCert, &hCryptProvIssuer);
if (FAILED(hr))
return hr;
}
// create this cert key pair (util function from peernet\common)
hr = CreateCryptProv(NULL, TRUE, &hCryptProvThis);
if (FAILED(hr))
return hr;
// create cert store
hSelfCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL,
CERT_STORE_CREATE_NEW_FLAG | CERT_STORE_NO_CRYPT_RELEASE_FLAG, NULL);
if (NULL == hSelfCertStore)
return HRESULT_FROM_WIN32(GetLastError());
// Make the self signed cert, and save it to a file
hr = MakeAndExportACert(pwzLocalCertName, pwzLocalCertName, pwzLocalCertFileName, hSelfCertStore, hCryptProvThis, hCryptProvThis, NULL);
if (FAILED(hr))
return hr;
// then, sign it if an issuer name was supplied
// (surprisingly, the same function does both, since it adds a signing record to existing cert)
// FUTURE: this is a bit inefficient, since we write the file twice, we can add a fWrite paramater, and not write the file when it is false
if (pwzIssuerCertFileName)
{
// must create a separate store, or we end up with a single cert and a chain cert in same store, apps can pick wrong cert
hSignedCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL,
CERT_STORE_CREATE_NEW_FLAG | CERT_STORE_NO_CRYPT_RELEASE_FLAG, NULL);
if (NULL == hSignedCertStore)
return HRESULT_FROM_WIN32(GetLastError());
hr = MakeAndExportACert(pwzIssuerCertName, pwzLocalCertName, pwzLocalCertFileName, hSignedCertStore, hCryptProvIssuer, hCryptProvThis, pIssuerCert);
}
return hr;
}
| 30.086826 | 157 | 0.533983 | windows-development |
1697eb193469b75698534159d177bde187a7da96 | 67 | hpp | C++ | 3rdparty/kapok/Kapok.hpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 202 | 2015-04-12T14:06:10.000Z | 2022-02-28T15:08:33.000Z | 3rdparty/kapok/Kapok.hpp | sinmx/ZPublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 7 | 2015-04-12T14:17:57.000Z | 2018-05-29T01:43:28.000Z | 3rdparty/kapok/Kapok.hpp | sinmx/ZPublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 93 | 2015-04-12T08:25:10.000Z | 2020-11-05T02:57:03.000Z | #pragma once
#include "Serializer.hpp"
#include "DeSerializer.hpp"
| 16.75 | 27 | 0.776119 | wohaaitinciu |
16988c3e07be73bc3d520b058bc1391636533902 | 1,663 | cpp | C++ | src/tests/main.cpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | 1 | 2019-02-17T15:56:26.000Z | 2019-02-17T15:56:26.000Z | src/tests/main.cpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | null | null | null | src/tests/main.cpp | benh/twesos | 194e1976d474005d807f37e7204ea08766e4b42a | [
"BSD-3-Clause"
] | 3 | 2017-07-10T07:28:30.000Z | 2020-07-25T19:48:07.000Z | #include <glog/logging.h>
#include <gtest/gtest.h>
#include <libgen.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "testing_utils.hpp"
#include "common/fatal.hpp"
#include "configurator/configurator.hpp"
using namespace mesos::internal;
using namespace mesos::internal::test;
namespace {
// Get absolute path to Mesos home directory based on where the alltests
// binary is located (which should be in MESOS_HOME/bin/tests)
string getMesosHome(int argc, char** argv) {
// Copy argv[0] because dirname can modify it
int lengthOfArg0 = strlen(argv[0]);
char* copyOfArg0 = new char[lengthOfArg0 + 1];
strncpy(copyOfArg0, argv[0], lengthOfArg0 + 1);
// Get its directory, and then the parent of the parent of that directory
string myDir = string(dirname(copyOfArg0));
string parentDir = myDir + "/../..";
// Get the real name of this parent directory
char path[PATH_MAX];
if (realpath(parentDir.c_str(), path) == 0) {
fatalerror("Failed to find location of MESOS_HOME using realpath");
}
return path;
}
}
int main(int argc, char** argv)
{
// Get absolute path to Mesos home directory based on location of alltests
mesos::internal::test::mesosHome = getMesosHome(argc, argv);
// Clear any MESOS_ environment variables so they don't affect our tests
Configurator::clearMesosEnvironmentVars();
// Initialize Google Logging and Google Test
google::InitGoogleLogging("alltests");
testing::InitGoogleTest(&argc, argv);
testing::FLAGS_gtest_death_test_style = "threadsafe";
if (argc == 2 && strcmp("-v", argv[1]) == 0)
google::SetStderrLogging(google::INFO);
return RUN_ALL_TESTS();
}
| 28.186441 | 76 | 0.719784 | benh |
169973eeda99fb85b47b792f8215de8cc9c04a21 | 508 | hpp | C++ | src/classifier/svm/svm_binary_classifier.hpp | bububa/openvision | 0864e48ec8e69ac13d6889d41f7e1171f53236dd | [
"Apache-2.0"
] | 1 | 2022-02-08T06:42:05.000Z | 2022-02-08T06:42:05.000Z | src/classifier/svm/svm_binary_classifier.hpp | bububa/openvision | 0864e48ec8e69ac13d6889d41f7e1171f53236dd | [
"Apache-2.0"
] | null | null | null | src/classifier/svm/svm_binary_classifier.hpp | bububa/openvision | 0864e48ec8e69ac13d6889d41f7e1171f53236dd | [
"Apache-2.0"
] | null | null | null | #ifndef _CLASSIFIER_SVM_BINARY_CLASSIFIER_H_
#define _CLASSIFIER_SVM_BINARY_CLASSIFIER_H_
#include "svm_classifier.hpp"
namespace ovclassifier {
class SVMBinaryClassifier : public SVMClassifier {
public:
SVMBinaryClassifier();
~SVMBinaryClassifier();
int LoadModel(const char *modelfile);
double Predict(const float *vec);
int Classify(const float *vec, std::vector<float> &scores);
private:
MODEL *model_ = NULL;
};
} // namespace ovclassifier
#endif // !_CLASSIFIER_SVM_BINARY_CLASSIFIER_H_
| 25.4 | 61 | 0.787402 | bububa |
169977495cb8e6861436c9b8b5ca9e435815dd5d | 1,093 | cpp | C++ | Codeforces/Gym100889D.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | Codeforces/Gym100889D.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | Codeforces/Gym100889D.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include <bits/stdc++.h>
#define MAXN 2000010
using namespace std;
const long long M=1e9+7;
int T,n,m,prime[MAXN],tot;
long long fac[MAXN],inv[MAXN],invfac[MAXN];
bool not_prime[MAXN];
inline void Sieve()
{
int n=2e6;
for (int i=2;i<=n;i++)
{
if (!not_prime[i]) prime[++tot]=i;
for (int j=1;i*prime[j]<=n;j++)
{
not_prime[i*prime[j]]=true;
if (!(i%prime[j])) break;
}
}
fac[0]=invfac[0]=inv[1]=1LL;
for (int i=1;i<=n;i++) fac[i]=(fac[i-1]*i)%M;
for (int i=2;i<=n;i++) inv[i]=(M-M/i)*inv[M%i]%M;
for (int i=1;i<=n;i++) invfac[i]=(invfac[i-1]*inv[i])%M;
return ;
}
inline long long C(int n,int m)
{
if (n>=M) return 0LL;
if (!m) return 1LL;
long long ans=invfac[m];
for (int i=n;i>n-m;i--) ans=(ans*i)%M;
return ans;
}
int main()
{
Sieve();not_prime[1]=true;
scanf("%d",&T);
while (T--)
{
scanf("%d %d",&n,&m);int pt=1;long long ans=1;
while (n!=1)
{
int cnt=0;
while (!(n%prime[pt])) n/=prime[pt],++cnt;
(ans*=C(m+cnt-1,cnt))%=M;
if (!not_prime[n])
{
(ans*=m)%=M;
break;
}
++pt;
}
printf("%lld\n",ans);
}
return 0;
} | 17.918033 | 57 | 0.546203 | HeRaNO |
169a7726b883813a797f1edb1cafbf61c2138cc6 | 10,234 | cpp | C++ | Rise/src/Platform/OpenGL/OpenGLShader.cpp | Super-Shadow/Rise | 38f0cfd1d63365958c6ff8252598ce871525c885 | [
"Apache-2.0"
] | null | null | null | Rise/src/Platform/OpenGL/OpenGLShader.cpp | Super-Shadow/Rise | 38f0cfd1d63365958c6ff8252598ce871525c885 | [
"Apache-2.0"
] | null | null | null | Rise/src/Platform/OpenGL/OpenGLShader.cpp | Super-Shadow/Rise | 38f0cfd1d63365958c6ff8252598ce871525c885 | [
"Apache-2.0"
] | null | null | null | #include "rspch.h"
#include "OpenGLShader.h"
#include <fstream>
#include <utility>
#include <glad/glad.h>
#include "glm/gtc/type_ptr.hpp"
namespace Rise
{
static GLenum ShaderTypeFromString(const std::string& type)
{
if (type == "vertex")
return GL_VERTEX_SHADER;
if (type == "fragment" || type == "pixel")
return GL_FRAGMENT_SHADER;
RS_CORE_ASSERT(false, "Unknown shader type '" + type + "'!");
return NULL;
}
OpenGLShader::OpenGLShader(const std::string& filePath)
{
RS_PROFILE_FUNCTION();
const auto source = ReadFile(filePath);
const auto shaderSources = PreProcess(source);
Compile(shaderSources);
// File name from file path
auto lastSlash = filePath.find_last_of("/\\");
lastSlash = lastSlash == std::string::npos ? 0 : lastSlash + 1;
const auto lastDot = filePath.rfind('.');
const auto count = lastDot == std::string::npos ? filePath.size() - lastSlash : lastDot - lastSlash;
m_Name = filePath.substr(lastSlash, count);
}
OpenGLShader::OpenGLShader(std::string name, const std::string& vertexSrc, const std::string& fragmentSrc) : m_Name(std::move(name))
{
RS_PROFILE_FUNCTION();
std::unordered_map<GLenum, std::string> sources;
sources[GL_VERTEX_SHADER] = vertexSrc;
sources[GL_FRAGMENT_SHADER] = fragmentSrc;
Compile(sources);
}
OpenGLShader::~OpenGLShader()
{
RS_PROFILE_FUNCTION();
glDeleteProgram(m_RendererID);
}
std::string OpenGLShader::ReadFile(const std::string& filePath)
{
RS_PROFILE_FUNCTION();
std::string result;
std::ifstream in(filePath, std::ios::in | std::ios::binary);
if (in)
{
in.seekg(0, std::ios::end);
const auto size = in.tellg();
if (size != -1)
{
result.resize(size);
in.seekg(0, std::ios::beg);
in.read(&result[0], size);
in.close();
}
else
{
RS_CORE_ERROR("Could not read from file '{0}'", filePath);
}
}
else
{
RS_CORE_ERROR("Could not open file '{0}'", filePath);
}
return result;
}
std::unordered_map<GLenum, std::string> OpenGLShader::PreProcess(const std::string& source)
{
RS_PROFILE_FUNCTION();
std::unordered_map<GLenum, std::string> shaderSources;
constexpr auto typeToken = "#type";
//const auto typeTokenLength = strlen(typeToken);
auto pos = source.find(typeToken, 0);
RS_CORE_ASSERT(pos != std::string::npos, "Shader missing #type!");
while (pos != std::string::npos)
{
const auto endOfLine = source.find_first_of("\r\n", pos);
RS_CORE_ASSERT(endOfLine != std::string::npos, "Syntax error");
const auto begin = pos + /*typeTokenLength + 1 */ 6; // The plus 1 is how many whitespaces between '#type vertex'
auto type = source.substr(begin, endOfLine - begin);
RS_CORE_ASSERT(ShaderTypeFromString(type), "Invalid shader type specification!"); // TODO: This is useless due to exact same asset in ShaderTypeFromString
const auto nextLinePos = source.find_first_not_of("\r\n", endOfLine);
RS_CORE_ASSERT(nextLinePos != std::string::npos, "Syntax error");
pos = source.find(typeToken, nextLinePos);
shaderSources[ShaderTypeFromString(type)] = source.substr(nextLinePos, pos - (nextLinePos == std::string::npos ? source.size() - 1 : nextLinePos));
}
return shaderSources;
}
void OpenGLShader::Compile(const std::unordered_map<GLenum, std::string>& shaderSources)
{
RS_PROFILE_FUNCTION();
// Now time to link them together into a program.
// Get a program object.
const auto program = glCreateProgram();
RS_CORE_ASSERT(shaderSources.size() <= 2, "Unsupported amount of shaders!");
std::array<GLenum, 2> glShaderIDs{};
auto glShaderIDIndex = 0;
for (const auto& [first, second] : shaderSources) // Good use of structural binding!
{
const auto type = first;
const auto source = second;
// Create an empty vertex shader handle
const auto shader = glCreateShader(type);
// Send the vertex shader source code to GL
// Note that std::string's .c_str is NULL character terminated.
auto sourceCstr = source.c_str();
glShaderSource(shader, 1, &sourceCstr, nullptr);
// Compile the vertex shader
glCompileShader(shader);
GLint isCompiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(shader, maxLength, &maxLength, &infoLog[0]);
// Either of them. Don't leak shaders.
glDeleteShader(shader);
// Use the infoLog as you see fit.
RS_CORE_ERROR("{0}", infoLog.data());
RS_CORE_ASSERT(false, "Shader compilation failure!");
// In this simple program, we'll just leave
break;
}
// Vertex and fragment shaders are successfully compiled.
// Attach our shaders to our program
glAttachShader(program, shader);
glShaderIDs[glShaderIDIndex++] = shader;
}
// Link our program
glLinkProgram(program);
// Note the different functions here: glGetProgram* instead of glGetShader*.
GLint isLinked;
glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
if (isLinked == GL_FALSE)
{
GLint maxLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);
// We don't need the program anymore.
glDeleteProgram(program);
// Don't leak shaders either.
for (const auto shader : glShaderIDs)
{
glDeleteShader(shader);
}
// Use the infoLog as you see fit.
RS_CORE_ERROR("{0}", infoLog.data());
RS_CORE_ASSERT(false, "Shader link failure!");
// In this simple program, we'll just leave
return;
}
// Always detach shaders after a successful link.
for (const auto shader : glShaderIDs)
{
glDetachShader(program, shader);
}
m_RendererID = program;
}
void OpenGLShader::Bind() const
{
RS_PROFILE_FUNCTION();
glUseProgram(m_RendererID);
}
void OpenGLShader::Unbind() const
{
RS_PROFILE_FUNCTION();
glUseProgram(0);
}
void OpenGLShader::SetInt(const std::string& name, const int value) const
{
RS_PROFILE_FUNCTION();
UploadUniformInt(name, value);
}
void OpenGLShader::SetIntArray(const std::string& name, const int* values, const int count) const
{
RS_PROFILE_FUNCTION();
UploadUniformIntArray(name, values, count);
}
void OpenGLShader::SetFloat(const std::string& name, const float value) const
{
RS_PROFILE_FUNCTION();
UploadUniformFloat(name, value);
}
void OpenGLShader::SetFloat3(const std::string& name, const glm::vec3& value) const
{
RS_PROFILE_FUNCTION();
UploadUniformFloat3(name, value);
}
void OpenGLShader::SetFloat4(const std::string& name, const glm::vec4& value) const
{
RS_PROFILE_FUNCTION();
UploadUniformFloat4(name, value);
}
void OpenGLShader::SetMat4(const std::string& name, const glm::mat4& value) const
{
RS_PROFILE_FUNCTION();
UploadUniformMat4(name, value);
}
void OpenGLShader::UploadUniformInt(const std::string& name, const int value) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if(location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform int named {1}.", m_Name, name);
glUniform1i(location, value);
}
void OpenGLShader::UploadUniformIntArray(const std::string& name, const int* values, const int count) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform int array named {1}.", m_Name, name);
glUniform1iv(location, count, values);
}
void OpenGLShader::UploadUniformFloat(const std::string& name, const float value) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform float named {1}.", m_Name, name);
glUniform1f(location, value);
}
void OpenGLShader::UploadUniformFloat2(const std::string& name, const glm::vec2& values) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform vec2 named {1}.", m_Name, name);
glUniform2f(location, values.x, values.y);
}
void OpenGLShader::UploadUniformFloat3(const std::string& name, const glm::vec3& values) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform vec3 named {1}.", m_Name, name);
glUniform3f(location, values.x, values.y, values.z);
}
void OpenGLShader::UploadUniformFloat4(const std::string& name, const glm::vec4& values) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform vec4 named {1}.", m_Name, name);
glUniform4f(location, values.x, values.y, values.z, values.w);
}
void OpenGLShader::UploadUniformMat3(const std::string& name, const glm::mat3& matrix) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform mat3 named {1}.", m_Name, name);
// count means how many matrices are we giving, so we put 1. If we used DirectX maths (column-major order) we would need to say GL_TRUE for auto transpose to OpenGL maths (row-major order).
glUniformMatrix3fv(location, 1, GL_FALSE, value_ptr(matrix)); // f means float and v means an array as it is 16 floats
}
void OpenGLShader::UploadUniformMat4(const std::string& name, const glm::mat4& matrix) const
{
const auto location = glGetUniformLocation(m_RendererID, name.c_str());
if (location < 0)
RS_CORE_ERROR("{0} shader unable to locate uniform mat4 named {1}.", m_Name, name);
// count means how many matrices are we giving, so we put 1. If we used DirectX maths (column-major order) we would need to say GL_TRUE for auto transpose to OpenGL maths (row-major order).
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix)); // f means float and v means an array as it is 16 floats
}
}
| 30.188791 | 191 | 0.707543 | Super-Shadow |
169b5d902e718a2729be42c7c2d447d5a6eef8f7 | 4,362 | cpp | C++ | luogu/APIO-fun/fun.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | luogu/APIO-fun/fun.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | luogu/APIO-fun/fun.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include "fun.h"
using namespace std;
typedef vector<int> V;
const int N=120000;
int dep[N],sz[N],rt=0,n,cnt=0,id[3],nowpos=-1;
vector<int> son[N],ans;
bool cmp(int x,int y){return dep[x]<dep[y];}
void solver2(int idx,int idy){//X first
while(!son[idx].empty()||!son[idy].empty()){
if(son[idx].empty()) break;
ans.push_back(son[idx].back());
son[idx].pop_back(); swap(idx,idy);
}
ans.push_back(rt);
if(!son[idx].empty()) ans.push_back(son[idx][0]);
if(!son[idy].empty()) ans.push_back(son[idy][0]);
}
typedef pair<int,int> pii;
#define mk make_pair
set<pii> st[N];
void solver3(){
int mx=0,ID;
for(int i=0;i<=2;i++)
if((int)son[id[i]].size()>mx) mx=(int)son[id[i]].size(), ID=i;
if(mx*2==n){
if(ID!=0) swap(id[ID],id[0]);
for(int i=0;i<(int)son[id[2]].size();i++)
son[id[1]].push_back(son[id[2]][i]);
sort(son[id[1]].begin(),son[id[1]].end(),cmp);
solver2(id[0],id[1]);
return;
}
for(int i=0;i<=2;i++) {
for(int j=0;j<(int)son[id[i]].size();j++){
int to=son[id[i]][j];
st[id[i]].insert(mk(dep[to],to));
}
}
int PRE=-1,rest=n,pre=1000000,predep=-1;
while('M'+'Y'+'Y'+'A'+'N'+'D'+'H'+'C'+'Y'+'A'+'K'+'I'+'O'+'I'){
int mx1=((st[id[0]].empty()||PRE==id[0]) ? -1 : st[id[0]].rbegin()->second);
int mx2=((st[id[1]].empty()||PRE==id[1]) ? -1 : st[id[1]].rbegin()->second);
int mx3=((st[id[2]].empty()||PRE==id[2]) ? -1 : st[id[2]].rbegin()->second);
mx=0; int iid;
if(mx1!=-1&&mx<dep[mx1]) mx=dep[mx1],ID=0,iid=mx1;
if(mx2!=-1&&mx<dep[mx2]) mx=dep[mx2],ID=1,iid=mx2;
if(mx3!=-1&&mx<dep[mx3]) mx=dep[mx3],ID=2,iid=mx3;
assert(mx1!=-1||mx2!=-1||mx3!=-1);
st[id[ID]].erase(mk(dep[iid],iid));
ans.push_back(iid); rest--;
assert(rest==n-2||predep+dep[iid]<=pre);
pre=predep+dep[iid]; predep=dep[iid];
PRE=id[ID];
mx=0,ID;
for(int i=0;i<=2;i++)
if((int)st[id[i]].size()>mx) mx=(int)st[id[i]].size(), ID=i;
if(mx*2==rest){
int tmpid=ID;
mx1=((st[id[0]].empty()||PRE==id[0]) ? -1 : st[id[0]].rbegin()->second);
mx2=((st[id[1]].empty()||PRE==id[1]) ? -1 : st[id[1]].rbegin()->second);
mx3=((st[id[2]].empty()||PRE==id[2]) ? -1 : st[id[2]].rbegin()->second);
mx=0;
if(mx1!=-1&&mx<dep[mx1]) mx=dep[mx1],ID=0,iid=mx1;
if(mx2!=-1&&mx<dep[mx2]) mx=dep[mx2],ID=1,iid=mx2;
if(mx3!=-1&&mx<dep[mx3]) mx=dep[mx3],ID=2,iid=mx3;
int CH=0;
if(ID!=tmpid&&mx>predep) CH=1;
for(int i=0;i<=2;i++){
son[id[i]].clear();
while(!st[id[i]].empty()) {
if(CH!=1||st[id[i]].begin()->second!=iid)
son[id[i]].push_back(st[id[i]].begin()->second);
st[id[i]].erase(st[id[i]].begin());
}
}
if(tmpid!=0) swap(id[tmpid],id[0]);
for(int i=0;i<(int)son[id[2]].size();i++)
son[id[1]].push_back(son[id[2]][i]);
sort(son[id[0]].begin(),son[id[0]].end(),cmp);
sort(son[id[1]].begin(),son[id[1]].end(),cmp);
if(CH) son[id[1]].push_back(iid);
if(!CH) solver2(id[0],id[1]);
else solver2(id[1],id[0]);
return;
}
}
}
void init()
{
sz[0]=n;
for(int i=1;i<n;i++) sz[i]=attractionsBehind(0,i);
for(int i=1;i<n;i++)
if(sz[i]<sz[rt]&&sz[i]>=(n+1)/2) rt=i;
for(int i=0;i<n;i++) if(i!=rt){
dep[i]=hoursRequired(rt,i);
if(dep[i]==1) id[cnt++]=i, son[i].push_back(i);
}
for(int i=0;i<n;i++) if(i!=rt&&dep[i]!=1){
int dis1=hoursRequired(id[0],i),dis2=hoursRequired(id[1],i);
if(dis1==dep[i]-1) son[id[0]].push_back(i);
else if(dis2==dep[i]-1) son[id[1]].push_back(i);
else son[id[2]].push_back(i);
}
for(int i=0;i<cnt;i++) sort(son[id[i]].begin(),son[id[i]].end(),cmp);
}
std::vector<int> createFunTour(int NN, int Q)
{
n=NN;
if(NN==2) {vector<int> TMP; TMP.push_back(0); TMP.push_back(1); return TMP;}
init();
if(cnt==2) solver2(id[0],id[1]);
else solver3();
return ans;
} | 36.655462 | 84 | 0.475928 | jinzhengyu1212 |
169fd335a59b3723d4d21ba0e9d773c14d5bee16 | 10,690 | hpp | C++ | tests/test_queue.hpp | bcfrutuozo/Data-Structures-C-Plus-Plus | decd87c89380dbd98445411772567706cfa1e9b4 | [
"MIT"
] | null | null | null | tests/test_queue.hpp | bcfrutuozo/Data-Structures-C-Plus-Plus | decd87c89380dbd98445411772567706cfa1e9b4 | [
"MIT"
] | null | null | null | tests/test_queue.hpp | bcfrutuozo/Data-Structures-C-Plus-Plus | decd87c89380dbd98445411772567706cfa1e9b4 | [
"MIT"
] | null | null | null | //
// Created by bcfrutuozo on 18/03/2022.
//
#ifndef CPPDATASTRUCTURES_TEST_QUEUE_HPP
#define CPPDATASTRUCTURES_TEST_QUEUE_HPP
#include <catch2/catch.hpp>
#include <cstring>
#include "../Queue.h"
TEST_CASE("Queue<T>")
{
SECTION("Instantiation")
{
SECTION("Primitive types")
{
SECTION("Queue<uint8_t>")
{
Queue<uint8_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1u);
c.Enqueue(2u);
c.Enqueue(3u);
c.Enqueue(4u);
c.Enqueue(5u);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint8_t>{1u, 2u, 3u, 4u, 5u});
}
SECTION("Queue<uint16_t>")
{
Queue<uint16_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1u);
c.Enqueue(2u);
c.Enqueue(3u);
c.Enqueue(4u);
c.Enqueue(5u);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint16_t>{1u, 2u, 3u, 4u, 5u});
}
SECTION("Queue<uint32_t>")
{
Queue<uint32_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1u);
c.Enqueue(2u);
c.Enqueue(3u);
c.Enqueue(4u);
c.Enqueue(5u);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint32_t>{1u, 2u, 3u, 4u, 5u});
}
SECTION("Queue<uint64_t>")
{
Queue<uint64_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1ul);
c.Enqueue(2ul);
c.Enqueue(3ul);
c.Enqueue(4ul);
c.Enqueue(5ul);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<uint64_t>{1ul, 2ul, 3ul, 4ul, 5ul});
}
SECTION("Queue<int8_t>")
{
Queue<int8_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1);
c.Enqueue(2);
c.Enqueue(3);
c.Enqueue(4);
c.Enqueue(5);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int8_t>{1, 2, 3, 4, 5});
}
SECTION("Queue<int16_t>")
{
Queue<int16_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1);
c.Enqueue(2);
c.Enqueue(3);
c.Enqueue(4);
c.Enqueue(5);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int16_t>{1, 2, 3, 4, 5});
}
SECTION("Queue<int32_t>")
{
Queue<int32_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1);
c.Enqueue(2);
c.Enqueue(3);
c.Enqueue(4);
c.Enqueue(5);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int32_t>{1, 2, 3, 4, 5});
}
SECTION("Queue<int64_t>")
{
Queue<int64_t> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1l);
c.Enqueue(2l);
c.Enqueue(3l);
c.Enqueue(4l);
c.Enqueue(5l);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<int64_t>{1l, 2l, 3l, 4l, 5l});
}
SECTION("Queue<char>")
{
Queue<char> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue('1');
c.Enqueue('2');
c.Enqueue('3');
c.Enqueue('4');
c.Enqueue('5');
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<char>{'1', '2', '3', '4', '5'});
}
SECTION("Queue<unsigned char>")
{
Queue<unsigned char> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue('1');
c.Enqueue('2');
c.Enqueue('3');
c.Enqueue('4');
c.Enqueue('5');
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<unsigned char>{'1', '2', '3', '4', '5'});
}
SECTION("Queue<float>")
{
Queue<float> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1.0f);
c.Enqueue(2.0f);
c.Enqueue(3.0f);
c.Enqueue(4.0f);
c.Enqueue(5.0);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
}
SECTION("Queue<double>")
{
Queue<double> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue(1.0f);
c.Enqueue(2.0f);
c.Enqueue(3.0f);
c.Enqueue(4.0f);
c.Enqueue(5.0);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<double>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
}
}
SECTION("Non-primitive types")
{
SECTION("Queue<const char*> Array")
{
Queue<const char *> c;
REQUIRE(c.GetLength() == 0);
c.Enqueue("ABC");
c.Enqueue("BRUNO");
c.Enqueue("FRUTUOZO");
REQUIRE(c.GetLength() == 3);
REQUIRE(c == Queue<const char*>{"ABC", "BRUNO", "FRUTUOZO"});
}
}
SECTION("Copy constructor")
{
Queue<int> a{1, 2, 3, 4, 5, 6};
Queue<int> b(a);
REQUIRE(a == b);
a.Enqueue(7);
REQUIRE(a != b);
REQUIRE(a.Dequeue() == 1);
REQUIRE(a == Queue<int>{2, 3, 4, 5, 6, 7});
a.Dequeue();
a.Enqueue(10);
REQUIRE(a != b);
}
SECTION("Copy assignment constructor")
{
Queue<int> a{1, 2, 3, 4, 5, 6};
Queue<int> b = a;
REQUIRE(a == b);
a.Enqueue(7);
REQUIRE(a != b);
Queue<int> c{2, 3, 4, 5, 6, 7};
REQUIRE(a.Dequeue() == 1);
REQUIRE(a == c);
a.Dequeue();
a.Enqueue(10);
REQUIRE(a != b);
}
SECTION("Move constructor")
{
Queue<int> a{1, 2, 3, 4};
Queue<int> b = std::move(a);
REQUIRE(a.IsEmpty());
REQUIRE(b == Queue<int>({1, 2, 3, 4}));
}
SECTION("Move assignment")
{
Queue<int> a{1, 2, 3, 4};
Queue<int> b{5, 6};
b = std::move(a);
REQUIRE(a.IsEmpty());
REQUIRE(b == Queue<int>({1, 2, 3, 4}));
}
}
SECTION("Comparison")
{
SECTION("Queue<T> == Queue<T>")
{
REQUIRE(Queue<int>{1, 2, 3, 4, 5, 6} == Queue<int>{1, 2, 3, 4, 5, 6});
}
SECTION("Queue<T> != Queue<T>")
{
REQUIRE(Queue<int>{1, 2, 3, 4, 5, 6} != Queue<int>{1, 2, 3, 0, 5, 6});
}
}
SECTION("Push elements")
{
SECTION("Single element")
{
Queue<const char *> c = {"A", "TEST", "LOREM"};
c.Enqueue("ZZZZZ");
REQUIRE(c.GetLength() == 4);
REQUIRE(strcmp(c.Dequeue(), "A") == 0);
}
SECTION("Array of elements")
{
SECTION("Single element")
{
Queue<const char *> c = {"A", "TEST", "LOREM"};
Array<const char *> a = {"ABC", "DEF", "ZZZ"};
c.Enqueue(a);
REQUIRE(c.GetLength() == 6);
REQUIRE(strcmp(c.Dequeue(), "A") == 0);
REQUIRE(c.GetLength() == 5);
REQUIRE(c == Queue<const char *> {"TEST", "LOREM", "ABC", "DEF", "ZZZ"});
}
SECTION("Array of elements")
{
Queue<const char *> c = {"A", "TEST", "LOREM", "TEST", "TEST2", "TEST3"};
REQUIRE(c.GetLength() == 6);
Array<const char *> a = c.Dequeue(3);
REQUIRE(a.GetLength() == 3);
REQUIRE(c.GetLength() == 3);
REQUIRE(strcmp(a[0], "A") == 0);
REQUIRE(strcmp(a[1], "TEST") == 0);
REQUIRE(strcmp(a[2], "LOREM") == 0);
}
}
}
SECTION("Pop elements")
{
Queue<int> c = {4, 99, -37, 0, 2};
REQUIRE(c.Dequeue() == 4);
REQUIRE(c.Dequeue() == 99);
REQUIRE(c.Dequeue() == -37);
REQUIRE(c.Dequeue() == 0);
REQUIRE(c.Dequeue() == 2);
CHECK_THROWS(c.Dequeue());
}
SECTION("Check peek")
{
Queue<int> c = {4, 99, -37, 0, 2};
REQUIRE(c.Peek() == 4);
REQUIRE(c.GetLength() == 5);
while (!c.IsEmpty())
c.Dequeue();
CHECK_THROWS(c.Peek());
}
SECTION("Clear container")
{
Queue<const char *> a{"ABC", "DEF", "GHIJKLM"};
a.Clear();
REQUIRE(a == Queue<const char*>{});
}
SECTION("Swap container")
{
Queue<int> a{0, 1, 2, 3};
Queue<int> b{9, 8, 7, 6};
a.Swap(b);
REQUIRE(a.Dequeue() == 9);
REQUIRE(a.Dequeue() == 8);
REQUIRE(a.Dequeue() == 7);
REQUIRE(a.Dequeue() == 6);
CHECK_THROWS(a.Dequeue());
REQUIRE(b.Dequeue() == 0);
REQUIRE(b.Dequeue() == 1);
REQUIRE(b.Dequeue() == 2);
REQUIRE(b.Dequeue() == 3);
CHECK_THROWS(b.Dequeue());
}
SECTION("Conversion to Array<T>") {
Queue<int> a{1, 2, 3, 4, 5};
Array<int> b = a.ToArray();
REQUIRE(a == Queue<int>{1, 2, 3, 4, 5});
REQUIRE(b == Array<int>{1, 2, 3, 4, 5});
}
SECTION("CopyTo(Array<T>)") {
Queue<int> a{1, 2, 3, 4, 5, 6};
Array<int> b{0, 0, 0, 0, 0, 0, 0, 0};
a.CopyTo(b, 2);
REQUIRE(b == Array<int>{0, 0, 1, 2, 3, 4, 5, 6});
Array<int> c;
CHECK_THROWS(a.CopyTo(c, 0));
Array<int> d{1, 2, 3};
a.CopyTo(d, 2);
REQUIRE(d == Array<int>{1, 2, 1, 2, 3, 4, 5, 6});
Array<int> e{1};
CHECK_THROWS(a.CopyTo(e, 1));
Array<int> f{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
a.CopyTo(f, 2);
REQUIRE(f == Array<int>{0, 0, 1, 2, 3, 4, 5, 6, 0, 0});
}
}
#endif //CPPDATASTRUCTURES_TEST_QUEUE_HPP | 29.449036 | 89 | 0.389429 | bcfrutuozo |
16a1b63592a799349ae4ceee6923bc274609e766 | 1,800 | cpp | C++ | aws-cpp-sdk-workspaces-web/source/model/CreatePortalRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-workspaces-web/source/model/CreatePortalRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-workspaces-web/source/model/CreatePortalRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/workspaces-web/model/CreatePortalRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::WorkSpacesWeb::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreatePortalRequest::CreatePortalRequest() :
m_additionalEncryptionContextHasBeenSet(false),
m_clientToken(Aws::Utils::UUID::RandomUUID()),
m_clientTokenHasBeenSet(true),
m_customerManagedKeyHasBeenSet(false),
m_displayNameHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Aws::String CreatePortalRequest::SerializePayload() const
{
JsonValue payload;
if(m_additionalEncryptionContextHasBeenSet)
{
JsonValue additionalEncryptionContextJsonMap;
for(auto& additionalEncryptionContextItem : m_additionalEncryptionContext)
{
additionalEncryptionContextJsonMap.WithString(additionalEncryptionContextItem.first, additionalEncryptionContextItem.second);
}
payload.WithObject("additionalEncryptionContext", std::move(additionalEncryptionContextJsonMap));
}
if(m_clientTokenHasBeenSet)
{
payload.WithString("clientToken", m_clientToken);
}
if(m_customerManagedKeyHasBeenSet)
{
payload.WithString("customerManagedKey", m_customerManagedKey);
}
if(m_displayNameHasBeenSet)
{
payload.WithString("displayName", m_displayName);
}
if(m_tagsHasBeenSet)
{
Array<JsonValue> tagsJsonList(m_tags.size());
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
}
payload.WithArray("tags", std::move(tagsJsonList));
}
return payload.View().WriteReadable();
}
| 24 | 130 | 0.757778 | perfectrecall |
16a8a92be01e8f75ab13847343727400919aa1bf | 234 | hpp | C++ | chaine/src/topology/vertex/vertex_topology.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/topology/vertex/vertex_topology.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/topology/vertex/vertex_topology.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | #pragma once
#include "index.hpp"
#include "mesh_topology.hpp"
#include "proxy.hpp"
namespace face_vertex {
inline
VertexTopology& vertex_topology(VertexTopologyProxy vtp) {
return mesh_topology(vtp).vertices[index(vtp)];
}
}
| 15.6 | 58 | 0.760684 | the-last-willy |
16a96378d705e59dea9725ce272640df3a1753d2 | 799 | cpp | C++ | test/training_data/plag_original_codes/01_000_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | 13 | 2021-01-20T19:53:16.000Z | 2021-11-14T16:30:32.000Z | test/training_data/plag_original_codes/01_000_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | test/training_data/plag_original_codes/01_000_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | // 引用元 : https://atcoder.jp/contests/abc122/submissions/5997478
// 得点 : 300
// コード長 : 695
// 実行時間 : 70
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
typedef long long ll;
int main() {
int n, q;
cin >> n >> q;
string s;
cin >> s;
vector<int> l(q), r(q);
rep(i, q) {
cin >> l[i] >> r[i];
}
vector<int> sum(n+1, 0);
for(int i = 1; i < n; i++) {
sum[i+1] = sum[i];
if(s[i-1] == 'A' && s[i] == 'C') {
sum[i+1]++;
}
}
rep(i, q) { int ans = sum[r[i]] - sum[l[i]];
cout << ans << "\n";
}
cout << endl;
return 0;
}
| 17.755556 | 64 | 0.439299 | xryuseix |
16a99c240a8c1823786c4c60cced12bd5401e5d4 | 103,675 | cpp | C++ | cxx4/ncVar.cpp | tkameyama/netcdf-cxx4 | c244f2de7818d9562eeadee548811872d4ac2975 | [
"NetCDF"
] | 93 | 2015-04-23T19:46:14.000Z | 2022-03-28T08:12:23.000Z | cxx4/ncVar.cpp | tkameyama/netcdf-cxx4 | c244f2de7818d9562eeadee548811872d4ac2975 | [
"NetCDF"
] | 90 | 2015-04-11T23:15:09.000Z | 2022-02-25T10:02:29.000Z | cxx4/ncVar.cpp | tkameyama/netcdf-cxx4 | c244f2de7818d9562eeadee548811872d4ac2975 | [
"NetCDF"
] | 59 | 2015-01-25T17:38:24.000Z | 2022-02-23T22:28:42.000Z | #include "ncVarAtt.h"
#include "ncDim.h"
#include "ncVar.h"
#include "ncGroup.h"
#include "ncCheck.h"
#include "ncException.h"
#include<netcdf.h>
using namespace std;
using namespace netCDF::exceptions;
namespace netCDF {
// Global comparator operator ==============
// comparator operator
bool operator<(const NcVar& lhs,const NcVar& rhs)
{
return false;
}
// comparator operator
bool operator>(const NcVar& lhs,const NcVar& rhs)
{
return true;
}
}
using namespace netCDF;
// assignment operator
NcVar& NcVar::operator=(const NcVar & rhs)
{
nullObject = rhs.nullObject;
myId = rhs.myId;
groupId = rhs.groupId;
return *this;
}
// The copy constructor.
NcVar::NcVar(const NcVar& rhs) :
nullObject(rhs.nullObject),
myId(rhs.myId),
groupId(rhs.groupId)
{}
// equivalence operator
bool NcVar::operator==(const NcVar & rhs) const
{
// simply check the netCDF id.
return (myId == rhs.myId);
}
// != operator
bool NcVar::operator!=(const NcVar & rhs) const
{
return !(*this == rhs);
}
/////////////////
// Constructors and intialization
/////////////////
// Constructor generates a null object.
NcVar::NcVar() : nullObject(true),
myId(-1),
groupId(-1)
{}
// Constructor for a variable (must already exist in the netCDF file.)
NcVar::NcVar (const NcGroup& grp, const int& varId) :
nullObject (false),
myId (varId),
groupId(grp.getId())
{}
// Gets parent group.
NcGroup NcVar::getParentGroup() const {
return NcGroup(groupId);
}
// Get the variable id.
int NcVar::getId() const {return myId;}
//////////////////////
// Information about the variable type
/////////////////////
// Gets the NcType object with a given name.
NcType NcVar::getType() const {
// if this variable has not been defined, return a NULL type
if(isNull()) return NcType();
// first get the typeid
nc_type xtypep;
ncCheck(nc_inq_vartype(groupId,myId,&xtypep),__FILE__,__LINE__);
if(xtypep == ncByte.getId() ) return ncByte;
if(xtypep == ncUbyte.getId() ) return ncUbyte;
if(xtypep == ncChar.getId() ) return ncChar;
if(xtypep == ncShort.getId() ) return ncShort;
if(xtypep == ncUshort.getId() ) return ncUshort;
if(xtypep == ncInt.getId() ) return ncInt;
if(xtypep == ncUint.getId() ) return ncUint;
if(xtypep == ncInt64.getId() ) return ncInt64;
if(xtypep == ncUint64.getId() ) return ncUint64;
if(xtypep == ncFloat.getId() ) return ncFloat;
if(xtypep == ncDouble.getId() ) return ncDouble;
if(xtypep == ncString.getId() ) return ncString;
multimap<string,NcType>::const_iterator it;
multimap<string,NcType> types(NcGroup(groupId).getTypes(NcGroup::ParentsAndCurrent));
for(it=types.begin(); it!=types.end(); it++) {
if(it->second.getId() == xtypep) return it->second;
}
// we will never reach here
return true;
}
/////////////////
// Information about Dimensions
/////////////////
// Gets the number of dimensions.
int NcVar::getDimCount() const
{
// get the number of dimensions
int dimCount;
ncCheck(nc_inq_varndims(groupId,myId, &dimCount),__FILE__,__LINE__);
return dimCount;
}
// Gets the set of Ncdim objects.
vector<NcDim> NcVar::getDims() const
{
// get the number of dimensions
int dimCount = getDimCount();
// create a vector of dimensions.
vector<NcDim> ncDims;
if (dimCount){
vector<int> dimids(dimCount);
ncCheck(nc_inq_vardimid(groupId,myId, &dimids[0]),__FILE__,__LINE__);
ncDims.reserve(dimCount);
for (int i=0; i<dimCount; i++){
NcDim tmpDim(getParentGroup(),dimids[i]);
ncDims.push_back(tmpDim);
}
}
return ncDims;
}
// Gets the i'th NcDim object.
NcDim NcVar::getDim(int i) const
{
vector<NcDim> ncDims = getDims();
if((size_t)i >= ncDims.size() || i < 0) throw NcException("Index out of range",__FILE__,__LINE__);
return ncDims[i];
}
/////////////////
// Information about Attributes
/////////////////
// Gets the number of attributes.
int NcVar::getAttCount() const
{
// get the number of attributes
int attCount;
ncCheck(nc_inq_varnatts(groupId,myId, &attCount),__FILE__,__LINE__);
return attCount;
}
// Gets the set of attributes.
map<string,NcVarAtt> NcVar::getAtts() const
{
// get the number of attributes
int attCount = getAttCount();
// create a container of attributes.
map<string,NcVarAtt> ncAtts;
for (int i=0; i<attCount; i++){
NcVarAtt tmpAtt(getParentGroup(),*this,i);
ncAtts.insert(pair<const string,NcVarAtt>(tmpAtt.getName(),tmpAtt));
}
return ncAtts;
}
// Gets attribute by name.
NcVarAtt NcVar::getAtt(const string& name) const
{
map<string,NcVarAtt> attributeList = getAtts();
map<string,NcVarAtt>::iterator myIter;
myIter = attributeList.find(name);
if(myIter == attributeList.end()){
string msg("Attribute '"+name+"' not found");
throw NcException(msg.c_str(),__FILE__,__LINE__);
}
return NcVarAtt(myIter->second);
}
/////////////////////////
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const string& dataValues) const {
ncCheckDefineMode(groupId);
ncCheck(nc_put_att_text(groupId,myId,name.c_str(),dataValues.size(),dataValues.c_str()),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const unsigned char* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_uchar(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const signed char* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_schar(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
/////////////////////////////////
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, short datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_short(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, int datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_int(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, long datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_long(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, float datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_float(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, double datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_double(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, unsigned short datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_ushort(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, unsigned int datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_uint(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, long long datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_longlong(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, unsigned long long datumValue) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_att_ulonglong(groupId,myId,name.c_str(),type.getId(),1,&datumValue),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
/////////////////////////////////
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const short* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_short(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const int* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_int(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const long* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_long(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const float* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_float(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const double* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_double(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const unsigned short* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_ushort(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const unsigned int* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_uint(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const long long* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_longlong(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const unsigned long long* dataValues) const {
ncCheckDefineMode(groupId);
NcType::ncType typeClass(type.getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_att(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_att_ulonglong(groupId,myId,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, size_t len, const char** dataValues) const {
ncCheckDefineMode(groupId);
ncCheck(nc_put_att_string(groupId,myId,name.c_str(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
// Creates a new NetCDF variable attribute or if already exisiting replaces it.
NcVarAtt NcVar::putAtt(const string& name, const NcType& type, size_t len, const void* dataValues) const {
ncCheckDefineMode(groupId);
ncCheck(nc_put_att(groupId,myId ,name.c_str(),type.getId(),len,dataValues),__FILE__,__LINE__);
// finally instantiate this attribute and return
return getAtt(name);
}
////////////////////
// Other Basic variable info
////////////////////
// The name of this variable.
string NcVar::getName() const{
char charName[NC_MAX_NAME+1];
ncCheck(nc_inq_varname(groupId, myId, charName),__FILE__,__LINE__);
return string(charName);
}
////////////////////
// Chunking details
////////////////////
// Sets chunking parameters.
void NcVar::setChunking(ChunkMode chunkMode, vector<size_t>& chunkSizes) const {
size_t *chunkSizesPtr = chunkSizes.empty() ? 0 : &chunkSizes[0];
ncCheck(nc_def_var_chunking(groupId,myId,static_cast<int> (chunkMode), chunkSizesPtr),__FILE__,__LINE__);
}
// Gets the chunking parameters
void NcVar::getChunkingParameters(ChunkMode& chunkMode, vector<size_t>& chunkSizes) const {
int chunkModeInt;
chunkSizes.resize(getDimCount());
size_t *chunkSizesPtr = chunkSizes.empty() ? 0 : &chunkSizes[0];
ncCheck(nc_inq_var_chunking(groupId,myId, &chunkModeInt, chunkSizesPtr),__FILE__,__LINE__);
chunkMode = static_cast<ChunkMode> (chunkModeInt);
}
////////////////////
// Fill details
////////////////////
// Sets the fill parameters
void NcVar::setFill(bool fillMode, void* fillValue) const {
// If fillMode is enabled, check that fillValue has a legal pointer.
if(fillMode && fillValue == NULL)
throw NcException("FillMode was set to zero but fillValue has invalid pointer",__FILE__,__LINE__);
ncCheck(nc_def_var_fill(groupId,myId,static_cast<int> (!fillMode),fillValue),__FILE__,__LINE__);
}
// Sets the fill parameters
void NcVar::setFill(bool fillMode,const void* fillValue) const {
setFill(fillMode,const_cast<void*>(fillValue));
}
// Gets the fill parameters
void NcVar::getFillModeParameters(bool& fillMode, void* fillValue)const{
int fillModeInt;
ncCheck(nc_inq_var_fill(groupId,myId,&fillModeInt,fillValue),__FILE__,__LINE__);
fillMode= static_cast<bool> (fillModeInt == 0);
}
////////////////////
// Compression details
////////////////////
// Sets the compression parameters
void NcVar::setCompression(bool enableShuffleFilter, bool enableDeflateFilter, int deflateLevel) const {
// Check that the deflate level is legal
if(enableDeflateFilter & (deflateLevel < 0 || deflateLevel >9))
throw NcException("The deflateLevel must be set between 0 and 9.",__FILE__,__LINE__);
ncCheck(nc_def_var_deflate(groupId,myId,
static_cast<int> (enableShuffleFilter),
static_cast<int> (enableDeflateFilter),
deflateLevel),__FILE__,__LINE__);
}
// Gets the compression parameters
void NcVar::getCompressionParameters(bool& shuffleFilterEnabled, bool& deflateFilterEnabled, int& deflateLevel) const {
int enableShuffleFilterInt;
int enableDeflateFilterInt;
ncCheck(nc_inq_var_deflate(groupId,myId,
&enableShuffleFilterInt,
&enableDeflateFilterInt,
&deflateLevel),__FILE__,__LINE__);
shuffleFilterEnabled = static_cast<bool> (enableShuffleFilterInt);
deflateFilterEnabled = static_cast<bool> (enableDeflateFilterInt);
}
// Define a variable filter to be used for compression (decompression)
void NcVar::setFilter( unsigned int id, size_t nparams,
const unsigned int* parms) const
{
ncCheck(nc_def_var_filter(groupId,myId,id,nparams,parms),__FILE__,__LINE__);
}
// Query filter details (if any) associated with a variable
void NcVar::getFilter( unsigned int* idp, size_t* nparamsp, unsigned int* params) const
{
ncCheck(nc_inq_var_filter(groupId, myId, idp, nparamsp, params),__FILE__,__LINE__);
}
// Query the length of a given Type
void NcVar::getTypeLen(nc_type type) const
{
ncCheck(nctypelen(type),__FILE__,__LINE__);
}
// Free string space allocated by the library
void NcVar::freeString(size_t len, char **data) const
{
ncCheck(nc_free_string(len, data),__FILE__,__LINE__);
}
// Change the cache settings for a chunked variable
void NcVar::setChunkCache(size_t size, size_t nelems, float preemption) const
{
ncCheck(nc_set_var_chunk_cache(groupId, myId, size, nelems, preemption),__FILE__,__LINE__);
}
////////////////////
// Endianness details
////////////////////
// Sets the endianness of the variable.
void NcVar::setEndianness(EndianMode endianMode) const {
ncCheck(nc_def_var_endian(groupId,myId,static_cast<int> (endianMode)),__FILE__,__LINE__);
}
// Gets the endianness of the variable.
NcVar::EndianMode NcVar::getEndianness() const {
int endianInt;
ncCheck(nc_inq_var_endian(groupId,myId,&endianInt),__FILE__,__LINE__);
return static_cast<EndianMode> (endianInt);
}
////////////////////
// Checksum details
////////////////////
// Sets the checksum parameters of a variable.
void NcVar::setChecksum(ChecksumMode checksumMode) const {
ncCheck(nc_def_var_fletcher32(groupId,myId,static_cast<int> (checksumMode)),__FILE__,__LINE__);
}
// Gets the checksum parameters of the variable.
NcVar::ChecksumMode NcVar::getChecksum() const {
int checksumInt;
ncCheck(nc_inq_var_fletcher32(groupId,myId,&checksumInt),__FILE__,__LINE__);
return static_cast<ChecksumMode> (checksumInt);
}
////////////////////
// renaming the variable
////////////////////
void NcVar::rename( const string& newname ) const
{
ncCheck(nc_rename_var(groupId,myId,newname.c_str()),__FILE__,__LINE__);
}
////////////////////
// data writing
////////////////////
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_text(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const unsigned char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_uchar(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const signed char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_schar(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_short(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_int(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_long(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const float* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_float(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const double* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_double(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const unsigned short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_ushort(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const unsigned int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_uint(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_longlong(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const unsigned long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_ulonglong(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable.
void NcVar::putVar(const char** dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_var_string(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Writes the entire data into the netCDF variable with no data conversion.
void NcVar::putVar(const void* dataValues) const {
ncCheckDataMode(groupId);
ncCheck(nc_put_var(groupId, myId,dataValues),__FILE__,__LINE__);
}
///////////////////
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const string& datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
throw NcException("user-defined type must be of type void",__FILE__,__LINE__);
else
{
const char* tmpPtr = datumValue.c_str();
ncCheck(nc_put_var1_string(groupId, myId,&index[0],&tmpPtr),__FILE__,__LINE__);
}
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const unsigned char* datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
throw NcException("user-defined type must be of type void",__FILE__,__LINE__);
else
ncCheck(nc_put_var1_uchar(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const signed char* datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
throw NcException("user-defined type must be of type void",__FILE__,__LINE__);
else
ncCheck(nc_put_var1_schar(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const short datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_short(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const int datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_int(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const long datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_long(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const float datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_float(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const double datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_double(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const unsigned short datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_ushort(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const unsigned int datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_uint(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const long long datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_longlong(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const unsigned long long datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_var1(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
else
ncCheck(nc_put_var1_ulonglong(groupId, myId,&index[0],&datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable.
void NcVar::putVar(const vector<size_t>& index, const char** datumValue) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
throw NcException("user-defined type must be of type void",__FILE__,__LINE__);
else
ncCheck(nc_put_var1_string(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Writes a single datum value into the netCDF variable with no data conversion.
void NcVar::putVar(const vector<size_t>& index, const void* datumValue) const {
ncCheckDataMode(groupId);
ncCheck(nc_put_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
////////////////////
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_text(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const unsigned char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_uchar(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const signed char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_schar(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_short(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_int(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_long(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const float* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_float(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const double* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_double(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const unsigned short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_ushort(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const unsigned int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_uint(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_longlong(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const unsigned long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_ulonglong(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const char** dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vara_string(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Writes an array of values into the netCDF variable with no data conversion.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>& countp, const void* dataValues) const {
ncCheckDataMode(groupId);
ncCheck(nc_put_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
////////////////////
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_text(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const unsigned char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_uchar(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const signed char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_schar(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_short(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_int(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_long(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const float* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_float(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const double* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_double(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const unsigned short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_ushort(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const unsigned int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_uint(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_longlong(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const unsigned long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_ulonglong(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const char** dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_vars_string(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Writes a set of subsampled array values into the netCDF variable with no data conversion.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const void* dataValues) const {
ncCheckDataMode(groupId);
ncCheck(nc_put_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
////////////////////
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_text(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const unsigned char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_uchar(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const signed char* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_schar(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_short(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_int(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_long(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const float* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_float(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const double* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_double(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const unsigned short* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_ushort(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const unsigned int* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_uint(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_longlong(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const unsigned long long* dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_ulonglong(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const char** dataValues) const {
ncCheckDataMode(groupId);
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_put_varm_string(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Writes a mapped array section of values into the netCDF variable with no data conversion.
void NcVar::putVar(const vector<size_t>& startp, const vector<size_t>&countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, const void* dataValues) const {
ncCheckDataMode(groupId);
ncCheck(nc_put_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Data reading
// Reads the entire data of the netCDF variable.
void NcVar::getVar(char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_text(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(unsigned char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_uchar(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(signed char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_schar(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_short(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_int(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_long(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(float* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_float(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(double* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_double(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(unsigned short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_ushort(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(unsigned int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_uint(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_longlong(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(unsigned long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_ulonglong(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable.
void NcVar::getVar(char** dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_var_string(groupId, myId,dataValues),__FILE__,__LINE__);
}
// Reads the entire data of the netCDF variable with no data conversion.
void NcVar::getVar(void* dataValues) const {
ncCheck(nc_get_var(groupId, myId,dataValues),__FILE__,__LINE__);
}
///////////
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, char* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_text(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, unsigned char* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_uchar(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, signed char* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_schar(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, short* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_short(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, int* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_int(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, long* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_long(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, float* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_float(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, double* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_double(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, unsigned short* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_ushort(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, unsigned int* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_uint(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, long long* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_longlong(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable
void NcVar::getVar(const vector<size_t>& index, unsigned long long* datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_ulonglong(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable.
void NcVar::getVar(const vector<size_t>& index, char** datumValue) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
else
ncCheck(nc_get_var1_string(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
// Reads a single datum value of a netCDF variable with no data conversion.
void NcVar::getVar(const vector<size_t>& index, void* datumValue) const {
ncCheck(nc_get_var1(groupId, myId,&index[0],datumValue),__FILE__,__LINE__);
}
///////////
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_text(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, unsigned char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_uchar(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, signed char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_schar(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_short(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_int(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_long(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, float* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_float(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, double* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_double(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, unsigned short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_ushort(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, unsigned int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_uint(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_longlong(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, unsigned long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_ulonglong(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, char** dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vara_string(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
// Reads an array of values from a netCDF variable with no data conversion.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, void* dataValues) const {
ncCheck(nc_get_vara(groupId, myId,&startp[0],&countp[0],dataValues),__FILE__,__LINE__);
}
///////////
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_text(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, unsigned char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_uchar(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, signed char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_schar(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_short(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_int(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_long(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, float* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_float(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, double* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_double(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, unsigned short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_ushort(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, unsigned int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_uint(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_longlong(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, unsigned long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_ulonglong(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, char** dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_vars_string(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
// Reads a subsampled (strided) array section of values from a netCDF variable with no data conversion.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, void* dataValues) const {
ncCheck(nc_get_vars(groupId, myId,&startp[0],&countp[0],&stridep[0],dataValues),__FILE__,__LINE__);
}
///////////
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_text(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, unsigned char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_uchar(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, signed char* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_schar(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_short(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_int(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_long(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, float* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_float(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, double* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_double(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, unsigned short* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN ||typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_ushort(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, unsigned int* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_uint(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_longlong(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, unsigned long long* dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_ulonglong(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, char** dataValues) const {
NcType::ncType typeClass(getType().getTypeClass());
if(typeClass == NcType::nc_VLEN || typeClass == NcType::nc_OPAQUE || typeClass == NcType::nc_ENUM || typeClass == NcType::nc_COMPOUND)
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
else
ncCheck(nc_get_varm_string(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
// Reads a mapped array section of values from a netCDF variable with no data conversion.
void NcVar::getVar(const vector<size_t>& startp, const vector<size_t>& countp, const vector<ptrdiff_t>& stridep, const vector<ptrdiff_t>& imapp, void* dataValues) const {
ncCheck(nc_get_varm(groupId, myId,&startp[0],&countp[0],&stridep[0],&imapp[0],dataValues),__FILE__,__LINE__);
}
| 53.997396 | 189 | 0.736542 | tkameyama |
16a9bfb5be620f91ef04c39ba3805580f30c4aff | 308 | cpp | C++ | C7Editing/data/c7framedata.cpp | xshanlin/c7es | 520ab5b7efe54521aeb930e6baf60b8bb62a8027 | [
"MIT"
] | null | null | null | C7Editing/data/c7framedata.cpp | xshanlin/c7es | 520ab5b7efe54521aeb930e6baf60b8bb62a8027 | [
"MIT"
] | null | null | null | C7Editing/data/c7framedata.cpp | xshanlin/c7es | 520ab5b7efe54521aeb930e6baf60b8bb62a8027 | [
"MIT"
] | null | null | null | #include "c7framedata.h"
PO1_IMPLEMENTATION_BEGIN(C7FrameData, RIID_C7FRAME_DATA)
//PO1_ITEM_IMPLEMENTATION(C7BufferIO2D, RIID_C7BUFFER_IO_2D)
PO1_IMPLEMENTATION_END(C7Obj)
C7FrameData::C7FrameData(std::weak_ptr<C7Obj> outerObj) : C7Obj(outerObj) {
//ctor
}
C7FrameData::~C7FrameData() {
//dtor
}
| 22 | 75 | 0.782468 | xshanlin |
16ab559f2ab33a517b17c65a9ff1d6f7754d6c18 | 1,618 | cpp | C++ | venv/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_advanced.cpp | uosorio/heroku_face | 7d6465e71dba17a15d8edaef520adb2fcd09d91e | [
"Apache-2.0"
] | 188 | 2019-02-08T14:11:02.000Z | 2022-01-27T08:37:05.000Z | 3rdparty/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_advanced.cpp | qingkouwei/mediaones | cec475e1bfd5807b5351cc7e38d244ac5298ca16 | [
"MIT"
] | 186 | 2016-05-05T14:01:09.000Z | 2019-11-20T22:38:43.000Z | 3rdparty/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_advanced.cpp | qingkouwei/mediaones | cec475e1bfd5807b5351cc7e38d244ac5298ca16 | [
"MIT"
] | 43 | 2019-02-09T16:16:55.000Z | 2022-01-25T20:24:36.000Z | // Copyright 2019 Hans Dembinski
//
// 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)
//[ guide_custom_accumulators_advanced
#include <boost/format.hpp>
#include <boost/histogram.hpp>
#include <iostream>
#include <sstream>
int main() {
using namespace boost::histogram;
// Accumulator accepts two samples and an optional weight and computes the mean of each.
struct multi_mean {
accumulators::mean<> mx, my;
// called when no weight is passed
void operator()(double x, double y) {
mx(x);
my(y);
}
// called when a weight is passed
void operator()(weight_type<double> w, double x, double y) {
mx(w, x);
my(w, y);
}
};
// Note: The implementation can be made more efficient by sharing the sum of weights.
// Create a 1D histogram that uses the custom accumulator.
auto h = make_histogram_with(dense_storage<multi_mean>(), axis::integer<>(0, 2));
h(0, sample(1, 2)); // samples go to first cell
h(0, sample(3, 4)); // samples go to first cell
h(1, sample(5, 6), weight(2)); // samples go to second cell
h(1, sample(7, 8), weight(3)); // samples go to second cell
std::ostringstream os;
for (auto&& bin : indexed(h)) {
os << boost::format("index %i mean-x %.1f mean-y %.1f\n") % bin.index() %
bin->mx.value() % bin->my.value();
}
std::cout << os.str() << std::flush;
assert(os.str() == "index 0 mean-x 2.0 mean-y 3.0\n"
"index 1 mean-x 6.2 mean-y 7.2\n");
}
//]
| 30.528302 | 90 | 0.623609 | uosorio |
16ac06a946869f05185c846abe524d4788a7399e | 29,035 | cc | C++ | src/ballistica/python/class/python_class_material.cc | Benefit-Zebra/ballistica | eb85df82cff22038e74a2d93abdcbe9cd755d782 | [
"MIT"
] | null | null | null | src/ballistica/python/class/python_class_material.cc | Benefit-Zebra/ballistica | eb85df82cff22038e74a2d93abdcbe9cd755d782 | [
"MIT"
] | null | null | null | src/ballistica/python/class/python_class_material.cc | Benefit-Zebra/ballistica | eb85df82cff22038e74a2d93abdcbe9cd755d782 | [
"MIT"
] | null | null | null | // Released under the MIT License. See LICENSE for details.
#include "ballistica/python/class/python_class_material.h"
#include "ballistica/dynamics/material/impact_sound_material_action.h"
#include "ballistica/dynamics/material/material.h"
#include "ballistica/dynamics/material/material_component.h"
#include "ballistica/dynamics/material/material_condition_node.h"
#include "ballistica/dynamics/material/node_message_material_action.h"
#include "ballistica/dynamics/material/node_mod_material_action.h"
#include "ballistica/dynamics/material/node_user_message_material_action.h"
#include "ballistica/dynamics/material/part_mod_material_action.h"
#include "ballistica/dynamics/material/python_call_material_action.h"
#include "ballistica/dynamics/material/roll_sound_material_action.h"
#include "ballistica/dynamics/material/skid_sound_material_action.h"
#include "ballistica/dynamics/material/sound_material_action.h"
#include "ballistica/game/game.h"
#include "ballistica/game/host_activity.h"
#include "ballistica/python/python.h"
namespace ballistica {
// Ignore signed bitwise stuff since python macros do a lot of it.
#pragma clang diagnostic push
#pragma ide diagnostic ignored "hicpp-signed-bitwise"
#pragma ide diagnostic ignored "RedundantCast"
bool PythonClassMaterial::s_create_empty_ = false;
PyTypeObject PythonClassMaterial::type_obj;
static void DoAddConditions(PyObject* cond_obj,
Object::Ref<MaterialConditionNode>* c);
static void DoAddAction(PyObject* actions_obj,
std::vector<Object::Ref<MaterialAction> >* actions);
// Attrs we expose through our custom getattr/setattr.
#define ATTR_LABEL "label"
// The set we expose via dir().
static const char* extra_dir_attrs[] = {ATTR_LABEL, nullptr};
void PythonClassMaterial::SetupType(PyTypeObject* obj) {
PythonClass::SetupType(obj);
obj->tp_name = "ba.Material";
obj->tp_repr = (reprfunc)tp_repr;
obj->tp_basicsize = sizeof(PythonClassMaterial);
// clang-format off
obj->tp_doc =
"Material(label: str = None)\n"
"\n"
"An entity applied to game objects to modify collision behavior.\n"
"\n"
"Category: Gameplay Classes\n"
"\n"
"A material can affect physical characteristics, generate sounds,\n"
"or trigger callback functions when collisions occur.\n"
"\n"
"Materials are applied to 'parts', which are groups of one or more\n"
"rigid bodies created as part of a ba.Node. Nodes can have any number\n"
"of parts, each with its own set of materials. Generally materials are\n"
"specified as array attributes on the Node. The 'spaz' node, for\n"
"example, has various attributes such as 'materials',\n"
"'roller_materials', and 'punch_materials', which correspond to the\n"
"various parts it creates.\n"
"\n"
"Use ba.Material() to instantiate a blank material, and then use its\n"
"add_actions() method to define what the material does.\n"
"\n"
"Attributes:\n"
"\n"
" " ATTR_LABEL ": str\n"
" A label for the material; only used for debugging.\n";
// clang-format on
obj->tp_new = tp_new;
obj->tp_dealloc = (destructor)tp_dealloc;
obj->tp_methods = tp_methods;
obj->tp_getattro = (getattrofunc)tp_getattro;
obj->tp_setattro = (setattrofunc)tp_setattro;
}
auto PythonClassMaterial::tp_new(PyTypeObject* type, PyObject* args,
PyObject* keywds) -> PyObject* {
auto* self = reinterpret_cast<PythonClassMaterial*>(type->tp_alloc(type, 0));
if (self) {
BA_PYTHON_TRY;
// Do anything that might throw an exception *before* our placement-new
// stuff so we don't have to worry about cleaning it up on errors.
if (!InGameThread()) {
throw Exception(
"ERROR: " + std::string(type_obj.tp_name)
+ " objects must only be created in the game thread (current is ("
+ GetCurrentThreadName() + ").");
}
PyObject* name_obj = Py_None;
std::string name;
Object::Ref<Material> m;
// Clion incorrectly things s_create_empty will always be false.
#pragma clang diagnostic push
#pragma ide diagnostic ignored "ConstantConditionsOC"
if (!s_create_empty_) {
static const char* kwlist[] = {"label", nullptr};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "|O",
const_cast<char**>(kwlist), &name_obj)) {
return nullptr;
}
if (name_obj != Py_None) {
name = Python::GetPyString(name_obj);
} else {
name = Python::GetPythonFileLocation();
}
if (HostActivity* host_activity = Context::current().GetHostActivity()) {
m = host_activity->NewMaterial(name);
m->set_py_object(reinterpret_cast<PyObject*>(self));
} else {
throw Exception("Can't create materials in this context.",
PyExcType::kContext);
}
}
self->material_ = new Object::Ref<Material>(m);
BA_PYTHON_NEW_CATCH;
#pragma clang diagnostic pop
}
return reinterpret_cast<PyObject*>(self);
}
void PythonClassMaterial::Delete(Object::Ref<Material>* m) {
assert(InGameThread());
// If we're the py-object for a material, clear them out.
if (m->exists()) {
assert((*m)->py_object() != nullptr);
(*m)->set_py_object(nullptr);
}
delete m;
}
void PythonClassMaterial::tp_dealloc(PythonClassMaterial* self) {
BA_PYTHON_TRY;
// These have to be deleted in the game thread - push a call if
// need be.. otherwise do it immediately.
if (!InGameThread()) {
Object::Ref<Material>* ptr = self->material_;
g_game->PushCall([ptr] { Delete(ptr); });
} else {
Delete(self->material_);
}
BA_PYTHON_DEALLOC_CATCH;
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
auto PythonClassMaterial::tp_repr(PythonClassMaterial* self) -> PyObject* {
BA_PYTHON_TRY;
return Py_BuildValue(
"s",
std::string("<ba.Material at " + Utils::PtrToString(self) + ">").c_str());
BA_PYTHON_CATCH;
}
auto PythonClassMaterial::tp_getattro(PythonClassMaterial* self, PyObject* attr)
-> PyObject* {
BA_PYTHON_TRY;
// Assuming this will always be a str?
assert(PyUnicode_Check(attr));
const char* s = PyUnicode_AsUTF8(attr);
if (!strcmp(s, ATTR_LABEL)) {
Material* material = self->material_->get();
if (!material) {
throw Exception("Invalid Material.", PyExcType::kNotFound);
}
return PyUnicode_FromString(material->label().c_str());
}
// Fall back to generic behavior.
PyObject* val;
val = PyObject_GenericGetAttr(reinterpret_cast<PyObject*>(self), attr);
return val;
BA_PYTHON_CATCH;
}
// Yes Clion, we always return -1 here.
#pragma clang diagnostic push
#pragma ide diagnostic ignored "ConstantFunctionResult"
auto PythonClassMaterial::tp_setattro(PythonClassMaterial* self, PyObject* attr,
PyObject* val) -> int {
BA_PYTHON_TRY;
assert(PyUnicode_Check(attr));
throw Exception("Attr '" + std::string(PyUnicode_AsUTF8(attr))
+ "' is not settable on Material objects.",
PyExcType::kAttribute);
// return PyObject_GenericSetAttr(reinterpret_cast<PyObject*>(self), attr,
// val);
BA_PYTHON_INT_CATCH;
}
#pragma clang diagnostic pop
auto PythonClassMaterial::Dir(PythonClassMaterial* self) -> PyObject* {
BA_PYTHON_TRY;
// Start with the standard python dir listing.
PyObject* dir_list = Python::generic_dir(reinterpret_cast<PyObject*>(self));
assert(PyList_Check(dir_list));
// ..and add in our custom attr names.
for (const char** name = extra_dir_attrs; *name != nullptr; name++) {
PyList_Append(
dir_list,
PythonRef(PyUnicode_FromString(*name), PythonRef::kSteal).get());
}
PyList_Sort(dir_list);
return dir_list;
BA_PYTHON_CATCH;
}
auto PythonClassMaterial::AddActions(PythonClassMaterial* self, PyObject* args,
PyObject* keywds) -> PyObject* {
BA_PYTHON_TRY;
assert(InGameThread());
PyObject* conditions_obj{Py_None};
PyObject* actions_obj{nullptr};
const char* kwlist[] = {"actions", "conditions", nullptr};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|O",
const_cast<char**>(kwlist), &actions_obj,
&conditions_obj)) {
return nullptr;
}
Object::Ref<MaterialConditionNode> conditions;
if (conditions_obj != Py_None) {
DoAddConditions(conditions_obj, &conditions);
}
Material* m = self->material_->get();
if (!m) {
throw Exception("Invalid Material.", PyExcType::kNotFound);
}
std::vector<Object::Ref<MaterialAction> > actions;
if (PyTuple_Check(actions_obj)) {
Py_ssize_t size = PyTuple_GET_SIZE(actions_obj);
if (size > 0) {
// If the first item is a string, process this tuple as a single action.
if (PyUnicode_Check(PyTuple_GET_ITEM(actions_obj, 0))) {
DoAddAction(actions_obj, &actions);
} else {
// Otherwise each item is assumed to be an action.
for (Py_ssize_t i = 0; i < size; i++) {
DoAddAction(PyTuple_GET_ITEM(actions_obj, i), &actions);
}
}
}
} else {
PyErr_SetString(PyExc_AttributeError,
"expected a tuple for \"actions\" argument");
return nullptr;
}
m->AddComponent(Object::New<MaterialComponent>(conditions, actions));
Py_RETURN_NONE;
BA_PYTHON_CATCH;
}
PyMethodDef PythonClassMaterial::tp_methods[] = {
{"add_actions", (PyCFunction)AddActions, METH_VARARGS | METH_KEYWORDS,
"add_actions(actions: Tuple, conditions: Optional[Tuple] = None)\n"
" -> None\n"
"\n"
"Add one or more actions to the material, optionally with conditions.\n"
"\n"
"Conditions:\n"
"\n"
"Conditions are provided as tuples which can be combined to form boolean\n"
"logic. A single condition might look like ('condition_name', cond_arg),\n"
"or a more complex nested one might look like (('some_condition',\n"
"cond_arg), 'or', ('another_condition', cond2_arg)).\n"
"\n"
"'and', 'or', and 'xor' are available to chain together 2 conditions, as\n"
" seen above.\n"
"\n"
"Available Conditions:\n"
"\n"
"('they_have_material', material) - does the part we\'re hitting have a\n"
" given ba.Material?\n"
"\n"
"('they_dont_have_material', material) - does the part we\'re hitting\n"
" not have a given ba.Material?\n"
"\n"
"('eval_colliding') - is 'collide' true at this point in material\n"
" evaluation? (see the modify_part_collision action)\n"
"\n"
"('eval_not_colliding') - is 'collide' false at this point in material\n"
" evaluation? (see the modify_part_collision action)\n"
"\n"
"('we_are_younger_than', age) - is our part younger than 'age'\n"
" (in milliseconds)?\n"
"\n"
"('we_are_older_than', age) - is our part older than 'age'\n"
" (in milliseconds)?\n"
"\n"
"('they_are_younger_than', age) - is the part we're hitting younger than\n"
" 'age' (in milliseconds)?\n"
"\n"
"('they_are_older_than', age) - is the part we're hitting older than\n"
" 'age' (in milliseconds)?\n"
"\n"
"('they_are_same_node_as_us') - does the part we're hitting belong to\n"
" the same ba.Node as us?\n"
"\n"
"('they_are_different_node_than_us') - does the part we're hitting\n"
" belong to a different ba.Node than us?\n"
"\n"
"Actions:\n"
"\n"
"In a similar manner, actions are specified as tuples. Multiple actions\n"
"can be specified by providing a tuple of tuples.\n"
"\n"
"Available Actions:\n"
"\n"
"('call', when, callable) - calls the provided callable; 'when' can be\n"
" either 'at_connect' or 'at_disconnect'. 'at_connect' means to fire\n"
" when the two parts first come in contact; 'at_disconnect' means to\n"
" fire once they cease being in contact.\n"
"\n"
"('message', who, when, message_obj) - sends a message object; 'who' can\n"
" be either 'our_node' or 'their_node', 'when' can be 'at_connect' or\n"
" 'at_disconnect', and message_obj is the message object to send.\n"
" This has the same effect as calling the node's handlemessage()\n"
" method.\n"
"\n"
"('modify_part_collision', attr, value) - changes some characteristic\n"
" of the physical collision that will occur between our part and their\n"
" part. This change will remain in effect as long as the two parts\n"
" remain overlapping. This means if you have a part with a material\n"
" that turns 'collide' off against parts younger than 100ms, and it\n"
" touches another part that is 50ms old, it will continue to not\n"
" collide with that part until they separate, even if the 100ms\n"
" threshold is passed. Options for attr/value are: 'physical' (boolean\n"
" value; whether a *physical* response will occur at all), 'friction'\n"
" (float value; how friction-y the physical response will be),\n"
" 'collide' (boolean value; whether *any* collision will occur at all,\n"
" including non-physical stuff like callbacks), 'use_node_collide'\n"
" (boolean value; whether to honor modify_node_collision overrides for\n"
" this collision), 'stiffness' (float value, how springy the physical\n"
" response is), 'damping' (float value, how damped the physical\n"
" response is), 'bounce' (float value; how bouncy the physical response\n"
" is).\n"
"\n"
"('modify_node_collision', attr, value) - similar to\n"
" modify_part_collision, but operates at a node-level.\n"
" collision attributes set here will remain in effect as long as\n"
" *anything* from our part's node and their part's node overlap.\n"
" A key use of this functionality is to prevent new nodes from\n"
" colliding with each other if they appear overlapped;\n"
" if modify_part_collision is used, only the individual parts that\n"
" were overlapping would avoid contact, but other parts could still\n"
" contact leaving the two nodes 'tangled up'. Using\n"
" modify_node_collision ensures that the nodes must completely\n"
" separate before they can start colliding. Currently the only attr\n"
" available here is 'collide' (a boolean value).\n"
"\n"
"('sound', sound, volume) - plays a ba.Sound when a collision occurs, at\n"
" a given volume, regardless of the collision speed/etc.\n"
"\n"
"('impact_sound', sound, targetImpulse, volume) - plays a sound when a\n"
" collision occurs, based on the speed of impact. Provide a ba.Sound, a\n"
" target-impulse, and a volume.\n"
"\n"
"('skid_sound', sound, targetImpulse, volume) - plays a sound during a\n"
" collision when parts are 'scraping' against each other. Provide a\n"
" ba.Sound, a target-impulse, and a volume.\n"
"\n"
"('roll_sound', sound, targetImpulse, volume) - plays a sound during a\n"
" collision when parts are 'rolling' against each other. Provide a\n"
" ba.Sound, a target-impulse, and a volume.\n"
"\n"
"# example 1: create a material that lets us ignore\n"
"# collisions against any nodes we touch in the first\n"
"# 100 ms of our existence; handy for preventing us from\n"
"# exploding outward if we spawn on top of another object:\n"
"m = ba.Material()\n"
"m.add_actions(conditions=(('we_are_younger_than', 100),\n"
" 'or',('they_are_younger_than', 100)),\n"
" actions=('modify_node_collision', 'collide', False))\n"
"\n"
"# example 2: send a DieMessage to anything we touch, but cause\n"
"# no physical response. This should cause any ba.Actor to drop dead:\n"
"m = ba.Material()\n"
"m.add_actions(actions=(('modify_part_collision', 'physical', False),\n"
" ('message', 'their_node', 'at_connect',\n"
" ba.DieMessage())))\n"
"\n"
"# example 3: play some sounds when we're contacting the ground:\n"
"m = ba.Material()\n"
"m.add_actions(conditions=('they_have_material',\n"
" shared.footing_material),\n"
" actions=(('impact_sound', ba.getsound('metalHit'), 2, 5),\n"
" ('skid_sound', ba.getsound('metalSkid'), 2, 5)))\n"
"\n"},
{"__dir__", (PyCFunction)Dir, METH_NOARGS,
"allows inclusion of our custom attrs in standard python dir()"},
{nullptr}};
void DoAddConditions(PyObject* cond_obj,
Object::Ref<MaterialConditionNode>* c) {
assert(InGameThread());
if (PyTuple_Check(cond_obj)) {
Py_ssize_t size = PyTuple_GET_SIZE(cond_obj);
if (size < 1) {
throw Exception("Malformed arguments.", PyExcType::kValue);
}
PyObject* first = PyTuple_GET_ITEM(cond_obj, 0);
assert(first);
// If the first element is a string,
// its a leaf node; process its elements as a single statement.
if (PyUnicode_Check(first)) {
(*c) = Object::New<MaterialConditionNode>();
(*c)->opmode = MaterialConditionNode::OpMode::LEAF_NODE;
int argc;
const char* cond_str = PyUnicode_AsUTF8(first);
bool first_arg_is_material = false;
if (!strcmp(cond_str, "they_have_material")) {
argc = 1;
first_arg_is_material = true;
(*c)->cond = MaterialCondition::kDstIsMaterial;
} else if (!strcmp(cond_str, "they_dont_have_material")) {
argc = 1;
first_arg_is_material = true;
(*c)->cond = MaterialCondition::kDstNotMaterial;
} else if (!strcmp(cond_str, "eval_colliding")) {
argc = 0;
(*c)->cond = MaterialCondition::kEvalColliding;
} else if (!strcmp(cond_str, "eval_not_colliding")) {
argc = 0;
(*c)->cond = MaterialCondition::kEvalNotColliding;
} else if (!strcmp(cond_str, "we_are_younger_than")) {
argc = 1;
(*c)->cond = MaterialCondition::kSrcYoungerThan;
} else if (!strcmp(cond_str, "we_are_older_than")) {
argc = 1;
(*c)->cond = MaterialCondition::kSrcOlderThan;
} else if (!strcmp(cond_str, "they_are_younger_than")) {
argc = 1;
(*c)->cond = MaterialCondition::kDstYoungerThan;
} else if (!strcmp(cond_str, "they_are_older_than")) {
argc = 1;
(*c)->cond = MaterialCondition::kDstOlderThan;
} else if (!strcmp(cond_str, "they_are_same_node_as_us")) {
argc = 0;
(*c)->cond = MaterialCondition::kSrcDstSameNode;
} else if (!strcmp(cond_str, "they_are_different_node_than_us")) {
argc = 0;
(*c)->cond = MaterialCondition::kSrcDstDiffNode;
} else {
throw Exception(
std::string("Invalid material condition: \"") + cond_str + "\".",
PyExcType::kValue);
}
if (size != (argc + 1)) {
throw Exception(
std::string("Wrong number of arguments for condition: \"")
+ cond_str + "\".",
PyExcType::kValue);
}
if (argc > 0) {
if (first_arg_is_material) {
(*c)->val1_material =
Python::GetPyMaterial(PyTuple_GET_ITEM(cond_obj, 1));
} else {
PyObject* o = PyTuple_GET_ITEM(cond_obj, 1);
if (!PyLong_Check(o)) {
throw Exception(
std::string("Expected int for first arg of condition: \"")
+ cond_str + "\".",
PyExcType::kType);
}
(*c)->val1 = static_cast<uint32_t>(PyLong_AsLong(o));
}
}
if (argc > 1) {
PyObject* o = PyTuple_GET_ITEM(cond_obj, 2);
if (!PyLong_Check(o)) {
throw Exception(
std::string("Expected int for second arg of condition: \"")
+ cond_str + "\".",
PyExcType::kType);
}
(*c)->val1 = static_cast<uint32_t>(PyLong_AsLong(o));
}
} else if (PyTuple_Check(first)) {
// First item is a tuple - assume its a tuple of size 3+2*n
// containing tuples for odd index vals and operators for even.
if (size < 3 || (size % 2 != 1)) {
throw Exception("Malformed conditional statement.", PyExcType::kValue);
}
Object::Ref<MaterialConditionNode> c2;
Object::Ref<MaterialConditionNode> c2_prev;
for (Py_ssize_t i = 0; i < (size - 1); i += 2) {
c2 = Object::New<MaterialConditionNode>();
if (c2_prev.exists()) {
c2->left_child = c2_prev;
} else {
DoAddConditions(PyTuple_GET_ITEM(cond_obj, i), &c2->left_child);
}
DoAddConditions(PyTuple_GET_ITEM(cond_obj, i + 2), &c2->right_child);
// Pull a string from between to set up our opmode with.
std::string opmode_str =
Python::GetPyString(PyTuple_GET_ITEM(cond_obj, i + 1));
const char* opmode = opmode_str.c_str();
if (!strcmp(opmode, "&&") || !strcmp(opmode, "and")) {
c2->opmode = MaterialConditionNode::OpMode::AND_OPERATOR;
} else if (!strcmp(opmode, "||") || !strcmp(opmode, "or")) {
c2->opmode = MaterialConditionNode::OpMode::OR_OPERATOR;
} else if (!strcmp(opmode, "^") || !strcmp(opmode, "xor")) {
c2->opmode = MaterialConditionNode::OpMode::XOR_OPERATOR;
} else {
throw Exception(
std::string("Invalid conditional operator: \"") + opmode + "\".",
PyExcType::kValue);
}
c2_prev = c2;
}
// Keep our lowest level.
(*c) = c2;
}
} else {
throw Exception("Conditions argument not a tuple.", PyExcType::kType);
}
}
void DoAddAction(PyObject* actions_obj,
std::vector<Object::Ref<MaterialAction> >* actions) {
assert(InGameThread());
if (!PyTuple_Check(actions_obj)) {
throw Exception("Expected a tuple.", PyExcType::kType);
}
Py_ssize_t size = PyTuple_GET_SIZE(actions_obj);
assert(size > 0);
PyObject* obj = PyTuple_GET_ITEM(actions_obj, 0);
std::string type = Python::GetPyString(obj);
if (type == "call") {
if (size != 3) {
throw Exception("Expected 3 values for command action tuple.",
PyExcType::kValue);
}
std::string when = Python::GetPyString(PyTuple_GET_ITEM(actions_obj, 1));
bool at_disconnect;
if (when == "at_connect") {
at_disconnect = false;
} else if (when == "at_disconnect") {
at_disconnect = true;
} else {
throw Exception("Invalid command execution time: '" + when + "'.",
PyExcType::kValue);
}
PyObject* call_obj = PyTuple_GET_ITEM(actions_obj, 2);
(*actions).push_back(Object::New<MaterialAction, PythonCallMaterialAction>(
at_disconnect, call_obj));
} else if (type == "message") {
if (size < 4) {
throw Exception("Expected >= 4 values for message action tuple.",
PyExcType::kValue);
}
std::string target = Python::GetPyString(PyTuple_GET_ITEM(actions_obj, 1));
bool target_other_val;
if (target == "our_node") {
target_other_val = false;
} else if (target == "their_node") {
target_other_val = true;
} else {
throw Exception("Invalid message target: '" + target + "'.",
PyExcType::kValue);
}
std::string when = Python::GetPyString(PyTuple_GET_ITEM(actions_obj, 2));
bool at_disconnect;
if (when == "at_connect") {
at_disconnect = false;
} else if (when == "at_disconnect") {
at_disconnect = true;
} else {
throw Exception("Invalid command execution time: '" + when + "'.",
PyExcType::kValue);
}
// Pull the rest of the message.
Buffer<char> b;
PyObject* user_message_obj = nullptr;
Python::DoBuildNodeMessage(actions_obj, 3, &b, &user_message_obj);
if (user_message_obj) {
(*actions).push_back(
Object::New<MaterialAction, NodeUserMessageMaterialAction>(
target_other_val, at_disconnect, user_message_obj));
} else if (b.size() > 0) {
(*actions).push_back(
Object::New<MaterialAction, NodeMessageMaterialAction>(
target_other_val, at_disconnect, b.data(), b.size()));
}
} else if (type == "modify_node_collision") {
if (size != 3) {
throw Exception(
"Expected 3 values for modify_node_collision action tuple.",
PyExcType::kValue);
}
std::string attr = Python::GetPyString(PyTuple_GET_ITEM(actions_obj, 1));
NodeCollideAttr attr_type;
if (attr == "collide") {
attr_type = NodeCollideAttr::kCollideNode;
} else {
throw Exception("Invalid node mod attr: '" + attr + "'.",
PyExcType::kValue);
}
// Pull value.
float val = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 2));
(*actions).push_back(
Object::New<MaterialAction, NodeModMaterialAction>(attr_type, val));
} else if (type == "modify_part_collision") {
if (size != 3) {
throw Exception(
"Expected 3 values for modify_part_collision action tuple.",
PyExcType::kValue);
}
PartCollideAttr attr_type;
std::string attr = Python::GetPyString(PyTuple_GET_ITEM(actions_obj, 1));
if (attr == "physical") {
attr_type = PartCollideAttr::kPhysical;
} else if (attr == "friction") {
attr_type = PartCollideAttr::kFriction;
} else if (attr == "collide") {
attr_type = PartCollideAttr::kCollide;
} else if (attr == "use_node_collide") {
attr_type = PartCollideAttr::kUseNodeCollide;
} else if (attr == "stiffness") {
attr_type = PartCollideAttr::kStiffness;
} else if (attr == "damping") {
attr_type = PartCollideAttr::kDamping;
} else if (attr == "bounce") {
attr_type = PartCollideAttr::kBounce;
} else {
throw Exception("Invalid part mod attr: '" + attr + "'.",
PyExcType::kValue);
}
float val = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 2));
(*actions).push_back(
Object::New<MaterialAction, PartModMaterialAction>(attr_type, val));
} else if (type == "sound") {
if (size != 3) {
throw Exception("Expected 3 values for sound action tuple.",
PyExcType::kValue);
}
Sound* sound = Python::GetPySound(PyTuple_GET_ITEM(actions_obj, 1));
float volume = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 2));
(*actions).push_back(
Object::New<MaterialAction, SoundMaterialAction>(sound, volume));
} else if (type == "impact_sound") {
if (size != 4) {
throw Exception("Expected 4 values for impact_sound action tuple.",
PyExcType::kValue);
}
PyObject* sounds_obj = PyTuple_GET_ITEM(actions_obj, 1);
std::vector<Sound*> sounds;
if (PySequence_Check(sounds_obj)) {
sounds = Python::GetPySounds(sounds_obj); // Sequence of sounds.
} else {
sounds.push_back(Python::GetPySound(sounds_obj)); // Single sound.
}
if (sounds.empty()) {
throw Exception("Require at least 1 sound.", PyExcType::kValue);
}
if (Utils::HasNullMembers(sounds)) {
throw Exception("One or more invalid sound refs passed.",
PyExcType::kValue);
}
float target_impulse = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 2));
float volume = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 3));
(*actions).push_back(Object::New<MaterialAction, ImpactSoundMaterialAction>(
sounds, target_impulse, volume));
} else if (type == "skid_sound") {
if (size != 4) {
throw Exception("Expected 4 values for skid_sound action tuple.",
PyExcType::kValue);
}
Sound* sound = Python::GetPySound(PyTuple_GET_ITEM(actions_obj, 1));
float target_impulse = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 2));
float volume = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 3));
(*actions).push_back(Object::New<MaterialAction, SkidSoundMaterialAction>(
sound, target_impulse, volume));
} else if (type == "roll_sound") {
if (size != 4) {
throw Exception("Expected 4 values for roll_sound action tuple.",
PyExcType::kValue);
}
Sound* sound = Python::GetPySound(PyTuple_GET_ITEM(actions_obj, 1));
float target_impulse = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 2));
float volume = Python::GetPyFloat(PyTuple_GET_ITEM(actions_obj, 3));
(*actions).push_back(Object::New<MaterialAction, RollSoundMaterialAction>(
sound, target_impulse, volume));
} else {
throw Exception("Invalid action type: '" + type + "'.", PyExcType::kValue);
}
}
#pragma clang diagnostic pop
} // namespace ballistica
| 40.214681 | 80 | 0.634786 | Benefit-Zebra |
16b03c60f3c722000fc79ede31fa65f040176794 | 266 | cpp | C++ | hamming-distance/Solution2.cpp | marcos-sb/leetcode | 35369f5cd9e84d3339343080087e32ec1264f410 | [
"Apache-2.0"
] | 1 | 2019-10-07T15:58:39.000Z | 2019-10-07T15:58:39.000Z | hamming-distance/Solution2.cpp | marcos-sb/leetcode | 35369f5cd9e84d3339343080087e32ec1264f410 | [
"Apache-2.0"
] | null | null | null | hamming-distance/Solution2.cpp | marcos-sb/leetcode | 35369f5cd9e84d3339343080087e32ec1264f410 | [
"Apache-2.0"
] | null | null | null | class Solution2 {
public:
int hammingDistance(int x, int y) {
int count = 0;
int diff = x ^ y;
int mask = 1;
while(diff > 0) {
if(diff & mask) count++;
diff >>= 1;
}
return count;
}
};
| 17.733333 | 39 | 0.424812 | marcos-sb |
16b134c8c7f46ce0ae27fbca44c4fc748ed6d916 | 5,703 | cc | C++ | services/video_capture/public/interfaces/device_descriptor_struct_traits.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | services/video_capture/public/interfaces/device_descriptor_struct_traits.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | services/video_capture/public/interfaces/device_descriptor_struct_traits.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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 "services/video_capture/public/interfaces/device_descriptor_struct_traits.h"
namespace mojo {
// static
video_capture::mojom::VideoCaptureApi
EnumTraits<video_capture::mojom::VideoCaptureApi,
media::VideoCaptureApi>::ToMojom(media::VideoCaptureApi input) {
switch (input) {
case media::VideoCaptureApi::LINUX_V4L2_SINGLE_PLANE:
return video_capture::mojom::VideoCaptureApi::LINUX_V4L2_SINGLE_PLANE;
case media::VideoCaptureApi::WIN_MEDIA_FOUNDATION:
return video_capture::mojom::VideoCaptureApi::WIN_MEDIA_FOUNDATION;
case media::VideoCaptureApi::WIN_DIRECT_SHOW:
return video_capture::mojom::VideoCaptureApi::WIN_DIRECT_SHOW;
case media::VideoCaptureApi::MACOSX_AVFOUNDATION:
return video_capture::mojom::VideoCaptureApi::MACOSX_AVFOUNDATION;
case media::VideoCaptureApi::MACOSX_DECKLINK:
return video_capture::mojom::VideoCaptureApi::MACOSX_DECKLINK;
case media::VideoCaptureApi::ANDROID_API1:
return video_capture::mojom::VideoCaptureApi::ANDROID_API1;
case media::VideoCaptureApi::ANDROID_API2_LEGACY:
return video_capture::mojom::VideoCaptureApi::ANDROID_API2_LEGACY;
case media::VideoCaptureApi::ANDROID_API2_FULL:
return video_capture::mojom::VideoCaptureApi::ANDROID_API2_FULL;
case media::VideoCaptureApi::ANDROID_API2_LIMITED:
return video_capture::mojom::VideoCaptureApi::ANDROID_API2_LIMITED;
case media::VideoCaptureApi::ANDROID_TANGO:
return video_capture::mojom::VideoCaptureApi::ANDROID_TANGO;
case media::VideoCaptureApi::UNKNOWN:
return video_capture::mojom::VideoCaptureApi::UNKNOWN;
}
NOTREACHED();
return video_capture::mojom::VideoCaptureApi::UNKNOWN;
}
// static
bool EnumTraits<video_capture::mojom::VideoCaptureApi, media::VideoCaptureApi>::
FromMojom(video_capture::mojom::VideoCaptureApi input,
media::VideoCaptureApi* output) {
switch (input) {
case video_capture::mojom::VideoCaptureApi::LINUX_V4L2_SINGLE_PLANE:
*output = media::VideoCaptureApi::LINUX_V4L2_SINGLE_PLANE;
return true;
case video_capture::mojom::VideoCaptureApi::WIN_MEDIA_FOUNDATION:
*output = media::VideoCaptureApi::WIN_MEDIA_FOUNDATION;
return true;
case video_capture::mojom::VideoCaptureApi::WIN_DIRECT_SHOW:
*output = media::VideoCaptureApi::WIN_DIRECT_SHOW;
return true;
case video_capture::mojom::VideoCaptureApi::MACOSX_AVFOUNDATION:
*output = media::VideoCaptureApi::MACOSX_AVFOUNDATION;
return true;
case video_capture::mojom::VideoCaptureApi::MACOSX_DECKLINK:
*output = media::VideoCaptureApi::MACOSX_DECKLINK;
return true;
case video_capture::mojom::VideoCaptureApi::ANDROID_API1:
*output = media::VideoCaptureApi::ANDROID_API1;
return true;
case video_capture::mojom::VideoCaptureApi::ANDROID_API2_LEGACY:
*output = media::VideoCaptureApi::ANDROID_API2_LEGACY;
return true;
case video_capture::mojom::VideoCaptureApi::ANDROID_API2_FULL:
*output = media::VideoCaptureApi::ANDROID_API2_FULL;
return true;
case video_capture::mojom::VideoCaptureApi::ANDROID_API2_LIMITED:
*output = media::VideoCaptureApi::ANDROID_API2_LIMITED;
return true;
case video_capture::mojom::VideoCaptureApi::ANDROID_TANGO:
*output = media::VideoCaptureApi::ANDROID_TANGO;
return true;
case video_capture::mojom::VideoCaptureApi::UNKNOWN:
*output = media::VideoCaptureApi::UNKNOWN;
return true;
}
NOTREACHED();
return false;
}
// static
video_capture::mojom::VideoCaptureTransportType EnumTraits<
video_capture::mojom::VideoCaptureTransportType,
media::VideoCaptureTransportType>::ToMojom(media::VideoCaptureTransportType
input) {
switch (input) {
case media::VideoCaptureTransportType::MACOSX_USB_OR_BUILT_IN:
return video_capture::mojom::VideoCaptureTransportType::
MACOSX_USB_OR_BUILT_IN;
case media::VideoCaptureTransportType::OTHER_TRANSPORT:
return video_capture::mojom::VideoCaptureTransportType::OTHER_TRANSPORT;
}
NOTREACHED();
return video_capture::mojom::VideoCaptureTransportType::OTHER_TRANSPORT;
}
// static
bool EnumTraits<video_capture::mojom::VideoCaptureTransportType,
media::VideoCaptureTransportType>::
FromMojom(video_capture::mojom::VideoCaptureTransportType input,
media::VideoCaptureTransportType* output) {
switch (input) {
case video_capture::mojom::VideoCaptureTransportType::
MACOSX_USB_OR_BUILT_IN:
*output = media::VideoCaptureTransportType::MACOSX_USB_OR_BUILT_IN;
return true;
case video_capture::mojom::VideoCaptureTransportType::OTHER_TRANSPORT:
*output = media::VideoCaptureTransportType::OTHER_TRANSPORT;
return true;
}
NOTREACHED();
return false;
}
// static
bool StructTraits<video_capture::mojom::DeviceDescriptorDataView,
media::VideoCaptureDeviceDescriptor>::
Read(video_capture::mojom::DeviceDescriptorDataView data,
media::VideoCaptureDeviceDescriptor* output) {
if (!data.ReadDisplayName(&(output->display_name)))
return false;
if (!data.ReadDeviceId(&(output->device_id)))
return false;
if (!data.ReadModelId(&(output->model_id)))
return false;
if (!data.ReadCaptureApi(&(output->capture_api)))
return false;
if (!data.ReadTransportType(&(output->transport_type)))
return false;
return true;
}
} // namespace mojo
| 40.161972 | 85 | 0.742241 | google-ar |
16b33500d7a4b5157cfb2a9e3712eee37cb3f193 | 23,355 | cpp | C++ | src/ClusterRGB.cpp | ArcGIS/lepcc | 5cbf22fe4aaf2d35263782db1f6b8b2ca7f41b40 | [
"Apache-2.0"
] | 23 | 2018-03-15T20:14:43.000Z | 2022-01-18T15:10:02.000Z | src/ClusterRGB.cpp | ArcGIS/lepcc | 5cbf22fe4aaf2d35263782db1f6b8b2ca7f41b40 | [
"Apache-2.0"
] | 3 | 2018-09-06T23:56:27.000Z | 2021-09-10T01:06:07.000Z | src/ClusterRGB.cpp | ArcGIS/lepcc | 5cbf22fe4aaf2d35263782db1f6b8b2ca7f41b40 | [
"Apache-2.0"
] | 9 | 2018-08-28T20:36:57.000Z | 2021-11-01T06:30:55.000Z | /*
Copyright 2016 Esri
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.
A local copy of the license and additional notices are located with the
source distribution at:
http://github.com/Esri/lepcc/
Contributors: Thomas Maurer
*/
#include <algorithm>
#include <cstring>
#include <climits>
#include "ClusterRGB.h"
#include "Common.h"
#include "utl_const_array.h"
using namespace std;
using namespace lepcc;
// -------------------------------------------------------------------------- ;
ErrCode ClusterRGB::ComputeNumBytesNeededToEncode(uint32 nPts, const RGB_t* colors, int64& nBytes)
{
nBytes = -1;
if (!nPts || !colors)
return ErrCode::WrongParam;
// count the colors
int numOrigColors = 0;
m_trueColorMask.SetSize(256 * 256, 256); // 2 MB
m_trueColorMask.SetAllInvalid();
// if few enough colors for lossless coding, collect them here
vector<int> losslessColors;
// init level 6 rgb histogram, for median cut method
const int numColorSteps = 1 << 6;
const int numCubes6 = numColorSteps * numColorSteps * numColorSteps;
const int colorShift6 = 8 - 6;
m_level6Histo.resize(numCubes6); // 1 MB
memset(&m_level6Histo[0], 0, numCubes6 * sizeof(int));
const_array<RGB_t> rgbArr(colors, nPts); // safe wrapper
vector<Box> boxVec;
// first pass: count orig colors, compute rgb histograms, init bounding box
{
Box box = { 0, 0, 256, 256, 256, -1, -1, -1 };
for (uint32 i = 0; i < nPts; i++)
{
Byte r = rgbArr[i].r;
Byte g = rgbArr[i].g;
Byte b = rgbArr[i].b;
// count orig colors
int n = (r << 8) + g;
if (!m_trueColorMask.IsValid(b, n))
{
m_trueColorMask.SetValid(b, n);
numOrigColors++;
if (numOrigColors <= m_maxNumColors)
losslessColors.push_back(Compute3DArrayIndex(r, g, b, 8));
}
int m = Compute3DArrayIndex(r, g, b, 6);
m_level6Histo[m]++;
// update bounding box
int sh = colorShift6;
box.rMin = min(r >> sh, box.rMin);
box.gMin = min(g >> sh, box.gMin);
box.bMin = min(b >> sh, box.bMin);
box.rMax = max(r >> sh, box.rMax);
box.gMax = max(g >> sh, box.gMax);
box.bMax = max(b >> sh, box.bMax);
box.numPoints++;
}
box.volume = (box.rMax - box.rMin + 1) *
(box.gMax - box.gMin + 1) *
(box.bMax - box.bMin + 1);
boxVec.push_back(box);
//printf("num valid pixel = %d\n", box.numPoints);
//printf("num orig colors = %d\n", numOrigColors);
} // first pass
int headerSize = HeaderSize();
// compare to number of points and decide
if (2 * nPts <= (uint32)3 * min(numOrigColors, m_maxNumColors))
{
m_colorLookupMethod = None;
m_rgbVec.resize(nPts);
memcpy(&m_rgbVec[0], &rgbArr[0], nPts * sizeof(rgbArr[0])); // keep the colors for later encoding
nBytes = headerSize + nPts * 3; // no colormap, store the colors raw per point
return ErrCode::Ok;
}
else if (numOrigColors <= m_maxNumColors)
{
m_colorLookupMethod = Lossless;
GenerateColormapLossless(losslessColors);
if (!TurnColorsToIndexes(nPts, colors, m_colorIndexVec))
return ErrCode::Failed;
nBytes = ComputeNumBytesNeededToEncodeColorIndexes();
if (nBytes < 0)
return ErrCode::Failed;
nBytes += headerSize + numOrigColors * 3; // lossless colormap
return ErrCode::Ok;
}
else
{
m_colorLookupMethod = Array3D;
// main loop: find the most populated box and split it in 2 if possible, iterate
int index = 0;
while ((int)boxVec.size() < m_maxNumColors && index != -1)
{
if ((int)boxVec.size() < (m_maxNumColors >> 1))
index = FindNextBox(boxVec, NumPixel);
else
index = FindNextBox(boxVec, NumPixelTimesVolume);
if (index > -1)
{
Box box1, box2;
SplitBox(boxVec[index], box1, box2, m_level6Histo, numColorSteps);
boxVec[index] = box1;
boxVec.push_back(box2);
}
}
m_colorIndexLUT.resize(0);
m_colorIndexLUT.assign(numCubes6, -1); // 1 MB
int size = (int)boxVec.size();
for (int i = 0; i < size; i++)
{
const Box& box = boxVec[i];
for (int ir = box.rMin; ir <= box.rMax; ir++)
for (int ig = box.gMin; ig <= box.gMax; ig++)
for (int ib = box.bMin; ib <= box.bMax; ib++)
{
int k = Compute3DArrayIndex2(ir, ig, ib, numColorSteps);
m_colorIndexLUT[k] = i;
}
}
// resize the color map to the number of boxes found
m_colorMap.resize(size);
}
// compute the palette colors as the means over their median cut boxes
int numColors = (int)m_colorMap.size();
vector<Point3D> clusterCenters(numColors);
vector<int> counts(numColors, 0);
memset(&clusterCenters[0], 0, numColors * sizeof(Point3D));
// second pass: cluster all RGB points
for (uint32 i = 0; i < nPts; i++)
{
Byte r = rgbArr[i].r;
Byte g = rgbArr[i].g;
Byte b = rgbArr[i].b;
int k = Compute3DArrayIndex(r, g, b, 6);
int index = m_colorIndexLUT[k];
Point3D& p = clusterCenters[index];
p.x += r;
p.y += g;
p.z += b;
counts[index]++;
}
// finalize the color map
for (int i = 0; i < numColors; i++)
{
Point3D p = clusterCenters[i];
int n = counts[i];
n = max(1, n);
Byte r = ClampToByte((int)(p.x / n + 0.5));
Byte g = ClampToByte((int)(p.y / n + 0.5));
Byte b = ClampToByte((int)(p.z / n + 0.5));
m_colorMap[i] = { r, g, b, 0 };
}
if (!TurnColorsToIndexes(nPts, colors, m_colorIndexVec))
return ErrCode::Failed;
nBytes = ComputeNumBytesNeededToEncodeColorIndexes();
if (nBytes < 0)
return ErrCode::Failed;
nBytes += headerSize + m_colorMap.size() * 3; // lossy colormap
return ErrCode::Ok;
}
// -------------------------------------------------------------------------- ;
ErrCode ClusterRGB::Encode(Byte** ppByte, int64 bufferSize) const
{
if (!ppByte)
return ErrCode::WrongParam;
int headerSize = HeaderSize();
if (bufferSize <= headerSize)
return ErrCode::BufferTooSmall;
Byte* ptr = *ppByte;
Byte* ptrStart = ptr; // keep for later
TopHeader topHd;
memcpy(ptr, &topHd, sizeof(topHd));
ptr += sizeof(topHd);
Header1 hd1;
hd1.blobSize = 0; // overide later when done
hd1.numPoints = (uint32)((m_colorLookupMethod != None) ? m_colorIndexVec.size() : m_rgbVec.size());
hd1.numColorsInColormap = (m_colorLookupMethod != None) ? (uint16)m_colorMap.size() : 0;
hd1.colorLookupMethod = (Byte)m_colorLookupMethod;
hd1.colorIndexCompressionMethod = (Byte)m_colorIndexCompressionMethod;
memcpy(ptr, &hd1, sizeof(hd1));
ptr += sizeof(hd1);
if (m_colorLookupMethod == None)
{
size_t rgbSize = m_rgbVec.size() * sizeof(RGB_t);
if (bufferSize < (int64)(headerSize + rgbSize))
return ErrCode::BufferTooSmall;
memcpy(ptr, &m_rgbVec[0], rgbSize); // write out the colors per point raw, no colormap
ptr += rgbSize;
}
else
{
if (bufferSize < (int64)(headerSize + hd1.numColorsInColormap * 3))
return ErrCode::BufferTooSmall;
for (uint16 i = 0; i < hd1.numColorsInColormap; i++) // write colormap
{
memcpy(ptr, &m_colorMap[i], 3);
ptr += 3;
}
if (m_colorIndexCompressionMethod == NoCompression)
{
if (bufferSize < (int64)(headerSize + hd1.numColorsInColormap * 3 + hd1.numPoints * 1))
return ErrCode::BufferTooSmall;
memcpy(ptr, &m_colorIndexVec[0], m_colorIndexVec.size()); // write color indexes uncompressed
ptr += m_colorIndexVec.size();
}
else if (m_colorIndexCompressionMethod == AllConst)
{
}
#ifdef TryHuffmanOnColor
else if (m_colorIndexCompressionMethod == HuffmanCodec)
{
int64 bufferSizeLeft = (int64)(ptr - *ppByte);
*ppByte = ptr;
if (!m_huffman.Encode(ppByte, bufferSizeLeft, m_colorIndexVec))
return ErrCode::Failed;
ptr = *ppByte;
}
#endif
else
return ErrCode::Failed;
}
*ppByte = ptr;
// add blob size
uint32 numBytes = (uint32)(*ppByte - ptrStart);
memcpy(ptrStart + sizeof(topHd), &numBytes, sizeof(numBytes)); // overide with the real num bytes
// add check sum
topHd.checkSum = Common::ComputeChecksumFletcher32(ptrStart + sizeof(topHd), (numBytes - sizeof(topHd)));
memcpy(ptrStart, &topHd, sizeof(topHd));
return ErrCode::Ok;
}
// -------------------------------------------------------------------------- ;
ErrCode ClusterRGB::GetBlobSize(const Byte* pByte, int64 bufferSize, uint32& blobSize)
{
blobSize = 0;
if (!pByte)
return ErrCode::WrongParam;
TopHeader refHd;
Header1 hd1;
if (bufferSize < sizeof(refHd) + sizeof(hd1.blobSize))
return ErrCode::BufferTooSmall;
if (0 != memcmp(pByte, refHd.fileKey, refHd.FileKeyLength())) // file key
return ErrCode::NotClusterRGB;
// get blob size
pByte += sizeof(refHd);
int64 nBytes = 0;
memcpy(&nBytes, pByte, sizeof(nBytes));
if (nBytes < bufferSize || nBytes > UINT_MAX)
return ErrCode::Failed;
blobSize = (uint32)nBytes;
return ErrCode::Ok;
}
// -------------------------------------------------------------------------- ;
ErrCode ClusterRGB::GetNumPointsFromHeader(const Byte* pByte, int64 bufferSize, uint32& nPts)
{
nPts = 0;
TopHeader topHd;
Header1 hd1;
ErrCode errCode;
if ((errCode = ReadHeaders(pByte, bufferSize, topHd, hd1)) != ErrCode::Ok)
return errCode;
nPts = hd1.numPoints;
return ErrCode::Ok;
}
// -------------------------------------------------------------------------- ;
ErrCode ClusterRGB::Decode(const Byte** ppByte, int64 bufferSize, uint32& nPtsInOut, RGB_t* colors)
{
if (!ppByte || !*ppByte || !nPtsInOut || !colors)
return ErrCode::WrongParam;
int headerSize = HeaderSize();
if (bufferSize <= headerSize)
return ErrCode::BufferTooSmall;
const Byte* ptr = *ppByte;
const Byte* ptrStart = ptr; // keep for later
TopHeader topHd;
Header1 hd1;
ErrCode errCode;
if ((errCode = ReadHeaders(ptr, bufferSize, topHd, hd1)) != ErrCode::Ok)
return errCode;
ptr += headerSize;
if (bufferSize < hd1.blobSize) // allocated buffer is too small
return ErrCode::BufferTooSmall;
// test check sum
uint32 checkSum = Common::ComputeChecksumFletcher32(ptrStart + sizeof(topHd), hd1.blobSize - sizeof(topHd));
if (checkSum != topHd.checkSum)
return ErrCode::WrongCheckSum;
uint16 numColors = hd1.numColorsInColormap;
if (hd1.numPoints > nPtsInOut)
return ErrCode::OutArrayTooSmall;
if (numColors == 0)
{
int nBytes = hd1.numPoints * 3;
if (bufferSize < (int64)(headerSize + nBytes))
return ErrCode::BufferTooSmall;
memcpy(colors, ptr, nBytes); // read in rgb per point for numPoints
ptr += nBytes;
}
else
{
if (bufferSize < (int64)(headerSize + numColors * 3))
return ErrCode::BufferTooSmall;
m_colorMap.resize(numColors);
memset(&m_colorMap[0], 0, m_colorMap.size() * sizeof(m_colorMap[0]));
for (uint16 i = 0; i < numColors; i++) // read colormap
{
memcpy(&m_colorMap[i], ptr, 3);
ptr += 3;
}
RGB_t* dstPtr = colors;
if (hd1.colorIndexCompressionMethod == NoCompression)
{
if (bufferSize < (int64)(headerSize + numColors * 3 + hd1.numPoints * 1))
return ErrCode::BufferTooSmall;
for (uint32 i = 0; i < hd1.numPoints; i++) // read color index per point
{
Byte index = *ptr++;
memcpy(dstPtr, &m_colorMap[index], 3);
dstPtr++;
}
}
else if (hd1.colorIndexCompressionMethod == AllConst)
{
RGBA_t rgba = m_colorMap[0];
for (uint32 i = 0; i < hd1.numPoints; i++) // special case all points have same color
{
memcpy(dstPtr, &rgba, 3);
dstPtr++;
}
}
#ifdef TryHuffmanOnColor
else if (hd1.colorIndexCompressionMethod == HuffmanCodec)
{
m_colorIndexVec.resize(hd1.numPoints);
int64 bufferSizeLeft = (int64)(ptr - *ppByte);
*ppByte = ptr;
if (!m_huffman.Decode(ppByte, bufferSizeLeft, m_colorIndexVec))
return ErrCode::Failed;
ptr = *ppByte;
for (uint32 i = 0; i < hd1.numPoints; i++)
{
Byte index = m_colorIndexVec[i];
memcpy(dstPtr, &m_colorMap[index], 3);
dstPtr++;
}
}
#endif
else
return ErrCode::Failed;
}
*ppByte = ptr;
nPtsInOut = hd1.numPoints; // num points really decoded
int64 nBytesRead = (int64)(*ppByte - ptrStart);
if (nBytesRead != hd1.blobSize || nBytesRead > bufferSize)
return ErrCode::Failed;
return ErrCode::Ok;
}
// -------------------------------------------------------------------------- ;
void ClusterRGB::Clear()
{
m_colorMap.clear();
m_trueColorMask.Clear();
m_level6Histo.clear();
m_colorIndexLUT.clear();
m_rgbVec.clear();
m_colorIndexVec.clear();
m_mapRGBValueToColormapIndex.clear();
#ifdef TryHuffmanOnColor
m_huffman.Clear();
#endif
}
// -------------------------------------------------------------------------- ;
// -------------------------------------------------------------------------- ;
int ClusterRGB::HeaderSize()
{
return (int)(sizeof(TopHeader) + sizeof(Header1));
}
// -------------------------------------------------------------------------- ;
void ClusterRGB::GenerateColormapLossless(const vector<int>& losslessColors)
{
int numColors = (int)losslessColors.size();
//assert(numColors <= m_maxNumColors);
m_colorMap.resize(numColors);
m_mapRGBValueToColormapIndex.clear();
for (int i = 0; i < numColors; i++)
{
int n = losslessColors[i];
Byte r = (n >> 16) & 255;
Byte g = (n >> 8) & 255;
Byte b = n & 255;
m_colorMap[i] = { r, g, b, 0 };
m_mapRGBValueToColormapIndex[n] = i;
}
}
// -------------------------------------------------------------------------- ;
int ClusterRGB::FindNextBox(const vector<Box>& boxVec, enum FindNextBoxMethod method) const
{
double maxPixVol = -1;
int index = -1;
int size = (int)boxVec.size();
for (int i = 0; i < size; i++)
{
const Box& box = boxVec[i];
double vol = (method == NumPixelTimesVolume) ? box.volume : 1;
if ((box.rMax > box.rMin ||
box.gMax > box.gMin ||
box.bMax > box.bMin) && box.numPoints * vol > maxPixVol)
{
maxPixVol = box.numPoints * vol;
index = i;
}
}
return index;
}
// -------------------------------------------------------------------------- ;
void ClusterRGB::ProjectHistogram(const vector<int>& histogram,
int numColorSteps,
const Box& box,
enum ColorAxis axis,
vector<int>& oneAxisHistogram) const
{
oneAxisHistogram.resize(0);
oneAxisHistogram.assign(numColorSteps, 0);
if (axis == RED)
{
for (int ir = box.rMin; ir <= box.rMax; ir++)
{
int cnt = 0;
for (int ig = box.gMin; ig <= box.gMax; ig++)
{
int k = Compute3DArrayIndex2(ir, ig, box.bMin, numColorSteps);
const int* ptr = &histogram[k];
for (int ib = box.bMin; ib <= box.bMax; ib++)
cnt += *ptr++;
}
oneAxisHistogram[ir] = cnt;
}
}
else if (axis == GREEN)
{
for (int ig = box.gMin; ig <= box.gMax; ig++)
{
int cnt = 0;
for (int ir = box.rMin; ir <= box.rMax; ir++)
{
int k = Compute3DArrayIndex2(ir, ig, box.bMin, numColorSteps);
const int* ptr = &histogram[k];
for (int ib = box.bMin; ib <= box.bMax; ib++)
cnt += *ptr++;
}
oneAxisHistogram[ig] = cnt;
}
}
else if (axis == BLUE)
{
for (int ib = box.bMin; ib <= box.bMax; ib++)
{
int cnt = 0;
for (int ir = box.rMin; ir <= box.rMax; ir++)
{
int k = Compute3DArrayIndex2(ir, box.gMin, ib, numColorSteps);
const int* ptr = &histogram[k];
for (int ig = box.gMin; ig <= box.gMax; ig++)
{
cnt += *ptr;
ptr += numColorSteps;
}
}
oneAxisHistogram[ib] = cnt;
}
}
}
// -------------------------------------------------------------------------- ;
// See which axis is the largest, do a histogram along that axis.
// Split at median point. Shrink both new boxes to fit points and return.
void ClusterRGB::SplitBox(const Box& box0, Box& box1, Box& box2,
const vector<int>& histogram,
int numColorSteps) const
{
vector<int> oneAxisHisto;
int dr = box0.rMax - box0.rMin;
int dg = box0.gMax - box0.gMin;
int db = box0.bMax - box0.bMin;
int first, last;
if (dr >= dg && dr >= db) // split along red axis
{
ProjectHistogram(histogram, numColorSteps, box0, RED, oneAxisHisto);
first = box0.rMin;
last = box0.rMax;
}
else if (dg >= db) // split along green axis
{
ProjectHistogram(histogram, numColorSteps, box0, GREEN, oneAxisHisto);
first = box0.gMin;
last = box0.gMax;
}
else // split along blue axis
{
ProjectHistogram(histogram, numColorSteps, box0, BLUE, oneAxisHisto);
first = box0.bMin;
last = box0.bMax;
}
// the famous median cut
int halfNumPixel = box0.numPoints / 2;
int sum = 0;
int median = first;
while (sum < halfNumPixel)
sum += oneAxisHisto[median++];
// clamp median to avoid empty box
median = max(first + 1, min(median, last));
int sum1 = 0;
for (int i = first; i < median; i++)
sum1 += oneAxisHisto[i];
int sum2 = 0;
for (int i = median; i < numColorSteps; i++)
sum2 += oneAxisHisto[i];
box1 = box0;
box2 = box0;
//assert(sum1 > 0);
//assert(sum2 > 0);
box1.numPoints = sum1;
box2.numPoints = sum2;
if (dr >= dg && dr >= db)
{
box1.rMax = median - 1;
box2.rMin = median;
}
else if (dg >= db)
{
box1.gMax = median - 1;
box2.gMin = median;
}
else
{
box1.bMax = median - 1;
box2.bMin = median;
}
ShrinkBox(box1, histogram, numColorSteps);
ShrinkBox(box2, histogram, numColorSteps);
}
// -------------------------------------------------------------------------- ;
void ClusterRGB::ShrinkBox(Box& box, const vector<int>& histogram, int numColorSteps) const
{
vector<int> oneAxisHisto;
if (box.rMax > box.rMin)
{
ProjectHistogram(histogram, numColorSteps, box, RED, oneAxisHisto);
while (oneAxisHisto[box.rMin] == 0) box.rMin++;
while (oneAxisHisto[box.rMax] == 0) box.rMax--;
}
if (box.gMax > box.gMin)
{
ProjectHistogram(histogram, numColorSteps, box, GREEN, oneAxisHisto);
while (oneAxisHisto[box.gMin] == 0) box.gMin++;
while (oneAxisHisto[box.gMax] == 0) box.gMax--;
}
if (box.bMax > box.bMin)
{
ProjectHistogram(histogram, numColorSteps, box, BLUE, oneAxisHisto);
while (oneAxisHisto[box.bMin] == 0) box.bMin++;
while (oneAxisHisto[box.bMax] == 0) box.bMax--;
}
box.volume = (box.rMax - box.rMin + 1) *
(box.gMax - box.gMin + 1) *
(box.bMax - box.bMin + 1);
}
// -------------------------------------------------------------------------- ;
bool ClusterRGB::TurnColorsToIndexes(uint32 nPts, const RGB_t* colors, vector<Byte>& colorIndexVec) const
{
if (!nPts || !colors)
return false;
if (m_colorLookupMethod != Array3D && m_colorLookupMethod != Lossless)
return false;
colorIndexVec.resize(nPts);
const bool useLUT = (m_colorLookupMethod == Array3D);
const int shift = useLUT ? 6 : 8;
const RGB_t* p = colors;
for (uint32 i = 0; i < nPts; i++)
{
int k = Compute3DArrayIndex(p->r, p->g, p->b, shift);
p++;
int index = useLUT ? m_colorIndexLUT[k] : m_mapRGBValueToColormapIndex.find(k)->second;
if (index >= 256) // for > 256 colors in colormap change the currently fixed byte array to bit stuffed array
return false;
colorIndexVec[i] = (Byte)index;
}
return true;
}
// -------------------------------------------------------------------------- ;
int64 ClusterRGB::ComputeNumBytesNeededToEncodeColorIndexes()
{
int numPoints = (int)m_colorIndexVec.size();
if (numPoints == 0)
return -1;
vector<int> histoVec;
int numNonZeroBins = 0;
ComputeHistoOnColorIndexes(m_colorIndexVec, histoVec, numNonZeroBins);
m_colorIndexCompressionMethod = AllConst;
int64 nBytes = 0; // if all indexes are the same
if (numNonZeroBins > 1)
{
m_colorIndexCompressionMethod = HuffmanCodec;
#ifdef TryHuffmanOnColor
nBytes = m_huffman.ComputeNumBytesNeededToEncode(histoVec); // try Huffman on indexes
#endif
if (nBytes <= 0 || nBytes >= numPoints * 1)
{
m_colorIndexCompressionMethod = NoCompression;
nBytes = numPoints * 1;
}
}
return nBytes;
}
// -------------------------------------------------------------------------- ;
void ClusterRGB::ComputeHistoOnColorIndexes(const vector<Byte>& colorIndexVec,
vector<int>& histoVec, int& numNonZeroBins) const
{
histoVec.resize(256);
memset(&histoVec[0], 0, 256);
numNonZeroBins = 0;
int len = (int)colorIndexVec.size();
for (int i = 0; i < len; i++)
{
int index = colorIndexVec[i];
numNonZeroBins += (histoVec[index] == 0) ? 1 : 0;
histoVec[index]++;
}
}
// -------------------------------------------------------------------------- ;
ErrCode ClusterRGB::ReadHeaders(const Byte* pByte, int64 bufferSize, TopHeader& topHd, Header1& hd1)
{
if (!pByte)
return ErrCode::WrongParam;
if (bufferSize <= HeaderSize())
return ErrCode::BufferTooSmall;
TopHeader refHd;
if (0 != memcmp(pByte, refHd.fileKey, refHd.FileKeyLength())) // file key
return ErrCode::NotClusterRGB;
memcpy(&topHd, pByte, sizeof(topHd));
pByte += sizeof(topHd);
if (topHd.version > kCurrVersion ) // this reader is outdated
return ErrCode::WrongVersion;
memcpy(&hd1, pByte, sizeof(hd1));
return ErrCode::Ok;
}
// -------------------------------------------------------------------------- ;
| 28.037215 | 116 | 0.56352 | ArcGIS |
16b57a15a8897b655aa2d8b37f92ea3b7bbf4cf3 | 5,047 | cpp | C++ | code/wxWidgets/src/mac/classic/metafile.cpp | Bloodknight/NeuTorsion | a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea | [
"MIT"
] | 38 | 2016-02-20T02:46:28.000Z | 2021-11-17T11:39:57.000Z | code/wxWidgets/src/mac/classic/metafile.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 17 | 2016-02-20T02:19:55.000Z | 2021-02-08T15:15:17.000Z | code/wxWidgets/src/mac/classic/metafile.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 46 | 2016-02-20T02:47:33.000Z | 2021-01-31T15:46:05.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: metafile.cpp
// Purpose: wxMetaFile, wxMetaFileDC etc. These classes are optional.
// Author: Stefan Csomor
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id: metafile.cpp,v 1.4 2005/07/28 22:08:23 VZ Exp $
// Copyright: (c) Stefan Csomor
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "metafile.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/setup.h"
#endif
#if wxUSE_METAFILE
#ifndef WX_PRECOMP
#include "wx/utils.h"
#include "wx/app.h"
#endif
#include "wx/metafile.h"
#include "wx/clipbrd.h"
#include "wx/mac/private.h"
#include <stdio.h>
#include <string.h>
extern bool wxClipboardIsOpen;
IMPLEMENT_DYNAMIC_CLASS(wxMetafile, wxObject)
IMPLEMENT_ABSTRACT_CLASS(wxMetafileDC, wxDC)
/*
* Metafiles
* Currently, the only purpose for making a metafile is to put
* it on the clipboard.
*/
wxMetafileRefData::wxMetafileRefData(void)
{
m_metafile = 0;
}
wxMetafileRefData::~wxMetafileRefData(void)
{
if (m_metafile)
{
KillPicture( (PicHandle) m_metafile ) ;
m_metafile = 0;
}
}
wxMetaFile::wxMetaFile(const wxString& file)
{
m_refData = new wxMetafileRefData;
M_METAFILEDATA->m_metafile = 0;
wxASSERT_MSG( file.IsEmpty() , wxT("no file based metafile support yet") ) ;
/*
if (!file.IsNull() && (file.Cmp("") == 0))
M_METAFILEDATA->m_metafile = (WXHANDLE) GetMetaFile(file);
*/
}
wxMetaFile::~wxMetaFile()
{
}
bool wxMetaFile::SetClipboard(int width, int height)
{
#if wxUSE_DRAG_AND_DROP
//TODO finishi this port , we need the data obj first
if (!m_refData)
return FALSE;
bool alreadyOpen=wxTheClipboard->IsOpened() ;
if (!alreadyOpen)
{
wxTheClipboard->Open();
wxTheClipboard->Clear();
}
wxDataObject *data =
new wxMetafileDataObject( *this) ;
bool success = wxTheClipboard->SetData(data);
if (!alreadyOpen)
wxTheClipboard->Close();
return (bool) success;
#endif
return TRUE ;
}
void wxMetafile::SetHMETAFILE(WXHMETAFILE mf)
{
if (!m_refData)
m_refData = new wxMetafileRefData;
if ( M_METAFILEDATA->m_metafile )
KillPicture( (PicHandle) M_METAFILEDATA->m_metafile ) ;
M_METAFILEDATA->m_metafile = mf;
}
bool wxMetaFile::Play(wxDC *dc)
{
if (!m_refData)
return FALSE;
if (!dc->Ok() )
return FALSE;
{
wxMacPortSetter helper( dc ) ;
PicHandle pict = (PicHandle) GetHMETAFILE() ;
DrawPicture( pict , &(**pict).picFrame ) ;
}
return TRUE;
}
wxSize wxMetaFile::GetSize() const
{
wxSize size = wxDefaultSize ;
if ( Ok() )
{
PicHandle pict = (PicHandle) GetHMETAFILE() ;
Rect &r = (**pict).picFrame ;
size.x = r.right - r.left ;
size.y = r.bottom - r.top ;
}
return size;
}
/*
* Metafile device context
*
*/
// New constructor that takes origin and extent. If you use this, don't
// give origin/extent arguments to wxMakeMetaFilePlaceable.
wxMetaFileDC::wxMetaFileDC(const wxString& filename ,
int width , int height ,
const wxString& WXUNUSED(description) )
{
wxASSERT_MSG( width == 0 || height == 0 , _T("no arbitration of metafilesize supported") ) ;
wxASSERT_MSG( filename.IsEmpty() , _T("no file based metafile support yet")) ;
m_metaFile = new wxMetaFile(filename) ;
Rect r={0,0,height,width} ;
RectRgn( (RgnHandle) m_macBoundaryClipRgn , &r ) ;
CopyRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ;
m_metaFile->SetHMETAFILE( OpenPicture( &r ) ) ;
::GetPort( (GrafPtr*) &m_macPort ) ;
m_ok = TRUE ;
SetMapMode(wxMM_TEXT);
}
wxMetaFileDC::~wxMetaFileDC()
{
}
void wxMetaFileDC::DoGetSize(int *width, int *height) const
{
wxCHECK_RET( m_metaFile , _T("GetSize() doesn't work without a metafile") );
wxSize sz = m_metaFile->GetSize() ;
if (width) (*width) = sz.x;
if (height) (*height) = sz.y;
}
wxMetaFile *wxMetaFileDC::Close()
{
ClosePicture() ;
return m_metaFile;
}
#if wxUSE_DATAOBJ
size_t wxMetafileDataObject::GetDataSize() const
{
return GetHandleSize( (Handle) (*((wxMetafile*)&m_metafile)).GetHMETAFILE() ) ;
}
bool wxMetafileDataObject::GetDataHere(void *buf) const
{
memcpy( buf , (*(PicHandle)(*((wxMetafile*)&m_metafile)).GetHMETAFILE()) ,
GetHandleSize( (Handle) (*((wxMetafile*)&m_metafile)).GetHMETAFILE() ) ) ;
return true ;
}
bool wxMetafileDataObject::SetData(size_t len, const void *buf)
{
Handle handle = NewHandle( len ) ;
SetHandleSize( handle , len ) ;
memcpy( *handle , buf , len ) ;
m_metafile.SetHMETAFILE( handle ) ;
return true ;
}
#endif
#endif
| 23.151376 | 96 | 0.626907 | Bloodknight |
16b5f2b5511dc3654c63a913753b1c2314fc2545 | 6,636 | cc | C++ | ch16/generic_programing/copy.cc | leschus/cpp_primer_plus_6th | 1d0ca7e22d41e5039dd08befd451c2c339e854f1 | [
"MIT"
] | 1 | 2022-03-04T08:34:18.000Z | 2022-03-04T08:34:18.000Z | ch16/generic_programing/copy.cc | leschus/cpp_primer_plus_6th | 1d0ca7e22d41e5039dd08befd451c2c339e854f1 | [
"MIT"
] | null | null | null | ch16/generic_programing/copy.cc | leschus/cpp_primer_plus_6th | 1d0ca7e22d41e5039dd08befd451c2c339e854f1 | [
"MIT"
] | null | null | null | #include <iterator> // 提供多种迭代器模板: ostream_iterator, istream_iterator,
// reverse_iterator, back_insert_iterator,
// front_insert_iterator, insert_iterator
#include <algorithm> // 提供了copy()函数
#include <iostream>
#include <vector>
#include <list>
using std::copy;
using std::cout;
using std::endl;
using std::cin;
using std::vector;
using std::ostream_iterator;
using std::istream_iterator;
using std::reverse_iterator;
using std::back_insert_iterator;
using std::for_each;
using std::list;
using std::front_insert_iterator;
using std::insert_iterator;
void output(const int n) { cout << n << " "; }
int main() {
cout << "### Testing basic usage of copy().\n";
vector<int> vec = {1, 2, 3, 4, 5, 6 ,7 ,8}; // 使用列表初始化
int ints[4] = {4, 3, 2, 1};
copy(ints, ints + 4, vec.begin()); // 用ints内的元素替换vec开头的内容
// copy()前两个参数指定要复制的内容(由迭代器类型指定)
// copy()的第三个参数指明要将复制内容的第一个元素放到什么位置(由迭代器类型指定)
for (int x: vec) { // 使用基于范围的for循环
cout << x << " ";
} // 预期输出: 4 3 2 1 5 6 7 8
cout << endl;
cout << "### Testing ostream_iterator used in copy().\n";
// 创建一个ostream_iterator迭代器, 并使用copy()来完成向屏幕输出字符的工作
// 第一个模板参数指明被发送给输出流的数据类型(double)
// 第二个模板参数指明输出流使用的字符类型(char)
// 构造函数的第一个参数指定使用的输出流(cout)
// 构造函数的第二个参数指定输出流中每个数据项之间的分隔符(" ")
ostream_iterator<double, char> out_iter(cout, " ");
vector<double> vec2 = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6};
copy(vec2.begin(), vec2.end(), out_iter);
cout << endl;
// 另一种在copy()中使用ostream_iterator的方法: 使用匿名ostream_iterator
copy(vec2.begin(), vec2.end(), ostream_iterator<double, char>(cout, " "));
cout << endl;
cout << "### Testing istream_iterator used in copy().\n";
// 创建一个istream_iterator, 并使用copy()来完成从键盘读取字符的工作
// 第一个模板参数指明要读取的数据类型(int)
// 第二个模板参数指明输入流使用的字符类型(char)
// 构造函数接收的单一参数指明使用的输入流(cin)
// 省略构造函数的参数表示输入失败, 可以用于标识输入的结束(碰到文件尾/类型不匹配/其他故障)
/* {
istream_iterator<int, char> in_iter(cin);
// istream_iterator<int, char> in_iter_end();
// 上述语句, 编译器没有将in_iter_end识别为一个istream_iterator迭代器实例,
// 难道说, istream_iterator的无参构造函数只是一种特殊标记, 并不能用来创建一个具体的
// istream_iterator实例?
// 由此导致地, copy()的第二个参数也不能设置为in_iter_end, 而只能显式地使用
// istream_iterator<int, char>()的形式
vector<int> vec3(5); // 创建一个容量为10的空向量
cout << "Enter integers to initialize vec3: ";
// copy(in_iter, in_iter_end, vec.begin()); // 出错
copy(in_iter, istream_iterator<int, char>(), vec3.begin());
for (int x: vec3) cout << x << " ";
cout << endl;
} */
// 测试表明, 使用预先创建istream_iterator实例再将其作为copy()的参数的方式来
// 读取输入, 程序会在创建完in_iter实例后就进入等待输入状态, 而不是预想的那样: 在调用
// copy()函数时才等待用户输入.
// 为避免出现这种情况, 应该尽量避免预先创建istream_iterator实例, 而是在调用copy()
// 时再临时创建.
vector<int> vec3(5); // 创建一个容量为10的空向量
cout << "Enter integers to initialize vec3: ";
copy(istream_iterator<int, char>(cin), istream_iterator<int, char>(),
vec3.begin());
// 另外需要注意的, ostream_iterator和istream_iterator并不会扩展目标容器的容量,
// 因此, 如果写入数据后导致目标容器容量超限, 将会引发运行错误
// 例如, 这里vec3容量为5, 如果istream_iterator通过cin读取了6个整数, 就会导致程序崩溃.
for (int x: vec3) cout << x << " ";
cout << endl;
cout << "### Testing reverse_iterator used in copy().\n";
// 使用reverse_iterator反向迭代器来倒序输出向量中的元素
// 怎么创建一个用于vector<int>的reverse_iterator迭代器实例?
vector<int> vec4 = {1, 3, 5, 7, 9};
// reverse_iterator<vector<int> > ri(vec4); // 这样? ==> 不行, 编译不通过
vector<int>::reverse_iterator ri2; // 还是这样? ==> OK
// for (ri2 = vec4.end(); ri2 != vec4.begin(); ri2++) {
// cout << *ri2 << " ";
// } // 由于vec4.end()返回vector<int>::iterator类型, 与ri2类型不匹配,
//导致上面编译出错. 应该使用rbegin()和rend()成员
for (ri2 = vec4.rbegin(); ri2 != vec4.rend(); ri2++) {
cout << *ri2 << " ";
}
cout << endl;
// 使用copy()和ostream_iterator迭代器, 可以不需要显式创建reverse_iterator迭代器就
// 完成将向量内容逆序输出至屏幕的工作
ostream_iterator<int, char> out_iter2(cout, " ");
copy(vec4.rbegin(), vec4.rend(), out_iter2);
cout << endl;
// 前述的例子中, 如果copy()的目标容器的容量不够用来存储其接收到的数据, 将会引发运行错误.
// 通过使用插入迭代器, 可以使得目标容器自动调整容量以容纳新加入的数据.
// 有三种插入迭代器:
// back_insert_iterator将新数据插入到容器尾部(最后一个元素之后)
// front_insert_iterator将新数据插入到容器头部(第一个元素之前)
// insert_iterator将新数据插入到容器指定元素之前
cout << "### Testing back_insert_iterator used in copy().\n";
// 使用限制: back_insert_iterator要求它处理的容器有一个push_back()方法, 即该容器
// 应当允许在尾部进行快速插入. vector类符合要求.
int ints2[5] = {2, 4, 6, 8, 10};
vector<int> vec5;
// 创建一个具名的back_insert_iterator实例并在copy()中使用
back_insert_iterator<vector<int> > back_iter(vec5);
copy(ints2, ints2 + 2, back_iter);
// 使用for_each搭配output()输出向量元素
for_each(vec5.begin(), vec5.end(), output);
cout << endl;
// 使用匿名的back_insert_iterator实例并在copy()中使用
copy(ints2 + 2, ints2 + 5, back_insert_iterator<vector<int> >(vec5));
for_each(vec5.begin(), vec5.end(), output);
cout << endl;
cout << "### Testing front_insert_iterator used in copy().\n";
// 使用限制: front_insert_iterator要求它处理的容器有一个push_front()方法, 即该容器
// 应当允许在头部进行快速插入. vector类不满足该要求, list类满足.
// front_insert_iterator执行插入时类似于链表的头插法.
list<int> l1;
// 使用具名的front_insert_iterator实例
front_insert_iterator<list<int> > front_iter(l1);
copy(ints2, ints2 + 2, front_iter);
for (int x: l1) { cout << x << " "; } // 使用基于范围的for循环输出l1内容
cout << endl;
// 使用匿名的front_insert_iterator实例
copy(ints2 + 2, ints2 + 5, front_insert_iterator<list<int> >(l1));
for (int x: l1) { cout << x << " "; }
cout << endl;
cout << "### Testing insert_iterator used in copy().\n";
// 注: insert_iterator没有像前两者那样的使用限制. 在创建insert_iterator实例时,
// 需要用构造函数的第二个参数指示插入位置.
vector<int> vec6 = {100, 200, 300, 400, 500};
// 使用具名的insert_iterator实例
insert_iterator<vector<int> > ins_iter(vec6, vec6.begin() + 2);
copy(ints2, ints2 + 2, ins_iter);
for_each(vec6.begin(), vec6.end(), output);
cout << endl;
// 使用匿名的insert_iterator实例
copy(ints2 + 2, ints2 + 5,
insert_iterator<vector<int> >(vec6, vec6.begin() + 2));
for_each(vec6.begin(), vec6.end(), output);
cout << endl;
// 另: 注意比较front_insert_iterator<A>(a)和insert_iterator<A>(a, a.begin())的
// 的区别. 在copy()中使用它们时, 前者类似于头插法, 目标容器中的元素顺序将与插入序列的顺序
// 相反, 而后者的效果则是目标容器中的元素顺序和插入序列的顺序相同.
}
/*
测试输出:
### Testing basic usage of copy().
4 3 2 1 5 6 7 8
### Testing ostream_iterator used in copy().
1.1 2.2 3.3 4.4 5.5 6.6
1.1 2.2 3.3 4.4 5.5 6.6
### Testing istream_iterator used in copy().
Enter integers to initialize vec3: 1 2 3 ^Z
1 2 3 0 0
### Testing reverse_iterator used in copy().
9 7 5 3 1
9 7 5 3 1
### Testing back_insert_iterator used in copy().
2 4
2 4 6 8 10
### Testing front_insert_iterator used in copy().
4 2
10 8 6 4 2
### Testing insert_iterator used in copy().
100 200 2 4 300 400 500
100 200 6 8 10 2 4 300 400 500
*/ | 35.486631 | 76 | 0.673297 | leschus |
16ba4692823cbbf7a6af51d11079ba6959c5bd4b | 1,165 | cpp | C++ | Core/Src/userInterface.cpp | xlord13/vescUserInterface | ff26bc1245ec35cb545042fe01ce3111c92ef80f | [
"MIT"
] | null | null | null | Core/Src/userInterface.cpp | xlord13/vescUserInterface | ff26bc1245ec35cb545042fe01ce3111c92ef80f | [
"MIT"
] | null | null | null | Core/Src/userInterface.cpp | xlord13/vescUserInterface | ff26bc1245ec35cb545042fe01ce3111c92ef80f | [
"MIT"
] | null | null | null | #include <userInterface.h>
#include <stdio.h>
#include <gui/common/FrontendApplication.hpp>
#include <touchgfx/hal/OSWrappers.hpp>
#ifdef __cplusplus
extern "C" {
#endif
int ui_initialize(void)
{
return 0;
}
void ui_print_esc_values(mc_values *val)
{
// printf("Input voltage: %.2f V\r\n", val->v_in);
// printf("Temp: %.2f degC\r\n", val->temp_mos);
// printf("Current motor: %.2f A\r\n", val->current_motor);
// printf("Current in: %.2f A\r\n", val->current_in);
// printf("RPM: %.1f RPM\r\n", val->rpm);
// printf("Duty cycle: %.1f %%\r\n", val->duty_now * 100.0);
// printf("Ah Drawn: %.4f Ah\r\n", val->amp_hours);
// printf("Ah Regen: %.4f Ah\r\n", val->amp_hours_charged);
// printf("Wh Drawn: %.4f Wh\r\n", val->watt_hours);
// printf("Wh Regen: %.4f Wh\r\n", val->watt_hours_charged);
// printf("Tacho: %i counts\r\n", val->tachometer);
// printf("Tacho ABS: %i counts\r\n", val->tachometer_abs);
// printf("Fault Code: %s\r\n", bldc_interface_fault_to_string(val->fault_code));
}
void signal_vsync(void)
{
touchgfx::OSWrappers::signalVSync();
}
#ifdef __cplusplus
}
#endif
| 28.414634 | 85 | 0.623176 | xlord13 |
16bf04bfeeb15804e59f194e27095c8ba412f58d | 798 | cpp | C++ | 1.5/1.5/Source.cpp | albusshin/CTCI | 0794c9f78cc881a60daf883ba2caa5d82bb8833d | [
"CC0-1.0"
] | 2 | 2015-03-25T09:33:38.000Z | 2016-05-23T06:57:31.000Z | 1.5/1.5/Source.cpp | albusshin/CTCI | 0794c9f78cc881a60daf883ba2caa5d82bb8833d | [
"CC0-1.0"
] | null | null | null | 1.5/1.5/Source.cpp | albusshin/CTCI | 0794c9f78cc881a60daf883ba2caa5d82bb8833d | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
void compressStr(char *str) {
int len = strlen(str);
if (len == 0) return;
char prev = str[0], now = prev;
int count = 1;
int i = 1;
stringstream ss;
while ((now = str[i++]) != NULL) {
if (now == prev) count++;
else {
ss << prev << count;
count = 1;
}
prev = now;
}
ss << prev << count;
/* Find the length of stringstream */
ss.seekp(0, ios::end);
stringstream::pos_type newLen = ss.tellp();
if (len <= newLen) return;
else ss >> str;
}
void test(char *str) {
cout << str << " ";
compressStr(str);
cout << str << endl;
}
int main() {
char* str1 = new char[100];
strcpy(str1, "aabcccccaaa");
test(str1);
strcpy(str1, "abcdefg");
test(str1);
strcpy(str1, "abbbccdd");
test(str1);
} | 18.55814 | 44 | 0.596491 | albusshin |
16bf682a8fd632322155badfd9a624fe0545db34 | 3,407 | cpp | C++ | third_party/CppADCodeGen/test/cppad/cg/patterns/cross_iteration.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppADCodeGen/test/cppad/cg/patterns/cross_iteration.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppADCodeGen/test/cppad/cg/patterns/cross_iteration.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | /* --------------------------------------------------------------------------
* CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation:
* Copyright (C) 2013 Ciengis
*
* CppADCodeGen is distributed under multiple licenses:
*
* - Eclipse Public License Version 1.0 (EPL1), and
* - GNU General Public License Version 3 (GPL3).
*
* EPL1 terms and conditions can be found in the file "epl-v10.txt", while
* terms and conditions for the GPL3 can be found in the file "gpl3.txt".
* ----------------------------------------------------------------------------
* Author: Joao Leal
*/
#include "CppADCGPatternTest.hpp"
using Base = double;
using CGD = CppAD::cg::CG<Base>;
using ADCGD = CppAD::AD<CGD>;
using namespace CppAD;
using namespace CppAD::cg;
/**
* @test Model with 2 equations which share indexed temporary variables, but
* also across iterations
*/
std::vector<ADCGD> modelCrossIteration1(const std::vector<ADCGD>& x, size_t repeat) {
size_t m = 2;
size_t n = 2;
size_t m2 = repeat * m;
// dependent variable vector
std::vector<ADCGD> y(m2);
ADCGD tmp1 = cos(x[0]);
ADCGD aux, aux1;
for (size_t i = 0; i < repeat; i++) {
if (i == 0) {
y[i * m] = 1; // dep 0
aux = x[i * n] * 2.5;
} else {
y[i * m] = aux; // dep 2 4 6...
}
aux1 = x[i * n] * 2.5;
y[i * m + 1] = tmp1 * aux; // dep 1 3 5 ...
aux = aux1;
}
return y;
}
TEST_F(CppADCGPatternTest, modelCrossIteration1) {
size_t m = 2;
size_t n = 2;
size_t repeat = 6;
std::vector<std::vector<std::set<size_t> > > loops(1);
loops[0].resize(2);
for (size_t i = 0; i < repeat; i++) {
if (i != 0)
loops[0][0].insert(i * m);
loops[0][1].insert(i * m + 1);
}
setModel(modelCrossIteration1);
testPatternDetection(m, n, repeat, loops);
testLibCreation("modelCrossIteration1", m, n, repeat);
}
/**
* @test Model with 2 equations which share indexed temporary variables, but
* also across iterations
*/
std::vector<ADCGD> modelCrossIteration2(const std::vector<ADCGD>& x, size_t repeat) {
size_t m = 2;
size_t n = 2;
size_t m2 = repeat * m;
// dependent variable vector
std::vector<ADCGD> y(m2);
ADCGD tmp1 = cos(x[0]);
ADCGD aux, aux1;
for (size_t i = 0; i < repeat; i++) {
if (i == 0) {
y[i * m] = 1; // dep 0
aux = x[i * n] * 2.5;
} else {
y[i * m] = x[i * n] * tmp1 * aux; // dep 2 4 6...
}
aux1 = x[i * n] * 2.5;
y[i * m + 1] = x[i * n + 1] * tmp1 * (aux1 - aux); // dep 1 3 5 ...
aux = aux1;
}
return y;
}
TEST_F(CppADCGPatternTest, modelCrossIteration2) {
size_t m = 2;
size_t n = 2;
size_t repeat = 6;
std::vector<std::vector<std::set<size_t> > > loops(1);
loops[0].resize(2);
for (size_t i = 0; i < repeat; i++) {
if (i != 0)
loops[0][0].insert(i * m);
loops[0][1].insert(i * m + 1);
}
//customJacSparsity_.resize(m * repeat);
//customJacSparsity_[1].insert(0);
//customHessSparsity_.resize(n * repeat);
//customHessSparsity_[0].insert(0);
setModel(modelCrossIteration2);
testPatternDetection(m, n, repeat, loops);
testLibCreation("modelCrossIteration2", m, n, repeat);
}
| 26.617188 | 85 | 0.533314 | eric-heiden |
16c1362b29ffb0307af36b5a0702ca43dc1462de | 1,808 | cpp | C++ | Exercise_3_16_springs/src/ofApp.cpp | ChongChongS/P52Of | 1904f58e02f15b329c6c01c47e251bbadf427e5e | [
"MIT"
] | null | null | null | Exercise_3_16_springs/src/ofApp.cpp | ChongChongS/P52Of | 1904f58e02f15b329c6c01c47e251bbadf427e5e | [
"MIT"
] | null | null | null | Exercise_3_16_springs/src/ofApp.cpp | ChongChongS/P52Of | 1904f58e02f15b329c6c01c47e251bbadf427e5e | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetWindowShape(640,360);
ofSetBackgroundColor(255);
m1 = new Mover(ofGetWindowWidth()/2,100);
m2 = new Mover(ofGetWindowWidth()/2,50);
m3 = new Mover(ofGetWindowWidth()/2,150);
s1 = new Spring(m1,m2,100);
s2 = new Spring(m1,m3,100);
s3 = new Spring(m3,m2,100);
}
//--------------------------------------------------------------
void ofApp::update(){
s1->update();
s2->update();
s3->update();
m1->update();
m2->update();
m3->update();
}
//--------------------------------------------------------------
void ofApp::draw(){
s1->display();
s2->display();
s3->display();
m1->display();
m2->display();
m3->display();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
m1->drag(x,y);
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
m1->clicked(x,y);
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
m1->stopDragging();
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 22.320988 | 64 | 0.369469 | ChongChongS |
16c4fa6645d5e1b0d521c7a1db5e3307559f7841 | 3,247 | cpp | C++ | tests/Graphics/Renderer/AbstractFramebufferRenderer.cpp | danielealbano/rpi4-status-display | 8ee56844715fb02e3070baa815e25e05f06d93f4 | [
"BSD-2-Clause"
] | 1 | 2021-01-09T17:38:08.000Z | 2021-01-09T17:38:08.000Z | tests/Graphics/Renderer/AbstractFramebufferRenderer.cpp | danielealbano/rpi4-status-display | 8ee56844715fb02e3070baa815e25e05f06d93f4 | [
"BSD-2-Clause"
] | 2 | 2021-01-09T17:32:52.000Z | 2021-01-09T17:42:32.000Z | tests/Graphics/Renderer/AbstractFramebufferRenderer.cpp | danielealbano/rpi4-status-display | 8ee56844715fb02e3070baa815e25e05f06d93f4 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright 2020-2021 Albano Daniele Salvatore
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdint>
#include <iostream>
#include "Graphics/Color.h"
#include "Graphics/Point2D.h"
#include "Graphics/Size2D.h"
#include "Graphics/Line2D.h"
#include "Graphics/Rect2D.h"
#include "Graphics/Framebuffer.h"
#include "Graphics/Renderer/RendererInterface.h"
#include "Graphics/Renderer/AbstractFramebufferRenderer.h"
#include <catch2/catch.hpp>
using namespace std;
using namespace Rpi4StatusDisplay::Graphics;
using namespace Rpi4StatusDisplay::Graphics::Renderer;
#define EMPTY_OVERRIDDEN_CLASS_METHOD(CLASS_NAME, METHOD_NAME, ...) \
CLASS_NAME &METHOD_NAME(__VA_ARGS__) override { \
return *this; \
}
class AbstractRendererTestWrapper : public AbstractFramebufferRenderer {
public:
explicit AbstractRendererTestWrapper(Framebuffer &framebuffer) : AbstractFramebufferRenderer(framebuffer) {
// do nothing
}
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, setColor, Color &c);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, flush);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, clear);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, text, Point2D &p, std::string &text);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, line, Line2D &l);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, rectOutline, Rect2D &r);
EMPTY_OVERRIDDEN_CLASS_METHOD(AbstractRendererTestWrapper, rectFilled, Rect2D &r);
};
TEST_CASE("Graphics::Renderer::AbstractFramebufferRenderer", "[Graphics][Renderer][AbstractFramebufferRenderer]") {
Size2D s0(20, 40);
Framebuffer f0(s0, 3, s0.width() * 3);
AbstractRendererTestWrapper abstractRendererTestWrapper0(f0);
SECTION("AbstractFramebufferRenderer(Framebuffer(Size2D(20, 40)))") {
REQUIRE(&abstractRendererTestWrapper0.framebuffer() == &f0);
}
}
| 46.385714 | 121 | 0.767478 | danielealbano |
16c5869e8b00276ebede32bfb0df9f5ff40bd596 | 214 | cpp | C++ | CluVRPsol.cpp | christofdefryn/CluVRP | 42c037f4c54eca461128efdcb8a574be8903da5f | [
"Apache-2.0"
] | 6 | 2018-11-30T04:04:25.000Z | 2021-04-22T14:14:15.000Z | CluVRPsol.cpp | RunningPhoton/CluVRP | 42c037f4c54eca461128efdcb8a574be8903da5f | [
"Apache-2.0"
] | 1 | 2017-12-28T02:43:50.000Z | 2018-10-01T08:45:48.000Z | CluVRPsol.cpp | RunningPhoton/CluVRP | 42c037f4c54eca461128efdcb8a574be8903da5f | [
"Apache-2.0"
] | 6 | 2019-09-19T08:59:09.000Z | 2020-06-12T19:43:36.000Z | #include "CluVRPsol.h"
CluVRPsol::CluVRPsol(ClusterSolution* sCluster, NodeSolution* sNode)
{
sCluster_ = sCluster;
sNode_ = sNode;
}
CluVRPsol::~CluVRPsol()
{
delete sNode_;
delete sCluster_;
} | 15.285714 | 69 | 0.691589 | christofdefryn |
16c6da7292c0fd8129bbb1a04f152b337f5a375c | 15,168 | cpp | C++ | snake-omp/main.cpp | jeffhammond/HeCBench | 926ad2a2d760d189008f637a52c24e0f30d31946 | [
"BSD-3-Clause"
] | 58 | 2020-08-06T18:53:44.000Z | 2021-10-01T07:59:46.000Z | snake-omp/main.cpp | jeffhammond/HeCBench | 926ad2a2d760d189008f637a52c24e0f30d31946 | [
"BSD-3-Clause"
] | 2 | 2020-12-04T12:35:02.000Z | 2021-03-04T22:49:25.000Z | snake-omp/main.cpp | jeffhammond/HeCBench | 926ad2a2d760d189008f637a52c24e0f30d31946 | [
"BSD-3-Clause"
] | 13 | 2020-08-19T13:44:18.000Z | 2021-09-08T04:25:34.000Z | /*
* Copyright (c) <2017 - 2020>, ETH Zurich and Bilkent University
* 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 names of the ETH Zurich, Bilkent University,
* 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 <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <chrono>
using namespace std::chrono;
#define warp_size 32
#define SharedPartDevice 64
#define FULL_MASK 0xffffffff
#define NBytes Nuints
#define PRINT 0
#define Number_of_Diagonals 9
#define F_ReadLength 100
#define BitVal(data,y) ( (data>>y) & 1) // Return Data.Y value
#define SetBit(data,y) data |= (1 << y) // Set Data.Y to 1
// suboptimal
#pragma omp declare target
uint popcnt( uint x )
{
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return x & 0x0000003f;
}
uint clz( uint x )
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return 32 - popcnt(x);
}
#pragma omp end declare target
int main(int argc, const char * const argv[])
{
if (argc != 4){
printf("Incorrect arguments..\nUsage: ./%s [ReadLength] [ReadandRefFile] [#reads]\n", argv[0]);
exit(-1);
}
int ReadLength = atoi(argv[1]);//in my inputs, it is always 100. Just for the generality we keep it as a variable
int NumReads = atoi(argv[3]); // Number of reads
int Size_of_uint_in_Bit = 32; //in Bits
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
char *p;//when reading each char_basepair from the file, we read it into the p.
int Number_of_warps_inside_each_block = 8;
int Concurrent_threads_In_Block = warp_size * Number_of_warps_inside_each_block;
int Number_of_blocks_inside_each_kernel = (NumReads + Concurrent_threads_In_Block - 1) /
Concurrent_threads_In_Block;
int F_ErrorThreshold =0;
uint* ReadSeq = (uint * ) calloc(NumReads * 8, sizeof(uint));
uint* RefSeq = (uint * ) calloc(NumReads * 8, sizeof(uint));
int* Results = (int * ) calloc(NumReads, sizeof(int));
int tokenIndex=1;
fp = fopen(argv[2], "r");
if (!fp){
printf("Sorry, the file does not exist or you do not have access permission\n");
return 0;
}
for(int this_read = 0; this_read < NumReads; this_read++) {
read = getline(&line, &len, fp);
tokenIndex=1;
for (p = strtok(line, "\t"); p != NULL; p = strtok(NULL, "\t"))
{
if (tokenIndex==1)
{
for (int j = 0; j < ReadLength; j++)
{
if(p[j] == 'A')
{
//do nothing (this is like storing 00)
}
else if (p[j] == 'C')
{
ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2 + 1));
}
else if (p[j] == 'G')
{
ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2));
}
else if (p[j] == 'T')
{
ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2));
ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2 + 1));
}
//printf("%c",p[j]);
//printf(" %08x", ReadSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)]);
}
}
else if(tokenIndex==2)
{
for (int j = 0; j < ReadLength; j++)
{
if(p[j] == 'A')
{
//do nothing (this is like storing 00)
}
else if (p[j] == 'C')
{
RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2 + 1));
}
else if (p[j] == 'G')
{
RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2));
}
else if (p[j] == 'T')
{
RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2));
RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)] = SetBit(RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)], 31 - ((j%(Size_of_uint_in_Bit/2)) * 2 + 1));
}
//printf("%c",p[j]);
//printf(" %08x", RefSeq[((j*2/Size_of_uint_in_Bit) + this_read * NBytes)]);
}
}
tokenIndex=tokenIndex+1;
}
}
fclose(fp);
#pragma omp target data map(to: ReadSeq[0:NumReads*8], RefSeq[0:NumReads*8]) \
map(alloc: Results[0:NumReads])
{
for (int n = 0; n < 100; n++) {
for (int loopPar = 0; loopPar <= 25; loopPar++) {
F_ErrorThreshold = (loopPar*ReadLength)/100;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
#pragma omp target teams distribute parallel for num_teams(Number_of_blocks_inside_each_kernel) \
thread_limit(Concurrent_threads_In_Block)
for (int tid = 0; tid < NumReads; tid++) {
// const int NBytes = 8;
uint ReadsPerThread[NBytes];
uint RefsPerThread[NBytes];
#pragma unroll
for (int i = 0; i < NBytes; i++)
{
ReadsPerThread[i] = ReadSeq[tid*8 + i];
RefsPerThread[i] = RefSeq[tid*8 + i];
}
/////////////////////////////////////////////////////////////////////////////
Results[tid] = 1;
uint ReadCompTmp = 0;
uint RefCompTmp = 0;
uint DiagonalResult = 0;
uint ReadTmp1 = 0;
uint ReadTmp2 = 0;
uint RefTmp1 = 0;
uint RefTmp2 = 0;
uint CornerCase = 0;
int localCounter= 0;
int localCounterMax=0;
int globalCounter = 0;
int Max_leading_zeros = 0;
int AccumulatedErrs = 0;
int ShiftValue = 0;
int Diagonal = 0;
int j = 0; //specifying the j-th uint that we are reading in each read-ref comparison (can be from 0 to 7)
while ( (j < 7) && (globalCounter < 200))
{
Diagonal = 0;
RefTmp1 = RefsPerThread[j] << ShiftValue;
RefTmp2 = RefsPerThread[j + 1] >> 32 - ShiftValue;
ReadTmp1 = ReadsPerThread[j] << ShiftValue;
ReadTmp2 = ReadsPerThread[j + 1] >> 32 - ShiftValue;
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
localCounterMax = clz(DiagonalResult);
//////////////////// Upper diagonals /////////////////////
for(int e = 1; e <= F_ErrorThreshold; e++)
{
Diagonal += 1;
CornerCase = 0;
if ( (j == 0) && ( (ShiftValue - (2*e)) < 0 ) )
{
ReadTmp1 = ReadsPerThread[j] >> ( (2*e) - ShiftValue );
ReadTmp2 = 0;
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
CornerCase = 0;
for(int Ci = 0; Ci < (2*e) - ShiftValue; Ci++)
{
SetBit(CornerCase, 31 - Ci);
}
DiagonalResult = DiagonalResult | CornerCase;
localCounter = clz(DiagonalResult);
}
else if ( (ShiftValue - (2*e) ) < 0 )
{
ReadTmp1 = ReadsPerThread[j-1] << 32 - ( (2*e) - ShiftValue );
ReadTmp2 = ReadsPerThread[j] >> (2*e) - ShiftValue;
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
localCounter = clz(DiagonalResult);
}
else
{
ReadTmp1 = ReadsPerThread[j] << ShiftValue - (2*e);
ReadTmp2 = ReadsPerThread[j+1] >> 32 - (ShiftValue - (2*e) ) ;
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
localCounter = clz(DiagonalResult);
}
if (localCounter>localCounterMax)
localCounterMax=localCounter;
}
/*
sh = shift
up = upper diagonal
RC = ReadCompTmp
FC = RefCompTmp
D = DiagonalResult
DN = diagonal
LC = localCounter
*/
//////////////////// Lower diagonals /////////////////////
for(int e = 1; e <= F_ErrorThreshold; e++)
{
Diagonal += 1;
CornerCase = 0;
if ( j<5)// ( (globalCounter + ShiftValue + (2*e) + 32) < 200) )
{
if ( (ShiftValue + (2*e) ) < 32)
{
ReadTmp1 = ReadsPerThread[j] << ShiftValue + (2*e);
ReadTmp2 = ReadsPerThread[j+1] >> 32 - ( ShiftValue + (2*e) );
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
localCounter = clz(DiagonalResult);
}
else
{
ReadTmp1 = ReadsPerThread[j+1] << ( ShiftValue + (2*e) ) % 32;
ReadTmp2 = ReadsPerThread[j+2] >> 32 - ( ( ShiftValue + (2*e) ) % 32 );
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = 0xffffffff;//ReadCompTmp ^ RefCompTmp;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
localCounter = clz(DiagonalResult);
}
}
else
{
//printf("HI3");
ReadTmp1 = ReadsPerThread[j] << ShiftValue + (2*e);
ReadTmp2 = ReadsPerThread[j+1] >> 32 - ( ShiftValue + (2*e) );
ReadCompTmp = ReadTmp1 | ReadTmp2;
RefCompTmp = RefTmp1 | RefTmp2;
DiagonalResult = ReadCompTmp ^ RefCompTmp;
CornerCase = 0;
if ((globalCounter+32)>200 ) {
for(int Ci = ((globalCounter+32)-200); Ci < (((globalCounter+32)-200)+ 2*e); Ci++)
{
SetBit(CornerCase, Ci);
}
}
else if ((globalCounter+32)>=(200- (2*e))){
for(int Ci = 0; Ci < (2*e); Ci++)
{
SetBit(CornerCase, Ci);
}
}
DiagonalResult = DiagonalResult | CornerCase;
localCounter = clz(DiagonalResult);
}
if (localCounter>localCounterMax)
localCounterMax=localCounter;
}
/*
CC = CornerCase
sh = shift
up = upper diagonal
RC = ReadCompTmp
FC = RefCompTmp
D = DiagonalResult
DN = diagonal
LC = localCounter
*/
Max_leading_zeros = 0;
if ( (j == 6) && ( ((localCounterMax/2)*2) >= 8) )
{
Max_leading_zeros = 8;
break;
}
else if( ((localCounterMax/2)*2) > Max_leading_zeros)
{
Max_leading_zeros = ((localCounterMax/2)*2);
}
if ( ( (Max_leading_zeros/2) < 16) && (j < 5) )
{
AccumulatedErrs += 1;
}
else if ( (j == 6) && ( (Max_leading_zeros/2) < 4) )
{
AccumulatedErrs += 1;
}
if(AccumulatedErrs > F_ErrorThreshold)
{
Results[tid] = 0;
break;
}
if(ShiftValue + Max_leading_zeros + 2 >= 32)
{
j += 1;
}
// ShiftValue_2Ref = (ShiftValue_2Ref + Max_leading_zeros + 2) %32;
if (Max_leading_zeros == 32)
{
globalCounter += Max_leading_zeros;
}
else
{
ShiftValue = ((ShiftValue + Max_leading_zeros + 2) % 32);
globalCounter += (Max_leading_zeros + 2);
}
}
}
#pragma omp target update from (Results[0:NumReads])
high_resolution_clock::time_point t2 = high_resolution_clock::now();
double elapsed_time = duration_cast<microseconds>(t2 - t1).count();
int accepted = 0;
for(int i = 0; i < NumReads; i++)
{
if(Results[i] == 1)
accepted += 1;
}
printf("E: \t %d \t Snake-on-GPU: \t %5.4f \t Accepted: \t %10d \t Rejected: \t %10d\n",
F_ErrorThreshold, elapsed_time, accepted, NumReads - accepted);
}
}
}
free(ReadSeq);
free(RefSeq);
free(Results);
return 0;
}
| 33.557522 | 182 | 0.516152 | jeffhammond |
16c78f9486ec6537376e122aef5ec3f3fa39bf7c | 621 | hpp | C++ | obsoleted/old/lib-obsolete/device/include/device.hpp | cppcoder123/led-server | 8ebac31e1241bb203d2cedfd644fe52619007cd6 | [
"MIT"
] | 1 | 2021-12-23T13:50:53.000Z | 2021-12-23T13:50:53.000Z | obsoleted/old/lib-obsolete/device/include/device.hpp | cppcoder123/led-server | 8ebac31e1241bb203d2cedfd644fe52619007cd6 | [
"MIT"
] | null | null | null | obsoleted/old/lib-obsolete/device/include/device.hpp | cppcoder123/led-server | 8ebac31e1241bb203d2cedfd644fe52619007cd6 | [
"MIT"
] | null | null | null | //
//
//
#ifndef DEVICE_DEVICE_HPP
#define DEVICE_DEVICE_HPP
#include "device-codec.hpp"
#include "device-id.h"
#include "matrix.hpp"
namespace device
{
class device_t
{
public:
virtual ~device_t () {}
using codec_t = core::device::codec_t;
using msg_t = codec_t::msg_t;
using char_t = codec_t::char_t;
// do not throw
virtual bool write (const msg_t &msg) = 0;
virtual bool read (msg_t &msg, bool block) = 0;
// throws
virtual void write_status (const msg_t &msg) = 0;
virtual void read_status (char_t status = ID_STATUS_OK) = 0;
};
} // namespace device
#endif
| 16.783784 | 64 | 0.653784 | cppcoder123 |
16c7906f922a315fa5e35d709cacfa8b2c6491cc | 411 | cpp | C++ | Vortex/src/Vortex/Core/Input.cpp | olleh-dlrow/Vortex | f52574bcf33f53c7ed21dabf54aa91e70fde9060 | [
"Apache-2.0"
] | null | null | null | Vortex/src/Vortex/Core/Input.cpp | olleh-dlrow/Vortex | f52574bcf33f53c7ed21dabf54aa91e70fde9060 | [
"Apache-2.0"
] | null | null | null | Vortex/src/Vortex/Core/Input.cpp | olleh-dlrow/Vortex | f52574bcf33f53c7ed21dabf54aa91e70fde9060 | [
"Apache-2.0"
] | null | null | null | #include "vtpch.h"
#include "Vortex/Core/Input.h"
#ifdef VT_PLATFORM_WINDOWS
#include "Platform/Windows/WindowsInput.h"
#endif
namespace Vortex {
Scope<Input> Input::s_Instance = Input::Create();
Scope<Input> Input::Create()
{
#ifdef VT_PLATFORM_WINDOWS
return CreateScope<WindowsInput>();
#else
VT_CORE_ASSERT(false, "Unknown platform!");
return nullptr;
#endif
}
}
| 18.681818 | 53 | 0.683698 | olleh-dlrow |
16c991fffd6c4aa1a1ae2485e5577a89c7eab0e7 | 1,647 | hpp | C++ | src/org/apache/poi/poifs/storage/SmallBlockTableReader.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/storage/SmallBlockTableReader.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/storage/SmallBlockTableReader.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/poifs/storage/SmallBlockTableReader.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/poifs/common/fwd-POI.hpp>
#include <org/apache/poi/poifs/property/fwd-POI.hpp>
#include <org/apache/poi/poifs/storage/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::poifs::storage::SmallBlockTableReader final
: public ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static BlockList* prepareSmallDocumentBlocks(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
static BlockAllocationTableReader* prepareReader(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, BlockList* list, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
public:
static BlockAllocationTableReader* _getSmallDocumentBlockReader(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
static BlockList* getSmallDocumentBlocks(::poi::poifs::common::POIFSBigBlockSize* bigBlockSize, RawDataBlockList* blockList, ::poi::poifs::property::RootProperty* root, int32_t sbatStart) /* throws(IOException) */;
// Generated
SmallBlockTableReader();
protected:
SmallBlockTableReader(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 41.175 | 243 | 0.757741 | pebble2015 |
16cda066b93ddef1f3818fdc45ced2af72b6a220 | 1,308 | cpp | C++ | sourcecode/02_hello_triangle/maths_funcs.cpp | FahrenheitKid/OpenGLAmbientOcclusion | 6fd0fbda5338d818d6156c6b1fc85fa51799f97f | [
"MIT"
] | null | null | null | sourcecode/02_hello_triangle/maths_funcs.cpp | FahrenheitKid/OpenGLAmbientOcclusion | 6fd0fbda5338d818d6156c6b1fc85fa51799f97f | [
"MIT"
] | null | null | null | sourcecode/02_hello_triangle/maths_funcs.cpp | FahrenheitKid/OpenGLAmbientOcclusion | 6fd0fbda5338d818d6156c6b1fc85fa51799f97f | [
"MIT"
] | null | null | null | /******************************************************************************\
| OpenGL 4 Example Code. |
| Accompanies written series "Anton's OpenGL 4 Tutorials" |
| Email: anton at antongerdelan dot net |
| First version 27 Jan 2014 |
| Copyright Dr Anton Gerdelan, Trinity College Dublin, Ireland. |
| See individual libraries' separate legal notices |
|******************************************************************************|
| Commonly-used maths structures and functions |
| Simple-as-possible. No disgusting templates. |
| Structs vec3, mat4, versor. just hold arrays of floats called "v","m","q", |
| respectively. So, for example, to get values from a mat4 do: my_mat.m |
| A versor is the proper name for a unit quaternion. |
\******************************************************************************/
#include "maths_funcs.h"
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
// lerp function
float lerp(float a, float b, float f)
{
return a + f * (b - a);
} | 50.307692 | 80 | 0.417431 | FahrenheitKid |
16d0ccf659fdcbb29fb75618ca5b4d978def871b | 5,179 | hh | C++ | tamer/websocket.hh | kohler/tamer | 0953029ad7fc5c3fd58869227976c359674c670f | [
"BSD-3-Clause"
] | 23 | 2015-04-11T06:41:04.000Z | 2021-11-06T21:34:14.000Z | tamer/websocket.hh | kohler/tamer | 0953029ad7fc5c3fd58869227976c359674c670f | [
"BSD-3-Clause"
] | 2 | 2015-04-15T07:00:31.000Z | 2016-08-16T13:46:22.000Z | tamer/websocket.hh | kohler/tamer | 0953029ad7fc5c3fd58869227976c359674c670f | [
"BSD-3-Clause"
] | 5 | 2015-08-18T19:24:07.000Z | 2021-04-18T04:35:35.000Z | #ifndef TAMER_WEBSOCKET_HH
#define TAMER_WEBSOCKET_HH 1
#include "http.hh"
namespace tamer {
class websocket_handshake {
public:
static bool request(http_message& req, std::string& key);
static bool is_request(const http_message& req);
static bool response(http_message& resp, const http_message& req);
static bool is_response(const http_message& resp, const std::string& key);
};
enum websocket_opcode {
WEBSOCKET_CONTINUATION = 0,
WEBSOCKET_TEXT = 1,
WEBSOCKET_BINARY = 2,
WEBSOCKET_CLOSE = 8,
WEBSOCKET_PING = 9,
WEBSOCKET_PONG = 10
};
class websocket_message {
public:
inline websocket_message();
inline bool ok() const;
inline bool operator!() const;
inline enum http_errno error() const;
inline enum websocket_opcode opcode() const;
inline bool text() const;
inline bool binary() const;
inline bool incomplete() const;
inline const std::string& body() const;
inline std::string& body();
inline websocket_message& clear();
inline websocket_message& error(enum http_errno e);
inline websocket_message& incomplete(bool c);
inline websocket_message& opcode(enum websocket_opcode o);
inline websocket_message& body(std::string body);
inline websocket_message& text(std::string body);
inline websocket_message& binary(std::string body);
private:
unsigned error_ : 8;
unsigned incomplete_ : 4;
unsigned opcode_ : 4;
std::string body_;
};
class websocket_parser : public tamed_class {
public:
inline websocket_parser(enum http_parser_type type);
inline bool ok() const;
inline bool operator!() const;
inline bool closed() const;
void receive_any(fd f, websocket_message& ctrl, websocket_message& data, event<int> done);
void receive(fd f, event<websocket_message> done);
void send(fd f, websocket_message m, event<> done);
inline void send_text(fd f, std::string text, event<> done);
inline void send_binary(fd f, std::string text, event<> done);
void close(fd f, uint16_t code, std::string reason, event<> done);
inline void close(fd f, uint16_t code, event<> done);
private:
enum http_parser_type type_;
uint8_t closed_;
uint16_t close_code_;
std::string close_reason_;
class closure__receive_any__2fdR17websocket_messageR17websocket_messageQi_;
void receive_any(closure__receive_any__2fdR17websocket_messageR17websocket_messageQi_&);
class closure__receive__2fdQ17websocket_message_;
void receive(closure__receive__2fdQ17websocket_message_&);
class closure__send__2fd17websocket_messageQ_;
void send(closure__send__2fd17websocket_messageQ_&);
};
inline websocket_message::websocket_message()
: error_(0), incomplete_(0), opcode_(0) {
}
inline bool websocket_message::ok() const {
return error_ == 0;
}
inline bool websocket_message::operator!() const {
return !ok();
}
inline enum http_errno websocket_message::error() const {
return http_errno(error_);
}
inline enum websocket_opcode websocket_message::opcode() const {
return websocket_opcode(opcode_);
}
inline bool websocket_message::text() const {
return websocket_opcode(opcode_) == WEBSOCKET_TEXT;
}
inline bool websocket_message::binary() const {
return websocket_opcode(opcode_) == WEBSOCKET_BINARY;
}
inline bool websocket_message::incomplete() const {
return incomplete_;
}
inline const std::string& websocket_message::body() const {
return body_;
}
inline std::string& websocket_message::body() {
return body_;
}
inline websocket_message& websocket_message::clear() {
error_ = 0;
incomplete_ = 0;
opcode_ = 0;
body_.clear();
return *this;
}
inline websocket_message& websocket_message::error(enum http_errno e) {
error_ = e;
return *this;
}
inline websocket_message& websocket_message::incomplete(bool c) {
incomplete_ = c;
return *this;
}
inline websocket_message& websocket_message::opcode(enum websocket_opcode o) {
opcode_ = o;
return *this;
}
inline websocket_message& websocket_message::body(std::string s) {
body_ = TAMER_MOVE(s);
return *this;
}
inline websocket_message& websocket_message::text(std::string s) {
opcode_ = WEBSOCKET_TEXT;
body_ = TAMER_MOVE(s);
return *this;
}
inline websocket_message& websocket_message::binary(std::string s) {
opcode_ = WEBSOCKET_BINARY;
body_ = TAMER_MOVE(s);
return *this;
}
inline websocket_parser::websocket_parser(enum http_parser_type type)
: type_(type), closed_(0), close_code_(0) {
}
inline bool websocket_parser::ok() const {
return !closed_;
}
inline bool websocket_parser::operator!() const {
return closed_;
}
inline bool websocket_parser::closed() const {
return closed_;
}
inline void websocket_parser::send_text(fd f, std::string s, event<> done) {
send(f, websocket_message().text(s), done);
}
inline void websocket_parser::send_binary(fd f, std::string s, event<> done) {
send(f, websocket_message().binary(s), done);
}
inline void websocket_parser::close(fd f, uint16_t close_code, event<> done) {
close(f, close_code, std::string(), done);
}
}
#endif
| 26.695876 | 94 | 0.720409 | kohler |
16d2ba13fc0d169b85e5e7aefbfdeb3f7ce6cbb9 | 2,411 | cpp | C++ | Main/RobotPoseQt/floatarrayframe.cpp | hpbader42/Klampt | 89faaef942c0c6fca579a3770314c6610e2ac772 | [
"BSD-3-Clause"
] | 238 | 2015-01-09T15:21:27.000Z | 2022-03-30T22:48:45.000Z | Main/RobotPoseQt/floatarrayframe.cpp | hpbader42/Klampt | 89faaef942c0c6fca579a3770314c6610e2ac772 | [
"BSD-3-Clause"
] | 89 | 2015-08-26T16:56:42.000Z | 2022-03-29T23:45:46.000Z | Main/RobotPoseQt/floatarrayframe.cpp | hpbader42/Klampt | 89faaef942c0c6fca579a3770314c6610e2ac772 | [
"BSD-3-Clause"
] | 84 | 2015-01-10T18:41:52.000Z | 2022-03-30T03:32:50.000Z | #include "floatarrayframe.h"
#include "ui_floatarrayframe.h"
#include <iostream>
using namespace std;
FloatArrayFrame::FloatArrayFrame(ResourceFrame* _frame,QWidget *parent)
:QGroupBox(parent),
resource(NULL),
frame(_frame),
ui(new Ui::FloatArrayFrame)
{
ui->setupUi(this);
}
void FloatArrayFrame::set(FloatArrayResource* r)
{
assert(r != NULL);
resource = r;
if(resource->data.empty()) {
ui->spin_index->setEnabled(false);
ui->edit_value->setEnabled(false);
}
else {
ui->spin_index->setEnabled(true);
ui->edit_value->setEnabled(true);
ui->spin_index->setMaximum(resource->data.size()-1);
}
}
FloatArrayFrame::~FloatArrayFrame()
{
delete ui;
}
void FloatArrayFrame::IndexChanged(int index)
{
blockSignals(true);
double v=resource->data[index];
ui->edit_value->setText(QString::number(v));
blockSignals(false);
}
void FloatArrayFrame::ValueChanged(QString val)
{
bool ok;
double v = val.toDouble(&ok);
if(ok) {
resource->data[ui->spin_index->value()] = v;
frame->onResourceEdit();
}
}
void FloatArrayFrame::Insert()
{
blockSignals(true);
if(resource->data.size()==0) {
ui->spin_index->setEnabled(true);
ui->edit_value->setEnabled(true);
ui->spin_index->setValue(0);
resource->data.push_back(0.0);
}
else {
int index=ui->spin_index->value();
assert(index >= 0 && index < (int)resource->data.size());
resource->data.insert(resource->data.begin()+index,0.0);
}
ui->spin_index->setMaximum(resource->data.size()-1);
int index=ui->spin_index->value();
assert(index >= 0 && index < (int)resource->data.size());
ui->edit_value->setText(QString::number(resource->data[index]));
blockSignals(false);
frame->onResourceEdit();
}
void FloatArrayFrame::Delete()
{
if(resource->data.empty()) return;
blockSignals(true);
resource->data.erase(resource->data.begin()+ui->spin_index->value());
if(resource->data.size()==0) {
ui->spin_index->setEnabled(false);
ui->edit_value->setEnabled(false);
}
else {
int index=ui->spin_index->value();
if(index >= (int)resource->data.size()) {
index = (int)resource->data.size()-1;
ui->spin_index->setValue(index);
}
ui->spin_index->setMaximum(resource->data.size()-1);
double v=resource->data[index];
ui->edit_value->setText(QString::number(v));
}
blockSignals(false);
frame->onResourceEdit();
}
| 24.85567 | 71 | 0.666528 | hpbader42 |
16d317e517655bc2b5010c6d9b60af3667acc089 | 7,112 | cpp | C++ | source/MultiLibrary/Media/SoundStream.cpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 2 | 2018-06-22T12:43:57.000Z | 2019-05-31T21:56:27.000Z | source/MultiLibrary/Media/SoundStream.cpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 1 | 2017-09-09T01:21:31.000Z | 2017-11-12T17:52:56.000Z | source/MultiLibrary/Media/SoundStream.cpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 1 | 2022-03-30T18:57:41.000Z | 2022-03-30T18:57:41.000Z | /*************************************************************************
* MultiLibrary - https://danielga.github.io/multilibrary/
* A C++ library that covers multiple low level systems.
*------------------------------------------------------------------------
* Copyright (c) 2014-2022, Daniel Almeida
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include <MultiLibrary/Media/SoundStream.hpp>
#include <MultiLibrary/Media/AudioDevice.hpp>
#include <MultiLibrary/Media/OpenAL.hpp>
namespace MultiLibrary
{
SoundStream::SoundStream( ) :
thread_active( true ),
stream_thread( &SoundStream::DataStreamer, this ),
is_streaming( false ),
should_loop( false ),
samples_processed( 0 ),
channel_count( 0 ),
sample_rate( 0 ),
audio_format( 0 ),
minimum_bufsize( 0 )
{ }
SoundStream::~SoundStream( )
{
Stop( );
thread_active = false;
stream_thread.join( );
}
void SoundStream::Play( )
{
if( is_streaming )
{
alCheck( alSourcePlay( audio_source ) );
return;
}
Seek( std::chrono::milliseconds::zero( ) );
samples_processed = 0;
is_streaming = true;
}
void SoundStream::Pause( )
{
alCheck( alSourcePause( audio_source ) );
}
void SoundStream::Stop( )
{
is_streaming = false;
}
uint32_t SoundStream::GetChannelCount( ) const
{
return channel_count;
}
uint32_t SoundStream::GetSampleRate( ) const
{
return sample_rate;
}
std::chrono::microseconds SoundStream::GetDuration( ) const
{
return audio_duration;
}
SoundStatus SoundStream::GetStatus( ) const
{
SoundStatus status = SoundSource::GetStatus( );
if( status == Stopped && is_streaming )
status = Playing;
return status;
}
void SoundStream::SetPlayingOffset( const std::chrono::microseconds &time_offset )
{
Stop( );
Seek( time_offset );
samples_processed = static_cast<uint64_t>( time_offset.count( ) / 1000000.0 * sample_rate * channel_count );
is_streaming = true;
}
std::chrono::microseconds SoundStream::GetPlayingOffset( ) const
{
ALfloat secs = 0.0f;
alCheck( alGetSourcef( audio_source, AL_SEC_OFFSET, &secs ) );
return std::chrono::microseconds( static_cast<int64_t>( secs + static_cast<double>( samples_processed ) / sample_rate / channel_count ) );
}
void SoundStream::SetLoop( bool looping )
{
should_loop = looping;
}
bool SoundStream::GetLoop( )
{
return should_loop;
}
void SoundStream::Initialize( uint32_t channels, uint32_t sampleRate, const std::chrono::microseconds &duration )
{
channel_count = channels;
sample_rate = sampleRate;
audio_duration = duration;
audio_format = AudioDevice::GetFormatFromChannelCount( channels );
minimum_bufsize = sample_rate * channel_count * sizeof( int16_t ) / 10;
temp_buffer.resize( minimum_bufsize );
std::vector<int16_t>( temp_buffer ).swap( temp_buffer );
temp_buffer.resize( 0 );
}
void SoundStream::DataStreamer( )
{
std::chrono::milliseconds millisecs = std::chrono::milliseconds( 1 );
while( thread_active )
{
if( !is_streaming )
{
std::this_thread::sleep_for( millisecs );
continue;
}
alCheck( alGenBuffers( MAX_AUDIO_BUFFERS, audio_buffers ) );
bool requestStop = false;
for( uint8_t i = 0; i < MAX_AUDIO_BUFFERS; ++i )
{
end_buffer[i] = false;
if( !requestStop && FillAndPushBuffer( i ) )
requestStop = true;
}
alCheck( alSourcePlay( audio_source ) );
while( is_streaming )
{
if( SoundSource::GetStatus( ) == Stopped )
{
if( !requestStop )
alCheck( alSourcePlay( audio_source ) );
else
is_streaming = false;
}
ALint nbProcessed = 0;
alCheck( alGetSourcei( audio_source, AL_BUFFERS_PROCESSED, &nbProcessed ) );
while( nbProcessed-- )
{
ALuint buffer;
alCheck( alSourceUnqueueBuffers( audio_source, 1, &buffer ) );
uint32_t bufferNum = 0;
for( uint8_t i = 0; i < MAX_AUDIO_BUFFERS; ++i )
if( audio_buffers[i] == buffer )
{
bufferNum = i;
break;
}
if( end_buffer[bufferNum] )
{
samples_processed = 0;
end_buffer[bufferNum] = false;
}
else
{
ALint size, bits;
alCheck( alGetBufferi( buffer, AL_SIZE, &size ) );
alCheck( alGetBufferi( buffer, AL_BITS, &bits ) );
samples_processed += size / ( bits / 8 );
}
if( !requestStop )
if( FillAndPushBuffer( bufferNum ) )
requestStop = true;
}
if( SoundSource::GetStatus( ) != Stopped )
std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
}
alCheck( alSourceStop( audio_source ) );
ALint nbQueued = 0;
alCheck( alGetSourcei( audio_source, AL_BUFFERS_QUEUED, &nbQueued ) );
ALuint buffer = 0;
for( ALint i = 0; i < nbQueued; ++i )
alCheck( alSourceUnqueueBuffers( audio_source, 1, &buffer ) );
alCheck( alSourcei( audio_source, AL_BUFFER, 0 ) );
alCheck( alDeleteBuffers( MAX_AUDIO_BUFFERS, audio_buffers ) );
}
}
bool SoundStream::FillAndPushBuffer( uint32_t buffer_num )
{
bool requestStop = false;
if( !GetData( temp_buffer, minimum_bufsize ) )
{
end_buffer[buffer_num] = true;
if( should_loop )
{
Seek( std::chrono::milliseconds::zero( ) );
if( temp_buffer.size( ) == 0 )
return FillAndPushBuffer( buffer_num );
}
else
{
requestStop = true;
}
}
if( temp_buffer.size( ) > 0 )
{
uint32_t buffer = audio_buffers[buffer_num];
ALsizei size = static_cast<ALsizei>( temp_buffer.size( ) * sizeof( int16_t ) );
alCheck( alBufferData( buffer, audio_format, &temp_buffer[0], size, sample_rate ) );
alCheck( alSourceQueueBuffers( audio_source, 1, &buffer ) );
}
temp_buffer.resize( 0 );
return requestStop;
}
} // namespace MultiLibrary
| 25.768116 | 139 | 0.683493 | danielga |
16d32c4153cac0729484ff226a9ea64ef4791e77 | 311 | cpp | C++ | ros/src/computing/perception/localization/packages/vmml/src/bin/lidar_mapper/ScanOdometry.cpp | sujiwo/autoware | 435869592aa98a6fcb2b0a24594c27ee85bb27fe | [
"Apache-2.0"
] | null | null | null | ros/src/computing/perception/localization/packages/vmml/src/bin/lidar_mapper/ScanOdometry.cpp | sujiwo/autoware | 435869592aa98a6fcb2b0a24594c27ee85bb27fe | [
"Apache-2.0"
] | null | null | null | ros/src/computing/perception/localization/packages/vmml/src/bin/lidar_mapper/ScanOdometry.cpp | sujiwo/autoware | 435869592aa98a6fcb2b0a24594c27ee85bb27fe | [
"Apache-2.0"
] | null | null | null | /*
* ScanOdometry.cpp
*
* Created on: Jun 4, 2019
* Author: sujiwo
*/
#include "LidarMapper.h"
#include "ScanOdometry.h"
ScanOdometry::ScanOdometry(const LidarMapper &parent)
{
// TODO Auto-generated constructor stub
}
ScanOdometry::~ScanOdometry() {
// TODO Auto-generated destructor stub
}
| 14.136364 | 53 | 0.694534 | sujiwo |
16d5304ea3611b73add7e09aaa9aa7d46d8f21ba | 27,541 | cxx | C++ | admin/netui/shell/enum/wnetenum.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/shell/enum/wnetenum.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/shell/enum/wnetenum.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
WNETENUM.CXX
This file contains the implementation of
NPOpenEnum - open a resource enumeration handle
NPEnumResource - walk through all the resource
NPCloseEnum - end of walk through
FILE HISTORY:
terryk 27-Sep-91 Created
terryk 01-Nov-91 WIN32 conversion
terryk 08-Nov-91 Code review changes
terryk 18-Nov-91 Split to 2 files - wnetenum.cxx and
enumnode.cxx
terryk 10-Dec-91 check parameters in WNetOpenEnum
terryk 28-Dec-91 changed DWORD to UINT
Yi-HsinS31-Dec-91 Unicode work
terryk 03-Jan-92 Capitalize the Resource_XXX manifest
terryk 10-Jan-92 Returned WN_SUCCESS if the buffer is too
small for 1 entry.
*/
#define INCL_WINDOWS
#define INCL_DOSERRORS
#define INCL_NETERRORS
#define INCL_NETCONS
#define INCL_NETUSE
#define INCL_NETWKSTA
#define INCL_NETACCESS // NetPasswordSet declaration
#define INCL_NETCONFIG
#define INCL_NETREMUTIL
#define INCL_NETSHARE
#define INCL_NETSERVER
#define INCL_NETSERVICE
#define INCL_NETLIB
#define INCL_ICANON
#define _WINNETWK_
#include <lmui.hxx>
#undef _WINNETWK_
#define INCL_BLT_WINDOW
#include <blt.hxx>
#include <dbgstr.hxx>
#include <winnetwk.h>
#include <winnetp.h>
#include <npapi.h>
#include <wnetenum.h>
#include <winlocal.h>
#include <mnet.h>
#include <lmobj.hxx>
#include <lmoshare.hxx>
#include <lmoesh.hxx>
#include <lmoeuse.hxx>
#include <lmodev.hxx>
#include <lmosrv.hxx>
#include <lmowks.hxx>
#include <lmoesrv.hxx>
#include <lmsvc.hxx>
#include <uibuffer.hxx>
#include <uitrace.hxx>
#include <uiassert.hxx>
#include <uatom.hxx>
#include <regkey.hxx>
#include <array.hxx>
#include <string.hxx>
#include <strchlit.hxx> // for SERVER_INIT_STRING
#include <miscapis.hxx>
#include <wnetenum.hxx>
//
// Macros for rounding a value up/down to a TCHAR boundary.
// Note: These macros assume that sizeof(TCHAR) is a power of 2.
//
#define ROUND_DOWN(x) ((x) & ~(sizeof(TCHAR) - 1))
#define ROUND_UP(x) (((x) + sizeof(TCHAR) - 1) & ~(sizeof(TCHAR) - 1))
/*******************************************************************
Global variables
********************************************************************/
#define ARRAY_SIZE 64
extern NET_ENUM_HANDLE_TABLE *vpNetEnumArray;
/* Winnet locking handle
*/
HANDLE vhSemaphore ;
/* Name of the provider
*/
const TCHAR * pszNTLanMan = NULL ;
#define LM_WKSTA_NODE SZ("System\\CurrentControlSet\\Services\\LanmanWorkstation\\NetworkProvider")
#define LM_PROVIDER_VALUE_NAME SZ("Name")
/*******************************************************************
NAME: InitWNetEnum
SYNOPSIS: Initialize the Enum handle array
RETURN: APIERR - it will return ERROR_OUT_OF_MEMORY if it does
not have enough space
HISTORY:
terryk 24-Oct-91 Created
davidhov 20-Oct-92 updated REG_KEY usage
********************************************************************/
APIERR InitWNetEnum()
{
TRACEEOL( "NTLANMAN.DLL: InitWNetEnum()" );
vpNetEnumArray = new NET_ENUM_HANDLE_TABLE( ARRAY_SIZE );
if ( vpNetEnumArray == NULL )
{
DBGEOL( "NTLANMAN.DLL: InitWNetEnum() ERROR_NOT_ENOUGH_MEMORY" );
return ERROR_NOT_ENOUGH_MEMORY;
}
APIERR err = vpNetEnumArray->QueryError();
if ( !err )
{
if ( (vhSemaphore = ::CreateSemaphore( NULL, 1, 1, NULL )) == NULL)
{
err = ::GetLastError() ;
DBGEOL( "NTLANMAN.DLL: InitWNetEnum() semaphore error " << err );
}
}
return err ;
}
/********************************************************************
NAME: GetLMProviderName
SYNOPSIS: Get Provider Name into the global variable pszNTLanMan
RETURN: APIERR - it will return ERROR_OUT_OF_MEMORY if it does
not have enough space
HISTORY:
congpay 14-Dec-92 Created
********************************************************************/
APIERR GetLMProviderName()
{
if (pszNTLanMan)
{
return NERR_Success;
}
APIERR err = NERR_Success;
REG_KEY *pRegKeyFocusServer = NULL;
do { // error breakout
/* Traverse the registry and get the list of computer alert
* names.
*/
pRegKeyFocusServer = REG_KEY::QueryLocalMachine();
if ( ( pRegKeyFocusServer == NULL ) ||
((err = pRegKeyFocusServer->QueryError())) )
{
err = err? err : ERROR_NOT_ENOUGH_MEMORY ;
break ;
}
ALIAS_STR nlsRegKeyName( LM_WKSTA_NODE ) ;
REG_KEY regkeyLMProviderNode( *pRegKeyFocusServer, nlsRegKeyName );
REG_KEY_INFO_STRUCT regKeyInfo;
REG_VALUE_INFO_STRUCT regValueInfo ;
if ( (err = regkeyLMProviderNode.QueryError()) ||
(err = regkeyLMProviderNode.QueryInfo( ®KeyInfo )) )
{
break ;
}
BUFFER buf( (UINT) regKeyInfo.ulMaxValueLen ) ;
regValueInfo.nlsValueName = LM_PROVIDER_VALUE_NAME ;
if ( (err = buf.QueryError() ) ||
(err = regValueInfo.nlsValueName.QueryError()) )
{
break;
}
regValueInfo.pwcData = buf.QueryPtr();
regValueInfo.ulDataLength = buf.QuerySize() ;
if ( (err = regkeyLMProviderNode.QueryValue( ®ValueInfo )))
{
break;
}
/* Null terminate the computer list string we just retrieved from
* the registry.
*/
TCHAR * pszProviderName = (TCHAR *)( buf.QueryPtr() +
regValueInfo.ulDataLengthOut -
sizeof(TCHAR) );
*pszProviderName = TCH('\0') ;
ALIAS_STR nlsComputerList( (TCHAR *) buf.QueryPtr()) ;
pszNTLanMan = new TCHAR[ nlsComputerList.QueryTextSize() ] ;
if ( pszNTLanMan == NULL )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
break ;
}
nlsComputerList.CopyTo( (TCHAR *) pszNTLanMan,
nlsComputerList.QueryTextSize()) ;
} while (FALSE) ;
delete pRegKeyFocusServer ;
return err;
}
/*******************************************************************
NAME: TermWNetEnum
SYNOPSIS: clear up the Enum handle array
HISTORY:
terryk 24-Oct-91 Created
********************************************************************/
VOID TermWNetEnum()
{
TRACEEOL( "NTLANMAN.DLL: TermWNetEnum()" );
delete vpNetEnumArray;
vpNetEnumArray = NULL;
REQUIRE( ::CloseHandle( vhSemaphore ) ) ;
vhSemaphore = NULL ;
delete (void *) pszNTLanMan ;
pszNTLanMan = NULL ;
}
/*******************************************************************
NAME: NPOpenEnum
SYNOPSIS: Create a new Enum handle
ENTRY: UINT dwScope - determine the scope of the enumeration.
This can be one of:
RESOURCE_CONNECTED - all currently connected resource
RESOURCE_GLOBALNET - all resources on the network
RESOURCE_CONTEXT - resources in the user's current
and default network context
UINT dwType - used to specify the type of resources of
interest. This is a bitmask which may be any
combination of:
RESOURCETYPE_DISK - all disk resources
RESOURCETYPE_PRINT - all print resources
If this is 0, all types of resources are returned.
If a provider does not have the capability to
distinguish between print and disk resources at a
level, it may return all resources.
UINT dwUsage - Used to specify the usage of resources
of interested. This is a bitmask which may be any
combination of:
RESOURCEUSAGE_CONNECTABLE - all connectable
resources
RESOURCEUSAGE_CONTAINER - all container resources
The bitmask may be 0 to match all.
RESOURCEUSAGE_ATTACHED - signifies that the function
should fail if the caller is not authenticated (even
if the network allows enumeration without authenti-
cation).
This parameter is ignored if dwScope is not
RESOURCE_GLOBALNET.
NETRESOURCE * lpNetResource - This specifies the
container to perform the enumeration. The
NETRESOURCE must have been obtained via
NPEnumResource( and must have the
RESOURCEUSAGE_Connectable bit set ), or NULL. If it
is NULL,the logical root of the network is assumed.
An application would normally start off by calling
NPOpenEnum with this parameter set to NULL, and
then use the returned results for further
enumeration. If dwScope is RESOURCE_CONNECTED, this
must be NULL.
If dwScope is RESOURCE_CONTEXT, this is ignored.
HANDLE * lphEnum - If function call is successful, this
will contain a handle that can then be used for
NPEnumResource.
EXIT: HANDLE * lphEnum - will contain the handle number
RETURNS: WN_SUCCESS if the call is successful. Otherwise,
GetLastError should be called for extended error
information. Extened error codes include:
WN_NOT_CONTAINER - lpNetResource does not point to a
container
WN_BAD_VALUE - Invalid dwScope or dwUsage or dwType,
or bad combination of parameters is specified
WN_NOT_NETWORK - network is not present
WN_NET_ERROR - a network specific error occured.
WNetGetLastError should be called to obtain further
information.
HISTORY:
terryk 24-Oct-91 Created
Johnl 06-Mar-1992 Added Computer validation check
on container enumeration
JohnL 03-Apr-1992 Fixed dwUsage == CONNECTED|CONTAINER
bug (would return WN_BAD_VALUE)
ChuckC 01-Aug-1992 Simplified, corrected and commented
the messy cases wrt to dwUsage.
AnirudhS 03-Mar-1995 Added support for RESOURCE_CONTEXT
AnirudhS 26-Apr-1996 Simplified, corrected and commented
the messy cases wrt dwScope.
********************************************************************/
extern
BOOLEAN IsThisADfsDomain(
IN LPCWSTR pwszDomainName);
DWORD APIENTRY
NPOpenEnum(
UINT dwScope,
UINT dwType,
UINT dwUsage,
LPNETRESOURCE lpNetResource,
HANDLE * lphEnum )
{
UIASSERT( lphEnum != NULL );
APIERR err ;
if ( err = CheckLMService() )
return err ;
if ( dwType & ~( RESOURCETYPE_DISK | RESOURCETYPE_PRINT ) )
{
return WN_BAD_VALUE;
}
NET_ENUMNODE *pNetEnum;
if ( dwScope == RESOURCE_CONNECTED )
{
/*
* we are looking for current uses
*/
if ( lpNetResource != NULL )
{
return WN_BAD_VALUE;
}
err = GetLMProviderName();
if (err)
return(err);
pNetEnum = new USE_ENUMNODE( dwScope, dwType, dwUsage, lpNetResource );
}
else if ( dwScope == RESOURCE_CONTEXT )
{
/*
* we are looking for servers in the domain
* Note that lpNetResource is ignored
* dwType is decoded in the CONTEXT_ENUMNODE constructor
*/
pNetEnum = new CONTEXT_ENUMNODE( dwScope, dwType, dwUsage, NULL );
}
else if ( dwScope == RESOURCE_SHAREABLE )
{
/*
* We are looking for shareable resources
* Use SHARE_ENUMNODE, which decodes dwScope when it enumerates
* If we're not given a server, return an EMPTY_ENUMNODE
*/
if (lpNetResource != NULL
&&
lpNetResource->lpRemoteName != NULL
&&
lpNetResource->lpRemoteName[0] == TCH('\\')
&&
lpNetResource->lpRemoteName[1] == TCH('\\')
)
{
if (!IsThisADfsDomain(lpNetResource->lpRemoteName))
{
pNetEnum = new SHARE_ENUMNODE( dwScope, dwType, dwUsage, lpNetResource );
}
else
{
pNetEnum = new EMPTY_ENUMNODE( dwScope, dwType, dwUsage, lpNetResource );
}
}
}
else if ( dwScope == RESOURCE_GLOBALNET )
{
/* Look for the combination of all bits and substitute "All" for
* them. Ignore bits we don't know about.
* Note: RESOURCEUSAGE_ATTACHED is a no-op for us, since LanMan
* always tries to authenticate when doing an enumeration.
*/
dwUsage &= (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER);
if ( dwUsage == (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER) )
{
dwUsage = 0 ;
}
/*
* we are looking for global resources out on the net
*/
if (lpNetResource == NULL || lpNetResource->lpRemoteName == NULL)
{
/*
* at top level, therefore enumerating domains. if user
* asked for connectable, well, there aint none.
*/
if ( dwUsage == RESOURCEUSAGE_CONNECTABLE )
{
pNetEnum = new EMPTY_ENUMNODE( dwScope,
dwType,
dwUsage,
lpNetResource );
}
else
{
pNetEnum = new DOMAIN_ENUMNODE( dwScope,
dwType,
dwUsage,
lpNetResource );
}
}
else
{
/*
* we are assured of lpRemoteName != NULL.
* things get interesting here. the cases are as follows:
*
* if (dwUsage == 0)
* if have \\ in front
* return shares
* else
* return servers
* else if (dwUsage == CONNECTABLE)
* if have \\ in front
* return shares
* else
* empty enum
* else if (dwUsage == CONTAINER)
* if have \\ in front
* empty enum
* else
* return server
*
* In interest of code size, i've reorganized the above
* cases to minimized the bodies of the ifs.
*
* chuckc.
*/
if ( ((dwUsage == RESOURCEUSAGE_CONNECTABLE) ||
(dwUsage == 0)
)
&&
((lpNetResource->lpRemoteName[0] == TCH('\\')) &&
(lpNetResource->lpRemoteName[1] == TCH('\\'))
)
)
{
/* Confirm that this really is a computer name (i.e., a
* container we can enumerate).
*/
if ( ::I_MNetNameValidate( NULL,
&(lpNetResource->lpRemoteName[2]),
NAMETYPE_COMPUTER,
0L))
{
return WN_BAD_VALUE ;
}
pNetEnum = new SHARE_ENUMNODE( dwScope, dwType, dwUsage,
lpNetResource );
}
else if ( ((dwUsage == RESOURCEUSAGE_CONTAINER) ||
(dwUsage == 0)
)
&&
(lpNetResource->lpRemoteName[0] != TCH('\\'))
)
{
pNetEnum = new SERVER_ENUMNODE( dwScope, dwType, dwUsage,
lpNetResource );
}
else if (
// ask for share but aint starting from server
(
(dwUsage == RESOURCEUSAGE_CONNECTABLE)
&&
(lpNetResource->lpRemoteName[0] != TCH('\\'))
)
||
// ask for server but is starting from server
(
(dwUsage == RESOURCEUSAGE_CONTAINER)
&&
((lpNetResource->lpRemoteName[0] == TCH('\\')) &&
(lpNetResource->lpRemoteName[1] == TCH('\\'))
)
)
)
{
pNetEnum = new EMPTY_ENUMNODE( dwScope,
dwType,
dwUsage,
lpNetResource );
}
else
{
// incorrect dwUsage
return WN_BAD_VALUE;
}
}
}
else
{
// invalid dwScope
return WN_BAD_VALUE;
}
if ( pNetEnum == NULL )
{
return WN_OUT_OF_MEMORY;
}
else if ( err = pNetEnum->QueryError() )
{
delete pNetEnum;
return MapError(err);
}
if ( pNetEnum->IsFirstGetInfo() )
{
if (( err = pNetEnum->GetInfo()) != WN_SUCCESS )
{
delete pNetEnum;
return MapError(err);
}
}
////////////////////////////////////////// Enter critical section
if ( err = WNetEnterCriticalSection() )
{
delete pNetEnum;
return err ;
}
ASSERT( vpNetEnumArray != NULL );
INT iPos = vpNetEnumArray->QueryNextAvail();
if ( iPos < 0 )
{
WNetLeaveCriticalSection() ;
delete pNetEnum;
return WN_OUT_OF_MEMORY;
}
vpNetEnumArray->SetNode( (UINT)iPos, pNetEnum );
*lphEnum = UintToPtr((UINT)iPos);
WNetLeaveCriticalSection() ;
////////////////////////////////////////// Leave critical section
return err ;
}
/*******************************************************************
NAME: NPEnumResource
SYNOPSIS: Perform an enumeration based on handle returned by
NPOpenEnum.
ENTRY: HANDLE hEnum - This must be a handle obtained from
NPOpenEnum call
UINT *lpcRequested - Specifies the number of entries
requested. It may be 0xFFFFFFFF to request as many as
possible. On successful call, this location will receive
the number of entries actually read.
VOID *lpBuffer - A pointer to the buffer to receive the
enumeration result, which are returned as an array
of NETRESOURCE entries. The buffer is valid until
the next call using hEnum.
UINT * lpBufferSize - This specifies the size of the
buffer passed to the function call. If WN_MORE_DATA
is returned and no entries were enumerated, then this
will be set to the minimum buffer size required.
EXIT: UINT *lpcRequested - will receive the number of entries
actually read.
RETURNS: WN_SUCCESS if the call is successful, the caller should
continue to call NPEnumResource to continue the
enumeration.
WN_NO_MORE_ENTRIES - no more entries found, the
enumeration completed successfully ( the contents of the
return buffer is undefined). Otherwise, GetLastError
should be called for extended error information.
Extended error codes include:
WN_MORE_DATA - the buffer is too small even for one
entry
WN_BAD_HANDLE - hEnum is not a valid handle
WN_NOT_NETWORK - network is not present. This
condition is checked for before hEnum is tested for
validity.
WN_NET_ERROR - a network specific error occured.
WNetGetLastError should be called to obtain further
information.
HISTORY:
terryk 24-Oct-91 Created
KeithMo 15-Sep-92 Align *lpcBufferSize as needed.
********************************************************************/
DWORD APIENTRY
NPEnumResource(
HANDLE hEnum,
UINT * lpcRequested,
LPVOID lpBuffer,
UINT * lpcBufferSize )
{
APIERR err ;
if (( lpBuffer == NULL ) ||
( lpcRequested == NULL ) ||
( lpcBufferSize == NULL ))
{
return WN_BAD_VALUE;
}
if ( err = WNetEnterCriticalSection() )
{
return err ;
}
ASSERT( vpNetEnumArray != NULL );
NET_ENUMNODE *pNode = vpNetEnumArray->QueryNode(PtrToUint(hEnum));
WNetLeaveCriticalSection() ;
if ( pNode == NULL )
{
return WN_BAD_HANDLE;
}
else if ( pNode->IsFirstGetInfo() )
{
if ( err = CheckLMService() )
{
return err ;
}
if (( err = pNode->GetInfo()) != WN_SUCCESS )
{
return ( MapError(err) );
}
}
LPNETRESOURCE pNetResource = ( LPNETRESOURCE ) lpBuffer;
UINT cbRemainSize = ROUND_DOWN(*lpcBufferSize);
UINT cRequested = (*lpcRequested);
*lpcRequested = 0;
while ( *lpcRequested < cRequested )
{
err = pNode->GetNetResource((BYTE *)pNetResource, &cbRemainSize );
if ( err == WN_MORE_DATA )
{
/* If we can't even fit one into the buffer, then set the required
* buffer size and return WN_MORE_DATA.
*/
if ( *lpcRequested == 0 )
{
*lpcBufferSize = ROUND_UP(cbRemainSize);
}
else
{
err = NERR_Success ;
}
break;
}
if ( err == WN_NO_MORE_ENTRIES )
{
if ( *lpcRequested != 0 )
{
err = NERR_Success ;
}
break;
}
if ( err != WN_SUCCESS )
{
break ;
}
/* err == WN_SUCCESS
*/
(*lpcRequested) ++;
if ( sizeof( NETRESOURCE ) > cbRemainSize )
{
break ;
}
pNetResource ++;
cbRemainSize -= (UINT)sizeof( NETRESOURCE );
}
return err ;
}
/*******************************************************************
NAME: NPCloseEnum
SYNOPSIS: Closes an enumeration.
ENTRY: HANDLE hEnum - this must be a handle obtained from
NPOpenEnum call.
RETURNS: WN_SUCCESS if the call is successful. Otherwise,
GetLastError should be called for extended error information.
Extended error codes include:
WN_NO_NETWORK - network is not present. this condition is
checked for before hEnum is tested for validity.
WN_BAD_HANDLE - hEnum is not a valid handle.
WN_NET_ERROR - a network specific error occured.
WNetGetLastError should be called to obtain further
information.
HISTORY:
terryk 24-Oct-91 Created
********************************************************************/
DWORD APIENTRY
NPCloseEnum(
HANDLE hEnum )
{
APIERR err ;
if ( err = WNetEnterCriticalSection() )
{
return err ;
}
ASSERT( vpNetEnumArray != NULL );
NET_ENUMNODE *pNode = vpNetEnumArray->QueryNode(PtrToUint(hEnum));
if ( pNode == NULL )
{
// cannot find the node
err = WN_BAD_HANDLE;
}
else
{
vpNetEnumArray->ClearNode(PtrToUint(hEnum));
}
WNetLeaveCriticalSection() ;
return err ;
}
/*******************************************************************
NAME: WNetEnterCriticalSection
SYNOPSIS: Locks the LM network provider enumeration code
EXIT: vhSemaphore will be locked
RETURNS: NERR_Success if successful, error code otherwise
NOTES: We wait for 7 seconds for the semaphonre to be freed
HISTORY:
Johnl 27-Apr-1992 Created
********************************************************************/
APIERR WNetEnterCriticalSection( void )
{
APIERR err = NERR_Success ;
switch( WaitForSingleObject( vhSemaphore, 7000L ))
{
case 0:
break ;
case WAIT_TIMEOUT:
err = WN_FUNCTION_BUSY ;
break ;
case 0xFFFFFFFF:
err = ::GetLastError() ;
break ;
default:
UIASSERT(FALSE) ;
err = WN_WINDOWS_ERROR ;
break ;
}
return err ;
}
/*******************************************************************
NAME: WNetLeaveCriticalSection
SYNOPSIS: Unlocks the enumeration methods
RETURNS:
NOTES:
HISTORY:
Johnl 27-Apr-1992 Created
********************************************************************/
void WNetLeaveCriticalSection( void )
{
REQUIRE( ReleaseSemaphore( vhSemaphore, 1, NULL ) ) ;
}
| 32.43934 | 110 | 0.48081 | npocmaka |
16d785a0b0b6666fc3a2d9598d015c24478537ec | 5,375 | cc | C++ | tensorflow_serving/servables/caffe/caffe_session_bundle.cc | rayglover-ibm/serving-caffe | 7dfc79fe42c06397c22a371fe67913a29a27e625 | [
"Apache-2.0"
] | 48 | 2016-10-31T08:16:29.000Z | 2021-03-25T08:49:24.000Z | tensorflow_serving/servables/caffe/caffe_session_bundle.cc | rayglover-ibm/serving-caffe | 7dfc79fe42c06397c22a371fe67913a29a27e625 | [
"Apache-2.0"
] | 12 | 2016-06-14T16:35:51.000Z | 2019-03-13T14:08:34.000Z | tensorflow_serving/servables/caffe/caffe_session_bundle.cc | rayglover-ibm/serving-caffe | 7dfc79fe42c06397c22a371fe67913a29a27e625 | [
"Apache-2.0"
] | 18 | 2016-08-30T10:30:50.000Z | 2018-02-12T05:51:49.000Z | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
#include "caffe/util/upgrade_proto.hpp"
#if CUDA_VERSION >= 7050
#define EIGEN_HAS_CUDA_FP16
#endif
#include "tensorflow_serving/servables/caffe/caffe_session_bundle.h"
#include <string>
#include <utility>
#include <vector>
#include <memory>
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow_serving/servables/caffe/caffe_serving_session.h"
namespace tensorflow {
namespace serving {
namespace {
// Create a network using the given options and load the graph.
Status CreateSessionFromGraphDef(
const CaffeSessionOptions& options, const CaffeMetaGraphDef& graph,
std::unique_ptr<CaffeServingSession>* session) {
session->reset(new CaffeServingSession(graph, options));
return Status::OK();
}
Status GetClassLabelsFromExport(const StringPiece export_dir,
tensorflow::TensorProto* proto) {
const string labels_path =
tensorflow::io::JoinPath(export_dir, kGraphTxtLabelFilename);
// default state
proto->set_dtype(DT_INVALID);
TensorShape({}).AsProto(proto->mutable_tensor_shape());
if (Env::Default()->FileExists(labels_path).ok()) {
/* Load labels. */
std::unique_ptr<RandomAccessFile> file;
TF_RETURN_IF_ERROR(Env::Default()->NewRandomAccessFile(labels_path, &file));
{
const size_t kBufferSizeBytes = 8192;
io::InputBuffer in(file.get(), kBufferSizeBytes);
string line;
while (in.ReadLine(&line).ok()) {
proto->add_string_val(line);
}
}
proto->set_dtype(DT_STRING);
TensorShape({1, proto->string_val().size()})
.AsProto(proto->mutable_tensor_shape());
}
return Status::OK();
}
Status GetGraphDefFromExport(const StringPiece export_dir,
caffe::NetParameter* model_def) {
const string model_def_path =
tensorflow::io::JoinPath(export_dir, kGraphDefFilename);
if (!Env::Default()->FileExists(model_def_path).ok()) {
return errors::NotFound(
strings::StrCat("Caffe model does not exist: ", model_def_path));
} else if (!ReadProtoFromTextFile(model_def_path, model_def)) {
return errors::InvalidArgument(strings::StrCat(
"Caffe network failed to load from file: ", model_def_path));
} else if (!UpgradeNetAsNeeded(model_def_path, model_def)) {
return errors::InvalidArgument(
strings::StrCat("Network upgrade failed from while loading from file: ",
model_def_path));
}
model_def->mutable_state()->set_phase(caffe::TEST);
return Status::OK();
}
string GetVariablesFilename(const StringPiece export_dir) {
return tensorflow::io::JoinPath(export_dir, kVariablesFilename);
}
Status RunRestoreOp(const StringPiece export_dir,
CaffeServingSession* session) {
LOG(INFO) << "Running restore op for CaffeSessionBundle";
string weights_path = GetVariablesFilename(export_dir);
if (Env::Default()->FileExists(weights_path).ok()) {
return session->CopyTrainedLayersFromBinaryProto(weights_path);
} else {
return errors::NotFound(
strings::StrCat("Caffe weights file does not exist: ", weights_path));
}
}
} // namespace
tensorflow::Status LoadSessionBundleFromPath(const CaffeSessionOptions& options,
const StringPiece export_dir,
CaffeSessionBundle* bundle) {
LOG(INFO) << "Attempting to load a SessionBundle from: " << export_dir;
// load model prototxt
TF_RETURN_IF_ERROR(
GetGraphDefFromExport(export_dir, &(bundle->meta_graph_def.model_def)));
// load class labels
TF_RETURN_IF_ERROR(
GetClassLabelsFromExport(export_dir, &(bundle->meta_graph_def.classes)));
// resolve network inputs and outputs
TF_RETURN_IF_ERROR(::caffe::ResolveNetInsOuts(
bundle->meta_graph_def.model_def, bundle->meta_graph_def.resolved_inputs,
bundle->meta_graph_def.resolved_outputs));
// initialize network
std::unique_ptr<CaffeServingSession> caffe_session;
TF_RETURN_IF_ERROR(CreateSessionFromGraphDef(options, bundle->meta_graph_def,
&caffe_session));
// load weights
TF_RETURN_IF_ERROR(RunRestoreOp(export_dir, caffe_session.get()));
bundle->session.reset(caffe_session.release());
LOG(INFO) << "Done loading SessionBundle";
return Status::OK();
}
void CaffeGlobalInit(int* pargc, char*** pargv) {
caffe::GlobalInit(pargc, pargv);
}
} // namespace serving
} // namespace tensorflow
| 34.455128 | 80 | 0.700465 | rayglover-ibm |
16d7de132ae061d3a4c8d66292cf5f887b3f685d | 3,495 | cpp | C++ | arch/drisc/AncillaryRegisterFile.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 7 | 2016-03-01T13:16:59.000Z | 2021-08-20T07:41:43.000Z | arch/drisc/AncillaryRegisterFile.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | null | null | null | arch/drisc/AncillaryRegisterFile.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 5 | 2015-04-20T14:29:38.000Z | 2018-12-29T11:09:17.000Z | #include "AncillaryRegisterFile.h"
#include <sim/config.h>
#include <iomanip>
using namespace std;
namespace Simulator
{
namespace drisc
{
void AncillaryRegisterFile::Cmd_Info(std::ostream& out, const std::vector<std::string>& /*arguments*/) const
{
out << "The ancillary registers hold information common to all threads on a processor.\n";
}
void AncillaryRegisterFile::Cmd_Read(std::ostream& out, const std::vector<std::string>& /*arguments*/) const
{
out << " Register | Value" << endl
<< "----------+----------------------" << endl;
for (size_t i = 0; i < m_numRegisters; ++i)
{
Integer value = ReadRegister(i);
out << setw(9) << setfill(' ') << right << i << left
<< " | "
<< setw(16 - sizeof(Integer) * 2) << setfill(' ') << ""
<< setw( sizeof(Integer) * 2) << setfill('0') << hex << right << value << left
<< endl;
}
}
size_t AncillaryRegisterFile::GetSize() const
{
return m_numRegisters * sizeof(Integer);
}
Integer AncillaryRegisterFile::ReadRegister(ARAddr addr) const
{
if (addr >= m_numRegisters)
{
throw exceptf<InvalidArgumentException>(*this, "Invalid ancillary register number: %u", (unsigned)addr);
}
return m_registers[addr];
}
void AncillaryRegisterFile::WriteRegister(ARAddr addr, Integer data)
{
if (addr >= m_numRegisters)
{
throw exceptf<InvalidArgumentException>(*this, "Invalid ancillary register number: %u", (unsigned)addr);
}
m_registers[addr] = data;
}
Result AncillaryRegisterFile::Read (MemAddr addr, void* data, MemSize size, LFID /*fid*/, TID /*tid*/, const RegAddr& /*writeback*/)
{
if (addr % sizeof(Integer) != 0 || (size != sizeof(Integer)) || (addr > m_numRegisters * sizeof(Integer)))
throw exceptf<InvalidArgumentException>(*this, "Invalid read from ancillary register: %#016llx (%u)", (unsigned long long)addr, (unsigned)size);
ARAddr raddr = addr / sizeof(Integer);
Integer value = ReadRegister(raddr);
COMMIT{
SerializeRegister(RT_INTEGER, value, data, size);
}
return SUCCESS;
}
Result AncillaryRegisterFile::Write(MemAddr addr, const void *data, MemSize size, LFID /*fid*/, TID /*tid*/)
{
if (addr % sizeof(Integer) != 0 || (size != sizeof(Integer)) || (addr > m_numRegisters * sizeof(Integer)))
throw exceptf<InvalidArgumentException>(*this, "Invalid write to ancillary register: %#016llx (%u)", (unsigned long long)addr, (unsigned)size);
addr /= sizeof(Integer);
Integer value = UnserializeRegister(RT_INTEGER, data, size);
COMMIT{
WriteRegister(addr, value);
}
return SUCCESS;
}
AncillaryRegisterFile::AncillaryRegisterFile(const std::string& name, Object& parent)
: MMIOComponent(name, parent),
m_numRegisters(name == "aprs" ? GetConf("NumAncillaryRegisters", size_t) : NUM_ASRS),
m_registers()
{
if (m_numRegisters == 0)
{
throw InvalidArgumentException(*this, "NumAncillaryRegisters must be 1 or larger");
}
m_registers.resize(m_numRegisters, 0);
if (name == "asrs")
{
WriteRegister(ASR_SYSTEM_VERSION, ASR_SYSTEM_VERSION_VALUE);
}
}
}
}
| 33.932039 | 156 | 0.589413 | svp-dev |
16d8f0aff39b6f2da129ebe7fd78c2c0e7cc6ea9 | 502 | cpp | C++ | vnext/Microsoft.ReactNative/Views/PaperShadowNode.cpp | terrorizer1980/react-native-windows | f656ccde6064dcff187240ee37220cbe26c3708a | [
"MIT"
] | 9,106 | 2019-05-06T21:04:22.000Z | 2022-03-31T11:32:09.000Z | vnext/Microsoft.ReactNative/Views/PaperShadowNode.cpp | sjalim/react-native-windows | 04e766ef7304d0852a06e772cbfc1982897a3808 | [
"MIT"
] | 5,657 | 2019-05-06T21:11:29.000Z | 2022-03-31T22:11:58.000Z | vnext/Microsoft.ReactNative/Views/PaperShadowNode.cpp | sjalim/react-native-windows | 04e766ef7304d0852a06e772cbfc1982897a3808 | [
"MIT"
] | 727 | 2019-05-06T21:06:55.000Z | 2022-03-31T21:49:11.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "Views/PaperShadowNode.h"
namespace Microsoft::ReactNative {
ShadowNode::~ShadowNode() {}
void ShadowNode::dispatchCommand(
const std::string &commandId,
winrt::Microsoft::ReactNative::JSValueArray &&commandArgs) {}
void ShadowNode::onDropViewInstance() {}
void ShadowNode::updateProperties(winrt::Microsoft::ReactNative::JSValueObject &props) {}
} // namespace Microsoft::ReactNative
| 26.421053 | 90 | 0.731076 | terrorizer1980 |
16d989b03f8829b29b5e973e716ba08d4b59ff59 | 130 | cpp | C++ | dependencies/physx-4.1/source/geomutils/src/mesh/GuMeshQuery.cpp | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | dependencies/physx-4.1/source/geomutils/src/mesh/GuMeshQuery.cpp | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | dependencies/physx-4.1/source/geomutils/src/mesh/GuMeshQuery.cpp | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:b02719bdb687f6f2a0ec35ad50b06f79819681104750d72ed46969554055bd46
size 11165
| 32.5 | 75 | 0.884615 | realtehcman |
16da084f143d809d68cc50f25d7e61ca8e896f3e | 28 | cpp | C++ | run/Builder.cpp | hzx/run | ed8c77ab0aae7ab4d1362f48ccd22a7f36e2ddcc | [
"MIT"
] | null | null | null | run/Builder.cpp | hzx/run | ed8c77ab0aae7ab4d1362f48ccd22a7f36e2ddcc | [
"MIT"
] | null | null | null | run/Builder.cpp | hzx/run | ed8c77ab0aae7ab4d1362f48ccd22a7f36e2ddcc | [
"MIT"
] | null | null | null |
class Builder {
public:
};
| 5.6 | 15 | 0.642857 | hzx |
16dbd308625bbaefd7670bfd290af308b019cd3f | 721 | cpp | C++ | server/Common/Packets/GCLeaveScene.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Common/Packets/GCLeaveScene.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Common/Packets/GCLeaveScene.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z | #include "stdafx.h"
#include "GCLeaveScene.h"
BOOL GCLeaveScene::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_ObjID), sizeof(ObjID_t));
iStream.Read( (CHAR*)(&m_byLeaveCode), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GCLeaveScene::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_ObjID), sizeof(ObjID_t) ) ;
oStream.Write( (CHAR*)(&m_byLeaveCode), sizeof(BYTE) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GCLeaveScene::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GCLeaveSceneHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 16.767442 | 60 | 0.700416 | viticm |
16dd3f927778627cd5faedcaebc1c2b5b069b778 | 399 | cpp | C++ | CppImport/src/ClangFrontendActionFactory.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | CppImport/src/ClangFrontendActionFactory.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | CppImport/src/ClangFrontendActionFactory.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | #include "ClangFrontendActionFactory.h"
#include "TranslateFrontendAction.h"
#include "manager/TranslateManager.h"
namespace CppImport {
ClangFrontendActionFactory::ClangFrontendActionFactory(ClangAstVisitor* visitor, CppImportLogger* log)
: visitor_{visitor}, log_{log}
{}
clang::FrontendAction* ClangFrontendActionFactory::create()
{
return new TranslateFrontendAction(visitor_, log_);
}
}
| 21 | 102 | 0.809524 | patrick-luethi |
16dec42dd1a8804c5551a1d3a5ee68feda5cd6b7 | 3,790 | hpp | C++ | apps/constellation/settings.hpp | chr15murray/ledger | 85be05221f19598de8c6c58652139a1f2d9e362f | [
"Apache-2.0"
] | 1 | 2019-09-23T07:58:16.000Z | 2019-09-23T07:58:16.000Z | apps/constellation/settings.hpp | chr15murray/ledger | 85be05221f19598de8c6c58652139a1f2d9e362f | [
"Apache-2.0"
] | null | null | null | apps/constellation/settings.hpp | chr15murray/ledger | 85be05221f19598de8c6c58652139a1f2d9e362f | [
"Apache-2.0"
] | 1 | 2019-12-06T10:02:35.000Z | 2019-12-06T10:02:35.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "core/feature_flags.hpp"
#include "network/uri.hpp"
#include "settings/setting.hpp"
#include "settings/setting_collection.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace fetch {
/**
* Command line / Environment variable settings
*/
class Settings : private settings::SettingCollection
{
public:
using PeerList = std::vector<network::Uri>;
// Construction / Destruction
Settings();
Settings(Settings const &) = delete;
Settings(Settings &&) = delete;
~Settings() = default;
bool Update(int argc, char **argv);
/// @name High Level Network Settings
/// @{
settings::Setting<uint32_t> num_lanes;
settings::Setting<uint32_t> num_slices;
settings::Setting<uint32_t> block_interval;
/// @}
/// @name Network Mode
/// @{
settings::Setting<bool> standalone;
settings::Setting<bool> private_network;
/// @}
/// @name Standalone parameters
/// @{
settings::Setting<std::string> initial_address;
/// @}
/// @name Shards
/// @{
settings::Setting<std::string> db_prefix;
/// @}
/// @name Networking / P2P Manifest
/// @{
settings::Setting<uint16_t> port;
settings::Setting<PeerList> peers;
settings::Setting<std::string> external;
settings::Setting<std::string> config;
settings::Setting<uint32_t> max_peers;
settings::Setting<uint32_t> transient_peers;
settings::Setting<uint32_t> peer_update_interval;
settings::Setting<bool> disable_signing;
settings::Setting<bool> kademlia_routing;
/// @}
/// @name Bootstrap Config
/// @{
settings::Setting<bool> bootstrap;
settings::Setting<bool> discoverable;
settings::Setting<std::string> hostname;
settings::Setting<std::string> network_name;
settings::Setting<std::string> token;
/// @}
/// @name Threading Settings
/// @{
settings::Setting<uint32_t> num_processor_threads;
settings::Setting<uint32_t> num_verifier_threads;
settings::Setting<uint32_t> num_executors;
/// @}
/// @name Genesis File
/// @{
settings::Setting<std::string> genesis_file_location;
/// @}
/// @name Experimental
/// @{
settings::Setting<core::FeatureFlags> experimental_features;
/// @}
/// @name Proof of Stake
/// @{
settings::Setting<bool> proof_of_stake;
settings::Setting<uint64_t> max_cabinet_size;
settings::Setting<uint64_t> stake_delay_period;
settings::Setting<uint64_t> aeon_period;
/// @}
/// @name Error handling
/// @{
settings::Setting<bool> graceful_failure;
settings::Setting<bool> fault_tolerant;
/// @}
/// @name Agent support functionality
/// @{
settings::Setting<bool> enable_agents;
settings::Setting<uint16_t> messenger_port;
/// @}
// Operators
Settings &operator=(Settings const &) = delete;
Settings &operator=(Settings &&) = delete;
friend std::ostream &operator<<(std::ostream &stream, Settings const &settings);
private:
bool Validate();
};
} // namespace fetch
| 27.071429 | 82 | 0.648813 | chr15murray |
16e3d26ca33464a0d4d0996c433ace93dc93fc6f | 386 | hpp | C++ | src/singleton.hpp | TulioAbreu/game-project | 24367a8abe982a022354b0586f95d78f3d851c8d | [
"MIT"
] | null | null | null | src/singleton.hpp | TulioAbreu/game-project | 24367a8abe982a022354b0586f95d78f3d851c8d | [
"MIT"
] | 20 | 2020-04-26T12:09:56.000Z | 2020-09-25T23:30:12.000Z | src/singleton.hpp | TulioAbreu/game-project | 24367a8abe982a022354b0586f95d78f3d851c8d | [
"MIT"
] | null | null | null | #ifndef SINGLETON_HPP
#define SINGLETON_HPP
template <typename T>
class Singleton {
protected:
static T* mInstance;
Singleton() {}
public:
virtual ~Singleton() {
}
static T* getInstance() {
if (!mInstance) {
mInstance = new T();
}
return mInstance;
}
};
template <typename T>
T* Singleton<T>::mInstance = nullptr;
#endif | 14.846154 | 37 | 0.598446 | TulioAbreu |
16e47215b684537f73a94d6b21173d6927967319 | 25,494 | hpp | C++ | stf-inc/stf_buffered_reader.hpp | sparcians/stf_lib | 9e4933bff0c956dba464ced72e311e73507342dc | [
"MIT"
] | 1 | 2022-02-17T00:48:44.000Z | 2022-02-17T00:48:44.000Z | stf-inc/stf_buffered_reader.hpp | sparcians/stf_lib | 9e4933bff0c956dba464ced72e311e73507342dc | [
"MIT"
] | null | null | null | stf-inc/stf_buffered_reader.hpp | sparcians/stf_lib | 9e4933bff0c956dba464ced72e311e73507342dc | [
"MIT"
] | null | null | null | /**
* \brief This file defines a buffered STF trace reader class
*
*/
#ifndef __STF_BUFFERED_READER_HPP__
#define __STF_BUFFERED_READER_HPP__
#include <sys/stat.h>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include "stf_enums.hpp"
#include "stf_exception.hpp"
#include "stf_item.hpp"
#include "stf_reader.hpp"
#include "stf_record.hpp"
#include "stf_record_pointers.hpp"
#include "stf_record_types.hpp"
/**
* \namespace stf
* \brief Defines all STF related classes
*
*/
namespace stf {
/**
* \class STFBufferedReader
* \brief The STFBufferedReader provides an iterator to a buffered stream of objects constructed from a trace
*/
template<typename ItemType, typename FilterType, typename ReaderType>
class STFBufferedReader: public STFReader {
protected:
/**
* \typedef IntDescriptor
* \brief Internal descriptor type
*/
using IntDescriptor = descriptors::internal::Descriptor;
static constexpr size_t DEFAULT_BUFFER_SIZE_ = 1024; /**< Default buffer size */
const size_t buffer_size_; /**< Size of the buffer */
const size_t buffer_mask_; /**< Mask value used to index into the buffer */
bool last_item_read_ = false; /**< If true, we have read to the end of the trace */
/**
* \typedef BufferT
* \brief Underlying buffer type
*/
using BufferT = ItemType[]; // NOLINT: Use C-array here so we can use [] operator on the unique_ptr
std::unique_ptr<BufferT> buf_; /**< Circular buffer */
size_t head_; /**< index of head of current item in circular buffer */
size_t tail_; /**< index of tail of current item in circular buffer */
size_t num_items_read_ = 0; /**< Counts number of items read from the buffer */
bool buffer_is_empty_ = true; /**< True if the buffer contains no items */
size_t num_skipped_items_ = 0; /**< Counts number of skipped items so that item indices can be adjusted */
FilterType filter_; /**< Filter type used to skip over certain record types */
/**
* Default skipped_ method
* \param item Item to check for skipping
*/
__attribute__((always_inline))
static inline bool skipped_(const ItemType& item) {
return false;
}
/**
* Checks whether an item should be skipped. Delegates the check to subclass if it defines a skipped_ method.
* \param item Item to check for skipping
*/
__attribute__((always_inline))
inline bool itemSkipped_(const ItemType& item) const {
return ReaderType::skipped_(item);
}
/**
* Increments the skipped item counter
* \param skip_item If true, increment skipped item counter
*/
__attribute__((always_inline))
inline void countSkipped_(const bool skip_item) {
num_skipped_items_ += skip_item;
}
/**
* Default item skipping cleanup callback. Does nothing.
*/
__attribute__((always_inline))
inline void skippedCleanup_() {
}
/**
* Invokes subclass callback to clean up any addtional state when an item is skipped
*/
__attribute__((always_inline))
inline void skippedItemCleanup_() {
static_cast<ReaderType*>(this)->skippedCleanup_();
}
/**
* Initializes the internal buffer
*/
bool initItemBuffer_() {
buf_ = std::make_unique<BufferT>(static_cast<size_t>(buffer_size_));
size_t i = 0;
while(i < buffer_size_) {
try {
readNextItem_(buf_[i]);
if(STF_EXPECT_FALSE(itemSkipped_(buf_[i]))) {
skippedItemCleanup_();
continue;
}
}
catch(const EOFException&) {
last_item_read_ = true;
break;
}
++tail_;
++i;
}
// no items in the file;
if (STF_EXPECT_FALSE(tail_ == 0)) {
buffer_is_empty_ = true;
return false;
}
buffer_is_empty_ = false;
--tail_; // Make tail_ point to the last item read instead of one past the last item
head_ = 0;
return true;
}
/**
* Internal function to validate item by index to prevent buffer under/overrun
* \param index Index value to check
*/
__attribute__((always_inline))
inline void validateItemIndex_(const uint64_t index) const {
const auto& tail = buf_[tail_];
stf_assert(index >= buf_[head_].index() && (itemSkipped_(tail) || index <= tail.index()),
"sliding window index out of range");
}
/**
* Gets item based on index and buffer location
* \param index Index of item (used only for validation)
* \param loc Location of item within the buffer
*/
__attribute__((always_inline))
inline const ItemType* getItem_(const uint64_t index, const size_t loc) const {
validateItemIndex_(index);
return &buf_[loc];
}
/**
* Gets item based on index and buffer location
* \param index Index of item (used only for validation)
* \param loc Location of item within the buffer
*/
__attribute__((always_inline))
inline ItemType* getItem_(const uint64_t index, const size_t loc) {
validateItemIndex_(index);
return &buf_[loc];
}
/**
* Checks if the specified item is the last one in the trace
* \param index Index of item (used only for validation)
* \param loc Location of item within the buffer
*/
inline bool isLastItem_(const uint64_t index, const size_t loc) {
validateItemIndex_(index);
if(STF_EXPECT_TRUE(!last_item_read_)) {
return false;
}
return loc == tail_;
}
/**
* Returns whether the reader decided to skip the specified item. Can be overridden by a subclass.
* \param index Item index
* \param loc Item buffer location
*/
__attribute__((always_inline))
inline bool readerSkipCallback_(uint64_t& index, size_t& loc) const {
return false;
}
/**
* Calls the subclass implementation of readerSkipCallback_
* \param index Item index
* \param loc Item buffer location
*/
__attribute__((always_inline))
inline bool callReaderSkipCallback_(uint64_t& index, size_t& loc) const {
return static_cast<const ReaderType*>(this)->readerSkipCallback_(index, loc);
}
/**
* Helper function for item iteration. The function does the following work;
* - refill the circular buffer if iterates to 2nd last item in the buffer;
* - handle buffer location crossing boundary;
* - pair the item index and buffer location;
* \param index Item index
* \param loc Item buffer location
*/
__attribute__((always_inline))
inline bool moveToNextItem_(uint64_t &index, size_t &loc) {
bool skip_item = false;
do {
// validate the item index;
validateItemIndex_(index);
// if current location is the 2nd last item in buffer;
// refill the half of the buffer;
if (STF_EXPECT_FALSE(loc == tail_ -1)) {
fillHalfBuffer_();
}
// since 2nd last is used for refill;
// the tail is absolute the end of trace;
if (STF_EXPECT_FALSE(loc == tail_)) {
return false;
}
index++;
loc = (loc + 1) & buffer_mask_;
// Check to see if the subclass decided to skip this item
skip_item = callReaderSkipCallback_(index, loc);
}
while(skip_item);
num_items_read_ = index;
return true;
}
/**
* Returns the number of items read so far without filtering
*/
__attribute__((always_inline))
inline size_t rawNumItemsRead_() const {
return static_cast<const ReaderType*>(this)->rawNumRead_();
}
/**
* Returns the number of items read from the reader so far with filtering
*/
__attribute__((always_inline))
inline size_t numItemsReadFromReader_() const {
return rawNumItemsRead_() - num_skipped_items_;
}
/**
* Initializes item index
*/
__attribute__((always_inline))
inline void initItemIndex_(ItemType& item) const {
delegates::STFItemDelegate::setIndex_(item, numItemsReadFromReader_());
}
/**
* Returns the number of items read from the buffer so far with filtering
*/
inline size_t numItemsRead_() const {
return num_items_read_;
}
/**
* Fill item into the half of the circular buffer;
*/
size_t fillHalfBuffer_() {
size_t pos = tail_;
const size_t init_item_cnt = numItemsReadFromReader_();
const size_t max_item_cnt = init_item_cnt + (buffer_size_ / 2);
while(numItemsReadFromReader_() < max_item_cnt) {
pos = (pos + 1) & buffer_mask_;
try {
readNextItem_(buf_[pos]);
if(STF_EXPECT_FALSE(itemSkipped_(buf_[pos]))) {
skippedItemCleanup_();
pos = (pos - 1) & buffer_mask_;
}
}
catch(const EOFException&) {
last_item_read_ = true;
break;
}
}
const size_t item_cnt = numItemsReadFromReader_() - init_item_cnt;
// adjust head and tail;
if (STF_EXPECT_TRUE(item_cnt != 0)) {
tail_ = (tail_ + item_cnt) & buffer_mask_;
head_ = (head_ + item_cnt) & buffer_mask_;
}
return item_cnt;
}
/**
* read STF records to construct a ItemType instance. readNext_ must be implemented by subclass
* \param item Item to modify with the record
*/
__attribute__((hot, always_inline))
inline void readNextItem_(ItemType &item) {
static_cast<ReaderType*>(this)->readNext_(item);
}
/**
* Calls handleNewRecord_ callback in subclass
* \param item Item to modify
* \param urec Record used to modify item
*/
__attribute__((hot, always_inline))
inline const STFRecord* handleNewItemRecord_(ItemType& item, STFRecord::UniqueHandle&& urec) {
return static_cast<ReaderType*>(this)->handleNewRecord_(item, std::move(urec));
}
/**
* \brief Read the next STF record, optionally using it to modify the specified item
* \param item Item to modify
* \return pointer to record if it is valid; otherwise nullptr
*/
__attribute__((hot, always_inline))
inline const STFRecord* readRecord_(ItemType& item) {
STFRecord::UniqueHandle urec;
operator>>(urec);
if(STF_EXPECT_FALSE(filter_.isFiltered(urec->getDescriptor()))) {
return nullptr;
}
return handleNewItemRecord_(item, std::move(urec));
}
/**
* Gets the index of the first item in the buffer
*/
inline uint64_t getFirstIndex_() {
return buf_[head_].index();
}
/**
* Returns whether the subclass thinks we should seek the slow way
*/
inline bool slowSeek_() const {
return false;
}
/**
* Returns whether we should seek the slow way
*/
inline bool slowItemSeek_() const {
return static_cast<const ReaderType*>(this)->slowSeek_();
}
/**
* \class base_iterator
* \brief iterator of the item stream that hides the sliding window.
* Decrement is not implemented. Rewinding is done by copying or assigning
* an existing iterator, with range limited by the sliding window size.
*
* Using the iterator ++ operator may advance the underlying trace stream,
* which is un-rewindable if the trace is compressed or via STDIN
*
*/
class base_iterator {
friend class STFBufferedReader;
private:
STFBufferedReader *sir_ = nullptr; // the reader
uint64_t index_ = 1; // index to the item stream
size_t loc_ = 0; // location in the sliding window buffer;
// keep it to speed up casting;
bool end_ = true; // whether this is an end iterator
protected:
/**
* \brief whether pointing to the last item
* \return true if last item
*/
inline bool isLastItem_() const {
return sir_->isLastItem_(index_, loc_);
}
public:
/**
* \typedef difference_type
* Type used for finding difference between two iterators
*/
using difference_type = std::ptrdiff_t;
/**
* \typedef value_type
* Type pointed to by this iterator
*/
using value_type = ItemType;
/**
* \typedef pointer
* Pointer to a value_type
*/
using pointer = const ItemType*;
/**
* \typedef reference
* Reference to a value_type
*/
using reference = const value_type&;
/**
* \typedef iterator_category
* Iterator type - using forward_iterator_tag because backwards iteration is not currently supported
*/
using iterator_category = std::forward_iterator_tag;
/**
* \brief Default constructor
*
*/
base_iterator() = default;
/**
* \brief Constructor
* \param sir The STF reader to iterate
* \param end Whether this is an end iterator
*
*/
explicit base_iterator(STFBufferedReader *sir, const bool end = false) :
sir_(sir),
end_(end)
{
if(!end) {
if (!sir_->buf_) {
if(!sir_->initItemBuffer_()) {
end_ = true;
}
loc_ = 0;
}
else {
end_ = sir_->buffer_is_empty_;
}
index_ = sir_->getFirstIndex_();
}
}
/**
* \brief Copy constructor
* \param rv The existing iterator to copy from
*
*/
base_iterator(const base_iterator & rv) = default;
/**
* \brief Assignment operator
* \param rv The existing iterator to copy from
*
*/
base_iterator & operator=(const base_iterator& rv) = default;
/**
* \brief Pre-increment operator
*/
__attribute__((always_inline))
inline base_iterator & operator++() {
stf_assert(!end_, "Can't increment the end iterator");
// index_ and loc_ are increased in moveToNextItem_;
if(STF_EXPECT_FALSE(!sir_->moveToNextItem_(index_, loc_))) {
end_ = true;
}
return *this;
}
/**
* \brief Post-increment operator
*/
__attribute__((always_inline))
inline base_iterator operator++(int) {
auto temp = *this;
operator++();
return temp;
}
/**
* \brief Return the ItemType pointer the iterator points to
*/
inline pointer current() const {
if (STF_EXPECT_FALSE(end_)) {
return nullptr;
}
return sir_->getItem_(index_, loc_);
}
/**
* \brief Returns whether the iterator is still valid
*/
inline bool valid() const {
try {
// Try to get a valid pointer
return current();
}
catch(const STFException&) {
// The item is outside the current window, so it's invalid
return false;
}
}
/**
* \brief Return the ItemType pointer the iterator points to
*/
inline const value_type& operator*() const { return *current(); }
/**
* \brief Return the ItemType pointer the iterator points to
*/
inline pointer operator->() const { return current(); }
/**
* \brief The equal operator to check ending
* \param rv The iterator to compare with
*/
inline bool operator==(const base_iterator& rv) const {
if (end_ || rv.end_) {
return end_ && rv.end_;
}
return index_ == rv.index_;
}
/**
* \brief The unequal operator to check ending
* \param rv The iterator to compare with
*/
inline bool operator!=(const base_iterator& rv) const {
return !operator==(rv);
}
};
public:
/**
* \brief Constructor
* \param buffer_size The size of the buffer sliding window
*/
explicit STFBufferedReader(const size_t buffer_size = DEFAULT_BUFFER_SIZE_) :
buffer_size_(buffer_size),
buffer_mask_(buffer_size_ - 1)
{
// Does NOT call open() automatically! Must be handled by derived classes.
}
/**
* \brief The beginning of the item stream
*
*/
template<typename U = ReaderType>
inline typename U::iterator begin() { return typename U::iterator(static_cast<U*>(this)); }
/**
* \brief The beginning of the item stream
* \param skip Skip this many items at the beginning
*
*/
template<typename U = ReaderType>
inline typename U::iterator begin(const size_t skip) {
if(skip) {
return seekFromBeginning(skip);
}
return typename U::iterator(static_cast<U*>(this));
}
/**
* \brief The end of the item stream
*
*/
template<typename U = ReaderType>
inline const typename U::iterator& end() {
static const auto end_it = typename U::iterator(static_cast<U*>(this), true);
return end_it;
}
/**
* \brief Opens a file
* \param filename The trace file name
* \param force_single_threaded_stream If true, forces single threaded mode in reader
*/
void open(const std::string_view filename,
const bool force_single_threaded_stream = false) {
STFReader::open(filename, force_single_threaded_stream);
buf_.reset();
head_ = 0;
tail_ = 0;
}
/**
* \brief Closes the file
*/
int close() {
buf_.reset();
head_ = 0;
tail_ = 0;
return STFReader::close();
}
/**
* Seeks the reader by the specified number of items and returns an iterator to that point
* \note Intended for seeking the reader prior to reading any items. For seeking in a reader that
* has already been iterated over, use the seek() method.
* \param num_items Number of items to skip
*/
template<typename U = ReaderType>
inline typename U::iterator seekFromBeginning(const size_t num_items) {
auto it = begin();
seek(it, num_items);
return it;
}
/**
* \brief Seeks an iterator by the given number of items
* \param it Iterator to seek
* \param num_items Number of items to seek by
*/
template<typename U = ReaderType>
inline void seek(typename U::iterator& it, const size_t num_items) {
const size_t num_buffered = tail_ - it.loc_ + 1;
// If the items are already buffered or skipping mode is enabled,
// we have to seek the slow way
if(slowItemSeek_() || num_items <= num_buffered) {
const auto end_it = end();
for(size_t i = 0; i < num_items && it != end_it; ++i) {
++it;
}
}
else {
// We don't need to seek the reader past items we've already read
const size_t num_to_skip = num_items - num_buffered;
STFReader::seek(num_to_skip);
head_ = 0;
tail_ = 0;
initItemBuffer_();
it = begin();
}
}
/**
* Returns the number of records read so far
*/
inline size_t numRecordsRead() const {
return STFReader::numRecordsRead();
}
/**
* Gets the filter object for this reader
*/
FilterType& getFilter() {
return filter_;
}
};
} //end namespace stf
// __STF_INST_READER_HPP__
#endif
| 37.491176 | 121 | 0.467169 | sparcians |
16e5c3adc2b7f9f761b415edb4a098df465cd777 | 5,463 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dswapchainwithswdc.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 5,937 | 2018-12-04T16:32:50.000Z | 2022-03-31T09:48:37.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dswapchainwithswdc.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 4,151 | 2018-12-04T16:38:19.000Z | 2022-03-31T18:41:14.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dswapchainwithswdc.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 1,084 | 2018-12-04T16:24:21.000Z | 2022-03-30T13:52:03.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
//
//
// Description:
// Contains CD3DSwapChainWithSwDC implementation
//
// This class overrides the GetDC method of CD3DSwapChain to implement
// GetDC using GetRenderTargetData. This approach acheived phenominal perf
// wins in WDDM.
//
#include "precomp.hpp"
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::CD3DSwapChainWithSwDC
//
// Synopsis:
// ctor
//
#pragma warning( push )
#pragma warning( disable : 4355 )
CD3DSwapChainWithSwDC::CD3DSwapChainWithSwDC(
__in HDC hdcPresentVia,
__in_range(>, 0) /*__out_range(==, this->m_cBackBuffers)*/ UINT cBackBuffers,
__inout_ecount(1) IDirect3DSwapChain9 *pD3DSwapChain
) : CD3DSwapChain(
pD3DSwapChain,
cBackBuffers,
reinterpret_cast<CD3DSurface **>(reinterpret_cast<BYTE *>(this) + sizeof(*this))
),
m_hdcCopiedBackBuffer(hdcPresentVia),
m_hbmpCopiedBackBuffer(NULL),
m_pBuffer(NULL)
{
}
#pragma warning( pop )
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::~CD3DSwapChainWithSwDC
//
// Synopsis:
// dtor
//
CD3DSwapChainWithSwDC::~CD3DSwapChainWithSwDC()
{
if (m_hdcCopiedBackBuffer)
{
DeleteDC(m_hdcCopiedBackBuffer);
}
if (m_hbmpCopiedBackBuffer)
{
DeleteObject(m_hbmpCopiedBackBuffer);
}
}
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::Init
//
// Synopsis:
// Inits the swap chain and creates the sysmem present surface
//
//-----------------------------------------------------------------------------
HRESULT
CD3DSwapChainWithSwDC::Init(
__inout_ecount(1) CD3DResourceManager *pResourceManager
)
{
HRESULT hr = S_OK;
// The base class must be initialized first
IFC(CD3DSwapChain::Init(pResourceManager));
Assert(m_cBackBuffers >= 1);
D3DSURFACE_DESC const &surfDesc = m_rgBackBuffers[0]->Desc();
// We don't handle anything else yet
Assert( surfDesc.Format == D3DFMT_A8R8G8B8
|| surfDesc.Format == D3DFMT_X8R8G8B8
);
BITMAPINFO bmi;
bmi.bmiHeader.biSize = sizeof(bmi);
bmi.bmiHeader.biWidth = surfDesc.Width;
bmi.bmiHeader.biHeight = -INT(surfDesc.Height);
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
bmi.bmiHeader.biXPelsPerMeter = 10000;
bmi.bmiHeader.biYPelsPerMeter = 10000;
bmi.bmiHeader.biClrUsed = 0;
bmi.bmiHeader.biClrImportant = 0;
IFCW32_CHECKOOH(GR_GDIOBJECTS, m_hbmpCopiedBackBuffer = CreateDIBSection(
m_hdcCopiedBackBuffer,
&bmi,
DIB_RGB_COLORS,
&m_pBuffer,
NULL,
0
));
MilPixelFormat::Enum milFormat = D3DFormatToPixelFormat(surfDesc.Format, TRUE);
IFC(HrCalcDWordAlignedScanlineStride(surfDesc.Width, milFormat, OUT m_stride));
IFC(HrGetRequiredBufferSize(
milFormat,
m_stride,
surfDesc.Width,
surfDesc.Height,
&m_cbBuffer));
IFCW32(SelectObject(
m_hdcCopiedBackBuffer,
m_hbmpCopiedBackBuffer
));
Cleanup:
RRETURN(hr);
}
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::GetDC
//
// Synopsis:
// Gets a DC that refers to a system memory bitmap.
//
// The system memory bitmap is updated during this call. The dirty rect is
// used to determine how much of it needs updating.
//
HRESULT
CD3DSwapChainWithSwDC::GetDC(
/*__in_range(<, this->m_cBackBuffers)*/ UINT iBackBuffer,
__in_ecount(1) const CMilRectU& rcDirty,
__deref_out HDC *phdcBackBuffer
) const
{
HRESULT hr = S_OK;
ENTER_USE_CONTEXT_FOR_SCOPE(Device());
Assert(iBackBuffer < m_cBackBuffers);
D3DSURFACE_DESC const &surfDesc = m_rgBackBuffers[iBackBuffer]->Desc();
UINT cbBufferInset =
m_stride * rcDirty.top
+ D3DFormatSize(surfDesc.Format) * rcDirty.left;
BYTE *pbBuffer = reinterpret_cast<BYTE*>(m_pBuffer) + cbBufferInset;
IFC(m_rgBackBuffers[iBackBuffer]->ReadIntoSysMemBuffer(
rcDirty,
0,
NULL,
D3DFormatToPixelFormat(surfDesc.Format, TRUE),
m_stride,
DBG_ANALYSIS_PARAM_COMMA(m_cbBuffer - cbBufferInset)
pbBuffer
));
*phdcBackBuffer = m_hdcCopiedBackBuffer;
Cleanup:
RRETURN(hr);
}
//+----------------------------------------------------------------------------
//
// Member:
// CD3DSwapChainWithSwDC::ReleaseDC
//
// Synopsis:
// Releases the DC returned by GetDC if necessary
//
HRESULT
CD3DSwapChainWithSwDC::ReleaseDC(
/*__in_range(<, this->m_cBackBuffers)*/ UINT iBackBuffer,
__in HDC hdcBackBuffer
) const
{
//
// Do nothing- GetDC just hands out the DC so release is not necessary.
//
UNREFERENCED_PARAMETER(iBackBuffer);
UNREFERENCED_PARAMETER(hdcBackBuffer);
return S_OK;
}
| 25.059633 | 92 | 0.601135 | txlos |
16e686c5373e5cd8974ef03a3f5f01e9ec49ac66 | 741 | cpp | C++ | test/nmea/Test_nmea_waypoint.cpp | mfkiwl/marnav | 53a1c987bf72d48df134c12dd1edc44d7f230921 | [
"BSD-4-Clause"
] | 62 | 2015-07-20T03:24:21.000Z | 2022-03-30T10:39:24.000Z | test/nmea/Test_nmea_waypoint.cpp | mfkiwl/marnav | 53a1c987bf72d48df134c12dd1edc44d7f230921 | [
"BSD-4-Clause"
] | 37 | 2016-03-30T05:38:32.000Z | 2021-12-26T18:11:38.000Z | test/nmea/Test_nmea_waypoint.cpp | mfkiwl/marnav | 53a1c987bf72d48df134c12dd1edc44d7f230921 | [
"BSD-4-Clause"
] | 39 | 2015-07-20T03:15:44.000Z | 2022-02-03T07:32:23.000Z | #include <marnav/nmea/waypoint.hpp>
#include <gtest/gtest.h>
namespace
{
using namespace marnav;
class Test_nmea_waypoint : public ::testing::Test
{
};
TEST_F(Test_nmea_waypoint, default_construction)
{
nmea::waypoint wp;
EXPECT_EQ(0u, wp.size());
EXPECT_TRUE(wp.empty());
EXPECT_STREQ("", wp.c_str());
}
TEST_F(Test_nmea_waypoint, normal_construction)
{
nmea::waypoint wp{"abc"};
EXPECT_STREQ("abc", wp.get().c_str());
}
TEST_F(Test_nmea_waypoint, construction_too_large_string)
{
EXPECT_ANY_THROW(nmea::waypoint{"123456789"});
}
TEST_F(Test_nmea_waypoint, size)
{
nmea::waypoint wp{"ABC"};
EXPECT_EQ(3u, wp.size());
}
TEST_F(Test_nmea_waypoint, c_str)
{
nmea::waypoint wp{"ABC"};
EXPECT_STREQ("ABC", wp.c_str());
}
}
| 15.765957 | 57 | 0.717949 | mfkiwl |
16e9059bdf585407db664ea77fbda7455c25e826 | 10,327 | cc | C++ | ash/common/devtools/ash_devtools_dom_agent.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | ash/common/devtools/ash_devtools_dom_agent.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/common/devtools/ash_devtools_dom_agent.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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 "ash/common/devtools/ash_devtools_dom_agent.h"
#include "ash/common/wm_lookup.h"
#include "ash/common/wm_window.h"
#include "components/ui_devtools/devtools_server.h"
namespace ash {
namespace devtools {
namespace {
using namespace ui::devtools::protocol;
DOM::NodeId node_ids = 1;
std::unique_ptr<DOM::Node> BuildNode(
const std::string& name,
std::unique_ptr<Array<std::string>> attributes,
std::unique_ptr<Array<DOM::Node>> children) {
constexpr int kDomElementNodeType = 1;
std::unique_ptr<DOM::Node> node = DOM::Node::create()
.setNodeId(node_ids++)
.setNodeName(name)
.setNodeType(kDomElementNodeType)
.setAttributes(std::move(attributes))
.build();
node->setChildNodeCount(children->length());
node->setChildren(std::move(children));
return node;
}
std::unique_ptr<Array<std::string>> GetAttributes(const ash::WmWindow* window) {
std::unique_ptr<Array<std::string>> attributes = Array<std::string>::create();
attributes->addItem("name");
attributes->addItem(window->GetName());
attributes->addItem("active");
attributes->addItem(window->IsActive() ? "true" : "false");
return attributes;
}
std::unique_ptr<Array<std::string>> GetAttributes(const views::Widget* widget) {
std::unique_ptr<Array<std::string>> attributes = Array<std::string>::create();
attributes->addItem("name");
attributes->addItem(widget->GetName());
attributes->addItem("active");
attributes->addItem(widget->IsActive() ? "true" : "false");
return attributes;
}
std::unique_ptr<Array<std::string>> GetAttributes(const views::View* view) {
std::unique_ptr<Array<std::string>> attributes = Array<std::string>::create();
attributes->addItem("name");
attributes->addItem(view->GetClassName());
return attributes;
}
WmWindow* FindPreviousSibling(WmWindow* window) {
std::vector<WmWindow*> siblings = window->GetParent()->GetChildren();
std::vector<WmWindow*>::iterator it =
std::find(siblings.begin(), siblings.end(), window);
DCHECK(it != siblings.end());
// If this is the first child of its parent, the previous sibling is null
return it == siblings.begin() ? nullptr : *std::prev(it);
}
} // namespace
AshDevToolsDOMAgent::AshDevToolsDOMAgent(ash::WmShell* shell) : shell_(shell) {
DCHECK(shell_);
}
AshDevToolsDOMAgent::~AshDevToolsDOMAgent() {
RemoveObserverFromAllWindows();
}
ui::devtools::protocol::Response AshDevToolsDOMAgent::disable() {
Reset();
return ui::devtools::protocol::Response::OK();
}
ui::devtools::protocol::Response AshDevToolsDOMAgent::getDocument(
std::unique_ptr<ui::devtools::protocol::DOM::Node>* out_root) {
*out_root = BuildInitialTree();
return ui::devtools::protocol::Response::OK();
}
// Handles removing windows.
void AshDevToolsDOMAgent::OnWindowTreeChanging(WmWindow* window,
const TreeChangeParams& params) {
// Only trigger this when window == params.old_parent.
// Only removals are handled here. Removing a node can occur as a result of
// reorganizing a window or just destroying it. OnWindowTreeChanged
// is only called if there is a new_parent. The only case this method isn't
// called is when adding a node because old_parent is then null.
// Finally, We only trigger this 0 or 1 times as an old_parent will
// either exist and only call this callback once, or not at all.
if (window == params.old_parent)
RemoveWindowNode(params.target);
}
// Handles adding windows.
void AshDevToolsDOMAgent::OnWindowTreeChanged(WmWindow* window,
const TreeChangeParams& params) {
// Only trigger this when window == params.new_parent.
// If there is an old_parent + new_parent, then this window's node was
// removed in OnWindowTreeChanging and will now be added to the new_parent.
// If there is only a new_parent, OnWindowTreeChanging is never called and
// the window is only added here.
if (window == params.new_parent)
AddWindowNode(params.target);
}
void AshDevToolsDOMAgent::OnWindowStackingChanged(WmWindow* window) {
RemoveWindowNode(window);
AddWindowNode(window);
}
WmWindow* AshDevToolsDOMAgent::GetWindowFromNodeId(int nodeId) {
return node_id_to_window_map_.count(nodeId) ? node_id_to_window_map_[nodeId]
: nullptr;
}
views::Widget* AshDevToolsDOMAgent::GetWidgetFromNodeId(int nodeId) {
return node_id_to_widget_map_.count(nodeId) ? node_id_to_widget_map_[nodeId]
: nullptr;
}
views::View* AshDevToolsDOMAgent::GetViewFromNodeId(int nodeId) {
return node_id_to_view_map_.count(nodeId) ? node_id_to_view_map_[nodeId]
: nullptr;
}
int AshDevToolsDOMAgent::GetNodeIdFromWindow(WmWindow* window) {
DCHECK(window_to_node_id_map_.count(window));
return window_to_node_id_map_[window];
}
int AshDevToolsDOMAgent::GetNodeIdFromWidget(views::Widget* widget) {
DCHECK(widget_to_node_id_map_.count(widget));
return widget_to_node_id_map_[widget];
}
int AshDevToolsDOMAgent::GetNodeIdFromView(views::View* view) {
DCHECK(view_to_node_id_map_.count(view));
return view_to_node_id_map_[view];
}
std::unique_ptr<DOM::Node> AshDevToolsDOMAgent::BuildTreeForView(
views::View* view) {
std::unique_ptr<Array<DOM::Node>> children = Array<DOM::Node>::create();
for (int i = 0, count = view->child_count(); i < count; i++) {
children->addItem(BuildTreeForView(view->child_at(i)));
}
std::unique_ptr<ui::devtools::protocol::DOM::Node> node =
BuildNode("View", GetAttributes(view), std::move(children));
view_to_node_id_map_[view] = node->getNodeId();
node_id_to_view_map_[node->getNodeId()] = view;
return node;
}
std::unique_ptr<DOM::Node> AshDevToolsDOMAgent::BuildTreeForRootWidget(
views::Widget* widget) {
std::unique_ptr<Array<DOM::Node>> children = Array<DOM::Node>::create();
children->addItem(BuildTreeForView(widget->GetRootView()));
std::unique_ptr<ui::devtools::protocol::DOM::Node> node =
BuildNode("Widget", GetAttributes(widget), std::move(children));
widget_to_node_id_map_[widget] = node->getNodeId();
node_id_to_widget_map_[node->getNodeId()] = widget;
return node;
}
std::unique_ptr<DOM::Node> AshDevToolsDOMAgent::BuildTreeForWindow(
ash::WmWindow* window) {
std::unique_ptr<Array<DOM::Node>> children = Array<DOM::Node>::create();
views::Widget* widget = window->GetInternalWidget();
if (widget)
children->addItem(BuildTreeForRootWidget(widget));
for (ash::WmWindow* child : window->GetChildren()) {
children->addItem(BuildTreeForWindow(child));
}
std::unique_ptr<ui::devtools::protocol::DOM::Node> node =
BuildNode("Window", GetAttributes(window), std::move(children));
// Only add as observer if window is not in map
if (!window_to_node_id_map_.count(window))
window->AddObserver(this);
window_to_node_id_map_[window] = node->getNodeId();
node_id_to_window_map_[node->getNodeId()] = window;
return node;
}
std::unique_ptr<ui::devtools::protocol::DOM::Node>
AshDevToolsDOMAgent::BuildInitialTree() {
std::unique_ptr<Array<DOM::Node>> children = Array<DOM::Node>::create();
for (ash::WmWindow* window : shell_->GetAllRootWindows()) {
children->addItem(BuildTreeForWindow(window));
}
return BuildNode("root", nullptr, std::move(children));
}
void AshDevToolsDOMAgent::AddWindowNode(WmWindow* window) {
DCHECK(window_to_node_id_map_.count(window->GetParent()));
WmWindow* prev_sibling = FindPreviousSibling(window);
frontend()->childNodeInserted(
window_to_node_id_map_[window->GetParent()],
prev_sibling ? window_to_node_id_map_[prev_sibling] : 0,
BuildTreeForWindow(window));
}
void AshDevToolsDOMAgent::RemoveWindowNode(WmWindow* window) {
WmWindow* parent = window->GetParent();
DCHECK(parent);
WindowToNodeIdMap::iterator window_to_node_id_it =
window_to_node_id_map_.find(window);
DCHECK(window_to_node_id_it != window_to_node_id_map_.end());
int node_id = window_to_node_id_it->second;
int parent_id = GetNodeIdFromWindow(parent);
NodeIdToWindowMap::iterator node_id_to_window_it =
node_id_to_window_map_.find(node_id);
DCHECK(node_id_to_window_it != node_id_to_window_map_.end());
views::Widget* widget = window->GetInternalWidget();
if (widget)
RemoveWidgetNode(widget);
window->RemoveObserver(this);
node_id_to_window_map_.erase(node_id_to_window_it);
window_to_node_id_map_.erase(window_to_node_id_it);
frontend()->childNodeRemoved(parent_id, node_id);
}
void AshDevToolsDOMAgent::RemoveWidgetNode(views::Widget* widget) {
WidgetToNodeIdMap::iterator widget_to_node_id_it =
widget_to_node_id_map_.find(widget);
DCHECK(widget_to_node_id_it != widget_to_node_id_map_.end());
int node_id = widget_to_node_id_it->second;
int parent_id =
GetNodeIdFromWindow(WmLookup::Get()->GetWindowForWidget(widget));
RemoveViewNode(widget->GetRootView());
NodeIdToWidgetMap::iterator node_id_to_widget_it =
node_id_to_widget_map_.find(node_id);
DCHECK(node_id_to_widget_it != node_id_to_widget_map_.end());
widget_to_node_id_map_.erase(widget_to_node_id_it);
node_id_to_widget_map_.erase(node_id_to_widget_it);
frontend()->childNodeRemoved(parent_id, node_id);
}
void AshDevToolsDOMAgent::RemoveViewNode(views::View* view) {
// TODO(mhashmi): Add observers to views/widgets so new views exist
// in the map and can be removed here
}
void AshDevToolsDOMAgent::RemoveObserverFromAllWindows() {
for (auto& pair : window_to_node_id_map_)
pair.first->RemoveObserver(this);
}
void AshDevToolsDOMAgent::Reset() {
RemoveObserverFromAllWindows();
window_to_node_id_map_.clear();
widget_to_node_id_map_.clear();
view_to_node_id_map_.clear();
node_id_to_window_map_.clear();
node_id_to_widget_map_.clear();
node_id_to_view_map_.clear();
node_ids = 1;
}
} // namespace devtools
} // namespace ash
| 37.014337 | 80 | 0.714535 | xzhan96 |
16e9faef1b0f81f6d70040eb863b7ffe84e61718 | 347 | cpp | C++ | OOP/stuclass.cpp | PranavDherange/Data_Structures | 9962b5145f6b42d9317e2c328c2b3124f028ca70 | [
"MIT"
] | 2 | 2021-02-25T11:54:50.000Z | 2021-02-25T11:54:54.000Z | OOP/stuclass.cpp | PranavDherange/Data_Structures | 9962b5145f6b42d9317e2c328c2b3124f028ca70 | [
"MIT"
] | null | null | null | OOP/stuclass.cpp | PranavDherange/Data_Structures | 9962b5145f6b42d9317e2c328c2b3124f028ca70 | [
"MIT"
] | 1 | 2021-10-03T17:39:10.000Z | 2021-10-03T17:39:10.000Z | #include <bits/stdc++.h>
using namespace std;
#include "Studentclass.cpp"
int main()
{
char name[] = "abcd";
Student s1(20, name);
s1.display();
Student s2(s1);
s2.name[0] = 'x';
s2.display();
s1.display();
// name[3] = 'e';
// Student s2(24, name);
// s2.display();
// s1.display();
return 0;
} | 15.772727 | 28 | 0.521614 | PranavDherange |
16ead209c586f2e074f1d4422af59ed6684e6b06 | 12,201 | cc | C++ | src/expression/typechecking.cc | pictavien/tchecker | 5db2430b5b75a5b94cfbbe885840a4809b267be8 | [
"MIT"
] | null | null | null | src/expression/typechecking.cc | pictavien/tchecker | 5db2430b5b75a5b94cfbbe885840a4809b267be8 | [
"MIT"
] | null | null | null | src/expression/typechecking.cc | pictavien/tchecker | 5db2430b5b75a5b94cfbbe885840a4809b267be8 | [
"MIT"
] | null | null | null | /*
* This file is a part of the TChecker project.
*
* See files AUTHORS and LICENSE for copyright details.
*
*/
#include <tuple>
#include "tchecker/expression/type_inference.hh"
#include "tchecker/expression/typechecking.hh"
namespace tchecker {
namespace details {
/*!
\class expression_typechecker_t
\brief Expression typechecking visitor
*/
class expression_typechecker_t : public tchecker::expression_visitor_t {
public:
/*!
\brief Constructor
\param intvars : integer variables
\param clocks : clock variables
\param log : logging facility
*/
expression_typechecker_t(tchecker::integer_variables_t const & intvars,
tchecker::clock_variables_t const & clocks,
std::function<void(std::string const &)> error)
: _typed_expr(nullptr),
_intvars(intvars),
_clocks(clocks),
_error(error)
{}
/*!
\brief Copy constructor (DELETED)
*/
expression_typechecker_t(tchecker::details::expression_typechecker_t const &) = delete;
/*!
\brief Move constructor (DELETED)
*/
expression_typechecker_t(tchecker::details::expression_typechecker_t &&) = delete;
/*!
\brief Destructor
*/
virtual ~expression_typechecker_t()
{
delete _typed_expr;
}
/*!
\brief Assignment operator (DELETED)
*/
tchecker::details::expression_typechecker_t & operator= (tchecker::details::expression_typechecker_t const &) = delete;
/*!
\brief Move assignment operator (DELETED)
*/
tchecker::details::expression_typechecker_t & operator= (tchecker::details::expression_typechecker_t &&) = delete;
/*!
\brief Accessor
\return typed expression computed by this visitor
\note the expression is released by the call, and should be handled by the
caller
*/
tchecker::typed_expression_t * release()
{
auto p = _typed_expr;
_typed_expr = nullptr;
return p;
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::int_expression_t const & expr)
{
_typed_expr = new tchecker::typed_int_expression_t(tchecker::EXPR_TYPE_INTTERM, expr.value());
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::var_expression_t const & expr)
{
// variable type, id and size
auto type_id_size = typecheck_variable(expr.name());
enum tchecker::expression_type_t const type = std::get<0>(type_id_size);
tchecker::variable_id_t const id = std::get<1>(type_id_size);
tchecker::variable_size_t const size = std::get<2>(type_id_size);
// bounded integer variable
if ((type == tchecker::EXPR_TYPE_INTVAR) || (type == tchecker::EXPR_TYPE_INTARRAY)) {
auto const & infos = _intvars.info(id);
_typed_expr = new tchecker::typed_bounded_var_expression_t(type, expr.name(), id, size, infos.min(), infos.max());
}
// clock variable
else if ((type == tchecker::EXPR_TYPE_CLKVAR) || (type == tchecker::EXPR_TYPE_CLKARRAY))
_typed_expr = new tchecker::typed_var_expression_t(type, expr.name(), id, size);
// otherwise (BAD)
else
_typed_expr = new tchecker::typed_var_expression_t(tchecker::EXPR_TYPE_BAD, expr.name(), id, size);
if (type == tchecker::EXPR_TYPE_BAD)
_error("in expression " + expr.to_string() + ", undeclared variable");
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
\note array expression on variables of size 1 are well typed
\note out-of-bounds access are not checked
*/
virtual void visit(tchecker::array_expression_t const & expr)
{
// Typecheck variable
expr.variable().visit(*this);
auto const * const typed_variable = dynamic_cast<tchecker::typed_var_expression_t const *>(this->release());
auto const variable_type = typed_variable->type();
// Typecheck offset
expr.offset().visit(*this);
auto const * const typed_offset = this->release();
auto const offset_type = typed_offset->type();
// Typed expression
enum tchecker::expression_type_t expr_type;
if (integer_dereference(variable_type) && integer_valued(offset_type))
expr_type = tchecker::EXPR_TYPE_INTLVALUE;
else if (clock_dereference(variable_type) && integer_valued(offset_type))
expr_type = tchecker::EXPR_TYPE_CLKLVALUE;
else
expr_type = tchecker::EXPR_TYPE_BAD;
_typed_expr = new tchecker::typed_array_expression_t(expr_type, typed_variable, typed_offset);
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if (offset_type != tchecker::EXPR_TYPE_BAD) {
if (! integer_valued(offset_type))
_error("in expression " + expr.to_string() +
", array subscript " + expr.offset().to_string() +
" does not have an integral value");
else
_error("in expression " + expr.to_string() +
", invalid array variable " + expr.variable().to_string());
}
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::par_expression_t const & expr)
{
// Sub expression
expr.expr().visit(*this);
tchecker::typed_expression_t * typed_sub_expr = this->release();
// Typed expression
enum tchecker::expression_type_t expr_type = type_par(typed_sub_expr->type());
_typed_expr = new tchecker::typed_par_expression_t(expr_type, typed_sub_expr);
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if (typed_sub_expr->type() != tchecker::EXPR_TYPE_BAD)
_error("in expression " + expr.to_string() + ", invalid parentheses around " + expr.expr().to_string());
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::binary_expression_t const & expr)
{
// Operands
expr.left_operand().visit(*this);
tchecker::typed_expression_t * typed_left_operand = this->release();
expr.right_operand().visit(*this);
tchecker::typed_expression_t * typed_right_operand = this->release();
// Typed expression
enum tchecker::expression_type_t expr_type = type_binary(expr.binary_operator(), typed_left_operand->type(),
typed_right_operand->type());
switch (expr_type) {
case tchecker::EXPR_TYPE_CLKCONSTR_SIMPLE:
_typed_expr = new tchecker::typed_simple_clkconstr_expression_t(expr_type, expr.binary_operator(), typed_left_operand,
typed_right_operand);
break;
case tchecker::EXPR_TYPE_CLKCONSTR_DIAGONAL:
_typed_expr = new tchecker::typed_diagonal_clkconstr_expression_t(expr_type, expr.binary_operator(), typed_left_operand,
typed_right_operand);
break;
default: // either EXPR_TYPE_ATOMIC_PREDICATE or EXPR_TYPE_BAD
_typed_expr = new tchecker::typed_binary_expression_t(expr_type, expr.binary_operator(), typed_left_operand,
typed_right_operand);
break;
}
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if ((typed_left_operand->type() != tchecker::EXPR_TYPE_BAD) && (typed_right_operand->type() != tchecker::EXPR_TYPE_BAD))
_error("in expression " + expr.to_string() + ", invalid composition of expressions " + expr.left_operand().to_string() +
" and " + expr.right_operand().to_string());
}
/*!
\brief Visitor
\param expr : expression
\post _typed_expr points to a typed clone of expr
*/
virtual void visit(tchecker::unary_expression_t const & expr)
{
// Operand
expr.operand().visit(*this);
tchecker::typed_expression_t * typed_operand = this->release();
// Typed expression
enum tchecker::expression_type_t expr_type = type_unary(expr.unary_operator(), typed_operand->type());
_typed_expr = new tchecker::typed_unary_expression_t(expr_type, expr.unary_operator(), typed_operand);
// Report bad type
if (expr_type != tchecker::EXPR_TYPE_BAD)
return;
if (typed_operand->type() != tchecker::EXPR_TYPE_BAD)
_error("in expression " + expr.to_string() + ", invalid operand " + expr.operand().to_string());
}
protected:
/*!
\brief Accessor
\param name : variable name
\return tchecker::EXPR_TYPE_INTARRAY if name is an array of integer
variables,
tchecker::EXPR_TYPE_INTVAR if name is an integer variable of size 1,
tchecker::EXPR_TYPE_CLKARRAY if name is an array of clock variables,
tchecker::EXPR_TYPE_CLKVAR if name is a clock variable of size 1
tchecker::EXPR_TYPE_BAD otherwise (name is not a declared variable)
\pre name is a declared integer or clock variable
*/
std::tuple<enum tchecker::expression_type_t, tchecker::variable_id_t, tchecker::variable_size_t>
typecheck_variable(std::string const & name)
{
// Integer variable ?
try {
auto id = _intvars.id(name);
auto size = _intvars.info(id).size();
if (size > 1)
return std::make_tuple(tchecker::EXPR_TYPE_INTARRAY, id, size);
else
return std::make_tuple(tchecker::EXPR_TYPE_INTVAR, id, size);
}
catch (...)
{}
// Clock variable ?
try {
auto id = _clocks.id(name);
auto size = _clocks.info(id).size();
if (size > 1)
return std::make_tuple(tchecker::EXPR_TYPE_CLKARRAY, id, size);
else
return std::make_tuple(tchecker::EXPR_TYPE_CLKVAR, id, size);
}
catch (...)
{}
// Not a variable name
return std::make_tuple(tchecker::EXPR_TYPE_BAD, std::numeric_limits<tchecker::variable_id_t>::max(), 1);
}
tchecker::typed_expression_t * _typed_expr; /*!< Typed expression */
tchecker::integer_variables_t const & _intvars; /*!< Integer variables */
tchecker::clock_variables_t const & _clocks; /*!< Clock variables */
std::function<void(std::string const &)> _error; /*!< Error logging func */
};
} // end of namespace details
tchecker::typed_expression_t * typecheck(tchecker::expression_t const & expr,
tchecker::integer_variables_t const & intvars,
tchecker::clock_variables_t const & clocks,
std::function<void(std::string const &)> error)
{
tchecker::details::expression_typechecker_t v(intvars, clocks, error);
expr.visit(v);
return v.release();
}
} // end of namespace tchecker
| 36.861027 | 132 | 0.58823 | pictavien |
16edb80f7661e00b275c94644380bfaf2f291740 | 318 | cpp | C++ | smb2/cpp/GUI/Wrapper/Controls/ctrackbar.cpp | loginsinex/smb2 | fd1347e8d730edd092df19a3d388684944016522 | [
"MIT"
] | 8 | 2018-02-23T20:39:02.000Z | 2022-02-14T23:57:36.000Z | smb2/cpp/GUI/Wrapper/Controls/ctrackbar.cpp | loginsinex/smb2 | fd1347e8d730edd092df19a3d388684944016522 | [
"MIT"
] | 1 | 2020-02-25T22:57:44.000Z | 2020-02-27T02:07:17.000Z | smb2/cpp/GUI/Wrapper/Controls/ctrackbar.cpp | loginsinex/smb2 | fd1347e8d730edd092df19a3d388684944016522 | [
"MIT"
] | 1 | 2017-06-08T00:56:42.000Z | 2017-06-08T00:56:42.000Z |
#include "precomp.h"
VOID CTrackBar::SetMinMax(UINT min, UINT max)
{
cSendMessage(TBM_SETRANGEMIN, TRUE, min);
cSendMessage(TBM_SETRANGEMAX, TRUE, max);
}
VOID CTrackBar::Pos(UINT uPos)
{
cSendMessage(TBM_SETPOS, TRUE, uPos);
}
UINT CTrackBar::Pos()
{
return (UINT) cSendMessage(TBM_GETPOS);
} | 17.666667 | 46 | 0.694969 | loginsinex |
16ef060d11c261a958069e8da8881267b134d95c | 1,412 | cpp | C++ | src/m581expT.cpp | CardinalModules/TheXOR | 910b76622c9100d9755309adf76542237c6d3a77 | [
"CC0-1.0"
] | 1 | 2021-12-12T22:08:23.000Z | 2021-12-12T22:08:23.000Z | src/m581expT.cpp | CardinalModules/TheXOR | 910b76622c9100d9755309adf76542237c6d3a77 | [
"CC0-1.0"
] | null | null | null | src/m581expT.cpp | CardinalModules/TheXOR | 910b76622c9100d9755309adf76542237c6d3a77 | [
"CC0-1.0"
] | 1 | 2021-12-12T22:08:29.000Z | 2021-12-12T22:08:29.000Z | #include "../include/m581expT.hpp"
void m581expT::process(const ProcessArgs &args)
{
int curStp = getStep();
if(curStp >= 0)
{
float v = params[Z8PULSE_TIME].getValue();
if(curStp != prevStep)
{
pulses[curStp].trigger(v/1000.f);
prevStep=curStp;
}
}
float deltaTime = 1.0 / args.sampleRate;
// 1 = in process; -1 = terminato; 0 = no operation
for(int k = 0; k < 16; k++)
{
int c = pulses[k].process(deltaTime);
if(c == 1)
outputs[OUT_1 + k].setVoltage(LVL_ON);
else if(c == -1)
outputs[OUT_1 + k].setVoltage(LVL_OFF);
}
}
m581expTWidget::m581expTWidget(m581expT *module)
{
CREATE_PANEL(module, this, 18, "res/modules/m581expT.svg");
if(module != NULL)
module->createWidget(this);
addParam(createParam<Davies1900hFixRedKnobSmall>(Vec(mm2px(79.067), yncscape(9.058, 8.0)), module, m581expT::Z8PULSE_TIME));
float dist_h = 14.52 - 3.559;
float dist_v = 97.737 - 86.980;
float y = 23.016;
float dled = 10.064 - 3.559;
float dledY = 102.571 - 97.737;
for (int c = 0; c < 8; c++)
{
for(int r = 0; r < 8; r++)
{
int n = c * 8 + r;
int posx = 3.559 + dist_h * c;
addOutput(createOutput<portBLUSmall>(Vec(mm2px(posx), yncscape(y + dist_v * r, 5.885)), module, m581expT::OUT_1 + n));
if(module != NULL)
addChild(createLight<TinyLight<RedLight>>(Vec(mm2px(dled + posx), yncscape(y + dledY + dist_v * r, 1.088)), module, module->ledID(n)));
}
}
}
| 25.672727 | 139 | 0.634561 | CardinalModules |
16efa27a12f51ec1eaac9620496887e857ae7aba | 612 | hpp | C++ | mod/memlite/src/interface/instancer.hpp | kniz/worldlang | 78701ab003c158211d42d129f91259d17febbb22 | [
"MIT"
] | 7 | 2019-03-12T03:04:32.000Z | 2021-12-26T04:33:44.000Z | mod/memlite/src/interface/instancer.hpp | kniz/worldlang | 78701ab003c158211d42d129f91259d17febbb22 | [
"MIT"
] | 7 | 2019-02-13T14:01:43.000Z | 2020-11-20T11:09:06.000Z | mod/memlite/src/interface/instancer.hpp | kniz/worldlang | 78701ab003c158211d42d129f91259d17febbb22 | [
"MIT"
] | null | null | null | #pragma once
#include "../pool/pool.hpp"
#include "../watcher/watcher.hpp"
namespace wrd {
class instancer {
WRD_DECL_ME(instancer)
WRD_INIT_META(me)
friend class instance;
public:
wbool bind(const instance& new1);
wbool rel(const instance& old);
const pool& getPool() const;
const watcher& getWatcher() const;
static WRD_SINGLETON_GETTER(me)
private:
void* _new1(size_t sz);
void _del(void* pt, wcnt sz);
wbool _hasBindTag(const instance& it) const;
pool _pool;
watcher _watcher;
};
}
| 21.103448 | 52 | 0.601307 | kniz |
16f095a49d917c5f723009ffd6c4ef8f7f0004d7 | 11,690 | cpp | C++ | include/re/input/joystick_input.cpp | Chukobyte/learn-engine-dev | 3f4437ed4abab9011d584bdc0ab4eff921393f00 | [
"CC-BY-4.0",
"CC0-1.0"
] | 5 | 2021-08-13T01:53:59.000Z | 2022-01-23T18:50:17.000Z | include/re/input/joystick_input.cpp | Chukobyte/learn-engine-dev | 3f4437ed4abab9011d584bdc0ab4eff921393f00 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | include/re/input/joystick_input.cpp | Chukobyte/learn-engine-dev | 3f4437ed4abab9011d584bdc0ab4eff921393f00 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | #include "joystick_input.h"
JoystickInput::JoystickInput() : logger(Logger::GetInstance()) {}
JoystickInput::~JoystickInput() {
SDL_JoystickClose(joystickController);
SDL_GameControllerClose(gameController);
}
void JoystickInput::ProcessButtonPress(InputEvent &inputEvent) {
const std::string &buttonValue = JOYSTICK_BUTTON_TYPE_TO_NAME_MAP[(JoystickButtonType) inputEvent.buttonValue];
JOYSTICK_BUTTON_INPUT_FLAGS[buttonValue].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[buttonValue].isJustPressed = true;
}
void JoystickInput::ProcessButtonRelease(InputEvent &inputEvent) {
const std::string &buttonValue = JOYSTICK_BUTTON_TYPE_TO_NAME_MAP[(JoystickButtonType) inputEvent.buttonValue];
JOYSTICK_BUTTON_INPUT_FLAGS[buttonValue].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[buttonValue].isJustReleased = true;
}
void JoystickInput::ProcessJoyhatMotion(InputEvent &inputEvent) {
if (inputEvent.hatValue & SDL_HAT_LEFT) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_LEFT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_LEFT].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_LEFT].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_LEFT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_LEFT].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_LEFT].isJustReleased = true;
}
}
if (inputEvent.hatValue & SDL_HAT_RIGHT) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_RIGHT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_RIGHT].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_RIGHT].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_RIGHT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_RIGHT].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_RIGHT].isJustReleased = true;
}
}
if (inputEvent.hatValue & SDL_HAT_UP) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_UP].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_UP].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_UP].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_UP].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_UP].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_UP].isJustReleased = true;
}
}
if (inputEvent.hatValue & SDL_HAT_DOWN) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_DOWN].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_DOWN].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_DOWN].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_DOWN].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_DOWN].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_KEYPAD_DOWN].isJustReleased = true;
}
}
}
void JoystickInput::ProcessAxisMotion() {
// LEFT AXIS
// Horizontal
Sint16 leftHorizontalValue = SDL_JoystickGetAxis(joystickController, (Uint8) JoystickAxisMotion::LEFT_HORIZONTAL_AXIS);
if (leftHorizontalValue < -(Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_LEFT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_LEFT].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_LEFT].isJustPressed = true;
}
} else if (leftHorizontalValue > (Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_RIGHT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_RIGHT].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_RIGHT].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_LEFT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_LEFT].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_LEFT].isJustReleased = true;
}
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_RIGHT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_RIGHT].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_RIGHT].isJustReleased = true;
}
}
// Vertical
Sint16 leftVerticalValue = SDL_JoystickGetAxis(joystickController, (Uint8) JoystickAxisMotion::LEFT_VERTICAL_AXIS);
if (leftVerticalValue < -(Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_UP].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_UP].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_UP].isJustPressed = true;
}
} else if (leftVerticalValue > (Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_DOWN].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_DOWN].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_DOWN].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_UP].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_UP].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_UP].isJustReleased = true;
}
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_DOWN].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_DOWN].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_ANALOG_DOWN].isJustReleased = true;
}
}
// RIGHT AXIS
// Horizontal
Sint16 rightHorizontalValue = SDL_JoystickGetAxis(joystickController, (Uint8) JoystickAxisMotion::RIGHT_HORIZONTAL_AXIS);
if (rightHorizontalValue < -(Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_LEFT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_LEFT].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_LEFT].isJustPressed = true;
}
} else if (rightHorizontalValue > (Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_RIGHT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_RIGHT].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_RIGHT].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_LEFT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_LEFT].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_LEFT].isJustReleased = true;
}
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_RIGHT].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_RIGHT].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_RIGHT].isJustReleased = true;
}
}
// Vertical
Sint16 rightVerticalValue = SDL_JoystickGetAxis(joystickController, (Uint8) JoystickAxisMotion::RIGHT_VERTICAL_AXIS);
if (rightVerticalValue < -(Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_UP].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_UP].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_UP].isJustPressed = true;
}
} else if (rightVerticalValue > (Uint8) JoystickDeadZone::AXIS) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_DOWN].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_DOWN].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_DOWN].isJustPressed = true;
}
} else {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_UP].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_UP].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_UP].isJustReleased = true;
}
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_DOWN].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_DOWN].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_ANALOG_DOWN].isJustReleased = true;
}
}
// Left Trigger
Sint16 leftTriggerValue = SDL_JoystickGetAxis(joystickController, (Uint8) JoystickAxisMotion::LEFT_TRIGGER);
if (leftTriggerValue < -(Uint8) JoystickDeadZone::TRIGGER) {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_TRIGGER].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_TRIGGER].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_TRIGGER].isJustReleased = true;
}
} else if (leftTriggerValue > (Uint8) JoystickDeadZone::TRIGGER) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_TRIGGER].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_TRIGGER].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_LEFT_TRIGGER].isJustPressed = true;
}
}
// Right Trigger
Sint16 rightTriggerValue = SDL_JoystickGetAxis(joystickController, (Uint8) JoystickAxisMotion::RIGHT_TRIGGER);
if (rightTriggerValue < -(Uint8) JoystickDeadZone::TRIGGER) {
if (JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_TRIGGER].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_TRIGGER].isPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_TRIGGER].isJustReleased = true;
}
} else if (rightTriggerValue > (Uint8) JoystickDeadZone::TRIGGER) {
if (!JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_TRIGGER].isPressed) {
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_TRIGGER].isPressed = true;
JOYSTICK_BUTTON_INPUT_FLAGS[JOYSTICK_RIGHT_TRIGGER].isJustPressed = true;
}
}
}
JoystickInput* JoystickInput::GetInstance() {
static JoystickInput *instance = new JoystickInput();
return instance;
}
void JoystickInput::ProcessSDLEvent(InputEvent &inputEvent) {}
void JoystickInput::LoadJoysticks() {
int result = SDL_GameControllerAddMappingsFromFile("assets/resources/game_controller_db.txt");
assert(result != -1 && "Failed to load game controller db text file!");
if (SDL_NumJoysticks() > 0) {
joystickController = SDL_JoystickOpen(0);
assert(joystickController != nullptr && "JoystickController didn't properly load!");
gameController = SDL_GameControllerOpen(0);
assert(gameController != nullptr && "GameController didn't properly load!");
} else {
logger->Warn("No joystick plugged in, not loading joysticks!");
}
}
void JoystickInput::ClearInputFlags() {
for (const auto &pair : JOYSTICK_BUTTON_INPUT_FLAGS) {
JOYSTICK_BUTTON_INPUT_FLAGS[pair.first].isJustPressed = false;
JOYSTICK_BUTTON_INPUT_FLAGS[pair.first].isJustReleased = false;
}
}
bool JoystickInput::IsJoystickValue(const std::string &value) const {
return false;
}
bool JoystickInput::IsActionPressed(const std::string &value) {
return false;
}
bool JoystickInput::IsActionJustPressed(const std::string &value) {
return false;
}
bool JoystickInput::IsActionJustReleased(const std::string &value) {
return false;
}
| 50.387931 | 125 | 0.735672 | Chukobyte |
16f0cd1949c0c93b84ebe4ce1972566fcd01344e | 5,134 | hpp | C++ | stan/math/opencl/kernel_generator/select.hpp | kedartal/math | 77248cf73c1110660006c9700f78d9bb7c02be1d | [
"BSD-3-Clause"
] | null | null | null | stan/math/opencl/kernel_generator/select.hpp | kedartal/math | 77248cf73c1110660006c9700f78d9bb7c02be1d | [
"BSD-3-Clause"
] | null | null | null | stan/math/opencl/kernel_generator/select.hpp | kedartal/math | 77248cf73c1110660006c9700f78d9bb7c02be1d | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/as_operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/is_valid_expression.hpp>
#include <stan/math/opencl/kernel_generator/common_return_scalar.hpp>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
namespace stan {
namespace math {
/**
* Represents a selection operation in kernel generator expressions. This is
* element wise ternary operator <code>condition ? then : els</code>, also
* equivalent to Eigen's \c .select().
* @tparam Derived derived type
* @tparam T_condition type of condition
* @tparam T_then type of then expression
* @tparam T_else type of else expression
*/
template <typename T_condition, typename T_then, typename T_else>
class select_ : public operation_cl<select_<T_condition, T_then, T_else>,
common_scalar_t<T_then, T_else>,
T_condition, T_then, T_else> {
public:
using Scalar = common_scalar_t<T_then, T_else>;
using base = operation_cl<select_<T_condition, T_then, T_else>, Scalar,
T_condition, T_then, T_else>;
using base::var_name;
protected:
using base::arguments_;
public:
/**
* Constructor
* @param condition condition expression
* @param then then expression
* @param els else expression
*/
select_(T_condition&& condition, T_then&& then, T_else&& els) // NOLINT
: base(std::forward<T_condition>(condition), std::forward<T_then>(then),
std::forward<T_else>(els)) {
if (condition.rows() != base::dynamic && then.rows() != base::dynamic) {
check_size_match("select", "Rows of ", "condition", condition.rows(),
"rows of ", "then", then.rows());
}
if (condition.cols() != base::dynamic && then.cols() != base::dynamic) {
check_size_match("select", "Columns of ", "condition", condition.cols(),
"columns of ", "then", then.cols());
}
if (condition.rows() != base::dynamic && els.rows() != base::dynamic) {
check_size_match("select", "Rows of ", "condition", condition.rows(),
"rows of ", "else", els.rows());
}
if (condition.cols() != base::dynamic && els.cols() != base::dynamic) {
check_size_match("select", "Columns of ", "condition", condition.cols(),
"columns of ", "else", els.cols());
}
}
/**
* generates kernel code for this (select) operation.
* @param i row index variable name
* @param j column index variable name
* @param var_name_condition variable name of the condition expression
* @param var_name_else variable name of the then expression
* @param var_name_then variable name of the else expression
* @return part of kernel with code for this expression
*/
inline kernel_parts generate(const std::string& i, const std::string& j,
const std::string& var_name_condition,
const std::string& var_name_then,
const std::string& var_name_else) const {
kernel_parts res{};
res.body = type_str<Scalar>() + " " + var_name + " = " + var_name_condition
+ " ? " + var_name_then + " : " + var_name_else + ";\n";
return res;
}
/**
* View of a matrix that would be the result of evaluating this expression.
* @return view
*/
inline matrix_cl_view view() const {
matrix_cl_view condition_view = std::get<0>(arguments_).view();
matrix_cl_view then_view = std::get<1>(arguments_).view();
matrix_cl_view else_view = std::get<2>(arguments_).view();
return both(either(then_view, else_view), both(condition_view, then_view));
}
};
/**
* Selection operation on kernel generator expressions. This is element wise
* ternary operator <code> condition ? then : els </code>.
* @tparam T_condition type of condition expression
* @tparam T_then type of then expression
* @tparam T_else type of else expression
* @param condition condition expression
* @param then then expression
* @param els else expression
* @return selection operation expression
*/
template <typename T_condition, typename T_then, typename T_else,
typename
= require_all_valid_expressions_t<T_condition, T_then, T_else>>
inline select_<as_operation_cl_t<T_condition>, as_operation_cl_t<T_then>,
as_operation_cl_t<T_else>>
select(T_condition&& condition, T_then&& then, T_else&& els) { // NOLINT
return {as_operation_cl(std::forward<T_condition>(condition)),
as_operation_cl(std::forward<T_then>(then)),
as_operation_cl(std::forward<T_else>(els))};
}
} // namespace math
} // namespace stan
#endif
#endif
| 39.79845 | 79 | 0.668679 | kedartal |
16f23bb4e00852d5112a4b9b4fe9b892a39c7bdc | 6,159 | cpp | C++ | RayEngine/Source/System/Application.cpp | Mumsfilibaba/RayEngine | 68496966c1d7b91bc8fbdd305226ece9b9f596b2 | [
"Apache-2.0"
] | null | null | null | RayEngine/Source/System/Application.cpp | Mumsfilibaba/RayEngine | 68496966c1d7b91bc8fbdd305226ece9b9f596b2 | [
"Apache-2.0"
] | null | null | null | RayEngine/Source/System/Application.cpp | Mumsfilibaba/RayEngine | 68496966c1d7b91bc8fbdd305226ece9b9f596b2 | [
"Apache-2.0"
] | null | null | null | /*////////////////////////////////////////////////////////////
Copyright 2018 Alexander Dahlin
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
THIS SOFTWARE IS PROVIDED "AS IS". MEANING NO WARRANTY
OR SUPPORT IS PROVIDED OF ANY KIND.
In event of any damages, direct or indirect that can
be traced back to the use of this software, shall no
contributor be held liable. This includes computer
failure and or malfunction of any kind.
////////////////////////////////////////////////////////////*/
#include <RayEngine.h>
#include <System/Application.h>
#include <Graphics/IShader.h>
#include <Graphics/IPipelineState.h>
#include <Graphics/IRenderer.h>
#include <Graphics/Viewport.h>
namespace RayEngine
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application::Application(GRAPHICS_API api)
: m_pWindow(nullptr),
m_pDevice(nullptr),
m_pRenderer(nullptr),
m_pPipeline(nullptr),
m_Api(api)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application::~Application()
{
ReRelease_S(m_pPipeline);
ReRelease_S(m_pRenderer);
ReRelease_S(m_pDevice);
if (m_pWindow != nullptr)
{
m_pWindow->Destroy();
m_pWindow = nullptr;
}
LOG_INFO("Destroying Application");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Application::OnUpdate()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Application::OnRender()
{
using namespace Graphics;
m_pRenderer->Begin();
float color[] = { 0.392f, 0.584f, 0.929f, 1.0f };
m_pRenderer->Clear(color);
m_pRenderer->Draw();
m_pRenderer->End();
m_pRenderer->Present();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int32 Application::Run()
{
OnCreate();
LOG_INFO("Starting RayEngine");
m_pWindow->Show();
Event event = {};
while (event.Type != EVENT_TYPE_CLOSE)
{
if (m_pWindow->PeekEvent(&event))
{
if (event.Type == EVENT_TYPE_RESIZE)
{
}
}
OnUpdate();
OnRender();
}
LOG_INFO("Exiting RayEngine");
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Application::OnCreate()
{
using namespace Graphics;
LOG_INFO("Initializing RayEngine");
WindowDesc wnd = {};
wnd.Style = WINDOW_STYLE_STANDARD;
wnd.Width = 1024;
wnd.Height = 768;
wnd.pTitle = "RayEngine";
wnd.BackgroundColor.r = 127;
wnd.BackgroundColor.g = 127;
wnd.BackgroundColor.b = 127;
wnd.x = 0;
wnd.y = 0;
wnd.pIcon = nullptr;
wnd.Cursor.pImage = nullptr;
DeviceDesc dev = {};
dev.DeviceFlags = DEVICE_FLAG_DEBUG;
dev.SamplerDescriptorCount = 8;
dev.ResourceDescriptorCount = 8;
dev.RendertargetDescriptorCount = 4;
dev.DepthStencilDescriptorCount = 4;
dev.SampleCount = 1;
dev.BackBuffer.Count = 2;
dev.BackBuffer.Format = FORMAT_R8G8B8A8_UNORM;
dev.DepthStencil.Format = FORMAT_D24_UNORM_S8_UINT;
dev.Width = wnd.Width;
dev.Height = wnd.Height;
InitGraphics(&m_pWindow, wnd, &m_pDevice, dev, m_Api);
m_pRenderer = m_pDevice->CreateRenderer();
std::string vs;
std::string ps;
ShaderDesc shader = {};
shader.Flags = SHADER_FLAGS_DEBUG;
shader.pEntryPoint = "main";
shader.Type = SHADER_TYPE_VERTEX;
if (m_Api == GRAPHICS_API_OPENGL)
{
shader.SrcLang = SHADER_SOURCE_LANG_GLSL;
vs =
"#version 330\n"
"\n"
"void main()\n"
"{\n"
" vec4 pos = vec4(0.0);\n"
" if (gl_VertexID == 0) { pos = vec4(0.0f, 0.5f, 0.0f, 1.0f); }\n"
" else if (gl_VertexID == 1) { pos = vec4(0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else if (gl_VertexID == 2) { pos = vec4(-0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else { pos = vec4(0.0f, 0.0f, 0.0f, 1.0f); }\n"
" gl_Position = pos;\n"
"}\n";
ps =
"#version 330\n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n"
"}\n";
}
else
{
shader.SrcLang = SHADER_SOURCE_LANG_HLSL;
vs =
"struct VS_OUT\n"
"{\n"
" float4 pos : SV_Position;\n"
"};\n"
"\n"
"VS_OUT main(uint id : SV_VertexID)\n"
"{\n"
" VS_OUT output;\n"
" if (id == 0) { output.pos = float4(0.0f, 0.5f, 0.0f, 1.0f); }\n"
" else if (id == 1) { output.pos = float4(0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else if (id == 2) { output.pos = float4(-0.5f, -0.5f, 0.0f, 1.0f); }\n"
" else { output.pos = float4(0.0f, 0.0f, 0.0f, 1.0f); }\n"
" return output;\n"
"}\n";
ps =
"struct PS_IN\n"
"{\n"
" float4 pos : SV_Position;\n"
"};\n"
"\n"
"float4 main(PS_IN input) : SV_Target0\n"
"{\n"
" return float4(1.0f, 1.0f, 1.0f, 1.0f);\n"
"}\n";
}
shader.pSource = vs.c_str();
IShader* pVS = nullptr;
m_pDevice->CreateShader(&pVS, &shader);
shader.pSource = ps.c_str();
shader.Type = SHADER_TYPE_PIXEL;
IShader* pPS = nullptr;
m_pDevice->CreateShader(&pPS, &shader);
PipelineStateDesc pipeline = PipelineStateDesc::DefaultGraphicsPipeline();
pipeline.Type = PIPELINE_TYPE_GRAPHICS;
pipeline.Graphics.pVertexShader = pVS;
pipeline.Graphics.pPixelShader = pPS;
pipeline.Graphics.RenderTargetCount = 1;
pipeline.Graphics.RenderTargetFormats[0] = dev.BackBuffer.Format;
pipeline.Graphics.DepthStencilFormat = dev.DepthStencil.Format;
pipeline.Graphics.SampleCount = dev.SampleCount;
pipeline.Graphics.Topology = PRIMITIVE_TOPOLOGY_TRIANGLELIST;
pipeline.Graphics.InputLayout.ElementCount = 0;
pipeline.Graphics.InputLayout.pElements = nullptr;
pipeline.Graphics.DepthStencilState.DepthEnable = true;
m_pDevice->CreatePipelineState(&m_pPipeline, &pipeline);
ReRelease_S(pVS);
ReRelease_S(pPS);
}
} | 25.878151 | 123 | 0.562267 | Mumsfilibaba |
16f4e67cff58e7112c1221c466841c08adc38c2f | 486 | cpp | C++ | Game/JMath.cpp | Jdasi/DXTK-Boids | 9612de4f91846ec9c5307ac6d675c0c07b373a7d | [
"MIT"
] | null | null | null | Game/JMath.cpp | Jdasi/DXTK-Boids | 9612de4f91846ec9c5307ac6d675c0c07b373a7d | [
"MIT"
] | null | null | null | Game/JMath.cpp | Jdasi/DXTK-Boids | 9612de4f91846ec9c5307ac6d675c0c07b373a7d | [
"MIT"
] | null | null | null | #include "JMath.h"
// Clamps a float. I.e. returns _min when _min is exceeded.
float JMath::clampf(float _curr, float _min, float _max)
{
if (_curr < _min)
return _min;
if (_curr > _max)
return _max;
return _curr;
}
// Inversely clamps a float. I.e. returns _min when _max is exceeded.
float JMath::iclampf(float _curr, float _min, float _max)
{
if (_curr < _min)
return _max;
if (_curr > _max)
return _min;
return _curr;
}
| 18.692308 | 69 | 0.623457 | Jdasi |
a84398d66f3c34c7da355a05051940f65ba14609 | 2,888 | hxx | C++ | include/cstddef.hxx | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | include/cstddef.hxx | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | include/cstddef.hxx | K-Wu/libcxx.doc | c3c0421b2a9cc003146e847d0b8dd3a37100f39a | [
"Apache-2.0"
] | null | null | null | // -*- C++ -*-
//===--------------------------- cstddef ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_CSTDDEF
#define _LIBCPP_CSTDDEF
/*
cstddef synopsis
Macros:
offsetof(type,member-designator)
NULL
namespace std
{
Types:
ptrdiff_t
size_t
max_align_t
nullptr_t
byte // C++17
} // std
*/
#ifndef __simt__
#include <__config.hxx>
#include <version.hxx>
#endif //__simt__
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifndef __simt__
// Don't include our own <stddef.h>; we don't want to declare ::nullptr_t.
#ifdef _MSC_VER
#include <../ucrt/stddef.h>
#else
#include_next <stddef.h>
#endif
#include <__nullptr.hxx>
#endif //__simt__
_LIBCPP_BEGIN_NAMESPACE_STD
using ::ptrdiff_t;
using ::size_t;
#if defined(__CLANG_MAX_ALIGN_T_DEFINED) || defined(_GCC_MAX_ALIGN_T) || \
defined(__DEFINED_max_align_t) || defined(__NetBSD__)
// Re-use the compiler's <stddef.h> max_align_t where possible.
using ::max_align_t;
#else
typedef long double max_align_t;
#endif
_LIBCPP_END_NAMESPACE_STD
#if _LIBCPP_STD_VER > 14
#ifdef _LIBCPP_BEGIN_NAMESPACE_STD_NOVERSION
_LIBCPP_BEGIN_NAMESPACE_STD_NOVERSION
#else
namespace std // purposefully not versioned
{
#endif //_LIBCPP_BEGIN_NAMESPACE_STD_NOVERSION
enum class byte : unsigned char {};
constexpr byte operator| (byte __lhs, byte __rhs) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
static_cast<unsigned int>(__lhs) | static_cast<unsigned int>(__rhs)
));
}
constexpr byte& operator|=(byte& __lhs, byte __rhs) noexcept
{ return __lhs = __lhs | __rhs; }
constexpr byte operator& (byte __lhs, byte __rhs) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
static_cast<unsigned int>(__lhs) & static_cast<unsigned int>(__rhs)
));
}
constexpr byte& operator&=(byte& __lhs, byte __rhs) noexcept
{ return __lhs = __lhs & __rhs; }
constexpr byte operator^ (byte __lhs, byte __rhs) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
static_cast<unsigned int>(__lhs) ^ static_cast<unsigned int>(__rhs)
));
}
constexpr byte& operator^=(byte& __lhs, byte __rhs) noexcept
{ return __lhs = __lhs ^ __rhs; }
constexpr byte operator~ (byte __b) noexcept
{
return static_cast<byte>(
static_cast<unsigned char>(
~static_cast<unsigned int>(__b)
));
}
#ifdef _LIBCPP_END_NAMESPACE_STD_NOVERSION
_LIBCPP_END_NAMESPACE_STD_NOVERSION
#else
}
#endif //_LIBCPP_END_NAMESPACE_STD_NOVERSION
#endif
#endif // _LIBCPP_CSTDDEF
| 22.387597 | 80 | 0.686981 | K-Wu |
a8442967a4b999bce6b62485ab930b954feed50d | 2,001 | cc | C++ | zircon/system/ulib/io-scheduler/stream.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | zircon/system/ulib/io-scheduler/stream.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | zircon/system/ulib/io-scheduler/stream.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia 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 <io-scheduler/stream.h>
#include <io-scheduler/io-scheduler.h>
#include <fbl/auto_lock.h>
namespace ioscheduler {
Stream::Stream(uint32_t id, uint32_t pri, Scheduler* sched)
: id_(id), priority_(pri), sched_(sched) {}
Stream::~Stream() {
fbl::AutoLock lock(&lock_);
ZX_DEBUG_ASSERT(open_ == false);
ZX_DEBUG_ASSERT(in_list_.is_empty());
ZX_DEBUG_ASSERT(retained_list_.is_empty());
}
zx_status_t Stream::Close() {
fbl::AutoLock lock(&lock_);
open_ = false;
if (retained_list_.is_empty()) {
return ZX_OK; // Stream is ready for immediate deletion.
}
return ZX_ERR_SHOULD_WAIT;
}
zx_status_t Stream::Insert(UniqueOp op, UniqueOp* op_err) {
ZX_DEBUG_ASSERT(op != nullptr);
fbl::AutoLock lock(&lock_);
if (!open_) {
op->set_result(ZX_ERR_BAD_STATE);
*op_err = std::move(op);
return ZX_ERR_BAD_STATE;
}
op->set_stream(this);
retained_list_.push_back(op.get());
bool was_empty = in_list_.is_empty();
in_list_.push_back(op.release());
if (was_empty) {
sched_->SetActive(StreamRef(this));
}
return ZX_OK;
}
void Stream::GetNext(UniqueOp* op_out) {
fbl::AutoLock lock(&lock_);
UniqueOp op(in_list_.pop_front());
ZX_DEBUG_ASSERT(op != nullptr);
*op_out = std::move(op);
if (!in_list_.is_empty()) {
sched_->SetActive(StreamRef(this));
}
}
void Stream::ReleaseOp(UniqueOp op, SchedulerClient* client) {
StreamOp* sop;
bool release = false;
{
fbl::AutoLock lock(&lock_);
op->set_stream(nullptr);
sop = retained_list_.erase(*op.release());
if (!open_ && retained_list_.is_empty()) {
// Stream is closed and has no more work to do. Ready for release.
release = true;
}
}
ZX_DEBUG_ASSERT(sop != nullptr);
client->Release(sop);
if (release) {
sched_->StreamRelease(id_);
}
}
} // namespace ioscheduler
| 25.329114 | 73 | 0.682659 | OpenTrustGroup |