hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ea8d3c8220c1d7b5590f4de0745222909c735b4 | 5,155 | cpp | C++ | Qt_GUI/DisplayPanelWidget.cpp | SDUBigDataCourse/RecursiveSubdivision-basedSampling | a187eabe37e64312b326461d29800f1aff25371c | [
"MIT"
] | 5 | 2020-10-26T09:42:16.000Z | 2022-02-16T10:36:24.000Z | Qt_GUI/DisplayPanelWidget.cpp | Ideas-Laboratory/RecursiveSubdivision-basedSampling | 2b8cbae9cb72a05089ace5ccee4745d33121d60f | [
"MIT"
] | null | null | null | Qt_GUI/DisplayPanelWidget.cpp | Ideas-Laboratory/RecursiveSubdivision-basedSampling | 2b8cbae9cb72a05089ace5ccee4745d33121d60f | [
"MIT"
] | 2 | 2019-09-09T08:01:37.000Z | 2019-12-01T03:36:47.000Z | #include "DisplayPanelWidget.h"
using namespace std;
DisplayPanelWidget::DisplayPanelWidget(SamplingProcessViewer *spv, unordered_map<uint, string> *c2l_mapping, QWidget * parent) : QWidget(parent), viewer(spv), class2label(c2l_mapping)
{
setFixedWidth(440);
container = dynamic_cast<QScrollArea*>(parent);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setAlignment(Qt::AlignTop);
setLayout(layout);
addClassToColorMappingTable();
connect(spv, &SamplingProcessViewer::inputImageChanged, [this]() {
clearAllChildren();
addClassToColorMappingTable();
});
connect(spv, &SamplingProcessViewer::areaCreated, [this](IndividualSampleArea* area) {
addAreaInfo("r", area->getTotalInfo(), area->getSampleInfo());
});
connect(spv, &SamplingProcessViewer::areaCounted, [this](StatisticalInfo* total_info, StatisticalInfo* sample_info) {
addAreaInfo("o", total_info, sample_info);
});
connect(spv, &SamplingProcessViewer::adjustmentStart, [this]() {
removeSpecifiedChildren([](QWidget* w) { return w->objectName() == "o"; });
});
connect(spv, &SamplingProcessViewer::sampleStart, [this]() {
removeSpecifiedChildren([](QWidget* w) { return !w->objectName().isEmpty(); });
});
connect(spv, &SamplingProcessViewer::redrawStart, [this]() {
removeSpecifiedChildren([](QWidget* w) { return !w->objectName().isEmpty(); });
});
//connect(spv, &SamplingProcessViewer::pointSelected, [this](uint index, uint class_) {
// qDebug() << index << ',' << QString(this->class2label->at(class_).c_str());
//});
}
void DisplayPanelWidget::resizeEvent(QResizeEvent * e)
{
QWidget::resizeEvent(e);
container->verticalScrollBar()->setValue(height());
}
void DisplayPanelWidget::addClassToColorMappingTable()
{
QGroupBox *mapping_box = new QGroupBox("Class to Color mapping:", this);
QVBoxLayout *box_layout = new QVBoxLayout(mapping_box);
mapping_box->setLayout(box_layout);
QTableWidget *tw = new QTableWidget(this);
tw->setShowGrid(false);
tw->setEditTriggers(QAbstractItemView::NoEditTriggers);
tw->verticalHeader()->setVisible(false);
tw->setRowCount(class2label->size());
tw->setColumnCount(2);
tw->setHorizontalHeaderLabels(QStringList{ "Class", "Color" });
tw->setColumnWidth(0, 300);
tw->setColumnWidth(1, 70);
int rows = 0;
for (auto &pr : *class2label) {
QTableWidgetItem *newItem = new QTableWidgetItem(tr(pr.second.c_str()));
tw->setItem(rows, 0, newItem);
newItem = new QTableWidgetItem();
newItem->setBackground(this->viewer->getColorBrushes()[pr.first]);
tw->setItem(rows, 1, newItem);
++rows;
}
tw->setRowCount(rows);
box_layout->addWidget(tw);
mapping_box->setFixedHeight(tw->horizontalHeader()->height() + 60 + tw->rowHeight(0)*rows);
this->layout()->addWidget(mapping_box);
}
void DisplayPanelWidget::addAreaInfo(const QString& name, StatisticalInfo * total_info, StatisticalInfo * sample_info)
{
if (total_info->total_num > 0) {
QTableWidget *tw = new QTableWidget(this);
tw->setObjectName(name);
tw->setEditTriggers(QAbstractItemView::NoEditTriggers);
tw->verticalHeader()->setVisible(false);
tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tw->setRowCount(total_info->class_point_num.size() + 1);
tw->setColumnCount(4);
tw->setHorizontalHeaderLabels(QStringList{ "", "Actual", "Sample", "Ratio" });
tw->setColumnWidth(0, 70);
auto &map_t = total_info->class_point_num, &map_s = sample_info->class_point_num;
int rows = 0;
for (int i = 0, sz = selected_class_order.size(); i < sz; ++i) {
int class_index = selected_class_order[i];
if (map_t.find(class_index) != map_t.end()) {
QTableWidgetItem *newItem = new QTableWidgetItem();
newItem->setBackground(this->viewer->getColorBrushes()[class_index]);
tw->setItem(rows, 0, newItem);
newItem = new QTableWidgetItem(QString::number(map_t[class_index]));
tw->setItem(rows, 1, newItem);
uint sample_num = map_s.find(class_index) != map_s.end() ? map_s[class_index] : 0;
newItem = new QTableWidgetItem(QString::number(sample_num));
tw->setItem(rows, 2, newItem);
newItem = new QTableWidgetItem(QString::number(100.0*sample_num/map_t[class_index], 'f', 2) + "%");
tw->setItem(rows, 3, newItem);
++rows;
}
}
tw->setItem(rows, 0, new QTableWidgetItem(tr("Sum:")));
tw->setItem(rows, 1, new QTableWidgetItem(QString::number(total_info->total_num)));
tw->setItem(rows, 2, new QTableWidgetItem(QString::number(sample_info->total_num)));
tw->setItem(rows, 3, new QTableWidgetItem(QString::number(100.0*sample_info->total_num/total_info->total_num, 'f', 2) + "%"));
tw->setRowCount(++rows);
tw->setFixedHeight(tw->horizontalHeader()->height() + 4 + tw->rowHeight(0)*rows);
this->layout()->addWidget(tw);
}
delete total_info;
delete sample_info;
}
void DisplayPanelWidget::removeSpecifiedChildren(std::function<bool(QWidget*)> pred)
{
for (int i = this->layout()->count() - 1; i > -1; --i) {
QWidget *w = this->layout()->itemAt(i)->widget();
if (pred(w)) {
this->layout()->removeWidget(w);
w->close();
}
}
}
void DisplayPanelWidget::clearAllChildren()
{
removeSpecifiedChildren([](QWidget* w) { return true; });
}
| 37.627737 | 183 | 0.711542 | SDUBigDataCourse |
9ea93736a1011d8434627a70580108e9b05f012d | 270 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/quest/QuickItemsSet.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace quest {
enum class QuickItemsSet : uint32_t
{
Q001_Kereznikov_Heal_Phone = 0,
Q003_All = 1,
};
} // namespace quest
} // namespace RED4ext
| 16.875 | 57 | 0.722222 | jackhumbert |
9eab0549271f5337d77b1c6db8edfc6e879c9a72 | 1,184 | cpp | C++ | workbench/src/audiostream.cpp | MasterQ32/cg-workbench | 3d6229b961192689e6dbd0a09ec4b61041ecb155 | [
"MIT"
] | 5 | 2017-12-27T12:57:36.000Z | 2021-10-02T03:21:40.000Z | workbench/src/audiostream.cpp | MasterQ32/cg-workbench | 3d6229b961192689e6dbd0a09ec4b61041ecb155 | [
"MIT"
] | 9 | 2020-09-29T22:40:49.000Z | 2020-10-17T20:05:05.000Z | workbench/src/audiostream.cpp | MasterQ32/cg-workbench | 3d6229b961192689e6dbd0a09ec4b61041ecb155 | [
"MIT"
] | null | null | null | #include "audiostream.hpp"
#include <cstring>
#include <cassert>
// Implement stb_vorbis here!
#undef STB_VORBIS_HEADER_ONLY
#include <stb_vorbis.h>
uint32_t audio_samplerate;
uint32_t audio_buffersize;
uint32_t audio_channels;
AudioStream::AudioStream(int channels) :
samples(audio_buffersize * channels),
channels(channels)
{
this->Clear();
}
AudioStream::AudioStream(AudioStream const &other) :
samples(other.samples),
channels(other.channels)
{
}
AudioStream::AudioStream(AudioStream && other) :
samples(std::move(other.samples)),
channels(other.channels)
{
}
AudioStream::~AudioStream()
{
}
void AudioStream::Clear()
{
memset(this->samples.data(), 0, sizeof(sample_t) * this->samples.size());
}
void AudioStream::SetFormatForStream(AudioStream const & other)
{
this->SetChannels(other.GetChannels());
}
void AudioStream::SetChannels(uint32_t chans)
{
assert(chans >= 1);
if(this->channels == chans)
return;
this->channels = chans;
this->samples.resize(audio_buffersize * this->channels);
this->Clear();
}
void AudioStream::CopyTo(AudioStream & target) const
{
target.channels = this->channels;
target.samples = this->samples;
}
| 17.939394 | 74 | 0.728041 | MasterQ32 |
9eacbcac940dcbd9bdf58f9fe934da294c7b8e8b | 499 | cpp | C++ | test/src/bextr_test.cpp | MatsuTaku/libbo | e139e1bd81898f22a903a7d43018c93ae2722601 | [
"Unlicense"
] | null | null | null | test/src/bextr_test.cpp | MatsuTaku/libbo | e139e1bd81898f22a903a7d43018c93ae2722601 | [
"Unlicense"
] | null | null | null | test/src/bextr_test.cpp | MatsuTaku/libbo | e139e1bd81898f22a903a7d43018c93ae2722601 | [
"Unlicense"
] | null | null | null | //
// Created by 松本拓真 on 2019/11/06.
//
#include "gtest/gtest.h"
#include "bo/bextr.hpp"
namespace {
constexpr int N = 1<<16;
uint64_t rand64() {
return uint64_t(random()) | (uint64_t(random()) << 32);
}
}
TEST(Bextr, 64) {
for (int i = 0; i < N; i++) {
auto val = rand64();
int s = random() % 64;
int l = random() % (64 - s) + 1;
uint64_t bar = (l < 64) ? (1ull<<l)-1 : -1;
uint64_t mask = bar << s;
EXPECT_EQ(bo::bextr_u64(val, s, l), (val & mask) >> s);
}
}
| 16.633333 | 59 | 0.529058 | MatsuTaku |
9eb0b41af51f4d54c4f306c07f27818893871ed7 | 185 | hpp | C++ | Extensions/Includes.hpp | CodeRedRL/CodeRed-Universal | d6dd12fea9d4a583a99666d7cf75b7e0e3db896a | [
"MIT"
] | 6 | 2021-04-22T01:50:35.000Z | 2021-07-16T21:06:46.000Z | Extensions/Includes.hpp | CodeRedRL/CodeRed-Universal | d6dd12fea9d4a583a99666d7cf75b7e0e3db896a | [
"MIT"
] | 2 | 2021-04-24T23:15:32.000Z | 2021-05-26T02:22:43.000Z | Extensions/Includes.hpp | CodeRedRL/CodeRed-Universal | d6dd12fea9d4a583a99666d7cf75b7e0e3db896a | [
"MIT"
] | 4 | 2021-04-23T18:26:08.000Z | 2021-06-02T09:41:14.000Z | #pragma once
#include "Extensions/Colors.hpp"
#include "Extensions/Formatting.hpp"
#include "Extensions/Math.hpp"
#include "Extensions/Memory.hpp"
#include "Extensions/UnrealMemory.hpp" | 30.833333 | 38 | 0.8 | CodeRedRL |
9ebdc49e6fbdfe07a2d77199fde267c9bbbadfb1 | 1,283 | cpp | C++ | tests/TestTiming/TestStopWatch.cpp | cvilas/grape-old | d8e9b184fff396982be8d230214a1f66a7a8fcc9 | [
"BSD-3-Clause"
] | null | null | null | tests/TestTiming/TestStopWatch.cpp | cvilas/grape-old | d8e9b184fff396982be8d230214a1f66a7a8fcc9 | [
"BSD-3-Clause"
] | 4 | 2018-06-04T08:18:21.000Z | 2018-07-13T14:36:03.000Z | tests/TestTiming/TestStopWatch.cpp | cvilas/grape-old | d8e9b184fff396982be8d230214a1f66a7a8fcc9 | [
"BSD-3-Clause"
] | null | null | null | #include "TestStopWatch.h"
//=============================================================================
TestStopWatch::TestStopWatch()
//=============================================================================
{
}
//-----------------------------------------------------------------------------
void TestStopWatch::resolution()
//-----------------------------------------------------------------------------
{
grape::StopWatch watch;
long long int resolution = watch.getResolutionNanoseconds();
qDebug() << " Watch resolution is " << resolution << "nanoseconds";
QVERIFY(resolution > 0);
}
//-----------------------------------------------------------------------------
void TestStopWatch::period()
//-----------------------------------------------------------------------------
{
grape::StopWatch watch;
unsigned long long sleepNs = 1234567890ULL;
unsigned long long errNsLimit = 1000000; // 1 millisecond
watch.start();
grape::StopWatch::nanoSleep(sleepNs);
watch.stop();
unsigned long long ns = watch.getAccumulatedNanoseconds();
unsigned long long errNs = ((ns > sleepNs)?(ns - sleepNs):(sleepNs - ns));
qDebug() << "Elapsed Time: " << ns << " ns. (error: " << errNs << " ns)";
QVERIFY(errNs < errNsLimit);
}
| 33.763158 | 79 | 0.411535 | cvilas |
9ebf9a324cc53593fa7691c79e70243ea47b5141 | 835 | cpp | C++ | EB_GUIDE_GTF/concepts/TraceOutputExample/src/CustomTraceOutputExport.cpp | pethipet/eb-guide-examples | 1c14fdb6eebdd8b164d99b519161160ecc5a29cf | [
"MIT"
] | 11 | 2020-02-12T16:35:59.000Z | 2022-03-26T14:36:28.000Z | EB_GUIDE_GTF/concepts/TraceOutputExample/src/CustomTraceOutputExport.cpp | pethipet/eb-guide-examples | 1c14fdb6eebdd8b164d99b519161160ecc5a29cf | [
"MIT"
] | 1 | 2020-02-12T16:49:56.000Z | 2020-03-20T15:22:58.000Z | EB_GUIDE_GTF/concepts/TraceOutputExample/src/CustomTraceOutputExport.cpp | pethipet/eb-guide-examples | 1c14fdb6eebdd8b164d99b519161160ecc5a29cf | [
"MIT"
] | 4 | 2020-02-12T16:36:07.000Z | 2022-03-26T14:36:22.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Elektrobit Automotive GmbH
// Alle Rechte vorbehalten. All Rights Reserved.
//
// Information contained herein is subject to change without notice.
// Elektrobit retains ownership and all other rights in the software and each
// component thereof.
// Any reproduction of the software or components thereof without the prior
// written permission of Elektrobit is prohibited.
////////////////////////////////////////////////////////////////////////////////
#include "CustomTraceOutput.h"
#include <gtf/pluginloader/PluginSymbols.h>
using namespace gtf::tracing;
extern "C" GTF_PLUGIN_SO_SYMBOL TraceOutput* TRACE_OUTPUT_FACTORY_FUNCTION_CALL(void)
{
static traceoutputexample::CustomTraceOutput s_fileOut;
return &s_fileOut;
}
| 37.954545 | 85 | 0.641916 | pethipet |
9ec11020b2fdba5457ef32048e476e371db4e26d | 1,411 | cpp | C++ | Gear/Math/Matrix.cpp | Alpha255/Rockcat | f04124b17911fb6148512dd8fb260bd84702ffc1 | [
"MIT"
] | null | null | null | Gear/Math/Matrix.cpp | Alpha255/Rockcat | f04124b17911fb6148512dd8fb260bd84702ffc1 | [
"MIT"
] | null | null | null | Gear/Math/Matrix.cpp | Alpha255/Rockcat | f04124b17911fb6148512dd8fb260bd84702ffc1 | [
"MIT"
] | null | null | null | #include "Gear/Math/Matrix.h"
NAMESPACE_START(Gear)
NAMESPACE_START(Math)
#if !defined(USE_SSE)
void Matrix::gaussJordanInverse()
{
/// Gauss-Jordan method
Matrix copy(*this);
int32_t i, j, k;
/// Forward elimination
for (i = 0; i < 3; ++i)
{
int32_t pivot = i;
float32_t pivotSize = copy.m[i][i];
pivotSize = pivotSize < 0.0f ? -pivotSize : pivotSize;
for (j = i + 1; j < 4; ++j)
{
float32_t temp = copy.m[j][i];
temp = temp < 0.0f ? -temp : temp;
if (temp > pivotSize)
{
pivot = j;
pivotSize = temp;
}
}
/// singular Matrix
assert(pivotSize != 0.0f);
if (pivot != i)
{
for (j = 0; j < 4; ++j)
{
std::swap(copy.m[i][j], copy.m[pivot][j]);
std::swap(m[i][j], m[pivot][j]);
}
}
for (j = i + 1; j < 4; ++j)
{
float32_t factor = copy.m[j][i] / copy.m[i][i];
for (k = 0; k < 4; ++k)
{
copy.m[j][k] -= factor * copy.m[i][k];
m[j][k] -= factor * m[i][k];
}
}
}
/// Backward substitution
for (i = 3; i >= 0; --i)
{
float32_t factor = copy.m[i][i];
/// singular Matrix
assert(factor != 0.0f);
for (j = 0; j < 4; ++j)
{
copy.m[i][j] /= factor;
m[i][j] /= factor;
}
for (j = 0; j < i; ++j)
{
factor = copy.m[j][i];
for (k = 0; k < 4; ++k)
{
copy.m[j][k] -= factor * copy.m[i][k];
m[j][k] -= factor * m[i][k];
}
}
}
}
#endif
NAMESPACE_END(Math)
NAMESPACE_END(Gear)
| 16.6 | 56 | 0.501063 | Alpha255 |
9ec490b05858d9d942213feb29bce4d98c8adbf7 | 379 | cpp | C++ | 0027. Remove Element/Solution.cpp | Solitudez/leetcode | a47bad8f0796d08e5996e55d38735295f8135703 | [
"MIT"
] | 1 | 2022-03-04T16:25:57.000Z | 2022-03-04T16:25:57.000Z | 0027. Remove Element/Solution.cpp | Solitudez/leetcode | a47bad8f0796d08e5996e55d38735295f8135703 | [
"MIT"
] | null | null | null | 0027. Remove Element/Solution.cpp | Solitudez/leetcode | a47bad8f0796d08e5996e55d38735295f8135703 | [
"MIT"
] | null | null | null | #include <vector>
using std::vector;
class Solution {
public:
int removeElement_1(vector<int>& nums, int val) {
int l = 0, r = nums.size();
while(l < r)
{
if (nums[l] == val)
{
nums[l] = nums[r - 1];
r--;
}
else
l++;
}
return r;
}
}; | 18.047619 | 53 | 0.364116 | Solitudez |
9eca7a702c29987590b725fd14f12a0f7580d2bf | 1,166 | hpp | C++ | include/timer/timer.hpp | lkskstlr/mc-mpi | fc197f4bdf8f3dc3692fc24019bfd7f3c12d6442 | [
"MIT"
] | null | null | null | include/timer/timer.hpp | lkskstlr/mc-mpi | fc197f4bdf8f3dc3692fc24019bfd7f3c12d6442 | [
"MIT"
] | 1 | 2019-03-05T09:05:10.000Z | 2019-03-05T09:05:10.000Z | include/timer/timer.hpp | lkskstlr/mc-mpi | fc197f4bdf8f3dc3692fc24019bfd7f3c12d6442 | [
"MIT"
] | null | null | null | #ifndef TIMER_HPP
#define TIMER_HPP
// I use the fact that structs with methods are still POD in memory which is
// guranteed by the standard. See:
// https://stackoverflow.com/questions/422830/structure-of-a-c-object-in-memory-vs-a-struct
#include <iostream>
#include <mpi.h>
#include <stdio.h>
class Timer {
public:
typedef int id_t;
enum Tag : id_t { Computation = 0, Send, Recv, Idle, STATE_COUNT };
typedef struct timestamp_tag {
Tag tag;
double time;
} Timestamp;
typedef struct state_tag {
double cumm_times[Tag::STATE_COUNT] = {0.0};
double starttime = 0.0;
double endtime = 0.0;
int sprintf(char *str);
static int sprintf_header(char *str);
static int sprintf_max_len();
static MPI_Datatype mpi_t();
} State;
Timer();
Timestamp start(Tag tag);
State restart(Timestamp ×tamp, Tag tag);
void change(Timestamp ×tamp, Tag tag);
State stop(Timestamp timestamp);
void reset();
double tick() const;
double time() const;
double starttime() const;
friend std::ostream &operator<<(std::ostream &stream, const Timer &timer);
private:
State state;
const double offset;
};
#endif | 23.795918 | 91 | 0.696398 | lkskstlr |
19b02a9ffe3cd60793242ec6536fb3844d69c274 | 3,993 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcConnectionVolumeGeometry.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcConnectionVolumeGeometry.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcConnectionVolumeGeometry.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcConnectionVolumeGeometry.h"
#include "include/IfcSolidOrShell.h"
// ENTITY IfcConnectionVolumeGeometry
IfcConnectionVolumeGeometry::IfcConnectionVolumeGeometry() { m_entity_enum = IFCCONNECTIONVOLUMEGEOMETRY; }
IfcConnectionVolumeGeometry::IfcConnectionVolumeGeometry( int id ) { m_id = id; m_entity_enum = IFCCONNECTIONVOLUMEGEOMETRY; }
IfcConnectionVolumeGeometry::~IfcConnectionVolumeGeometry() {}
shared_ptr<IfcPPObject> IfcConnectionVolumeGeometry::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcConnectionVolumeGeometry> copy_self( new IfcConnectionVolumeGeometry() );
if( m_VolumeOnRelatingElement ) { copy_self->m_VolumeOnRelatingElement = dynamic_pointer_cast<IfcSolidOrShell>( m_VolumeOnRelatingElement->getDeepCopy(options) ); }
if( m_VolumeOnRelatedElement ) { copy_self->m_VolumeOnRelatedElement = dynamic_pointer_cast<IfcSolidOrShell>( m_VolumeOnRelatedElement->getDeepCopy(options) ); }
return copy_self;
}
void IfcConnectionVolumeGeometry::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCCONNECTIONVOLUMEGEOMETRY" << "(";
if( m_VolumeOnRelatingElement ) { m_VolumeOnRelatingElement->getStepParameter( stream, true ); } else { stream << "$" ; }
stream << ",";
if( m_VolumeOnRelatedElement ) { m_VolumeOnRelatedElement->getStepParameter( stream, true ); } else { stream << "$" ; }
stream << ");";
}
void IfcConnectionVolumeGeometry::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcConnectionVolumeGeometry::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcConnectionVolumeGeometry, expecting 2, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
m_VolumeOnRelatingElement = IfcSolidOrShell::createObjectFromSTEP( args[0], map );
m_VolumeOnRelatedElement = IfcSolidOrShell::createObjectFromSTEP( args[1], map );
}
void IfcConnectionVolumeGeometry::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcConnectionGeometry::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "VolumeOnRelatingElement", m_VolumeOnRelatingElement ) );
vec_attributes.push_back( std::make_pair( "VolumeOnRelatedElement", m_VolumeOnRelatedElement ) );
}
void IfcConnectionVolumeGeometry::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcConnectionGeometry::getAttributesInverse( vec_attributes_inverse );
}
void IfcConnectionVolumeGeometry::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcConnectionGeometry::setInverseCounterparts( ptr_self_entity );
}
void IfcConnectionVolumeGeometry::unlinkFromInverseCounterparts()
{
IfcConnectionGeometry::unlinkFromInverseCounterparts();
}
| 57.042857 | 235 | 0.771851 | linsipese |
19b471af1eb0ed5c4eeb8ad92b4e5bd7b27dd3ac | 10,075 | inl | C++ | src/bad/math/f32x4_calc/f32x4_calc_no_simd.inl | Bad-Sam/bad | a16717bd39c1607a042c673494e9c4a695905868 | [
"MIT"
] | null | null | null | src/bad/math/f32x4_calc/f32x4_calc_no_simd.inl | Bad-Sam/bad | a16717bd39c1607a042c673494e9c4a695905868 | [
"MIT"
] | null | null | null | src/bad/math/f32x4_calc/f32x4_calc_no_simd.inl | Bad-Sam/bad | a16717bd39c1607a042c673494e9c4a695905868 | [
"MIT"
] | null | null | null | // ==== Arithmetic & math functions ===
static bad_forceinline f32x4 f32x4_add(f32x4 a, f32x4 b)
{
f32x4 res;
res.x = a.x + b.x;
res.y = a.y + b.y;
res.z = a.z + b.z;
res.w = a.w + b.w;
return res;
}
static bad_forceinline f32x4 f32x4_sub(f32x4 a, f32x4 b)
{
f32x4 res;
res.x = a.x - b.x;
res.y = a.y - b.y;
res.z = a.z - b.z;
res.w = a.w - b.w;
return res;
}
static bad_forceinline f32x4 f32x4_mul(f32x4 a, f32x4 b)
{
f32x4 res;
res.x = a.x * b.x;
res.y = a.y * b.y;
res.z = a.z * b.z;
res.w = a.w * b.w;
return res;
}
static bad_forceinline f32x4 f32x4_div(f32x4 a, f32x4 b)
{
f32x4 res;
res.x = a.x / b.x;
res.y = a.y / b.y;
res.z = a.z / b.z;
res.w = a.w / b.w;
return res;
}
static bad_forceinline f32x4 f32x4_hadd3(f32x4 a)
{
return (f32x4)
{
f32x4_sum3(a),
a.y,
a.z,
a.w
};
}
static bad_forceinline f32x4 f32x4_hadd4(f32x4 a)
{
return (f32x4)
{
f32x4_sum4(a),
a.y,
a.z,
a.w
};
}
static bad_forceinline f32 f32x4_sum3(f32x4 a)
{
return a.x + a.y + a.z;
}
static bad_forceinline f32 f32x4_sum4(f32x4 a)
{
return a.x + a.y + a.z + a.w;
}
static bad_forceinline f32x4 f32x4_rcp(f32x4 a)
{
f32x4 res;
res.x = 1.f / a.x;
res.y = 1.f / a.y;
res.z = 1.f / a.z;
res.w = 1.f / a.w;
return res;
}
static bad_forceinline f32x4 f32x4_sqrt(f32x4 a)
{
return f32x4_sqrt(a);
}
static bad_forceinline f32x4 f32x4_rsqrt(f32x4 a)
{
return f32_rcp(f32x4_sqrt(a));
}
static bad_forceinline f32x4 f32x4_min(f32x4 a, f32x4 b)
{
f32x4 res;
res.x = f32x_min(a, b);
res.y = f32x_min(a, b);
res.z = f32x_min(a, b);
res.w = f32x_min(a, b);
return res;
}
static bad_forceinline f32x4 f32x4_max(f32x4 a, f32x4 b)
{
f32x4 res;
res.x = f32x_max(a, b);
res.y = f32x_max(a, b);
res.z = f32x_max(a, b);
res.w = f32x_max(a, b);
return res;
}
static bad_forceinline f32x4 f32x4_abs(f32x4 a)
{
const u32 value_mask = 0x7FFFFFFF;
mask128 a_mask = f32x4_as_mask128(a);
a_mask.x &= value_mask;
a_mask.y &= value_mask;
a_mask.z &= value_mask;
a_mask.w &= value_mask;
return mask128_as_f32x4(a_mask);
}
static bad_forceinline f32x4 f32x4_sign(f32x4 a)
{
const u32 sign_mask = 0x80000000;
const u32 one_mask = 0x3F800000;
mask128 a_mask = f32x4_as_mask128(a);
a_mask.x = (a_mask.x & sign_mask) | one_mask;
a_mask.y = (a_mask.y & sign_mask) | one_mask;
a_mask.z = (a_mask.z & sign_mask) | one_mask;
a_mask.w = (a_mask.w & sign_mask) | one_mask;
return mask128_as_f32x4(a_mask);
}
static bad_forceinline f32x4 f32x4_neg(f32x4 a)
{
const u32 sign_mask = 0x80000000;
mask128 a_mask = f32x4_as_mask128(a);
a_mask.x ^= sign_mask;
a_mask.y ^= sign_mask;
a_mask.z ^= sign_mask;
a_mask.w ^= sign_mask;
return mask128_as_f32x4(a_mask);
}
static bad_forceinline f32x4 bad_veccall f32x4_frac(f32x4 a)
{
return f32x4_sub(a, f32x4_trunc(a));
}
static bad_forceinline f32x4 f32x4_mod(f32x4 a, f32x4 b)
{
a.x = f32_mod(a.x, b.x);
a.y = f32_mod(a.y, b.y);
a.z = f32_mod(a.z, b.z);
a.w = f32_mod(a.w, b.w);
return a;
}
static bad_forceinline f32x4 f32x4_trunc(f32x4 a)
{
f32x4 res;
res.x = f32_trunc(a.x);
res.y = f32_trunc(a.y);
res.z = f32_trunc(a.z);
res.w = f32_trunc(a.w);
return res;
}
static bad_forceinline f32x4 f32x4_round(f32x4 a)
{
f32x4 sign_a = f32x4_sign(a);
f32x4 trunc_a = f32x4_trunc(a);
f32x4 offset = f32x4_mul(sign_a, f32x4_sub(a, trunc_a));
offset.x = (offset.x > .5f) ? 1.f : .0f;
offset.y = (offset.y > .5f) ? 1.f : .0f;
offset.z = (offset.z > .5f) ? 1.f : .0f;
offset.w = (offset.w > .5f) ? 1.f : .0f;
return f32x4_mul_add(sign_a, offset, trunc_a);
}
static bad_forceinline f32x4 f32x4_floor(f32x4 a)
{
a.x = f32_floor(a.x);
a.y = f32_floor(a.y);
a.z = f32_floor(a.z);
a.w = f32_floor(a.w);
return a;
}
static bad_forceinline f32x4 f32x4_ceil(f32x4 a)
{
a.x = f32_ceil(a.x);
a.y = f32_ceil(a.y);
a.z = f32_ceil(a.z);
a.w = f32_ceil(a.w);
return a;
}
static bad_forceinline f32x4 f32x4_clamp(f32x4 a, f32x4 min, f32x4 max)
{
return f32x4_min(f32x4_max(a, min), max);
}
static bad_forceinline f32x4 f32x4_lerp(f32x4 a, f32x4 b, f32x4 t)
{
f32x4 one_min_t = f32x4_sub(f32x4_one(), t);
return f32x4_mul_add(a, one_min_t, f32x4_mul(b, t));
}
static bad_forceinline f32x4 bad_veccall f32x4_copysign(f32x4 a, f32x4 reference_sign)
{
mask128 res;
mask128 a_mask = f32x4_as_mask128(a);
mask128 sign_mask = f32x4_as_mask128(reference_sign);
res.x = (a_mask.x & 0x7FFFFFFF) | (sign_mask.x & 0x80000000);
res.y = (a_mask.y & 0x7FFFFFFF) | (sign_mask.y & 0x80000000);
res.z = (a_mask.z & 0x7FFFFFFF) | (sign_mask.z & 0x80000000);
res.w = (a_mask.w & 0x7FFFFFFF) | (sign_mask.w & 0x80000000);
return mask128_as_f32x4(res);
}
static bad_forceinline f32x4 f32x4_mul_by_sign(f32x4 a, f32x4 reference_sign)
{
mask128 res;
mask128 a_bits = f32x4_as_mask128(a);
mask128 sign_bits = f32x4_as_mask128(reference_sign);
res.x = a_bits.x ^ (sign_bits.x & 0x80000000);
res.y = a_bits.y ^ (sign_bits.y & 0x80000000);
res.z = a_bits.z ^ (sign_bits.z & 0x80000000);
res.w = a_bits.w ^ (sign_bits.w & 0x80000000);
return mask128_as_f32x4(res);
}
// ========== Trigonometry ===========
static bad_forceinline f32x4 bad_veccall f32x4_cos(f32x4 a)
{
return (f32x4)
{
f32_cos(x.x),
f32_cos(x.y),
f32_cos(x.z),
f32_cos(x.w)
};
}
static bad_forceinline f32x4 bad_veccall f32x4_sin(f32x4 a)
{
return (f32x4)
{
f32_sin(x.x),
f32_sin(x.y),
f32_sin(x.z),
f32_sin(x.w)
};
}
static bad_forceinline f32x4 bad_veccall f32x4_tan(f32x4 a)
{
return (f32x4)
{
f32_tan(x.x),
f32_tan(x.y),
f32_tan(x.z),
f32_tan(x.w)
};
}
// Expects inputs in [-1; 1]
// Max error: ~1.5974045e-5
// Max relative error: ~0.0005%
static bad_forceinline f32x4 bad_veccall f32x4_acos(f32x4 x)
{
return (f32x4)
{
f32_acos(x.x),
f32_acos(x.y),
f32_acos(x.z),
f32_acos(x.w)
};
}
// ======== Fused operations ========
static bad_forceinline f32x4 f32x4_mul_add(f32x4 a, f32x4 b, f32x4 c)
{
return f32x4_add(f32x4_mul(a, b), c);
}
static bad_forceinline f32x4 f32x4_mul_sub(f32x4 a, f32x4 b, f32x4 c)
{
return f32x4_sub(f32x4_mul(a, b), c);
}
static bad_forceinline f32x4 f32x4_nmul_add(f32x4 a, f32x4 b, f32x4 c)
{
return f32x4_neg(f32x4_mul_sub(a, b, c));
}
static bad_forceinline f32x4 f32x4_nmul_sub(f32x4 a, f32x4 b, f32x4 c)
{
return f32x4_neg(f32x4_mul_add(a, b, c));
}
// ============ Comparison ============
static bad_forceinline mask128 f32x4_neq(f32x4 a, f32x4 b)
{
mask128 res;
res.x = (a.x != b.x) * 0xFFFFFFFF;
res.y = (a.y != b.y) * 0xFFFFFFFF;
res.z = (a.z != b.z) * 0xFFFFFFFF;
res.w = (a.w != b.w) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_eq(f32x4 a, f32x4 b)
{
mask128 res;
res.x = (a.x == b.x) * 0xFFFFFFFF;
res.y = (a.y == b.y) * 0xFFFFFFFF;
res.z = (a.z == b.z) * 0xFFFFFFFF;
res.w = (a.w == b.w) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_ge(f32x4 a, f32x4 b)
{
mask128 res;
res.x = (a.x >= b.x) * 0xFFFFFFFF;
res.y = (a.y >= b.y) * 0xFFFFFFFF;
res.z = (a.z >= b.z) * 0xFFFFFFFF;
res.w = (a.w >= b.w) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_gt(f32x4 a, f32x4 b)
{
mask128 res;
res.x = (a.x > b.x) * 0xFFFFFFFF;
res.y = (a.y > b.y) * 0xFFFFFFFF;
res.z = (a.z > b.z) * 0xFFFFFFFF;
res.w = (a.w > b.w) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_le(f32x4 a, f32x4 b)
{
mask128 res;
res.x = (a.x <= b.x) * 0xFFFFFFFF;
res.y = (a.y <= b.y) * 0xFFFFFFFF;
res.z = (a.z <= b.z) * 0xFFFFFFFF;
res.w = (a.w <= b.w) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_lt(f32x4 a, f32x4 b)
{
mask128 res;
res.x = (a.x < b.x) * 0xFFFFFFFF;
res.y = (a.y < b.y) * 0xFFFFFFFF;
res.z = (a.z < b.z) * 0xFFFFFFFF;
res.w = (a.w < b.w) * 0xFFFFFFFF;
return res;
}
// ======= Selection & tests ========
static bad_forceinline mask128 f32x4_is_positive(f32x4 a)
{
mask128 res;
res.x = (a.x >= .0f) * 0xFFFFFFFF;
res.y = (a.y >= .0f) * 0xFFFFFFFF;
res.z = (a.z >= .0f) * 0xFFFFFFFF;
res.w = (a.w >= .0f) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_is_negative(f32x4 a)
{
mask128 res;
res.x = (a.x < .0f) * 0xFFFFFFFF;
res.y = (a.y < .0f) * 0xFFFFFFFF;
res.z = (a.z < .0f) * 0xFFFFFFFF;
res.w = (a.w < .0f) * 0xFFFFFFFF;
return res;
}
static bad_forceinline mask128 f32x4_is_nan(f32x4 a)
{
return f32x4_neq(a, a);
}
static bad_forceinline mask128 f32x4_is_infinite(f32x4 a)
{
const u32 value_mask = 0x7FFFFFFF;
const u32 inf_mask = 0x7F800000;
mask128 a_mask = f32x4_as_mask128(a);
a_mask.x &= value_mask;
a_mask.y &= value_mask;
a_mask.z &= value_mask;
a_mask.w &= value_mask;
a_mask.x = (a_mask.x == inf_mask);
a_mask.y = (a_mask.y == inf_mask);
a_mask.z = (a_mask.z == inf_mask);
a_mask.w = (a_mask.w == inf_mask);
return a_mask;
}
static bad_forceinline mask128 f32x4_is_finite(f32x4 a)
{
const u32 expo_mask = 0x7F800000;
mask128 a_mask = f32x4_as_mask128(a);
a_mask.x &= expo_mask;
a_mask.y &= expo_mask;
a_mask.z &= expo_mask;
a_mask.w &= expo_mask;
a_mask.x = (a_mask.x != expo_mask);
a_mask.y = (a_mask.y != expo_mask);
a_mask.z = (a_mask.z != expo_mask);
a_mask.w = (a_mask.w != expo_mask);
return a_mask;
} | 19.300766 | 86 | 0.596824 | Bad-Sam |
19b5803a8cfd16435200eee8f5c0fa004b281350 | 1,317 | hpp | C++ | source/AsioExpress/ClientServer/ClientEventHandler.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | source/AsioExpress/ClientServer/ClientEventHandler.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | source/AsioExpress/ClientServer/ClientEventHandler.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | // Copyright Ross MacGregor 2013
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "AsioExpress/Error.hpp"
#include "AsioExpress/CompletionHandler.hpp"
#include "AsioExpress/ClientServer/ClientMessage.hpp"
#include "AsioExpress/ClientServer/ClientConnection.hpp"
namespace AsioExpress {
namespace MessagePort {
class ClientEventHandler
{
public:
virtual ~ClientEventHandler() {};
virtual void ClientConnected(
AsioExpress::MessagePort::ClientConnection) = 0;
virtual void ClientDisconnected(
AsioExpress::MessagePort::ClientConnection connection,
AsioExpress::Error error) = 0;
virtual void AsyncProcessMessage(
AsioExpress::MessagePort::ClientMessage message) = 0;
virtual AsioExpress::Error ConnectionError(
AsioExpress::MessagePort::ClientConnection connection,
AsioExpress::Error error) = 0;
virtual AsioExpress::Error MessageError(
AsioExpress::MessagePort::ClientMessage message,
AsioExpress::Error error) = 0;
};
typedef boost::shared_ptr<ClientEventHandler> ClientEventHandlerPointer;
} // namespace MessagePort
} // namespace AsioExpress
| 29.931818 | 73 | 0.725892 | suhao |
19b81538e09ab959ef0690421b96ee0eb115adc6 | 1,038 | cpp | C++ | src/lib/vector3.cpp | abainbridge/trex-warrior | fac95802ce7efd8dc9c50f915ce8d5891f545640 | [
"BSD-2-Clause"
] | null | null | null | src/lib/vector3.cpp | abainbridge/trex-warrior | fac95802ce7efd8dc9c50f915ce8d5891f545640 | [
"BSD-2-Clause"
] | null | null | null | src/lib/vector3.cpp | abainbridge/trex-warrior | fac95802ce7efd8dc9c50f915ce8d5891f545640 | [
"BSD-2-Clause"
] | null | null | null | #include "lib/universal_include.h"
#include <math.h>
#include <float.h>
#include "lib/vector2.h"
#include "lib/vector3.h"
Vector3 const g_upVector(0.0f, 1.0f, 0.0f);
Vector3 const g_zeroVector(0.0f, 0.0f, 0.0f);
void Vector3::RotateAroundX(float angle)
{
FastRotateAround(Vector3(1,0,0), angle);
}
void Vector3::RotateAroundY(float angle)
{
FastRotateAround(g_upVector, angle);
}
void Vector3::RotateAroundZ(float angle)
{
FastRotateAround(Vector3(0,0,1), angle);
}
// ASSUMES that _norm is normalized
void Vector3::FastRotateAround(Vector3 const &norm, float angle)
{
float dot = (*this) * norm;
Vector3 a = norm * dot;
Vector3 n1 = *this - a;
Vector3 n2 = norm.CrossProduct(n1);
float s = sinf(angle);
float c = cosf(angle);
*this = a + c*n1 + s*n2;
}
void Vector3::RotateAround(Vector3 const &axis)
{
float angle = axis.LenSquared();
if (angle < 1e-8) return;
angle = sqrtf(angle);
Vector3 norm(axis / angle);
FastRotateAround(norm, angle);
}
| 19.222222 | 65 | 0.656069 | abainbridge |
19c69b52917fbebe98a96eda954ba83ae41f50ef | 1,016 | cpp | C++ | spoj/Diehard/diehard.cpp | Abhinavlamba/competitive-programming | fdf26f55e5559cde32651ef91f1927b1137442f9 | [
"MIT"
] | 1 | 2020-05-12T04:28:55.000Z | 2020-05-12T04:28:55.000Z | spoj/Diehard/diehard.cpp | devkant/competitive-programming | fdf26f55e5559cde32651ef91f1927b1137442f9 | [
"MIT"
] | null | null | null | spoj/Diehard/diehard.cpp | devkant/competitive-programming | fdf26f55e5559cde32651ef91f1927b1137442f9 | [
"MIT"
] | 5 | 2017-10-22T06:04:17.000Z | 2020-08-04T11:08:47.000Z | #include <bits/stdc++.h>
using namespace std;
int dp[1007][1007][1];
int diehard(int h,int a,int air){
if(h<=0 || a<=0){
return 0;
}
if(dp[h][a][air]!=-1){
return dp[h][a][air];
}
if(air){
dp[h][a][air]=1+diehard(h+3,a+2,0);
return dp[h][a][air];
}else{
int maxi=max(diehard(h-20,a+5,1), diehard(h-5,a-10,1));
if(maxi==0){
dp[h][a][air]=0;
return dp[h][a][air];
}else{
dp[h][a][air]=1+maxi;
return dp[h][a][air];
}
}
}
int main()
{
int t;
scanf("%d",&t);
for(int j=0;j<=1006;j++){
for(int k=0;k<=1006;k++){
if(j==0 || k==0){
dp[j][k][0]=0;
dp[j][k][1]=0;
}else{
dp[j][k][0]=-1;
dp[j][k][1]=-1;
}
}
}
while(t--){
int h,a;
scanf("%d%d",&h,&a);
printf("%d\n",diehard(h,a,1));
}
return 0;
}
| 18.142857 | 63 | 0.36122 | Abhinavlamba |
19c88b00bae7f0ed1e3b3f2bcda0667632890368 | 630 | cpp | C++ | src/ui/ui_frame_buffers.cpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | 1 | 2020-09-23T11:17:35.000Z | 2020-09-23T11:17:35.000Z | src/ui/ui_frame_buffers.cpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | null | null | null | src/ui/ui_frame_buffers.cpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | null | null | null | #include "ui_frame_buffers.hpp"
#include <sstream>
#include "../imgui/imgui-SFML.h"
#include "../engine.hpp"
namespace space
{
UIFrameBuffers::UIFrameBuffers() : UIWindow("FrameBuffers")
{
}
void UIFrameBuffers::doDraw(Engine &engine)
{
auto &renderCameras = engine.renderCameras();
ImGui::Text("Frame Buffers: %i", (int)renderCameras.objects().size());
for (auto &renderCamera : renderCameras.objects())
{
ImGui::Text("- %s", renderCamera->camera().debugName.c_str());
ImGui::Image(renderCamera->texture().getTexture());
}
}
} // space | 24.230769 | 78 | 0.612698 | astrellon |
19cecee5716dda019d8e0e84c8d54cf348fb1878 | 4,027 | cpp | C++ | src/macro.cpp | reveluxlabs/Tilton | d8ff1a58366023422e1a83178fd8d7370081477e | [
"MIT"
] | null | null | null | src/macro.cpp | reveluxlabs/Tilton | d8ff1a58366023422e1a83178fd8d7370081477e | [
"MIT"
] | 1 | 2019-10-17T12:58:18.000Z | 2019-10-17T12:58:18.000Z | src/macro.cpp | reveluxlabs/Tilton | d8ff1a58366023422e1a83178fd8d7370081477e | [
"MIT"
] | 2 | 2019-10-16T12:45:50.000Z | 2019-10-17T12:08:10.000Z | // Copyright (c) 2011 Revelux Labs, LLC. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include "macro.h"
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include "tilton.h"
Macro::Macro() {
InitializeMacro(NULL, 0);
}
Macro::Macro(int len) {
InitializeMacro(NULL, len);
}
Macro::Macro(const char* s) {
InitializeMacro(s, static_cast<int>(strlen(s)));
}
Macro::Macro(Text* t) {
if (t) {
InitializeMacro(t->string_, t->length_);
} else {
InitializeMacro(NULL, 0);
}
}
Macro::~Macro() {
delete this->definition_;
delete this->name_;
}
void Macro::AddToString(const char* s, int len) {
if (s && len) {
CheckLengthAndIncrease(len);
memmove(&definition_[length_], s, len);
length_ += len;
my_hash_ = 0;
}
}
void Macro::AddToString(Text* t) {
if (t) {
AddToString(t->string_, t->length_);
}
}
void Macro::CheckLengthAndIncrease(int len) {
int newMaxLength;
int req = length_ + len;
if (max_length_ < req) {
newMaxLength = max_length_ * 2;
if (newMaxLength < req) {
newMaxLength = req;
}
char* newString = new char[newMaxLength];
memmove(newString, definition_, max_length_);
delete definition_;
definition_ = newString;
max_length_ = newMaxLength;
}
}
void Macro::PrintMacroList() {
Macro* t = this;
while (t) {
fwrite(t->name_, sizeof(char), t->name_length_, stderr);
if (t->length_) {
fputc('~', stderr);
fwrite(t->definition_, sizeof(char), t->length_, stderr);
}
fprintf(stderr, "\n");
t = t->link_;
}
}
int Macro::FindFirstSubstring(Text *t) {
int len = t->length_;
char* s = t->string_;
if (len) {
bool b;
int d = length_ - len;
int i;
int r;
for (r = 0; r <= d; r += 1) {
b = true;
for (i = 0; i < len; i += 1) {
if (definition_[r + i] != s[i]) {
b = false;
break;
}
}
if (b) {
return r;
}
};
}
return -1;
}
void Macro::InitializeMacro(const char* s, int len) {
name_ = NULL;
link_ = NULL;
length_ = name_length_ = 0;
my_hash_ = 0;
max_length_ = len;
if (len == 0) {
definition_ = NULL;
} else {
definition_ = new char[len];
if (s) {
memmove(definition_, s, len);
length_ = len;
}
}
}
bool Macro::IsNameEqual(Text* t) {
if (name_length_ != t->length_) {
return false;
}
for (int i = 0; i < name_length_; i += 1) {
if (name_[i] != t->string_[i]) {
return false;
}
}
return true;
}
int Macro::FindLastSubstring(Text *t) {
int len = t->length_;
char* s = t->string_;
if (len) {
bool b;
int d = length_ - len;
for (int r = d; r >= 0; r -= 1) {
b = true;
for (int i = 0; i < len; i += 1) {
if (definition_[r + i] != s[i]) {
b = false;
break;
}
}
if (b) {
return r;
}
}
}
return -1;
}
void Macro::set_string(Text* t) {
my_hash_ = 0;
if (t && t->length_) {
length_ = t->length_;
if (length_ > max_length_) {
delete definition_;
definition_ = new char[length_];
max_length_ = length_;
}
memmove(definition_, t->string_, length_);
} else {
length_ = 0;
}
}
void Macro::set_name(const char* s) {
set_name(s, static_cast<int>(strlen(s)));
}
void Macro::set_name(const char* s, int len) {
delete name_;
name_length_ = len;
name_ = new char[name_length_];
memmove(name_, s, name_length_);
}
void Macro::set_name(Text* t) {
set_name(t->string_, t->length_);
}
void Macro::ReplaceDefWithSubstring(int start, int len) {
memmove(definition_, &definition_[start], len);
length_ = len;
}
| 21.08377 | 73 | 0.532158 | reveluxlabs |
19d1ae34118cdbad622550dcb7b215a3ac151442 | 395 | cpp | C++ | C or C++/poinTer.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-11-01T05:48:04.000Z | 2021-04-25T05:33:47.000Z | C or C++/poinTer.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | null | null | null | C or C++/poinTer.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-10-31T05:29:55.000Z | 2021-06-19T09:33:53.000Z | #include <iostream>
#include <new>
#include <cstdlib>
#include <map>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
int a = 90;
int b = 100;
cout << "Address = " << (long)&a << " " << (long)&b << endl;
int *p = &a;
cout << "p = " << *p << " " << endl;
p++;
cout << "p after increment = " << *p << " " << endl;
return 0;
}
| 18.809524 | 64 | 0.496203 | amitShindeGit |
19d23aa18ab8775f38678c4dc264a93cdadc54c5 | 6,979 | hpp | C++ | include/conduit/mixin/promise_parts.hpp | jantonioperez/conduit | 1366d710fb3afac5dbc3b71f8285c62c03bdf201 | [
"MIT"
] | 6 | 2021-09-18T07:49:46.000Z | 2022-02-03T12:21:16.000Z | include/conduit/mixin/promise_parts.hpp | functionalperez/conduit | 1366d710fb3afac5dbc3b71f8285c62c03bdf201 | [
"MIT"
] | 1 | 2021-08-05T22:48:51.000Z | 2021-08-05T23:27:30.000Z | include/conduit/mixin/promise_parts.hpp | codeinred/conduit | 1366d710fb3afac5dbc3b71f8285c62c03bdf201 | [
"MIT"
] | null | null | null | #pragma once
#include <conduit/async/callback.hpp>
#include <conduit/async/immediate_value.hpp>
#include <conduit/mem/allocator.hpp>
#include <conduit/mixin/awaitable_parts.hpp>
#include <conduit/util/tag_types.hpp>
#include <exception>
namespace conduit::mixin {
enum suspend : bool { always = true, never = false };
#if CONDUIT_USE_GCC_EXCEPTION_WORKAROUND
namespace detail {
using remuse_coro_t = void (*)();
using destroy_coro_t = void (*)();
struct frame_header_t {
remuse_coro_t resume_coro;
destroy_coro_t destroy_coro;
};
} // namespace detail
template <bool suspend>
struct InitialSuspend {
// If CONDUIT_USE_GCC_EXCEPTION_WORKAROUND is defined, then we need to keep
// track of this value in order to destroy the frame manually. This value is
// recorded inside initial_suspend_t
detail::destroy_coro_t destroy_coro = nullptr;
struct initial_suspend_t {
detail::destroy_coro_t& destroy_coro_ref;
inline constexpr bool await_ready() { return false; }
inline bool await_suspend(std::coroutine_handle<> h) {
destroy_coro_ref = ((detail::frame_header_t*)h.address())
->destroy_coro;
return suspend; // The coroutine is resumed if suspend is false
}
inline constexpr void await_resume() noexcept {}
};
inline constexpr auto initial_suspend() noexcept {
return initial_suspend_t {destroy_coro};
}
};
#else
template <bool suspend>
struct InitialSuspend {
inline constexpr auto initial_suspend() noexcept {
if constexpr (suspend) {
return std::suspend_always {};
} else {
return std::suspend_never {};
}
}
};
#endif
template <bool suspend>
struct FinalSuspend {
inline constexpr auto final_suspend() noexcept {
if constexpr (suspend) {
return std::suspend_always {};
} else {
return std::suspend_never {};
}
}
};
struct ReturnVoid {
inline constexpr void return_void() noexcept {}
};
template <class DerivedPromise>
struct UnhandledException {
void unhandled_exception() {
// NB: for some reason, GCC doesn't destroy the coroutine frame if
// there's an exception raised inside the coroutine. As a result, if
// we're on GCC, we need to destroy it manually.
#ifdef CONDUIT_USE_GCC_EXCEPTION_WORKAROUND
DerivedPromise& promise = static_cast<DerivedPromise&>(*this);
auto coro_frame = static_cast<detail::frame_header_t*>(
std::coroutine_handle<DerivedPromise>::from_promise(promise)
.address());
coro_frame->destroy_coro = promise.destroy_coro;
std::coroutine_handle<>::from_address(coro_frame).destroy();
#endif
std::rethrow_exception(std::current_exception());
}
};
template <class Promise, bool IsNoexcept = true>
struct GetReturnObject;
template <class Promise>
struct GetReturnObject<Promise, false> {
using handle_type = std::coroutine_handle<Promise>;
// Used by the compiler to produce the return_object when starting the
// coroutine
handle_type get_return_object() noexcept { return get_handle(); }
// Allows you access to the promise object from within a coroutine via
// auto& promise = co_yield get_promise;
// await_ready() always returns true
inline auto yield_value(tags::get_promise_t) noexcept {
return async::immediate_value {static_cast<Promise*>(this)};
}
inline auto yield_value(tags::get_handle_t) noexcept {
return async::immediate_value {get_handle()};
}
inline handle_type get_handle() noexcept {
return handle_type::from_promise(static_cast<Promise&>(*this));
}
};
template <class Promise>
struct GetReturnObject<Promise, true> : GetReturnObject<Promise, false> {
using super = GetReturnObject<Promise, false>;
using super::get_handle;
using super::get_return_object;
using super::yield_value;
using handle_type = typename super::handle_type;
// If there's an allocation failure, returns a null coroutine handle
static handle_type get_return_object_on_allocation_failure() noexcept {
return nullptr;
}
};
template <class Alloc>
struct NewAndDelete {
template <class... T>
static void* operator new(size_t size, Alloc& alloc, T&&...) {
return alloc.alloc(size);
}
template <class... T>
static void* operator new(size_t size, Alloc* alloc, T&&...) {
return alloc->alloc(size);
}
static void operator delete(void* pointer, size_t size) {
std::decay_t<Alloc>::dealloc(pointer, size);
}
};
class HasOwnerAndCallback : public mixin::InitialSuspend<true> {
protected:
std::coroutine_handle<>* owner = nullptr;
async::callback callback;
public:
template <class T>
inline void set_owner(std::coroutine_handle<T>* owner) noexcept {
this->owner = reinterpret_cast<std::coroutine_handle<>*>(owner);
}
inline void set_callback(std::coroutine_handle<> handle) noexcept {
callback.emplace(handle);
}
inline auto final_suspend() noexcept { return callback.release(); }
~HasOwnerAndCallback() noexcept {
if (owner) {
*owner = nullptr;
}
}
};
class ExceptionHandler {
std::exception_ptr exception_ptr;
constexpr static bool unhandled_noexcept = std::
is_nothrow_copy_assignable_v<std::exception_ptr>;
public:
void unhandled_exception() noexcept(unhandled_noexcept) {
exception_ptr = std::current_exception();
}
void rethrow_if_exception() const {
if (exception_ptr) {
std::rethrow_exception(exception_ptr);
}
}
void clear_and_rethrow_if_exception() {
if (exception_ptr) {
auto hold = exception_ptr;
exception_ptr = nullptr;
std::rethrow_exception(hold);
}
}
};
template <class T>
class YieldValue {
public:
using value_type = std::remove_reference_t<T>;
using reference_type = std::
conditional_t<std::is_reference_v<T>, T, T const&>;
using pointer_type = std::remove_reference_t<reference_type>*;
private:
pointer_type value_ptr = nullptr;
protected:
void clear() noexcept { value_ptr = nullptr; }
public:
constexpr bool has_value() const noexcept { return value_ptr; }
constexpr auto yield_value(reference_type value) noexcept
-> std::suspend_always {
value_ptr = std::addressof(value);
return {};
}
constexpr auto get_pointer() const noexcept -> pointer_type {
return value_ptr;
}
constexpr auto value() const noexcept -> reference_type {
return *value_ptr;
}
};
// Protects incorrect co_await operations by deleting await_transform
struct DisableCoAwait {
template <typename U>
std::suspend_never await_transform(U&& value) = delete;
};
} // namespace conduit::mixin
| 31.017778 | 80 | 0.674882 | jantonioperez |
19d6905fcc00e21a5f9c27f212201722b919eeb1 | 176 | cpp | C++ | src/basic/src/listener_node.cpp | sgermanserrano/gitlab_ci_test | df415655757d9674a31ca704bef6bb7c456e7c09 | [
"Apache-2.0"
] | null | null | null | src/basic/src/listener_node.cpp | sgermanserrano/gitlab_ci_test | df415655757d9674a31ca704bef6bb7c456e7c09 | [
"Apache-2.0"
] | null | null | null | src/basic/src/listener_node.cpp | sgermanserrano/gitlab_ci_test | df415655757d9674a31ca704bef6bb7c456e7c09 | [
"Apache-2.0"
] | 1 | 2019-03-05T16:33:21.000Z | 2019-03-05T16:33:21.000Z | #include "basic/listener.h"
int main(int argc, char **argv) {
ros::init(argc, argv, "listener_node");
Listener listener_node;
listener_node.spin();
return 0;
}
| 11 | 41 | 0.659091 | sgermanserrano |
19d6d426f1ac47a9e74c87895d7b3ba67e038bc4 | 3,527 | cpp | C++ | esm/Util.cpp | kstemp/TESviewer | 2905367f0e30c586633831e0312a7902fb645b4e | [
"MIT"
] | null | null | null | esm/Util.cpp | kstemp/TESviewer | 2905367f0e30c586633831e0312a7902fb645b4e | [
"MIT"
] | null | null | null | esm/Util.cpp | kstemp/TESviewer | 2905367f0e30c586633831e0312a7902fb645b4e | [
"MIT"
] | null | null | null | #include "Util.h"
#include "records\CELL.h"
ESM::Record* ESM::getBaseFromREFR(const ESM::Record* refr, ESM::File& file) {
return file.findByFormID(refr->fieldOr<uint32_t>("NAME"));
}
std::vector<ESM::Group>* ESM::findCellChildrenTopLevel(const ESM::Record* cell, ESM::File& file) {
int block = getCellBlock(cell);
int subBlock = getCellSubBlock(cell);
std::vector<ESM::Group>* cellChildrenTop = (cell->fieldOr<uint16_t>("DATA") & ESM::CellFlags::Interior) ?
&file.groups[57].subgroups[block].subgroups[subBlock].subgroups
: &file.groups[58].subgroups[0].subgroups[0].subgroups;//.subgroups[2].subgroups;
return cellChildrenTop;
}
ESM::Group* ESM::findCellChildren(ESM::Record* cell, std::vector<ESM::Group>* cellChildrenTop) {
auto cellChildren = std::find_if(
cellChildrenTop->begin(),
cellChildrenTop->end(),
[&](const auto& g) {
const uint32_t groupParentFormID = g.labelAsFormID();
return g.type == ESM::GroupType::CellChildren && groupParentFormID == cell->formID;
});
return &(*cellChildren);
}
ESM::Group* ESM::findCellTemporaryChildren(ESM::Record* cell, ESM::Group* cellChildren) {
auto cellTemporaryChildren = std::find_if(
cellChildren->subgroups.begin(),
cellChildren->subgroups.end(),
[](const auto& g) {
return g.type == ESM::GroupType::CellTemporaryChildren;
});
return &(*cellTemporaryChildren);
}
int ESM::getCellBlock(const ESM::Record* cell) {
if (cell->fieldOr<uint16_t>("DATA") & ESM::CellFlags::Interior)
// last digit of formID in decimal
return cell->formID % 10;
else
return 0;
}
int ESM::getCellSubBlock(const ESM::Record* cell) {
if (cell->fieldOr<uint16_t>("DATA") & ESM::CellFlags::Interior)
// penultimate digit of formID in decimal
return ((cell->formID / 10) % 10);
else
return 0;
}
QString ESM::getRecordFullName(const std::string& name) {
if (name == "CELL")
return "Cell";
else if (name == "TES4")
return "TES Header";
else if (name == "WRLD")
return "Worldspace";
else if (name == "STAT")
return "Static";
else if (name == "FURN")
return "Furniture";
else if (name == "CONT")
return "Container";
else if (name == "DOOR")
return "Door";
else if (name == "LIGH")
return "Light";
else if (name == "MISC")
return "Miscellanous Object";
else if (name == "ALCH")
return "Potion";
else if (name == "FLOR")
return "Flora";
else if (name == "MATO")
return "Material Object";
else if (name == "TREE")
return "Tree";
else if (name == "NAVM")
return "Navigation Mesh";
return QString::fromStdString(name);
}
QString ESM::getGroupCaption(const ESM::Group& group) {
switch (group.type) {
case ESM::GroupType::Top:
return getRecordFullName(group.label);
break;
case ESM::GroupType::WorldChildren:
return "World Children";
break;
case ESM::GroupType::InteriorCellBlock:
return "Block " + QString::number(*(int32_t*)(&group.label[0]));
break;
case ESM::GroupType::InteriorCellSubBlock:
return "Sub-Block " + QString::number(*(int32_t*)(&group.label[0]));
break;
case ESM::GroupType::ExteriorCellBlock:
return "Block";
break;
case ESM::GroupType::ExteriorCellSubBlock:
return "Sub-Block";
break;
case ESM::GroupType::CellChildren:
return "Cell children";
break;
case ESM::GroupType::TopicChildren:
return "Topic children";
break;
case ESM::GroupType::CellPersistentChildren:
return "Persistent";
break;
case ESM::GroupType::CellTemporaryChildren:
return "Temporary";
break;
default:
return "Group"; // TODO should not happen?
break;
}
} | 26.719697 | 106 | 0.68727 | kstemp |
19d984e9b5562b1f89838d17a1e10c164a8a6b78 | 1,360 | cpp | C++ | D01/ex00/main.cpp | amoinier/piscine-cpp | 43d4806d993eb712f49a32e54646d8c058a569ea | [
"MIT"
] | null | null | null | D01/ex00/main.cpp | amoinier/piscine-cpp | 43d4806d993eb712f49a32e54646d8c058a569ea | [
"MIT"
] | null | null | null | D01/ex00/main.cpp | amoinier/piscine-cpp | 43d4806d993eb712f49a32e54646d8c058a569ea | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amoinier <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/03 09:09:58 by amoinier #+# #+# */
/* Updated: 2017/10/04 17:39:41 by amoinier ### ########.fr */
/* */
/* ************************************************************************** */
#include "Pony.hpp"
static void ponyOnTheHeap(void)
{
Pony* ponyHeap = new Pony("Petit_Tonerre");
std::cout << ponyHeap->getName() << " attacks you !" << std::endl;
delete ponyHeap;
return ;
}
static void ponyOnTheStack(void)
{
Pony ponyStack = Pony("Chocolat");
std::cout << ponyStack.getName() << " attacks you !" << std::endl;
return ;
}
int main()
{
ponyOnTheHeap();
ponyOnTheStack();
std::cout << "Where are ponies ?" << std::endl;
return 0;
}
| 32.380952 | 80 | 0.294118 | amoinier |
19dcb470546b54f68991f8e4df94417ed86b88d1 | 1,201 | cpp | C++ | app/main.cpp | frachop/ezWebSockify | a35ff5aa7867830b0b51d9d7dfedc44e55f27eab | [
"MIT"
] | null | null | null | app/main.cpp | frachop/ezWebSockify | a35ff5aa7867830b0b51d9d7dfedc44e55f27eab | [
"MIT"
] | null | null | null | app/main.cpp | frachop/ezWebSockify | a35ff5aa7867830b0b51d9d7dfedc44e55f27eab | [
"MIT"
] | null | null | null | //
// main.cpp
// ezWebSockify
//
// Created by Franck on 22/07/2020.
// Copyright © 2020 Frachop. All rights reserved.
//
#include <ezWebSockifyLib/ezWebSockifyLib.hpp>
#include <iostream>
#include <limits>
#include <csignal>
#include <thread>
namespace
{
volatile std::sig_atomic_t gSignalStatus;
}
void signal_handler(int signal)
{
std::cout << "handling ctrl-c signal" << std::endl;
gSignalStatus = signal;
ezWebSockify::stop();
}
int main(int argc, const char * argv[])
{
if (argc != 4)
{
std::cerr << "ezWebSockify version " << ezWebSockify::getVersionString() << std::endl;
std::cerr << "Usage: ezWebSockify <wsPort> <tcpHost> <tcpPort>" << std::endl;
return 1;
}
auto const wsPort{ std::atoi(argv[1]) };
auto const tcpHost{ argv[2] };
auto const tcpPort{ std::atoi(argv[3]) };
if ((wsPort <= 0) || (tcpPort <= 0) || (wsPort > std::numeric_limits<uint16_t>::max()) || (tcpPort > std::numeric_limits<uint16_t>::max()))
{
std::cerr << "port out of range" << std::endl;
return 1;
}
// Install a signal handler
std::signal(SIGINT, signal_handler);
ezWebSockify::start(wsPort, tcpHost, tcpPort);
ezWebSockify::wait();
ezWebSockify::cleanup();
return 0;
}
| 21.446429 | 140 | 0.661948 | frachop |
19e5207ad65c5f2f519ab2a797b1c27220dabaab | 2,048 | cpp | C++ | tests/test_asm/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | tests/test_asm/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | tests/test_asm/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | // Ассемблерные вставки на GCC с флагом -masm=intel в .pro для синтаксиса Intel
// (тоже самое можно и через команды .intel_syntax noprefix в начале asm вставки (и после кода, но внутри вставки, надо было вкл обратно AT&T .att_syntax noprefix)
// использовать либо глобальные переменные, или локальные объявлять согласно AT&T syntax (или это GAS ассемблер, не знаю точно) после кода через : выходные операнды, .., .., : входные, .., ..
// в квадратных скобках можно указать имя операнда входного / выходного
// m - ограничитель, означает, что операнд передается через память, а всякие ir, r и так далее - это РОН
// во 2 функции показал, как можно без \n обойтись
#include <stdio.h>
#include <iostream>
inline int cmp_asm(int a, int b, int c){
asm( //ассемблерная функция
"mov edx, %[a]\n" // помещение в регистр еdх значения переменной а
"cmp edx, %[b]\n" // сравнение содержимого регистра edx и переменной b
"ja m1\n" // условный переход
"mov edx, %[b]\n" // помещение в регистр еdх значения переменной b
"m1: cmp edx, %[c]\n" // сравнение содержимого регистра edx и переменной c
"jna m2\n" // условный переход
"mov %[c], edx\n" // помещение в переменную c содержимого регистра еdх
"m2:\n"
: [c] "+m" (c)
: [a] "m" (a), [b] "m" (b)
);
return c;
}
inline int cmp_asm_2(int a, int b, int c){
asm (
R"(
mov edx, %[a] # коммент
cmp edx, %[b]
ja m1
mov edx, %[b]
m1: cmp edx, %[c]
jna m2
mov %[c], edx
m2:
)"
: [c] "+m" (c)
: [a] "m" (a), [b] "m" (b)
);
return c;
}
int main()
{
int k, m, n; //инициализация целочисленных переменных
printf("Compare\n");
printf("Please, input 1st number\n");
scanf("%d", &k);
printf("Please, input 2nd number\n");
scanf("%d", &m);
printf("Please, input 2nd number\n");
scanf("%d", &n);
std::cout << cmp_asm(k, m, n);
scanf("%d", &n);
return 0;
}
| 29.681159 | 192 | 0.581055 | SgAkErRu |
19e87cf737beb7be0f14c977cf595772b345c4d6 | 166 | hpp | C++ | modules/anti_nd/functions/CfgFunctions.hpp | goosko/Olsen-Framework-Arma-3 | bb77aa28195bb04cc3b94ec768901308162e555c | [
"MIT"
] | 4 | 2020-05-04T18:03:59.000Z | 2020-05-06T19:40:27.000Z | modules/anti_nd/functions/CfgFunctions.hpp | goosko/Olsen-Framework-Arma-3 | bb77aa28195bb04cc3b94ec768901308162e555c | [
"MIT"
] | 64 | 2020-09-13T23:26:04.000Z | 2022-03-19T07:27:54.000Z | modules/anti_nd/functions/CfgFunctions.hpp | goosko/Olsen-Framework-Arma-3 | bb77aa28195bb04cc3b94ec768901308162e555c | [
"MIT"
] | 5 | 2020-12-07T20:37:05.000Z | 2022-02-03T21:03:49.000Z | #include "..\script_component.hpp"
class COMPONENT {
tag = COMPONENT;
class ANTI_ND {
file = "modules\anti_nd\functions\anti_nd";
class Init {};
};
};
| 18.444444 | 46 | 0.644578 | goosko |
19e98193d98bf64799596d2ad3257aebf61f771e | 1,224 | hpp | C++ | include/c9/time.hpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | 1 | 2015-02-13T02:03:29.000Z | 2015-02-13T02:03:29.000Z | include/c9/time.hpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | include/c9/time.hpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null |
#pragma once
#include <time.h>
#include <sys/time.h>
class Time {
double t;
public:
Time(){
struct timeval time;
gettimeofday(&time, NULL);
t = time.tv_sec + (double)time.tv_usec/1000000;
}
Time(double a) : t(a) { }
Time(const struct timeval & time){
t = time.tv_sec + (double)time.tv_usec/1000000;
}
int to_i() const { return (int)t; }
long long in_msec() const { return (long long)(t*1000); }
long long in_usec() const { return (long long)(t*1000000); }
double to_f() const { return t; }
Time operator + (double a) const { return Time(t+a); }
Time & operator += (double a) { t += a; return *this; }
double operator - (const Time & a) const { return t - a.t; }
Time operator - (double a) const { return Time(t-a); }
Time & operator -= (double a) { t -= a; return *this; }
bool operator < (const Time & a) const { return t < a.t; }
bool operator <= (const Time & a) const { return t <= a.t; }
bool operator > (const Time & a) const { return t > a.t; }
bool operator >= (const Time & a) const { return t >= a.t; }
bool operator == (const Time & a) const { return t == a.t; }
bool operator != (const Time & a) const { return t != a.t; }
};
| 31.384615 | 68 | 0.589869 | stormbrew |
19eef03109ee5a2f874e7d1472c806102736e9aa | 173 | cc | C++ | src/Encoder/encoders/none.cc | grzegorzmatczak/PostProcessingModules | bc815541453453f58fc40bd9c00bfc03be1fa3b5 | [
"MIT"
] | null | null | null | src/Encoder/encoders/none.cc | grzegorzmatczak/PostProcessingModules | bc815541453453f58fc40bd9c00bfc03be1fa3b5 | [
"MIT"
] | null | null | null | src/Encoder/encoders/none.cc | grzegorzmatczak/PostProcessingModules | bc815541453453f58fc40bd9c00bfc03be1fa3b5 | [
"MIT"
] | null | null | null | #include "none.h"
Encoders::None::None() {}
void Encoders::None::process(std::vector<_postData> &_data) {}
void Encoders::None::endProcess(std::vector<_postData> &_data) {} | 34.6 | 65 | 0.710983 | grzegorzmatczak |
19f09c1442cbb814783fca9449d00971fcadc05f | 5,300 | hpp | C++ | vendor/libbitcoin/include/bitcoin/bitcoin/chain/header.hpp | X9Developers/xsn-wallet | 7b5aaf6de15928c8cf5b86a844e56710c301df1f | [
"MIT"
] | 1 | 2018-08-20T11:15:45.000Z | 2018-08-20T11:15:45.000Z | vendor/libbitcoin/include/bitcoin/bitcoin/chain/header.hpp | X9Developers/xsn-wallet | 7b5aaf6de15928c8cf5b86a844e56710c301df1f | [
"MIT"
] | null | null | null | vendor/libbitcoin/include/bitcoin/bitcoin/chain/header.hpp | X9Developers/xsn-wallet | 7b5aaf6de15928c8cf5b86a844e56710c301df1f | [
"MIT"
] | 3 | 2018-08-30T08:35:43.000Z | 2019-03-29T15:36:26.000Z | /**
* Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_CHAIN_HEADER_HPP
#define LIBBITCOIN_CHAIN_HEADER_HPP
#include <cstddef>
#include <cstdint>
#include <istream>
#include <string>
#include <memory>
#include <vector>
#include <bitcoin/bitcoin/chain/chain_state.hpp>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/error.hpp>
#include <bitcoin/bitcoin/math/hash.hpp>
#include <bitcoin/bitcoin/utility/data.hpp>
#include <bitcoin/bitcoin/utility/reader.hpp>
#include <bitcoin/bitcoin/utility/thread.hpp>
#include <bitcoin/bitcoin/utility/writer.hpp>
namespace libbitcoin {
namespace chain {
class BC_API header
{
public:
typedef std::vector<header> list;
typedef std::shared_ptr<header> ptr;
typedef std::shared_ptr<const header> const_ptr;
typedef std::vector<ptr> ptr_list;
typedef std::vector<const_ptr> const_ptr_list;
// THIS IS FOR LIBRARY USE ONLY, DO NOT CREATE A DEPENDENCY ON IT.
struct validation
{
size_t height = 0;
uint32_t median_time_past = 0;
};
// Constructors.
//-----------------------------------------------------------------------------
header();
header(header&& other);
header(const header& other);
header(header&& other, hash_digest&& hash);
header(const header& other, const hash_digest& hash);
header(uint32_t version, const hash_digest& previous_block_hash,
const hash_digest& merkle, uint32_t timestamp, uint32_t bits,
uint32_t nonce);
header(uint32_t version, hash_digest&& previous_block_hash,
hash_digest&& merkle, uint32_t timestamp, uint32_t bits, uint32_t nonce);
// Operators.
//-----------------------------------------------------------------------------
/// This class is move and copy assignable.
header& operator=(header&& other);
header& operator=(const header& other);
bool operator==(const header& other) const;
bool operator!=(const header& other) const;
// Deserialization.
//-----------------------------------------------------------------------------
static header factory_from_data(const data_chunk& data, bool wire=true);
static header factory_from_data(std::istream& stream, bool wire=true);
static header factory_from_data(reader& source, bool wire=true);
bool from_data(const data_chunk& data, bool wire=true);
bool from_data(std::istream& stream, bool wire=true);
bool from_data(reader& source, bool wire=true);
bool is_valid() const;
// Serialization.
//-----------------------------------------------------------------------------
data_chunk to_data(bool wire=true) const;
void to_data(std::ostream& stream, bool wire=true) const;
void to_data(writer& sink, bool wire=true) const;
// Properties (size, accessors, cache).
//-----------------------------------------------------------------------------
static size_t satoshi_fixed_size();
size_t serialized_size(bool wire=true) const;
uint32_t version() const;
void set_version(uint32_t value);
// Deprecated (unsafe).
hash_digest& previous_block_hash();
const hash_digest& previous_block_hash() const;
void set_previous_block_hash(const hash_digest& value);
void set_previous_block_hash(hash_digest&& value);
// Deprecated (unsafe).
hash_digest& merkle();
const hash_digest& merkle() const;
void set_merkle(const hash_digest& value);
void set_merkle(hash_digest&& value);
uint32_t timestamp() const;
void set_timestamp(uint32_t value);
uint32_t bits() const;
void set_bits(uint32_t value);
uint32_t nonce() const;
void set_nonce(uint32_t value);
hash_digest hash() const;
// Validation.
//-----------------------------------------------------------------------------
bool is_valid_timestamp() const;
bool is_valid_proof_of_work(bool retarget=true) const;
code check(bool retarget=false) const;
code accept(const chain_state& state) const;
// THIS IS FOR LIBRARY USE ONLY, DO NOT CREATE A DEPENDENCY ON IT.
mutable validation validation;
protected:
// So that block may call reset from its own.
friend class block;
void reset();
void invalidate_cache() const;
private:
mutable upgrade_mutex mutex_;
mutable std::shared_ptr<hash_digest> hash_;
uint32_t version_;
hash_digest previous_block_hash_;
hash_digest merkle_;
uint32_t timestamp_;
uint32_t bits_;
uint32_t nonce_;
};
} // namespace chain
} // namespace libbitcoin
#endif
| 30.813953 | 83 | 0.648679 | X9Developers |
19f40170d4c897b616e1a728cb76fe4ffb49a816 | 1,025 | cpp | C++ | src/inputwin.cpp | mastereuclid/cs494project | 8131fb23e20a96c50e7d1252af2bc359e1009a52 | [
"Apache-2.0"
] | null | null | null | src/inputwin.cpp | mastereuclid/cs494project | 8131fb23e20a96c50e7d1252af2bc359e1009a52 | [
"Apache-2.0"
] | null | null | null | src/inputwin.cpp | mastereuclid/cs494project | 8131fb23e20a96c50e7d1252af2bc359e1009a52 | [
"Apache-2.0"
] | null | null | null | #include "inputwin.hpp"
#include <iostream>
inputwin::inputwin()
: nc::window(nc::points_t(getmaxy(stdscr) - 5, 0, getmaxy(stdscr), getmaxx(stdscr)),
nc::border_t(false, true, false, false)) {}
void inputwin::on_focus() {
clear();
echo();
wmove(winptr(), 1, 0);
}
void inputwin::get_input(std::function<void(std::string)> pass_along) const {
for (int input = wgetch(winptr()); input != nc::button_tab; input = wgetch(winptr())) {
if (input == nc::button_enter) {
clear();
// do something with buffer
pass_along(buffer);
buffer.clear();
wmove(winptr(), 1, 0);
continue;
}
const char key = static_cast<char>(input);
buffer.append(1, key);
}
buffer.clear();
}
void inputwin::clear() const {
int max_x = getmaxx(winptr()), max_y = getmaxy(winptr());
for (int y = 1; y < max_y; y++) {
for (int x = 0; x < max_x; x++) {
wmove(winptr(), y, x);
waddch(winptr(), ' ');
}
}
wmove(winptr(), 1, 0);
wrefresh(winptr());
} | 26.973684 | 89 | 0.578537 | mastereuclid |
19f71e32a9786be81906c094a023a4beb7db4852 | 548 | cpp | C++ | coffeeDBR/src/cml_oneMin/cml_golden.cpp | CoFFeeMaN11/CoffeeDBR | 1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b | [
"Apache-2.0"
] | null | null | null | coffeeDBR/src/cml_oneMin/cml_golden.cpp | CoFFeeMaN11/CoffeeDBR | 1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b | [
"Apache-2.0"
] | null | null | null | coffeeDBR/src/cml_oneMin/cml_golden.cpp | CoFFeeMaN11/CoffeeDBR | 1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b | [
"Apache-2.0"
] | null | null | null | #include "cml_golden.h"
#include <cassert>
#define GOLDEN_RADIO 0.6180339887498949L
void GoldenSec::Iterate()
{
assert(func);
long double fL, fR;
func(xL, params, fL);
func(xR, params, fR);
if (fL < fR)
{
b = xR;
xR = xL;
xL = b - GOLDEN_RADIO * (b - a);
}
else
{
a = xL;
xL = xR;
xR = a + GOLDEN_RADIO * (b - a);
}
minimum = (a + b) / 2;
}
bool GoldenSec::InitMethod(long double xStart)
{
if(!IOneMin::InitMethod(xStart))
return false;
xL = b - GOLDEN_RADIO * (b - a);
xR = a + GOLDEN_RADIO * (b - a);
return true;
}
| 16.606061 | 46 | 0.596715 | CoFFeeMaN11 |
19fb6c685d7ac8c20c312ac9b8f969207a4dc116 | 1,737 | hpp | C++ | src/svg/svg_parser.hpp | malasiot/xg | 02bdcc208f479afb448767e4d2f2764e913e5d43 | [
"MIT"
] | 1 | 2019-09-06T01:48:15.000Z | 2019-09-06T01:48:15.000Z | src/svg/svg_parser.hpp | malasiot/xg | 02bdcc208f479afb448767e4d2f2764e913e5d43 | [
"MIT"
] | null | null | null | src/svg/svg_parser.hpp | malasiot/xg | 02bdcc208f479afb448767e4d2f2764e913e5d43 | [
"MIT"
] | null | null | null | #ifndef __XG_SVG_PARSER_HPP__
#define __XG_SVG_PARSER_HPP__
#include <string>
#include <xg/util/dictionary.hpp>
#include <iostream>
#include "svg_dom.hpp"
namespace xg {
class SVGLoadException ;
class SVGDocument ;
class SVGParser {
public:
SVGParser(SVGDocument &doc): document_(doc) {}
void parseString(const std::string &xml) ;
void parseStream(std::istream &strm, size_t buffer_sz = 1024) ;
protected:
template <typename T>
std::shared_ptr<T> createNode(const Dictionary &a, bool is_root = false) {
auto node = std::make_shared<T>() ;
if ( is_root )
root_ = dynamic_cast<svg::SVGElement *>(node.get()) ;
node->setDocument(&document_) ;
auto ele = std::dynamic_pointer_cast<svg::Element>(node) ;
if ( !nodes_.empty() ) {
auto stack_node = nodes_.back() ;
stack_node->addChild(ele) ;
}
nodes_.push_back(ele) ;
node->parseAttributes(a) ;
return node ;
}
void beginElement(const std::string &name, const Dictionary &attributes) ;
void endElement() ;
void characters(const std::string &name) ;
private:
static void start_element_handler(void *data, const char *element_name, const char **attributes) ;
static void end_element_handler(void *data, const char *elelemnt_name);
static void character_data_handler(void *data, const char *character_data, int length);
void handleCharacterData() ;
std::string processWhiteSpace(const std::string &);
private:
std::string text_ ;
SVGDocument &document_ ;
std::deque<std::shared_ptr<svg::Element>> nodes_ ;
std::deque<std::string> elements_ ;
svg::SVGElement *root_ = nullptr;
};
}
#endif
| 23.794521 | 102 | 0.663212 | malasiot |
19fe25e1a06c3a0e321ce78d8fc2e4e2c5a1ba3f | 514 | cpp | C++ | Tree/Convert BT to Doubly Linked List.cpp | Benson1198/CPP | b12494becadc9431303cfdb51c5134dc68c679c3 | [
"MIT"
] | null | null | null | Tree/Convert BT to Doubly Linked List.cpp | Benson1198/CPP | b12494becadc9431303cfdb51c5134dc68c679c3 | [
"MIT"
] | null | null | null | Tree/Convert BT to Doubly Linked List.cpp | Benson1198/CPP | b12494becadc9431303cfdb51c5134dc68c679c3 | [
"MIT"
] | 1 | 2020-10-06T09:17:33.000Z | 2020-10-06T09:17:33.000Z | #include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left;
Node *right;
Node(int k){
data = k;
left = NULL;
right = NULL;
}
}
Node *prev = NULL;
Node *BTToDLL(Node *root){
if(root == NULL){
return root;
}
Node* head = BTToDLL(root->left);
if(prev == NULL){
head = root;
}
else{
root->left = prev;
prev->right = root;
}
prev = root;
BTToDLL(root->right);
return head;
} | 13.526316 | 37 | 0.490272 | Benson1198 |
c205135c11d51528b686eccfca8179e398d42899 | 5,015 | cpp | C++ | DarkSpace/GadgetAreaWeapon.cpp | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | 1 | 2016-05-22T21:28:29.000Z | 2016-05-22T21:28:29.000Z | DarkSpace/GadgetAreaWeapon.cpp | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | null | null | null | DarkSpace/GadgetAreaWeapon.cpp | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | null | null | null | /*
GadgetAreaWeapon.cpp
(c)2000 Palestar Inc, Richard Lyle
*/
#include "GadgetAreaWeapon.h"
#include "GameContext.h"
static Constant AI_USE_AREA_WEAPON( "AI_USE_AREA_WEAPON", 0.75f );
//----------------------------------------------------------------------------
IMPLEMENT_ABSTRACT_FACTORY( GadgetAreaWeapon, NounGadget );
REGISTER_FACTORY_KEY( GadgetAreaWeapon, 4373539570291853529LL );
BEGIN_ABSTRACT_PROPERTY_LIST( GadgetAreaWeapon, NounGadget );
ADD_TRANSMIT_UPDATE_PROPERTY( m_Energy );
END_PROPERTY_LIST();
GadgetAreaWeapon::GadgetAreaWeapon() : m_Energy( 0 ), m_nEnergyTick( 0 ), m_fChargeRate( 0.0f )
{}
//----------------------------------------------------------------------------
void GadgetAreaWeapon::setup()
{
NounGadget::setup();
// start out with full energy
m_Energy = energyNeeded();
}
//----------------------------------------------------------------------------
NounGadget::Type GadgetAreaWeapon::type() const
{
return WEAPON;
}
NounGadget::EnergyClass GadgetAreaWeapon::energyClass() const
{
return ENERGY_CLASS_WEAPONS;
}
dword GadgetAreaWeapon::hotkey() const
{
return 'V';
}
CharString GadgetAreaWeapon::useTip( Noun * pTarget, bool shift ) const
{
CharString tip;
// usage information
tip += CharString().format("\nRange:<X;100>%.0fgu", range() * calculateModifier( MT_WEAPON_RANGE ) );
tip += CharString().format("\nDamage:<X;100>%.0f-%.0f", ( damageCaused() * calculateModifier( MT_WEAPON_DAMAGE ) ) * damageRolls(), ( ( damageCaused() + damageRandom() ) * calculateModifier( MT_WEAPON_DAMAGE ) ) * damageRolls() );
tip += CharString().format("\nRecharge Time:<X;100>%.1fs", energyNeeded() / ( ( ( chargeRate() * TICKS_PER_SECOND ) * damageRatioInv() ) * calculateModifier( MT_WEAPON_ENERGY ) ) );
tip += CharString().format("\nEnergy Cost:<X;100>%.1f", energyNeeded() / 1000.0f );
return tip;
}
//----------------------------------------------------------------------------
int GadgetAreaWeapon::usableWhen() const
{
return (100 - ((m_Energy * 100) / energyNeeded()));
}
bool GadgetAreaWeapon::usable( Noun * pTarget, bool shift ) const
{
if (! NounGadget::usable( pTarget, shift ) )
return false;
if ( destroyed() )
return false;
if ( WidgetCast<NounShip>( parent() ) && ((NounShip *)parent())->testFlags( NounShip::FLAG_CLOAKED|NounShip::FLAG_IN_SAFE_ZONE ) )
return false;
if ( m_Energy < energyNeeded() )
return false;
return true;
}
void GadgetAreaWeapon::use( dword when, Noun * pTarget, bool shift)
{
NounGadget::use( when, pTarget, shift );
createUseEffect( false );
m_Energy = 0;
m_nEnergyTick = when;
Vector3 origin( worldPosition() );
float fRange = range() * calculateModifier( MT_WEAPON_RANGE );
Array< GameContext::NounCollision > collide;
if ( context()->proximityCheck( origin, fRange, collide ) )
{
for(int i=0;i<collide.size();i++)
{
NounGame * pCollide = WidgetCast<NounGame>( collide[ i ].pNoun );
if ( pCollide != NULL && pCollide != parent() && isEnemy( pCollide )
&& pCollide->canDamage( damageType() ) )
{
float fDistance = collide[i].fDistance - pCollide->radius();
if ( fDistance < range() )
{
float damageRatio = 1.0f - (fDistance / range());
for(int k=0;k<damageRolls();++k)
{
int damage = damageRatio * damageCaused();
if ( damageRandom() > 0 )
damage += rand() % damageRandom();
if ( damage > 0 )
{
// send the damage verb
damage *= calculateModifier( MT_WEAPON_DAMAGE );
pCollide->inflictDamage( tick() + k, parentBody(), damage, damageType(),
pCollide->worldFrame() * (origin - pCollide->worldPosition()) );
}
}
}
}
}
}
}
int GadgetAreaWeapon::useEnergy( dword nTick, int energy )
{
int nElapsed = nTick - m_nEnergyTick;
m_nEnergyTick = nTick;
if ( m_Energy < energyNeeded() )
{
float fEnergyMod = calculateModifier( MT_WEAPON_ENERGY );
float fChargeScale = damageRatioInv() * fEnergyMod;
m_fChargeRate += chargeRate() * fChargeScale * nElapsed;
int chargeRate = floor( m_fChargeRate );
m_fChargeRate -= chargeRate; // leave fractional amount in the float for next update..
int charge = Min( Min( energyNeeded() - m_Energy, chargeRate ), energy );
energy -= charge;
m_Energy += charge;
}
return energy;
}
bool GadgetAreaWeapon::updateLogic()
{
if ( useActive() || usableWhen() > 0 )
return true;
if ( WidgetCast<NounShip>( parent() ) )
{
NounShip * pShip = (NounShip *)parent();
bool bFireWeapon = false;
for(int i=0;i<pShip->contactCount() && !bFireWeapon;++i)
{
Noun * pContact = pShip->contact( i );
if (! pContact || !isEnemy( pContact ) )
continue;
float fDistance = (pContact->worldPosition() - pShip->worldPosition()).magnitude();
if ( fDistance < (range() * AI_USE_AREA_WEAPON) )
bFireWeapon = true;
}
if ( bFireWeapon )
pShip->useGadget( this, NULL, false );
}
return false;
}
//----------------------------------------------------------------------------
//EOF
| 27.861111 | 232 | 0.619143 | SnipeDragon |
c207f71a6fd127e7e6284e909bba8ab6efdf6876 | 283 | cpp | C++ | src/TextureManager.cpp | ArionasMC/Asteroids | b5a81f833af1615ede2706bfe41baa8b661fa209 | [
"Apache-2.0"
] | 3 | 2019-02-23T18:20:24.000Z | 2019-02-23T18:30:18.000Z | src/TextureManager.cpp | ArionasMC/Asteroids | b5a81f833af1615ede2706bfe41baa8b661fa209 | [
"Apache-2.0"
] | null | null | null | src/TextureManager.cpp | ArionasMC/Asteroids | b5a81f833af1615ede2706bfe41baa8b661fa209 | [
"Apache-2.0"
] | null | null | null | #include "TextureManager.h"
SDL_Texture* TextureManager::LoadTexture(const char* fileName, SDL_Renderer* ren) {
SDL_Surface* tmp = IMG_Load(fileName);
SDL_Texture* texture = SDL_CreateTextureFromSurface(ren, tmp);
SDL_FreeSurface(tmp);
return texture;
}
| 25.727273 | 84 | 0.717314 | ArionasMC |
c209b94f8e83db1255f3296bc6425698edd7cb86 | 976 | cpp | C++ | String/is_substring_hash.cpp | ShreyashRoyzada/C-plus-plus-Algorithms | 9db89faf0a9b9e636aece3e7289f21ab6a1e3748 | [
"MIT"
] | 21 | 2020-10-03T03:57:19.000Z | 2022-03-25T22:41:05.000Z | String/is_substring_hash.cpp | ShreyashRoyzada/C-plus-plus-Algorithms | 9db89faf0a9b9e636aece3e7289f21ab6a1e3748 | [
"MIT"
] | 40 | 2020-10-02T07:02:34.000Z | 2021-10-30T16:00:07.000Z | String/is_substring_hash.cpp | ShreyashRoyzada/C-plus-plus-Algorithms | 9db89faf0a9b9e636aece3e7289f21ab6a1e3748 | [
"MIT"
] | 90 | 2020-10-02T07:06:22.000Z | 2022-03-25T22:41:17.000Z | #include<bits/stdc++.h>
using namespace std;
#define ll long long
ll compute_hash(string s){
const int p= 3;
const int m= 1e9+9;
ll hash_value= 0;
ll p_pow= (ll)pow(p,s.length()-1);
for(auto c:s){
hash_value= (hash_value+ (c-'a')*p_pow)%m;
p_pow= p_pow/p;
}
return hash_value;
}
ll rolling_hash(ll H,string prev,char nxt)
{
const int p = 31;
const int m = 1e9 + 9;
ll Hnxt=( ( H - (prev[0]-'a')*(ll)pow(p,prev.length()-1) ) * p + (nxt-'a') ) % m;
return Hnxt;
}
bool is_substring(string s1,string s2){
int j=0;
string prev= s1.substr(j,s2.length());
j++;
map<ll,int>m1,m2;
ll h2= compute_hash(s2);
ll h1= compute_hash(s1);
m1[h1]=1;
m2[h2]=1;
for(int i=s2.length();i<s1.length();i++){
h1= rolling_hash(h1,prev,s1[i]);
m1[h1]=1;
prev=s1.substr(j,s2.length());
j++;
}
return m1[h2]==m2[h2];
}
int main()
{
string s1= "iitian";
string s2= "iiti";
if(is_substring(s1,s2)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
| 19.918367 | 84 | 0.597336 | ShreyashRoyzada |
c20b48bd40a8ae93332191ba4e3bb061a3fa2e7b | 929 | hpp | C++ | lib/SensorNode/SHT30Node.hpp | RobAxt/SmartWeatherStation | 5b756f91d6b9c8c10eab6eac1403f2362e91670c | [
"MIT"
] | null | null | null | lib/SensorNode/SHT30Node.hpp | RobAxt/SmartWeatherStation | 5b756f91d6b9c8c10eab6eac1403f2362e91670c | [
"MIT"
] | null | null | null | lib/SensorNode/SHT30Node.hpp | RobAxt/SmartWeatherStation | 5b756f91d6b9c8c10eab6eac1403f2362e91670c | [
"MIT"
] | null | null | null | #ifndef SHT30Node_hpp
#define SHT30Node_hpp
#include <Wire.h>
#include <SHT3x.h>
#include "SensorNode.hpp"
class SHT30Node : public SensorNode {
public:
explicit SHT30Node(const char *id, const char *name, const int i2cAddress = 0x45);
~SHT30Node();
protected:
virtual void setup() override;
virtual void onReadyToOperate() override;
virtual void sendMeasurement() override;
virtual void takeMeasurement() override;
private:
const char* TMP_TOPIC = "temperature";
const char* HUM_TOPIC = "humidity";
HomieSetting<double> *_humidityFactor;
HomieSetting<double> *_humidityOffset;
HomieSetting<double> *_temperatureFactor;
HomieSetting<double> *_temperatureOffset;
SHT3x _sht30;
float _temperature = NAN;
float _humidity = NAN;
};
#endif //SHT30Node_hpp
//https://www.wemos.cc/en/latest/d1_mini_shield/sht30.html
//https://github.com/Risele/SHT3x.git#master | 25.805556 | 87 | 0.724435 | RobAxt |
c20c40dd4339ae0b5bff34aa20c9ac6a9d0d58dc | 8,396 | cpp | C++ | src/Engine/Engine/Shibboleth_Image.cpp | Connway/Shibboleth | 23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35 | [
"MIT"
] | 1 | 2020-04-06T17:35:47.000Z | 2020-04-06T17:35:47.000Z | src/Engine/Engine/Shibboleth_Image.cpp | Connway/Shibboleth | 23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35 | [
"MIT"
] | null | null | null | src/Engine/Engine/Shibboleth_Image.cpp | Connway/Shibboleth | 23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35 | [
"MIT"
] | null | null | null | /************************************************************************************
Copyright (C) 2021 by Nicholas LaCroix
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 "Shibboleth_Image.h"
#include "Shibboleth_LogManager.h"
#include "Shibboleth_Utilities.h"
#include "Shibboleth_String.h"
#include "Shibboleth_Vector.h"
#include "Shibboleth_IApp.h"
#include <Gaff_Math.h>
#include <tiffio.h>
#include <png.h>
NS_SHIBBOLETH
static ProxyAllocator g_image_allocator("Image");
static void* ImageMalloc(png_structp, png_alloc_size_t size)
{
return SHIB_ALLOC(size, g_image_allocator);
}
static void ImageFree(png_structp, void* ptr)
{
SHIB_FREE(ptr, g_image_allocator);
}
static void ImageWarning(png_structp, png_const_charp message)
{
LogWarningDefault("%s", message);
}
static void ImageError(png_structp, png_const_charp message)
{
LogErrorDefault("%s", message);
}
struct BufferData final
{
const void* buffer;
const size_t size;
size_t curr_byte_offset;
};
static void PNGRead(png_structp png_ptr, png_bytep out_buffer, png_size_t out_size)
{
const png_voidp io_ptr = png_get_io_ptr(png_ptr);
if (!io_ptr) {
return;
}
BufferData* const buffer_data = reinterpret_cast<BufferData*>(io_ptr);
const size_t read_size = Gaff::Min(buffer_data->size - buffer_data->curr_byte_offset, out_size);
memcpy(out_buffer, reinterpret_cast<const int8_t*>(buffer_data->buffer) + buffer_data->curr_byte_offset, read_size);
buffer_data->curr_byte_offset += read_size;
}
static tsize_t TIFFRead(thandle_t st, tdata_t buffer, tsize_t size)
{
const BufferData* const data = reinterpret_cast<const BufferData*>(st);
const size_t bytes_read = Gaff::Min(static_cast<size_t>(size), data->size - data->curr_byte_offset);
memcpy(buffer, data->buffer, bytes_read);
return bytes_read;
}
static tsize_t TIFFWrite(thandle_t st, tdata_t buffer, tsize_t size)
{
//BufferData* const data = reinterpret_cast<BufferData*>(st);
//const size_t bytes_written = Gaff::Min(static_cast<size_t>(size), data->size - data->curr_byte_offset);
//memcpy(reinterpret_cast<int8_t*>(data->buffer) + data->curr_byte_offset, buffer, bytes_written);
//return bytes_written;
GAFF_REF(st, buffer, size);
return 0;
}
static int TIFFClose(thandle_t)
{
return 0;
}
static toff_t TIFFSeek(thandle_t st, toff_t pos, int whence)
{
if (pos == 0xFFFFFFFF) {
return 0xFFFFFFFF;
}
BufferData* const data = reinterpret_cast<BufferData*>(st);
switch (whence) {
case SEEK_SET:
GAFF_ASSERT(pos < data->size);
data->curr_byte_offset = pos;
break;
case SEEK_CUR:
GAFF_ASSERT((data->curr_byte_offset + pos) < data->size);
data->curr_byte_offset += pos;
break;
case SEEK_END:
// Unsupported.
break;
}
return data->curr_byte_offset;
}
static toff_t TIFFSize(thandle_t st)
{
return reinterpret_cast<const BufferData*>(st)->size;
}
static int TIFFMap(thandle_t st, tdata_t* buffer, toff_t* size)
{
BufferData* const data = reinterpret_cast<BufferData*>(st);
*buffer = const_cast<void*>(data->buffer);
*size = data->size;
return 1;
}
static void TIFFError(const char* module, const char* format, va_list va)
{
U8String format_string;
format_string.sprintf_va_list(format, va);
LogErrorDefault("TIFF [%s]: %s", module, format);
}
static void TIFFWarning(const char* module, const char* format, va_list va)
{
U8String format_string;
format_string.sprintf_va_list(format, va);
LogWarningDefault("TIFF [%s]: %s", module, format);
}
static void TIFFUnmap(thandle_t, tdata_t, toff_t)
{
}
int32_t Image::getWidth(void) const
{
return _width;
}
int32_t Image::getHeight(void) const
{
return _height;
}
int32_t Image::getBitDepth(void) const
{
return _bit_depth;
}
int32_t Image::getNumChannels(void) const
{
return _num_channels;
}
const uint8_t* Image::getBuffer(void) const
{
return _image.data();
}
uint8_t* Image::getBuffer(void)
{
return _image.data();
}
bool Image::load(const void* buffer, size_t size, const char* file_ext)
{
if (Gaff::EndsWith(file_ext, ".png")) {
return loadPNG(buffer, size);
} else if (Gaff::EndsWith(file_ext, ".tiff") || Gaff::EndsWith(file_ext, ".tif")) {
return loadTIFF(buffer, size);
}
return false;
}
bool Image::loadTIFF(const void* buffer, size_t size)
{
TIFFSetWarningHandler(TIFFWarning);
TIFFSetErrorHandler(TIFFError);
BufferData data = { buffer, size, 0 };
TIFF* const tiff = TIFFClientOpen(
"Memory",
"r",
&data,
TIFFRead,
TIFFWrite,
TIFFSeek,
TIFFClose,
TIFFSize,
TIFFMap,
TIFFUnmap
);
uint32_t width;
uint32_t height;
TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height);
_image.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * sizeof(uint32_t));
const bool success = TIFFReadRGBAImageOriented(tiff, width, height, reinterpret_cast<uint32_t*>(_image.data()), ORIENTATION_TOPLEFT);
TIFFClose(tiff);
if (success) {
_width = static_cast<int32_t>(width);
_height = static_cast<int32_t>(height);
_bit_depth = 8;
_num_channels = 4;
}
return success;
}
bool Image::loadPNG(const void* buffer, size_t size)
{
constexpr size_t PNG_SIG_SIZE = 8;
if (!png_check_sig(reinterpret_cast<png_const_bytep>(buffer), PNG_SIG_SIZE)) {
return false;
}
png_structp png_ptr = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, nullptr, ImageError, ImageWarning, nullptr, ImageMalloc, ImageFree);
if (!png_ptr) {
// $TODO: Log error.
return false;
}
const png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
// $TODO: Log error.
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return false;
}
BufferData data = { buffer, size, PNG_SIG_SIZE };
png_set_read_fn(png_ptr, &data, PNGRead);
// tell libpng we already read the signature
png_set_sig_bytes(png_ptr, PNG_SIG_SIZE);
png_read_info(png_ptr, info_ptr);
png_uint_32 width = 0;
png_uint_32 height = 0;
int bit_depth = 0;
int color_type = -1;
const png_uint_32 retval = png_get_IHDR(
png_ptr,
info_ptr,
&width,
&height,
&bit_depth,
&color_type,
nullptr,
nullptr,
nullptr
);
if (retval != 1) {
// $TODO: Log error
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return false;
}
const png_byte num_channels = png_get_channels(png_ptr, info_ptr);
const size_t bytes_per_row = png_get_rowbytes(png_ptr, info_ptr);
_image.resize(
static_cast<size_t>(width) *
static_cast<size_t>(height) *
(static_cast<size_t>(bit_depth) / 8) *
static_cast<size_t>(num_channels)
);
uint8_t* const start = _image.data();
for (int32_t i = 0; i < static_cast<int32_t>(height); ++i) {
const size_t byte_offset = static_cast<size_t>(i) * bytes_per_row;
png_read_row(png_ptr, start + byte_offset, nullptr);
}
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
_width = static_cast<int32_t>(width);
_height = static_cast<int32_t>(height);
_bit_depth = static_cast<int32_t>(bit_depth);
_num_channels = static_cast<int32_t>(num_channels);
return true;
}
NS_END
| 25.365559 | 140 | 0.699738 | Connway |
c20cca8b430598341fc2947ba45c9dc91f001dc4 | 26,399 | cpp | C++ | src/cpu/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32.cpp | Bil17t/mkl-dnn | 8910895abc655e8e5d9d54ab91c040b26a28902d | [
"Apache-2.0"
] | 6 | 2020-06-04T06:03:36.000Z | 2022-01-27T02:41:49.000Z | src/cpu/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32.cpp | Bil17t/mkl-dnn | 8910895abc655e8e5d9d54ab91c040b26a28902d | [
"Apache-2.0"
] | null | null | null | src/cpu/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32.cpp | Bil17t/mkl-dnn | 8910895abc655e8e5d9d54ab91c040b26a28902d | [
"Apache-2.0"
] | 3 | 2021-07-07T09:55:36.000Z | 2022-01-12T06:59:55.000Z | /*******************************************************************************
* Copyright 2018 Intel Corporation
*
* 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 <cstdint>
#include <mutex>
#include "common.hpp"
#include "mkldnn_types.h"
#include "nstl.hpp"
#include "jit_avx512_core_gemm_s8u8s32.hpp"
namespace mkldnn {
namespace impl {
namespace cpu {
enum {
PARTITION_1D_ROW,
PARTITION_1D_COL,
PARTITION_2D_COL_MAJOR,
PARTITION_2D = PARTITION_2D_COL_MAJOR,
};
enum {
COPY_NONE,
COPY_A,
};
// Alias for any dimension related variable.
typedef long long int dim_t;
typedef struct {
// Interface arguments.
int transa, transb, offsetc;
dim_t m, n, k;
dim_t lda, ldb, ldc;
const int8_t *a;
const uint8_t *b;
int32_t *c;
const float *alpha, *beta;
int8_t ao, bo;
const int32_t *co;
// Kernel parameters.
dim_t um, un, uk, bm, bn, bk;
dim_t bn_small_k, bk_traditional, blocking_small_k;
int (*copyA)(const dim_t *m, const dim_t *n, const int8_t *a, const dim_t *lda, const int8_t *alpha, int8_t *b);
int (*copyB)(const dim_t *m, const dim_t *n, const uint8_t *a, const dim_t *lda, const uint8_t *alpha, uint8_t *b);
int (*kernel) (const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int *c, const dim_t ldc);
int (*kernel_b0)(const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int *c, const dim_t ldc);
// Threading parameters.
int nthrs;
int nthrs_m, nthrs_n;
int thread_partition;
int thread_copy;
} blas_t;
static inline void round_to_nearest(int32_t *rounded_val, double fp_val) {
if (fp_val >= 0.) {
fp_val += 0.5;
if (fp_val > INT32_MAX) {
fp_val = INT32_MAX;
}
} else {
fp_val -= 0.5;
if (fp_val < INT32_MIN) {
fp_val = INT32_MIN;
}
}
*rounded_val = (int32_t) fp_val;
}
static inline void add_results(const dim_t m, const dim_t n, const dim_t k,
const float alpha, const float beta, const int32_t *c_partial_sum,
const dim_t ldcp, int32_t *c_data, const dim_t ldc,
const int32_t *a_row_sum, const int32_t *b_col_sum, const int8_t ao,
const int8_t bo, const int32_t *co, int offsetc)
{
for (dim_t j = 0; j < n; ++j) {
for (dim_t i = 0; i < m; ++i) {
int32_t ctemp = c_partial_sum[i + j * ldcp];
if (ao != 0 || bo != 0)
ctemp += a_row_sum[i] * bo + b_col_sum[j] * ao + ao * bo * (int32_t) k;
if (alpha == 1.0f) {
if (beta == 0.0f) {
c_data[i + j * ldc] = ctemp;
} else {
double c_float = (double) beta * (double) c_data[i + j * ldc];
c_float += (double) ctemp;
round_to_nearest(&c_data[i + j * ldc], c_float);
}
} else if (alpha == -1.0f) {
if (beta == 0.0f) {
c_data[i + j * ldc] = -ctemp;
} else {
double c_float = (double) beta * (double) c_data[i + j * ldc];
c_float -= (double) ctemp;
round_to_nearest(&c_data[i + j * ldc], c_float);
}
} else {
if (beta == 0.0f) {
double c_float = alpha * (double) ctemp;
round_to_nearest(&c_data[i + j * ldc], c_float);
} else {
double c_float = alpha * (double) ctemp +
beta * (double) c_data[i + j * ldc];
round_to_nearest(&c_data[i + j * ldc], c_float);
}
}
if (offsetc == 0) { // Fix offset.
c_data[i + j * ldc] += co[0];
} else if (offsetc == 1) { // Row offset.
c_data[i + j * ldc] += co[j];
} else if (offsetc == 2) { // Col offset.
c_data[i + j * ldc] += co[i];
}
}
}
}
static inline void get_a_row_sum(const int transa, const dim_t nrows,
const dim_t ncols, const int8_t *a, const dim_t lda, const int8_t bo,
int32_t *a_row_sum)
{
if (bo != 0) {
dim_t strideAm = (transa == 0)? 1 : lda;
dim_t strideAn = (transa != 0)? 1 : lda;
for (dim_t i = 0; i < nrows; i++) {
a_row_sum[i] = 0;
for (dim_t j = 0; j < ncols; j++) {
a_row_sum[i] += a[i * strideAm + j * strideAn];
}
}
}
}
static inline void get_b_col_sum(const int transb, const dim_t nrows,
const dim_t ncols, const uint8_t *b, const dim_t ldb, const int8_t ao,
int32_t *b_col_sum)
{
if (ao != 0) {
dim_t strideBm = (transb == 0)? 1 : ldb;
dim_t strideBn = (transb != 0)? 1 : ldb;
for (dim_t j = 0; j < ncols; j++) {
b_col_sum[j] = 0;
for (dim_t i = 0; i < nrows; i++) {
b_col_sum[j] += b[i * strideBm + j * strideBn];
}
}
}
}
// TODO Find a better place for those macros.
#define VAL_PADD(y, x, x1) y = ((x) % (x1)) ? (((x) / (x1)) + 1) * (x1) : (x)
#define LD_PADD(y,x) (y) = ((((x) + ((2048 / sizeof(int8_t)) - 1)) / (2048 / sizeof(int8_t))) * (2048 / sizeof(int8_t)) + (512 / sizeof(int8_t)));
static int gemm_kernel_driver(const dim_t m, const dim_t n, const dim_t k,
const int8_t *a, const uint8_t *b, int32_t *c, const int32_t *co,
const blas_t *arg)
{
dim_t lda = arg->lda;
dim_t ldb = arg->ldb;
dim_t ldc = arg->ldc;
int8_t ao = arg->ao;
int8_t bo = arg->bo;
float alpha = *arg->alpha;
float beta = *arg->beta;
// Padding along K dimension.
dim_t k_padd = 0;
if (k <= arg->bk_traditional) {
VAL_PADD(k_padd, k, arg->uk);
k_padd = nstl::max(128LL, k_padd);
} else if (k < 2 * arg->bk) {
k_padd = k / 2;
VAL_PADD(k_padd, k_padd, arg->uk);
} else {
k_padd = arg->bk;
}
// Padding along M dimension.
dim_t m_padd = 0;
VAL_PADD(m_padd, nstl::min(nstl::max(m, arg->um), arg->bm), arg->um);
// Padding along N dimension.
dim_t n_padd = 0;
if (k < arg->blocking_small_k) {
VAL_PADD(n_padd, nstl::min(nstl::max(n, arg->un), arg->bn_small_k), arg->un);
} else {
VAL_PADD(n_padd, nstl::min(nstl::max(n, arg->un), arg->bn), arg->un);
}
// Padding for temporary buffer for C
dim_t ldc_buf = m_padd;
LD_PADD(ldc_buf, m_padd);
dim_t strideAm = (arg->transa == 0)? 1 : lda;
dim_t strideAn = (arg->transa != 0)? 1 : lda;
dim_t strideBm = (arg->transb == 0)? 1 : ldb;
dim_t strideBn = (arg->transb != 0)? 1 : ldb;
int8_t *bufferA = (int8_t *) malloc(m_padd * k_padd * sizeof(*bufferA),
PAGE_2M);
if (!bufferA) {
return -1;
}
uint8_t *bufferB = (uint8_t *) malloc(k_padd * n_padd * sizeof(*bufferB),
PAGE_4K);
if (!bufferB) {
free(bufferA);
return -1;
}
int32_t *bufferC = NULL;
if (arg->offsetc != 0 || ao != 0 || bo != 0 || co[0] != 0
|| alpha != 1.0 || (beta != 1.0 && beta != 0.0)) {
bufferC = (int32_t *) malloc(ldc_buf * n_padd * sizeof(*bufferC),
PAGE_4K);
if (!bufferC) {
free(bufferA);
free(bufferB);
return -1;
}
}
int32_t *a_row_sum = (int32_t *) malloc(m_padd * sizeof(*a_row_sum),
PAGE_4K);
if (!a_row_sum) {
free(bufferA);
free(bufferB);
free(bufferC);
return -1;
}
int32_t *b_col_sum = (int32_t *) malloc(n_padd * sizeof(*b_col_sum),
PAGE_4K);
if (!b_col_sum) {
free(bufferA);
free(bufferB);
free(bufferC);
free(a_row_sum);
return -1;
}
float beta_saved = beta;
int a_block_copied = 0;
dim_t sizeM = 0;
for (dim_t Bm = 0; Bm < m; Bm += sizeM) {
sizeM = m - Bm;
if (sizeM > m_padd)
sizeM = m_padd;
dim_t sizeK = 0;
for (dim_t Bk = 0; Bk < k; Bk += sizeK) {
sizeK = k - Bk;
if (sizeK > k_padd)
sizeK = k_padd;
// Scale C blocks by beta only for the first time
if (Bk == 0)
beta = beta_saved;
else
beta = 1.0f;
// Apply C offset when to the last k-block of the partial sum.
int offsetc = -1;
if (Bk + sizeK == k)
offsetc = arg->offsetc;
dim_t sizeN = 0;
for (dim_t Bn = 0; Bn < n; Bn += sizeN) {
sizeN = n - Bn;
if (sizeN > n_padd)
sizeN = n_padd;
const uint8_t *b_block = b + Bk * strideBm + Bn * strideBn;
arg->copyB(&sizeK, &sizeN, b_block, &ldb, NULL, bufferB);
get_b_col_sum(arg->transb, sizeK, sizeN, b_block, ldb, ao, b_col_sum);
dim_t sizeUM = 0;
for (dim_t Um = 0; Um < sizeM; Um += sizeUM) {
sizeUM = sizeM - Um;
if (sizeUM > arg->um)
sizeUM = arg->um;
const int8_t *a_block = a + (Bm + Um) * strideAm + Bk * strideAn;
if (!a_block_copied) {
arg->copyA(&sizeK, &sizeUM, a_block, &lda, NULL, bufferA + Um * sizeK);
get_a_row_sum(arg->transa, sizeUM, sizeK, a_block, lda, bo, a_row_sum + Um);
}
int32_t *c_block = c + (Bm + Um) + Bn * ldc;
if (bufferC) {
arg->kernel_b0(&sizeUM, &sizeN, &sizeK, NULL, bufferA + Um * sizeK, bufferB, bufferC + Um, ldc_buf);
// Finish the block adding the necessary alpha, beta
// and offsets.
dim_t co_stride = 0;
if (offsetc == 0) { // Fix offset.
co_stride = 0;
} else if (offsetc == 1) { // Row offset.
co_stride = Bn;
} else if (offsetc == 2) { // Column offset.
co_stride = Bm + Um;
}
add_results(sizeUM, sizeN, sizeK, alpha, beta, bufferC + Um, ldc_buf, c_block, ldc, a_row_sum + Um, b_col_sum, ao, bo, co + co_stride, offsetc);
} else {
if (beta == 0.0f)
arg->kernel_b0(&sizeUM, &sizeN, &sizeK, NULL, bufferA + Um * sizeK, bufferB, c_block, ldc);
else
arg->kernel(&sizeUM, &sizeN, &sizeK, NULL, bufferA + Um * sizeK, bufferB, c_block, ldc);
}
}
a_block_copied = 1;
}
a_block_copied = 0;
}
}
free(bufferA);
free(bufferB);
free(bufferC);
free(a_row_sum);
free(b_col_sum);
return 0;
}
#undef VAL_PADD
#undef LD_PADD
#define N2D_MAX_AVX512 384
#define M2D_MIN_AVX512 384
#define VECLEN 16
#define NCONS 1
static inline void set_thread_opts_avx512(int *p_nthrs, blas_t *arg)
{
int nthrs = *p_nthrs;
dim_t m = arg->m;
dim_t n = arg->n;
int condition_2D_bsrc = -1;
if ((256 * m > nthrs * n) && (nthrs * m < 256 * n)) {
condition_2D_bsrc = 1;
} else {
condition_2D_bsrc = 0;
}
arg->thread_copy = COPY_NONE; // By default don't do parallel copy.
if (condition_2D_bsrc == 1) {
int nthrs_m = 1;
int nthrs_n = nthrs;
while ((nthrs_n % 2 == 0) &&
(n / nthrs > N2D_MAX_AVX512 || n / nthrs_n <= N2D_MAX_AVX512 / 2) &&
(m / nthrs_m >= 2 * M2D_MIN_AVX512) &&
(nthrs_m < 4)) {
nthrs_m *= 2;
nthrs_n /= 2;
}
arg->nthrs_m = nthrs_m;
arg->nthrs_n = nthrs_n;
arg->thread_partition = PARTITION_2D;
// Reset the total number of threads that will be used.
*p_nthrs = nthrs_m * nthrs_n;
} else {
if ((m > n) && (m / nthrs >= VECLEN || n < NCONS * nthrs)) {
arg->thread_partition = PARTITION_1D_ROW;
} else {
arg->thread_partition = PARTITION_1D_COL;
}
}
}
#undef N2D_MAX_AVX512
#undef M2D_MIN_AVX512
#undef VECLEN
#undef NCONS
static inline void partition_1d(const int ithr, const int nthrs, const dim_t n,
dim_t *t_offset, dim_t *t_block)
{
dim_t band = n / nthrs;
dim_t tail = n - (nthrs - 1) * band;
if (tail > (band + 1))
band++;
tail = n - (nthrs - 1) * band;
if (ithr < (nthrs - 1))
*t_block = band;
else
*t_block = tail;
*t_offset = ithr * band;
if (*t_offset >= n) {
*t_block = 0;
*t_offset = 0;
} else if ((*t_offset + *t_block) > n) {
*t_block = n - *t_offset;
}
}
static inline void partition_2d(const int ithr, int *nthrs, const int ithr_i,
const int ithr_j, const int nthrs_m, const int nthrs_n, const dim_t m,
const dim_t n, dim_t *p_m_disp, dim_t *p_m_band, dim_t *p_n_disp,
dim_t *p_n_band)
{
dim_t m_disp = 0, n_disp = 0;
dim_t m_band = 0, n_band = 0;
int mdiv = nthrs_m;
int ndiv = nthrs_n;
dim_t m_bandt = m / mdiv; /* size per thread */
dim_t n_bandt = n / ndiv; /* size per thread */
int firstmgroup = mdiv - 1;
int firstngroup = ndiv - 1;
dim_t firstmval = m_bandt;
dim_t firstnval = n_bandt;
int mthr_used = mdiv;
if (m - (mdiv - 1) * m_bandt > m_bandt + 1) {
if (m - (mdiv - 1) * m_bandt > mdiv)
++m_bandt;
firstmval = m_bandt + 1;
mthr_used = (int) (m / firstmval);
if (mthr_used * firstmval < m)
++mthr_used;
firstmgroup = mthr_used - 1;
}
int nthr_used = ndiv;
if (n - (ndiv - 1) * n_bandt > n_bandt + 1) {
firstnval = n_bandt + 1;
nthr_used = (int) (n / firstnval);
if (nthr_used * firstnval < n)
++nthr_used;
firstngroup = nthr_used - 1;
}
*nthrs = mthr_used * nthr_used;
if (ithr < *nthrs) {
if (ithr_i < firstmgroup) {
m_band = firstmval;
m_disp = ithr_i * firstmval;
} else if (ithr_i <= mthr_used - 2) {
m_band = m_bandt;
m_disp = firstmgroup * firstmval + (ithr_i - firstmgroup) * m_bandt;
} else {
m_disp = firstmgroup * firstmval + (mthr_used - 1 - firstmgroup) * m_bandt;
m_band = nstl::max(0LL, m - m_disp);
}
if (ithr_j < firstngroup) {
n_band = firstnval;
n_disp = ithr_j * firstnval;
} else if (ithr_j <= nthr_used - 2) {
n_band = n_bandt;
n_disp = firstngroup * firstnval + (ithr_j - firstngroup) * n_bandt;
} else {
n_disp = firstngroup * firstnval + (nthr_used - 1 - firstngroup) * n_bandt;
n_band = nstl::max(0LL, n - n_disp);
}
m_disp = nstl::max(nstl::min(m_disp, m - 1), 0LL);
n_disp = nstl::max(nstl::min(n_disp, n - 1), 0LL);
}
if (ithr < *nthrs) {
*p_m_disp = m_disp;
*p_n_disp = n_disp;
*p_m_band = m_band;
*p_n_band = n_band;
} else {
*p_m_disp = 0;
*p_n_disp = 0;
*p_m_band = 0;
*p_n_band = 0;
}
return;
}
static inline void decompose_matrices(const int ithr, int *nthrs, dim_t *m,
dim_t *n, dim_t *k, const int8_t **a, const uint8_t **b, int32_t **c,
const int32_t **co, const blas_t *arg)
{
dim_t strideAm = (arg->transa == 0)? 1 : arg->lda;
dim_t strideBn = (arg->transb != 0)? 1 : arg->ldb;
int offsetc = arg->offsetc;
switch (arg->thread_partition) {
case PARTITION_1D_ROW:
{
dim_t offset = 0;
dim_t block = 0;
partition_1d(ithr, *nthrs, arg->m, &offset, &block);
*m = block;
*n = arg->n;
*k = arg->k;
// Set matrix A.
*a = arg->a + offset * strideAm;
// Set matrix B.
*b = arg->b;
// Set matrix C.
*c = arg->c + offset;
// Set offset vector for C matrix
dim_t co_stride = 0;
if (offsetc == 0) { // Fix offset.
co_stride = 0;
} else if (offsetc == 1) { // Row offset.
co_stride = 0;
} else if (offsetc == 2) { // Column offset.
co_stride = offset;
}
*co = arg->co + co_stride;
break;
}
case PARTITION_1D_COL:
{
dim_t offset = 0;
dim_t block = 0;
partition_1d(ithr, *nthrs, arg->n, &offset, &block);
*m = arg->m;
*n = block;
*k = arg->k;
// Set matrix A.
*a = arg->a;
// Set matrix B.
*b = arg->b + offset * strideBn;
// Set matrix C.
*c = arg->c + offset * arg->ldc;
// Set offset vector for C matrix
dim_t co_stride = 0;
if (offsetc == 0) { // Fix offset.
co_stride = 0;
} else if (offsetc == 1) { // Row offset.
co_stride = offset;
} else if (offsetc == 2) { // Column offset.
co_stride = 0;
}
*co = arg->co + co_stride;
break;
}
case PARTITION_2D_COL_MAJOR:
{
int nthrs_m = arg->nthrs_m;
int nthrs_n = arg->nthrs_n;
int ithr_i = ithr % nthrs_m;
int ithr_j = ithr / nthrs_m;
dim_t m_disp = 0;
dim_t m_band = 0;
dim_t n_disp = 0;
dim_t n_band = 0;
partition_2d(ithr, nthrs, ithr_i, ithr_j, nthrs_m, nthrs_n,
arg->m, arg->n, &m_disp, &m_band, &n_disp, &n_band);
*m = m_band;
*n = n_band;
*k = arg->k;
// Set matrix A.
*a = arg->a + m_disp * strideAm;
// Set matrix B.
*b = arg->b + n_disp * strideBn;
// Set matrix C.
*c = arg->c + m_disp + n_disp * arg->ldc;
// Set offset vector for C matrix
dim_t co_stride = 0;
if (offsetc == 0) { // Fix offset.
co_stride = 0;
} else if (offsetc == 1) { // Row offset.
co_stride = n_disp;
} else if (offsetc == 2) { // Column offset.
co_stride = m_disp;
}
*co = arg->co + co_stride;
break;
}
}
}
static int gemm_threading_driver(blas_t *arg)
{
if ((arg->m <= 0) || (arg->n <= 0))
return mkldnn_success;
const int nthr = (mkldnn_in_parallel()) ? 1 : mkldnn_get_max_threads();
/*
* TODO Add a thread checker.
*/
if (nthr == 1) {
return gemm_kernel_driver(arg->m, arg->n, arg->k, arg->a, arg->b,
arg->c, arg->co, arg);
}
int status = 0;
parallel(nthr, [&](const int ithr, const int nthr) {
int nthrs = nthr;
if (nthrs == 1) {
status = gemm_kernel_driver(arg->m, arg->n, arg->k, arg->a, arg->b,
arg->c, arg->co, arg);
} else {
set_thread_opts_avx512(&nthrs, arg);
const int8_t *a = NULL;
const uint8_t *b = NULL;
int32_t *c = NULL;
const int32_t *co = NULL;
dim_t m = -1;
dim_t n = -1;
dim_t k = -1;
decompose_matrices(ithr, &nthrs, &m, &n, &k, &a, &b, &c, &co, arg);
if (ithr < nthrs) {
int result = gemm_kernel_driver(m, n, k, a, b, c, co, arg);
if (result < 0) {
status = result;
}
}
}
});
return status;
}
static jit_avx512_core_u8_copy_an_kern *copy_an;
static jit_avx512_core_u8_copy_at_kern *copy_at;
static jit_avx512_core_u8_copy_bn_kern *copy_bn;
static jit_avx512_core_u8_copy_bt_kern *copy_bt;
static jit_avx512_core_kernel_gemm_s8u8s32_kern *kernel;
static jit_avx512_core_kernel_b0_gemm_s8u8s32_kern *kernel_b0;
static void jit_init(blas_t *arg)
{
static int (*copyAn )(const dim_t *m, const dim_t *n, const int8_t *a , const dim_t *lda, const int8_t *alpha, int8_t *b);
static int (*copyAt )(const dim_t *m, const dim_t *n, const int8_t *a , const dim_t *lda, const int8_t *alpha, int8_t *b);
static int (*copyBn )(const dim_t *m, const dim_t *n, const uint8_t *a, const dim_t *lda, const uint8_t *alpha, uint8_t *b);
static int (*copyBt )(const dim_t *m, const dim_t *n, const uint8_t *a, const dim_t *lda, const uint8_t *alpha, uint8_t *b);
static int (*kern )(const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int32_t *c, const dim_t ldc);
static int (*kern_b0)(const dim_t *m, const dim_t *n, const dim_t *k, const float *alpha, const int8_t *a, const uint8_t *b, int32_t *c, const dim_t ldc);
if (mayiuse(avx512_core_vnni)) {
arg->um = AVX512_UNROLL_M;
arg->un = AVX512_UNROLL_N;
arg->uk = AVX512_UNROLL_K;
arg->bm = AVX512_BM;
arg->bn = AVX512_BN;
arg->bk = AVX512_BK_VNNI;
arg->bk_traditional = AVX512_BK_TRADITIONAL;
arg->bn_small_k = AVX512_BN_SMALL_K;
arg->blocking_small_k = AVX512_BLOCKING_SMALL_K;
} else {
arg->um = AVX512_UNROLL_M;
arg->un = AVX512_UNROLL_N;
arg->uk = AVX512_UNROLL_K;
arg->bm = AVX512_BM;
arg->bn = AVX512_BN;
arg->bk = AVX512_BK;
arg->bk_traditional = AVX512_BK_TRADITIONAL;
arg->bn_small_k = AVX512_BN_SMALL_K;
arg->blocking_small_k = AVX512_BLOCKING_SMALL_K;
}
static std::once_flag initialized;
std::call_once(initialized, []{
copy_an = new jit_avx512_core_u8_copy_an_kern();
copy_at = new jit_avx512_core_u8_copy_at_kern();
copy_bn = new jit_avx512_core_u8_copy_bn_kern();
copy_bt = new jit_avx512_core_u8_copy_bt_kern();
kernel = new jit_avx512_core_kernel_gemm_s8u8s32_kern();
kernel_b0 = new jit_avx512_core_kernel_b0_gemm_s8u8s32_kern();
copyAn = copy_an -> getCode<int (*)(const dim_t *, const dim_t *, const int8_t *, const dim_t *, const int8_t *, int8_t *)>();
copyAt = copy_at -> getCode<int (*)(const dim_t *, const dim_t *, const int8_t *, const dim_t *, const int8_t *, int8_t *)>();
copyBn = copy_bn -> getCode<int (*)(const dim_t *, const dim_t *, const uint8_t *, const dim_t *, const uint8_t *, uint8_t *)>();
copyBt = copy_bt -> getCode<int (*)(const dim_t *, const dim_t *, const uint8_t *, const dim_t *, const uint8_t *, uint8_t *)>();
kern = kernel -> getCode<int (*)(const dim_t *, const dim_t *, const dim_t *, const float *, const int8_t *, const uint8_t *, int32_t *, const dim_t)>();
kern_b0 = kernel_b0 -> getCode<int (*)(const dim_t *, const dim_t *, const dim_t *, const float *, const int8_t *, const uint8_t *, int32_t *, const dim_t)>();
});
if (arg->transa == 0) {
arg->copyA = copyAn;
} else {
arg->copyA = copyAt;
}
if (arg->transb == 0) {
arg->copyB = copyBn;
} else {
arg->copyB = copyBt;
}
arg->kernel = kern;
arg->kernel_b0 = kern_b0;
}
mkldnn_status_t jit_avx512_core_gemm_s8u8s32(
const char *transA, const char *transB, const char *offsetC,
const int *m, const int *n, const int *k,
const float *alpha, const int8_t *a, const int *lda, const int8_t *oa,
const uint8_t *b, const int *ldb, const int8_t *ob,
const float *beta, int32_t *c, const int *ldc, const int32_t *oc)
{
char transa = *transA;
char transb = *transB;
char offsetc = *offsetC;
blas_t args;
// Initialize blas structure
args.m = *m;
args.n = *n;
args.k = *k;
args.alpha = alpha;
args.a = a;
args.lda = *lda;
args.b = b;
args.ldb = *ldb;
args.beta = beta;
args.c = c;
args.ldc = *ldc;
args.transa = (transa == 'N' || transa == 'n') ? 0 : 1;
args.transb = (transb == 'N' || transb == 'n') ? 0 : 1;
args.um = 0;
args.un = 0;
args.bm = 0;
args.bn = 0;
args.bk = 0;
args.copyA = NULL;
args.copyB = NULL;
args.kernel = NULL;
args.kernel_b0 = NULL;
args.ao = *oa;
args.bo = *ob;
args.co = oc;
if (offsetc == 'F' || offsetc == 'f') {
args.offsetc = 0;
} else if (offsetc == 'R' || offsetc == 'r') {
args.offsetc = 1;
} else { // offsetc == 'C' || offsetc == 'c'
args.offsetc = 2;
}
jit_init(&args);
int result = gemm_threading_driver(&args);
return (result < 0 ) ? mkldnn_out_of_memory : mkldnn_success;
}
}
}
}
| 32.67203 | 168 | 0.502746 | Bil17t |
c217d399851f509ee29ab5c0ddb0a334b18ea89f | 3,645 | hpp | C++ | libs/xpressive/boost/xpressive/proto/v1_/proto_typeof.hpp | xoxox4dev/madedit | 8e0dd08818e040b099251c1eb8833b836cb36c6e | [
"Ruby"
] | 22 | 2015-06-28T17:48:54.000Z | 2021-04-16T08:47:26.000Z | libs/xpressive/boost/xpressive/proto/v1_/proto_typeof.hpp | mcanthony/madedit | 8e0dd08818e040b099251c1eb8833b836cb36c6e | [
"Ruby"
] | null | null | null | libs/xpressive/boost/xpressive/proto/v1_/proto_typeof.hpp | mcanthony/madedit | 8e0dd08818e040b099251c1eb8833b836cb36c6e | [
"Ruby"
] | 12 | 2015-04-25T00:40:35.000Z | 2021-11-11T06:39:48.000Z | ///////////////////////////////////////////////////////////////////////////////
/// \file proto_typeof.hpp
/// Type registrations so that proto1 expression templates can be used together
/// with the Boost.Typeof library.
//
// Copyright 2007 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_XPRESSIVE_PROTO_PROTO_TYPEOF_H
#define BOOST_XPRESSIVE_PROTO_PROTO_TYPEOF_H
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <boost/config.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/xpressive/proto/v1_/proto_fwd.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::binary_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::nary_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::noop_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_plus_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_minus_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_star_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::complement_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::address_of_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::logical_not_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::pre_inc_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::pre_dec_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::post_inc_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::post_dec_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::left_shift_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::right_shift_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::multiply_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::divide_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::modulus_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::add_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::subtract_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::less_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::greater_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::less_equal_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::greater_equal_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::equal_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::not_equal_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::logical_or_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::logical_and_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitand_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitor_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitxor_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::comma_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::mem_ptr_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::left_shift_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::right_shift_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::multiply_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::divide_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::modulus_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::add_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::subtract_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitand_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitor_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitxor_assign_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::subscript_tag)
BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::function_tag)
BOOST_TYPEOF_REGISTER_TEMPLATE(boost::proto1::unary_op, (typename)(typename))
BOOST_TYPEOF_REGISTER_TEMPLATE(boost::proto1::binary_op, (typename)(typename)(typename))
#endif
| 47.960526 | 88 | 0.836763 | xoxox4dev |
c21e828b819fbdc15790471d7b9b16ed3aff16b2 | 8,475 | hpp | C++ | src/CellGraph.hpp | iosonofabio/ExpressionMatrix2 | a6fc6938fe857fe1bd6a9200071957691295ba3c | [
"MIT"
] | null | null | null | src/CellGraph.hpp | iosonofabio/ExpressionMatrix2 | a6fc6938fe857fe1bd6a9200071957691295ba3c | [
"MIT"
] | null | null | null | src/CellGraph.hpp | iosonofabio/ExpressionMatrix2 | a6fc6938fe857fe1bd6a9200071957691295ba3c | [
"MIT"
] | null | null | null | // The cell graph is a graph in which each vertex
// corresponds to a cell.
// An undirected edge is created between two vertices
// if the there is good similarity between the
// expression vectors of the corresponding cells.
#ifndef CZI_EXPRESSION_MATRIX2_CELL_GRAPH_HPP
#define CZI_EXPRESSION_MATRIX2_CELL_GRAPH_HPP
#include "CZI_ASSERT.hpp"
#include "Ids.hpp"
#include "orderPairs.hpp"
#include <boost/graph/adjacency_list.hpp>
#include "array.hpp"
#include "iosfwd.hpp"
#include "map.hpp"
#include "string.hpp"
#include "utility.hpp"
#include "vector.hpp"
namespace ChanZuckerberg {
namespace ExpressionMatrix2 {
class CellGraph;
class CellGraphVertex;
class CellGraphVertexInfo;
class CellGraphEdge;
class ClusterTable;
// The base class for class CellGraph.
typedef boost::adjacency_list<
boost::listS,
boost::listS,
boost::undirectedS,
CellGraphVertex,
CellGraphEdge> CellGraphBaseClass;
namespace MemoryMapped {
template<class T> class Vector;
}
}
}
// A class used by label propagation algorithm to keep track
// of the total weight of each cluster for each vertex.
class ChanZuckerberg::ExpressionMatrix2::ClusterTable {
public:
void addWeight(uint32_t clusterId, float weight);
void addWeightQuick(uint32_t clusterId, float weight); // Does not check if already there. Does not update the best cluster.
uint32_t bestCluster();
void findBestCluster();
void clear();
bool isEmpty() const;
private:
vector< pair<uint32_t, float> > data;
uint32_t bestClusterId = std::numeric_limits<uint32_t>::max();
float bestWeight = -1.;
};
inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::addWeightQuick(uint32_t clusterId, float weight)
{
data.push_back(make_pair(clusterId, weight));
}
inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::addWeight(uint32_t clusterId, float weight)
{
for(pair<uint32_t, float>& p: data) {
if(p.first == clusterId) {
p.second += weight;
if(clusterId == bestClusterId) {
if(weight < 0.) {
findBestCluster();
} else {
bestWeight = p.second;
}
} else {
if(p.second > bestWeight) {
bestClusterId = clusterId;
bestWeight = p.second;
}
}
return;
}
}
data.push_back(make_pair(clusterId, weight));
if(weight > bestWeight) {
bestClusterId = clusterId;
bestWeight = weight;
}
}
inline uint32_t ChanZuckerberg::ExpressionMatrix2::ClusterTable::bestCluster()
{
return bestClusterId;
}
inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::findBestCluster()
{
bestClusterId = std::numeric_limits<uint32_t>::max();
bestWeight = -1.;
for(const pair<uint32_t, float>& p: data) {
if(p.second > bestWeight) {
bestWeight = p.second;
bestClusterId = p.first;
}
}
}
inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::clear()
{
data.clear();
}
inline bool ChanZuckerberg::ExpressionMatrix2::ClusterTable::isEmpty() const
{
return data.empty();
}
// A vertex of the cell graph.
// The base class CellGraphVertexInfo is used to communicate with Python.
class ChanZuckerberg::ExpressionMatrix2::CellGraphVertexInfo {
public:
CellId cellId = invalidCellId;
array<double, 2> position;
ClusterTable clusterTable;
double x() const
{
return position[0];
}
double y() const
{
return position[1];
}
CellGraphVertexInfo()
{
}
CellGraphVertexInfo(const CellGraphVertexInfo& that) :
cellId(that.cellId), position(that.position)
{
}
CellGraphVertexInfo(CellId cellId) :
cellId(cellId)
{
}
bool operator==(const CellGraphVertexInfo& that)
{
return cellId==that.cellId && position==that.position;
}
};
class ChanZuckerberg::ExpressionMatrix2::CellGraphVertex : public CellGraphVertexInfo {
public:
// Use the base class constructors.
using CellGraphVertexInfo::CellGraphVertexInfo;
// Additional fields not needed in Python.
uint32_t group = 0;
uint32_t clusterId = 0;
string color;
double value = 0.;
};
// An edge of the cell graph.
class ChanZuckerberg::ExpressionMatrix2::CellGraphEdge {
public:
float similarity = -1.;
CellGraphEdge()
{
}
CellGraphEdge(float similarity) :
similarity(similarity)
{
}
string color;
};
class ChanZuckerberg::ExpressionMatrix2::CellGraph : public CellGraphBaseClass {
public:
// Use the constructors of the base class.
using CellGraphBaseClass::CellGraphBaseClass;
typedef CellGraph Graph;
Graph& graph()
{
return *this;
}
const Graph& graph() const
{
return *this;
}
CellGraph(
const MemoryMapped::Vector<CellId>& cellSet, // The cell set to be used.
const string& similarPairsName, // The name of the SimilarPairs object to be used to create the graph.
double similarityThreshold, // The minimum similarity to create an edge.
size_t maxConnectivity // The maximum number of neighbors (k of the k-NN graph).
);
// Only keep an edge if it is one of the best k edges for either
// of the two vertices. This turns the graph into a k-nearest-neighbor graph.
void keepBestEdgesOnly(std::size_t k);
// Write in Graphviz format.
void write(ostream&) const;
void write(const string& fileName) const;
// Simple graph statistics.
ostream& writeStatistics(ostream&) const;
// Remove isolated vertices and returns\ the number of vertices that were removed
size_t removeIsolatedVertices();
// Use Graphviz to compute the graph layout and store it in the vertex positions.
void computeLayout();
bool layoutWasComputed = false;
// Clustering using the label propagation algorithm.
// The cluster each vertex is assigned to is stored in the clusterId data member of the vertex.
void labelPropagationClustering(
ostream&,
size_t seed, // Seed for random number generator.
size_t stableIterationCountThreshold, // Stop after this many iterations without changes.
size_t maxIterationCount // Stop after this many iterations no matter what.
);
// Vertex table, keyed by cell id.
map<CellId, vertex_descriptor> vertexTable;
// Compute minimum and maximum coordinates of all the vertices.
void computeCoordinateRange(
double& xMin,
double& xMax,
double& yMin,
double& yMax) const;
// Assign integer colors to groups.
// The same color can be used for multiple groups, but if two
// groups are joined by one or more edges they must have distinct colors.
// On return, colorTable[group] contains the integer color assigned to each group.
// This processes the groups in increasing order beginning at group 0,
// so it is best if the group numbers are all contiguous, starting at zero,
// and in decreasing size of group.
void assignColorsToGroups(vector<uint32_t>& colorTable);
// Write the graph in svg format.
// This does not use Graphviz. It uses the graph layout stored in the vertices,
// and previously computed using Graphviz.
// The last argument specifies the color assigned to each vertex group.
// If empty, vertex groups are not used, and each vertex is drawn
// with its own color.
void writeSvg(
ostream& s,
bool hideEdges,
double svgSizePixels,
double xViewBoxCenter,
double yViewBoxCenter,
double viewBoxHalfSize,
double vertexRadius,
double edgeThickness,
const map<int, string>& groupColors,
const string& geneSetName // Used for the cell URL
) const;
class Writer {
public:
Writer(const Graph&);
void operator()(ostream&) const;
void operator()(ostream&, vertex_descriptor) const;
void operator()(ostream&, edge_descriptor) const;
const Graph& graph;
double minEdgeSimilarity;
};
};
#endif
| 29.023973 | 128 | 0.653923 | iosonofabio |
c2204f53bccd49ff55d67f901341be870061d5c3 | 955 | hpp | C++ | lib/Array/concat.hpp | LiquidFun/WiredLedCube | dc2aac8bccf02d325b31081d6dc52f8ca79bd62a | [
"MIT"
] | 1 | 2021-04-06T09:48:39.000Z | 2021-04-06T09:48:39.000Z | lib/Array/concat.hpp | LiquidFun/WiredLedCube | dc2aac8bccf02d325b31081d6dc52f8ca79bd62a | [
"MIT"
] | null | null | null | lib/Array/concat.hpp | LiquidFun/WiredLedCube | dc2aac8bccf02d325b31081d6dc52f8ca79bd62a | [
"MIT"
] | null | null | null | #pragma once
#include <stddef.h>
#include "Array.hpp"
#include "IntegerSequence.hpp"
#include "make_array.hpp"
#include "MakeIntegerSequence.hpp"
namespace T27
{
namespace intern
{
template <class T, int... inds1, int... inds2>
constexpr Array<T, sizeof...(inds1) + sizeof...(inds2)> concat_(
const Array<T, sizeof...(inds1)> &arr1,
IntSequence<inds1...>,
const Array<T, sizeof...(inds2)> &arr2,
IntSequence<inds2...>)
{
return make_array<T>(arr1[inds1]..., arr2[inds2]...);
}
} // namespace intern
template <class T, size_t size1, size_t size2>
constexpr Array<T, size1 + size2> concat(
const Array<T, size1> &arr1,
const Array<T, size2> &arr2)
{
return intern::concat_(
arr1,
MakeIntSequence<size1>{},
arr2,
MakeIntSequence<size2>{});
}
} // namespace T27
| 25.131579 | 72 | 0.559162 | LiquidFun |
c222d086ec30d6d6ac0c7e70eca167724294b61b | 31,512 | cpp | C++ | sdl2_framework/DrawingSurface.cpp | chrisjpurdy/ksp_2d | 54f6f31aea7b6228a62168f7963058fa3a9243a2 | [
"MIT"
] | 2 | 2022-01-07T11:35:35.000Z | 2022-01-09T22:37:06.000Z | sdl2_framework/DrawingSurface.cpp | chrisjpurdy/ksp_2d | 54f6f31aea7b6228a62168f7963058fa3a9243a2 | [
"MIT"
] | null | null | null | sdl2_framework/DrawingSurface.cpp | chrisjpurdy/ksp_2d | 54f6f31aea7b6228a62168f7963058fa3a9243a2 | [
"MIT"
] | null | null | null | #include "header.h"
#if defined(_MSC_VER)
#include <SDL_syswm.h>
#endif
#include <math.h>
#include "BaseEngine.h"
#include "DisplayableObject.h"
#include "DrawingSurface.h"
#include "DrawingFilters.h"
#include "FontManager.h"
#include "templates.h"
/*
Template function to swap two values over, storing one in a temporary variable of the correct type and using assignment operator
Note: this existed before std::swap() existed, and is only used for ints and floats in the coursework framework.
You could instead "#include <utility>" and use "std::swap()"
*/
template <typename T>
inline void swapPoints(T& v1, T& v2)
{
T t = v1;
v1 = v2;
v2 = t;
}
// Constant for PI - used in GetAngle below.
const double DrawingSurface::MY_PI = 3.14159265358979323846;
DrawingSurface::DrawingSurface(BaseEngine* m_pCreatorEngine)
: m_pSDLSurface(nullptr), m_pCreatorEngine(m_pCreatorEngine), mySDLSurfaceLockedCount(0), m_pFilter(nullptr),
checkBoundsForDrawings(false), m_iBoundsTop(0), m_iBoundsBottom(0), m_iBoundsLeft(0), m_iBoundsRight(0),
m_bTempUnlocked(false)
{
// Default to checking that points are on the screen unless anyone says otherwise (e.g. unless someone clears it)
this->setDrawPointsFilter(m_pCreatorEngine);
}
/*
Determine the angle (in radians) of point 2 from point 1.
Note that it also checks the quadrant, so you get a result from 0 to 2PI.
Implemented as a template so you can use with ints, doubles, etc
*/
double DrawingSurface::getAngle(double tX1, double tY1, double tX2, double tY2)
{
double dAngle = MY_PI / 2; // Default when X1==X2
if (tX1 != tX2)
dAngle = atan((double)(tY2 - tY1) / (double)(tX2 - tX1));
else if (tY2 < tY1)
dAngle += MY_PI;
if (tX2 < tX1)
dAngle += MY_PI;
return dAngle;
}
/*
Draw a string in the specified font to the specified surface (foreground or background).
*/
void DrawingSurface::drawFastString(int iX, int iY, const char* pText, unsigned int uiColour, Font* pFont)
{
if (pFont == NULL)
pFont = m_pCreatorEngine->getDefaultFont();
SDL_Color color = { (Uint8)((uiColour & 0xff0000) >> 16), (Uint8)((uiColour & 0xff00) >> 8), (Uint8)((uiColour & 0xff)), 0 };
if ((pFont != NULL) && (pFont->getTTFFont() != NULL))
{
SDL_Surface *sText = TTF_RenderText_Solid(pFont->getTTFFont(), pText, color);
SDL_Rect rcDest = { iX,iY,0,0 };
mySDLTempUnlockSurface();
SDL_BlitSurface(sText, NULL, m_pSDLSurface, &rcDest);
mySDLTempRelockSurface();
SDL_FreeSurface(sText);
}
}
/*
Draw a scalable string in the specified font to the specified surface (foreground or background).
*/
void DrawingSurface::drawScalableString(int iX, int iY, const char* pText, unsigned int uiColour, Font* pFont)
{
if (pFont == NULL)
pFont = m_pCreatorEngine->getDefaultFont();
SDL_Color color = { (Uint8)((uiColour & 0xff0000) >> 16), (Uint8)((uiColour & 0xff00) >> 8), (Uint8)((uiColour & 0xff)), 0 };
unsigned int testColor = 0;
if ((pFont != NULL) && (pFont->getTTFFont() != NULL))
{
SDL_Surface *sText = TTF_RenderText_Solid(pFont->getTTFFont(), pText, color);
SDL_Rect rcDest = { iX,iY,0,0 };
for (int x = 0; x < sText->w; x++)
{
for (int y = 0; y < sText->h; y++)
{
// Get colour from the surface drawing to...
switch (sText->format->BitsPerPixel)
{
case 8:
testColor = *((Uint8*)sText->pixels + y * sText->pitch + x);
break;
case 16:
testColor = *((Uint16*)sText->pixels + y * sText->pitch / 2 + x);
break;
case 32:
testColor = *((Uint32*)sText->pixels + y * sText->pitch / 4 + x);
break;
default: // Should never happen
testColor = 0;
break;
}
//testColor = ((unsigned int*)(sText->pixels))[y*sText->w + x];
//printf("%08x ", testColor);
if ( testColor )
setPixel(x + iX, y + iY, uiColour);
}
//printf("\n");
}
SDL_FreeSurface(sText);
}
}
/* Copy all of the background (e.g. tiles) to the foreground display. e.g. removing any object drawn on top. */
void DrawingSurface::copyEntireSurface( DrawingSurface* pFrom )
{
memcpy(m_pSDLSurface->pixels, pFrom->m_pSDLSurface->pixels, sizeof(unsigned int) * getIntsPerWindowRow() * getSurfaceHeight());
// ::SDL_UpperBlitScaled
}
/*
Copy some of the background onto the foreground, e.g. removing an object which was drawn on top.
Note that x, y, width and height are trimmed to fit inside THIS surface (that is being copied FROM) and that these are REAL not VIRTUAL positions. (Ignore this if you aren't using filters.)
*/
void DrawingSurface::copyRectangleFrom(DrawingSurface* pFrom, int iRealX, int iRealY, int iWidth, int iHeight, int iSourceOffsetX, int iSourceOffsetY)
{
if (iRealX + iWidth < 0)
return; // Nothing to do
if (iRealY + iHeight < 0)
return; // Nothing to do
if (iRealX >= pFrom->getSurfaceWidth() )
return; // Nothing to do
if (iRealY >= pFrom->getSurfaceHeight() )
return; // Nothing to do
// Ensure position is within the bounds
if (iRealX < 0) { iWidth += iRealX; iRealX = 0; /*Note that iRealX was negative*/ }
if (iRealY < 0) { iHeight += iRealY; iRealY = 0; /*Note that iRealY was negative*/ }
// In case source offsets are -ve...
if (iRealX + iSourceOffsetX < 0) { iWidth += (iRealX + iSourceOffsetX); iRealX = -iSourceOffsetX; /*Note that offset was negative*/ }
if (iRealY + iSourceOffsetY < 0) { iHeight += (iRealY + iSourceOffsetY); iRealY = -iSourceOffsetY; /*Note that offset was negative*/ }
// Ensure width is within bounds
if ((iRealX + iWidth) >= pFrom->getSurfaceWidth())
iWidth = pFrom->getSurfaceWidth() - iRealX;
// Ensure height is within bounds
if ((iRealY + iHeight) >= pFrom->getSurfaceHeight())
iHeight = pFrom->getSurfaceHeight() - iRealY;
// In case source offsets were +ve...
if (iRealX + iSourceOffsetX + iWidth >= pFrom->getSurfaceWidth() ) iWidth = pFrom->getSurfaceWidth() - iRealX - iSourceOffsetX;
if (iRealY + iSourceOffsetY + iHeight >= pFrom->getSurfaceHeight() ) iHeight = pFrom->getSurfaceHeight() - iRealY - iSourceOffsetY;
int iStartDest = iRealY * getIntsPerWindowRow() + iRealX;
int iStartSrc = (iRealY + iSourceOffsetY) * getIntsPerWindowRow() + iRealX + iSourceOffsetX;
int iIncrement = getIntsPerWindowRow() - iWidth;
//std::cout << "Copy to " << iRealX << "," << iRealY << " from " << (iRealX + iSourceOffsetX) << "," << (iRealY + iSourceOffsetY) << " size " << iWidth << "," << iHeight << std::endl;
// Use drawing code or use blit?
#if AVOID_BLIT
unsigned int * puiSource = ((unsigned int *)pFrom->m_pSDLSurface->pixels) + iStartSrc;
unsigned int * puiDest = ((unsigned int *)m_pSDLSurface->pixels) + iStartDest;
for (int i = 0; i < iHeight; i++)
{
// Copy a line
for (int j = 0; j < iWidth; j++)
*puiDest++ = *puiSource++;
// Align on the next line
puiSource += iIncrement;
puiDest += iIncrement;
}
#else
SDL_Rect rectDest = { iRealX, iRealY, iWidth, iHeight };
SDL_Rect rectSrc = { iRealX + iSourceOffsetX, iRealY + iSourceOffsetY, iWidth, iHeight };
mySDLTempUnlockSurface();
CHECK_BLIT_SURFACE(this);
::SDL_BlitSurface(pFrom->m_pSDLSurface, &rectSrc, m_pSDLSurface, &rectDest);
mySDLTempRelockSurface();
#endif
}
/*
Draw a vertical sided region.
If two points are the same then it is a triangle.
To do an arbitrary triangle, just draw two next to each other, one for left and one for right.
Basically to ensure that the triangle is filled (no pixels are missed) it is better to draw lines down each column than to try to draw at arbitrary angles.
This means that we have a shape where the starting and ending points are horizontally fixed (same x coordinate), and we are drawing a load of vertical lines from points on the top to points on the bottom of the region.
*/
void DrawingSurface::drawVerticalSidedRegion(
double fX1, double fX2,// X positions
double fY1a, double fY2a, // Start y positions for x1 and x2
double fY1b, double fY2b, // End y positions for x1 and x2
unsigned int uiColour)
{
if ( checkBoundsForDrawings )
{
if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft)
return; // No need to draw cos this is off the left of the display
if (fX1 > m_iBoundsRight && fX2 > m_iBoundsRight)
return; // No need to draw cos this is off the right of the display
if (fY1a < m_iBoundsTop && fY1b < m_iBoundsTop && fY2a < m_iBoundsTop && fY2b < m_iBoundsTop)
return; // No need to draw cos this is off the top of the display
if (fY1a > m_iBoundsBottom && fY1b > m_iBoundsBottom && fY2a > m_iBoundsBottom && fY2b > m_iBoundsBottom)
return; // No need to draw cos this is off the bottom of the display
}
// Ensure X1< X2, otherwise steps will go wrong!
// Switch the points if x and y are wrong way round
if (fX2< fX1) { swapPoints(fX1, fX2); swapPoints(fY1a, fY2a); swapPoints(fY1b, fY2b); }
int iXStart = (int)(fX1 + 0.5);
int iXEnd = (int)(fX2 + 0.5);
// If integer x positions are the same then avoid floating point inaccuracy problems by a special case
if (iXStart == iXEnd)
{
int iYStart = (int)(fY1a + 0.5);
int iYEnd = (int)(fY2a + 0.5);
for (int iY = iYStart; iY <= iYEnd; iY++)
setPixel(iXStart, iY, uiColour);
}
else
{
// Draw left hand side
int iYStart = (int)(fY1a + 0.5);
int iYEnd = (int)(fY1b + 0.5);
if (iYStart > iYEnd) swapPoints(iYStart, iYEnd);
//printf( "Firstline %d to %d (%f to %f)\n", iYStart, iYEnd, fY1a, fY1b );
for (int iY = iYStart; iY <= iYEnd; iY++)
setPixel(iXStart, iY, uiColour);
// Draw the middle
for (int iX = iXStart + 1; iX< iXEnd; iX++)
{
double fYStart = fY1a + ((((double)iX) - fX1)*(fY2a - fY1a)) / (fX2 - fX1);
double fYEnd = fY1b + ((((double)iX) - fX1)*(fY2b - fY1b)) / (fX2 - fX1);
if (fYEnd< fYStart) swapPoints(fYStart, fYEnd);
int iYStart2 = (int)(fYStart + 0.5);
int iYEnd2 = (int)(fYEnd + 0.5);
//printf( "Line from %d to %d (%f to %f)\n", iYStart, iYEnd, fYStart, fYEnd );
for (int iY = iYStart2; iY <= iYEnd2; iY++)
setPixel(iX, iY, uiColour);
}
// Draw right hand side
iYStart = (int)(fY2a + 0.5);
iYEnd = (int)(fY2b + 0.5);
if (iYStart> iYEnd) swapPoints(iYStart, iYEnd);
//printf( "Last line %d to %d (%f to %f)\n", iYStart, iYEnd, fY2a, fY2b );
for (int iY = iYStart; iY <= iYEnd; iY++)
setPixel(iXEnd, iY, uiColour);
}
}
/*
Draw a triangle, as two vertical sided regions.
Try this on paper to see how it works.
Basically to ensure that the triangle is filled (no pixels are missed) it is better to draw lines down each column than to try to draw at arbitrary angles.
*/
void DrawingSurface::drawTriangle(
double fX1, double fY1,
double fX2, double fY2,
double fX3, double fY3,
unsigned int uiColour)
{
if (checkBoundsForDrawings)
{
if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft && fX3 < m_iBoundsLeft)
return; // No need to draw cos this is off the left of the display
if (fX1 >= m_iBoundsRight && fX2 >= m_iBoundsRight && fX3 >= m_iBoundsRight)
return; // No need to draw cos this is off the right of the display
if (fY1 < m_iBoundsTop && fY2 < m_iBoundsTop && fY3 < m_iBoundsTop)
return; // No need to draw cos this is off the top of the display
if (fY1 >= m_iBoundsBottom && fY2 >= m_iBoundsBottom && fY3 >= m_iBoundsBottom )
return; // No need to draw cos this is off the bottom of the display
}
// Ensure order is 1 2 3 from left to right
if (fX1 > fX2) { swapPoints(fX1, fX2); swapPoints(fY1, fY2); } // Bigger of 1 and 2 is in position 2
if (fX2 > fX3) { swapPoints(fX2, fX3); swapPoints(fY2, fY3); } // Bigger of new 2 and 3 is in position 3
if (fX1 > fX2) { swapPoints(fX1, fX2); swapPoints(fY1, fY2); } // Bigger of 1 and new 2 is in position 2
if (fX1 == fX2)
drawVerticalSidedRegion(fX1, fX3, fY1, fY3, fY2, fY3, uiColour);
else if (fX2 == fX3)
drawVerticalSidedRegion(fX1, fX3, fY1, fY2, fY1, fY3, uiColour);
else
{
// Split into two triangles. Find position on line 1-3 to split at
double dSplitPointY = (double)fY1 +
(((double)((fX2 - fX1)*(fY3 - fY1)))
/ (double)(fX3 - fX1));
drawVerticalSidedRegion(fX1, fX2, fY1, fY2, fY1, dSplitPointY, uiColour);
drawVerticalSidedRegion(fX2, fX3, fY2, fY3, dSplitPointY, fY3, uiColour);
}
}
/*
Draw a rectangle on the specified surface
This is probably the easiest function to do, hence is a special case.
*/
void DrawingSurface::drawRectangle(int iX1, int iY1, int iX2, int iY2, unsigned int uiColour)
{
if (checkBoundsForDrawings)
{
if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft)
return; // No need to draw cos this is off the left of the display
if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight)
return; // No need to draw cos this is off the right of the display
if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop)
return; // No need to draw cos this is off the top of the display
if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom)
return; // No need to draw cos this is off the bottom of the display
}
if (iX2 < iX1) { int t = iX1; iX1 = iX2; iX2 = t; }
if (iY2 < iY1) { int t = iY1; iY1 = iY2; iY2 = t; }
for (int iX = iX1; iX <= iX2; iX++)
for (int iY = iY1; iY <= iY2; iY++)
setPixel(iX, iY, uiColour);
}
/*
Draw an oval on the specified surface.
This is drawn by checking each pixel inside a bounding rectangle to see whether it should be filled or not.
There are probably faster ways to do this!
*/
void DrawingSurface::drawOval(int iX1, int iY1, int iX2, int iY2, unsigned int uiColour)
{
if (checkBoundsForDrawings)
{
if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft )
return; // No need to draw cos this is off the left of the display
if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight )
return; // No need to draw cos this is off the right of the display
if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop )
return; // No need to draw cos this is off the top of the display
if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom )
return; // No need to draw cos this is off the bottom of the display
}
if (iX2 < iX1) { int t = iX1; iX1 = iX2; iX2 = t; }
if (iY2 < iY1) { int t = iY1; iY1 = iY2; iY2 = t; }
double fCentreX = ((double)(iX2 + iX1)) / 2.0;
double fCentreY = ((double)(iY2 + iY1)) / 2.0;
double fXFactor = (double)((iX2 - iX1) * (iX2 - iX1)) / 4.0;
double fYFactor = (double)((iY2 - iY1) * (iY2 - iY1)) / 4.0;
double fDist;
for (int iX = iX1; iX <= iX2; iX++)
for (int iY = iY1; iY <= iY2; iY++)
{
fDist = ((double)iX - fCentreX) * ((double)iX - fCentreX) / fXFactor
+ ((double)iY - fCentreY) * ((double)iY - fCentreY) / fYFactor;
if (fDist <= 1.0)
setPixel(iX, iY, uiColour);
}
}
/*
Draw an oval on the specified surface.
This is a REALLY slow version of the above function, which just draws a perimeter pixel.
Probably there is a much better way to do this.
*/
void DrawingSurface::drawHollowOval(int iX1, int iY1, int iX2, int iY2, int iX3, int iY3, int iX4, int iY4, unsigned int uiColour)
{
if (checkBoundsForDrawings)
{
if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft && iX3 < m_iBoundsLeft && iX4 < m_iBoundsLeft)
return; // No need to draw cos this is off the left of the display
if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight && iX3 >= m_iBoundsRight && iX4 >= m_iBoundsRight)
return; // No need to draw cos this is off the right of the display
if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop && iY3 < m_iBoundsTop && iY4 < m_iBoundsTop)
return; // No need to draw cos this is off the top of the display
if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom && iY3 >= m_iBoundsBottom && iY4 >= m_iBoundsBottom)
return; // No need to draw cos this is off the bottom of the display
}
if (iX2 < iX1) swapPoints(iX1, iX2);
if (iY2 < iY1) swapPoints(iY1, iY2);
if (iX4 < iX3) swapPoints(iX3, iX4);
if (iY4 < iY3) swapPoints(iY3, iY4);
double fCentreX1 = ((double)(iX2 + iX1)) / 2.0;
double fCentreY1 = ((double)(iY2 + iY1)) / 2.0;
double fXFactor1 = (double)((iX2 - iX1) * (iX2 - iX1)) / 4.0;
double fYFactor1 = (double)((iY2 - iY1) * (iY2 - iY1)) / 4.0;
double fCentreX2 = ((double)(iX4 + iX3)) / 2.0;
double fCentreY2 = ((double)(iY4 + iY3)) / 2.0;
double fXFactor2 = (double)((iX4 - iX3) * (iX4 - iX3)) / 4.0;
double fYFactor2 = (double)((iY4 - iY3) * (iY4 - iY3)) / 4.0;
double fDist1, fDist2;
for (int iX = iX1; iX <= iX2; iX++)
for (int iY = iY1; iY <= iY2; iY++)
{
fDist1 = ((double)iX - fCentreX1) * ((double)iX - fCentreX1) / fXFactor1
+ ((double)iY - fCentreY1) * ((double)iY - fCentreY1) / fYFactor1;
fDist2 = ((double)iX - fCentreX2) * ((double)iX - fCentreX2) / fXFactor2
+ ((double)iY - fCentreY2) * ((double)iY - fCentreY2) / fYFactor2;
if ((fDist1 <= 1.0) && (fDist2 >= 1.0))
setPixel(iX, iY, uiColour);
}
}
/*
Draw a line on the specified surface.
For each horizontal pixel position, work out which vertical position at which to colour in the pixel.
*/
void DrawingSurface::drawLine(double fX1, double fY1, double fX2, double fY2,
unsigned int uiColour)
{
if (checkBoundsForDrawings)
{
if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft )
return; // No need to draw cos this is off the left of the display
if (fX1 >= m_iBoundsRight && fX2 >= m_iBoundsRight )
return; // No need to draw cos this is off the right of the display
if (fY1 < m_iBoundsTop && fY2 < m_iBoundsTop )
return; // No need to draw cos this is off the top of the display
if (fY1 >= m_iBoundsBottom && fY2 >= m_iBoundsBottom )
return; // No need to draw cos this is off the bottom of the display
}
int iX1 = (int)(fX1 + 0.5);
int iX2 = (int)(fX2 + 0.5);
int iY1 = (int)(fY1 + 0.5);
int iY2 = (int)(fY2 + 0.5);
int iSteps = (iX2 - iX1);
if (iSteps < 0) iSteps = -iSteps;
if (iY2 > iY1) iSteps += (iY2 - iY1); else iSteps += (iY1 - iY2);
iSteps += 2;
double fXStep = ((double)(fX2 - fX1)) / iSteps;
double fYStep = ((double)(fY2 - fY1)) / iSteps;
for (int i = 0; i <= iSteps; i++)
{
setPixel((int)(0.5 + fX1 + fXStep * i), (int)(0.5 + fY1 + fYStep * i), uiColour);
}
}
/*
Draw a thick line on the specified surface.
This is like the DrawLine() function, but has a width to the line.
*/
void DrawingSurface::drawThickLine(double fX1, double fY1, double fX2, double fY2,
unsigned int uiColour, int iThickness)
{
if (checkBoundsForDrawings)
{
if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft )
return; // No need to draw cos this is off the left of the display
if (fX1 >= m_iBoundsRight && fX2 >= m_iBoundsRight )
return; // No need to draw cos this is off the right of the display
if (fY1 < m_iBoundsTop && fY2 < m_iBoundsTop )
return; // No need to draw cos this is off the top of the display
if (fY1 >= m_iBoundsBottom && fY2 >= m_iBoundsBottom )
return; // No need to draw cos this is off the bottom of the display
}
if (iThickness < 2)
{ // Go to the quicker draw function
drawLine(fX1, fY1, fX2, fY2, uiColour);
return;
}
double fAngle1 = getAngle(fX1, fY1, fX2, fY2);
double fAngle1a = fAngle1 - ((5 * M_PI) / 4.0);
double fAngle1b = fAngle1 + ((5 * M_PI) / 4.0);
double fRectX1 = fX1 + iThickness * cos(fAngle1a) * 0.5;
double fRectY1 = fY1 + iThickness * sin(fAngle1a) * 0.5;
double fRectX2 = fX1 + iThickness * cos(fAngle1b) * 0.5;
double fRectY2 = fY1 + iThickness * sin(fAngle1b) * 0.5;
double fAngle2 = fAngle1 + M_PI;
double fAngle2a = fAngle2 - ((5 * M_PI) / 4.0);
double fAngle2b = fAngle2 + ((5 * M_PI) / 4.0);
double fRectX3 = fX2 + iThickness * cos(fAngle2a) * 0.5;
double fRectY3 = fY2 + iThickness * sin(fAngle2a) * 0.5;
double fRectX4 = fX2 + iThickness * cos(fAngle2b) * 0.5;
double fRectY4 = fY2 + iThickness * sin(fAngle2b) * 0.5;
drawTriangle(fRectX1, fRectY1, fRectX2, fRectY2, fRectX3, fRectY3, uiColour);
drawTriangle(fRectX3, fRectY3, fRectX4, fRectY4, fRectX1, fRectY1, uiColour);
}
/*
Draw a filled polygon on the specified surface.
The trick here is to not fill in any bits that shouldn't be filled, but to not miss anything.
This was a pain to write to be honest, and there is a chance it may have an error I have not found so far.
*/
void DrawingSurface::drawPolygon(
int iPoints, double* pXArray, double* pYArray,
unsigned int uiColour)
{
if (iPoints == 1)
{
setPixel( (int)(pXArray[0]+0.5), (int)(pYArray[0] + 0.5), uiColour);
return;
}
if (iPoints == 2)
{
drawLine(pXArray[0], pYArray[0], pXArray[1], pYArray[1], uiColour);
return;
}
/* if ( iPoints == 3 )
{
printf( "Draw triangle for points 0, 1, 2 of %d available\n", iPoints );
DrawTriangle( pXArray[0], pYArray[0], pXArray[1], pYArray[1], pXArray[2], pYArray[2],
uiColour, pTarget );
return;
}
*/
// Otherwise attempt to eliminate a point by filling the polygon, then call this again
double fXCentre, fYCentre; //fX1, fX2, fX3, fY1, fY2, fY3;
int i2, i3;
double fAngle1, fAngle2, fAngle3;
for (int i1 = 0; i1 < iPoints; i1++)
{
i2 = i1 + 1; if (i2 >= iPoints) i2 -= iPoints;
i3 = i1 + 2; if (i3 >= iPoints) i3 -= iPoints;
fXCentre = (pXArray[i1] + pXArray[i2] + pXArray[i3]) / 3.0;
fYCentre = (pYArray[i1] + pYArray[i2] + pYArray[i3]) / 3.0;
fAngle1 = getAngle(fXCentre, fYCentre, pXArray[i1], pYArray[i1]);
fAngle2 = getAngle(fXCentre, fYCentre, pXArray[i2], pYArray[i2]);
fAngle3 = getAngle(fXCentre, fYCentre, pXArray[i3], pYArray[i3]);
// Now work out the relative angle positions and make sure all are positive
fAngle2 -= fAngle1; if (fAngle2 < 0) fAngle2 += 2 * M_PI;
fAngle3 -= fAngle1; if (fAngle3 < 0) fAngle3 += 2 * M_PI;
if (fAngle2 < fAngle3)
{ // Then points are in clockwise order so central one can be eliminated as long as we don't
// fill an area that we shouldn't
bool bPointIsWithinTriangle = false;
if (iPoints > 3)
{ // Need to check that there isn't a point within the area - for convex shapes
double fLineAngle12 = getAngle(pXArray[i1], pYArray[i1], pXArray[i2], pYArray[i2]);
if (fLineAngle12 < 0)
fLineAngle12 += M_PI * 2.0;
double fLineAngle23 = getAngle(pXArray[i2], pYArray[i2], pXArray[i3], pYArray[i3]);
if (fLineAngle23 < 0)
fLineAngle23 += M_PI * 2.0;
double fLineAngle31 = getAngle(pXArray[i3], pYArray[i3], pXArray[i1], pYArray[i1]);
if (fLineAngle31 < 0)
fLineAngle31 += M_PI * 2.0;
for (int i = i3 + 1; i != i1; i++)
{
if (i >= iPoints)
{
i = 0;
if (i1 == 0)
break; // From the for loop - finished
}
// Otherwise we need to work out whether point i is to right of line i3 to i1
double fPointAngle1 = getAngle(pXArray[i1], pYArray[i1], pXArray[i], pYArray[i]);
if (fPointAngle1 < 0)
fPointAngle1 += M_PI * 2.0;
fPointAngle1 -= fLineAngle12;
if (fPointAngle1 < 0)
fPointAngle1 += M_PI * 2.0;
double fPointAngle2 = getAngle(pXArray[i2], pYArray[i2], pXArray[i], pYArray[i]);
if (fPointAngle2 < 0)
fPointAngle2 += M_PI * 2.0;
fPointAngle2 -= fLineAngle23;
if (fPointAngle2 < 0)
fPointAngle2 += M_PI * 2.0;
double fPointAngle3 = getAngle(pXArray[i3], pYArray[i3], pXArray[i], pYArray[i]);
if (fPointAngle3 < 0)
fPointAngle3 += M_PI * 2.0;
fPointAngle3 -= fLineAngle31;
if (fPointAngle3 < 0)
fPointAngle3 += M_PI * 2.0;
if ((fPointAngle1 < M_PI) && (fPointAngle2 < M_PI) && (fPointAngle3 < M_PI))
bPointIsWithinTriangle = true;
}
}
if (!bPointIsWithinTriangle)
{// If not then try the next position
//printf("Draw for points %d, %d, %d of %d available\n", i1, i2, i3, iPoints);
drawTriangle(pXArray[i1], pYArray[i1], pXArray[i2], pYArray[i2],
pXArray[i3], pYArray[i3], /*GetColour(iPoints)*/uiColour);
// Remove the point i2 and then recurse
for (int i = i2; i < (iPoints - 1); i++)
{
//printf("\tCopy point %d to %d\n", i + 1, i);
pXArray[i] = pXArray[i + 1];
pYArray[i] = pYArray[i + 1];
}
if (iPoints > 3)
drawPolygon(iPoints - 1, pXArray, pYArray, uiColour);
return; // Done
}
}
}
}
/* Added in 2014 since it was used in the GroundMovement playback program so may be useful elsewhere too, but students can ignore this */
void DrawingSurface::drawShortenedArrow(int iX1, int iY1, int iX2, int iY2,
int iShortenedStart, int iShortenedEnd,
unsigned int uiColour, int iThickness,
int iHeadSize)
{
if (checkBoundsForDrawings)
{
if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft)
return; // No need to draw cos this is off the left of the display
if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight)
return; // No need to draw cos this is off the right of the display
if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop)
return; // No need to draw cos this is off the top of the display
if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom)
return; // No need to draw cos this is off the bottom of the display
}
double dAngle1 = getAngle(iX1, iY1, iX2, iY2);
double dAngle2 = dAngle1 + M_PI;
double dX1 = iX1 + iShortenedStart * cos(dAngle1);
double dY1 = iY1 + iShortenedStart * sin(dAngle1);
double dX2 = iX2 + iShortenedEnd * cos(dAngle2);
double dY2 = iY2 + iShortenedEnd * sin(dAngle2);
// First draw the line
if (iThickness < 2)
{ // Go to the quicker draw function
drawLine(dX1, dY1, dX2, dY2, uiColour);
}
else
{
double dX1l = iX1 + iShortenedStart * cos(dAngle1);
double dY1l = iY1 + iShortenedStart * sin(dAngle1);
double dX2l = iX2 + (iShortenedEnd + iThickness * 1.5) * cos(dAngle2);
double dY2l = iY2 + (iShortenedEnd + iThickness * 1.5) * sin(dAngle2);
drawThickLine(dX1l, dY1l, dX2l, dY2l, uiColour, iThickness);
}
// Now draw the arrow head.
// Need three points - one is end of line and others are at 60 degrees from it.
drawTriangle(
dX2, dY2,
dX2 + iHeadSize * cos(dAngle2 + M_PI / 6.0), dY2 + iHeadSize * sin(dAngle2 + M_PI / 6.0),
dX2 + iHeadSize * cos(dAngle2 - M_PI / 6.0), dY2 + iHeadSize * sin(dAngle2 - M_PI / 6.0),
uiColour);
}
/* Added in 2014 since it was used in the GroundMovement playback program so may be useful elsewhere too, but students can ignore this */
void DrawingSurface::drawShortenedLine(int iX1, int iY1, int iX2, int iY2, int iShortenedStart, int iShortenedEnd, unsigned int uiColour, int iThickness)
{
if (checkBoundsForDrawings)
{
if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft )
return; // No need to draw cos this is off the left of the display
if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight )
return; // No need to draw cos this is off the right of the display
if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop )
return; // No need to draw cos this is off the top of the display
if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom )
return; // No need to draw cos this is off the bottom of the display
}
double dAngle1 = getAngle(iX1, iY1, iX2, iY2);
double dAngle2 = dAngle1 + M_PI;
// First draw the line
if (iThickness < 2)
{ // Go to the quicker draw function
double dX1 = iX1 + iShortenedStart * cos(dAngle1);
double dY1 = iY1 + iShortenedStart * sin(dAngle1);
double dX2 = iX2 + iShortenedEnd * cos(dAngle2);
double dY2 = iY2 + iShortenedEnd * sin(dAngle2);
drawLine(dX1, dY1, dX2, dY2, uiColour);
}
else
{
double dX1l = iX1 + iShortenedStart * cos(dAngle1);
double dY1l = iY1 + iShortenedStart * sin(dAngle1);
double dX2l = iX2 + iShortenedEnd * cos(dAngle2);
double dY2l = iY2 + iShortenedEnd * sin(dAngle2);
//if (iX1 == iX2)
// printf("Draw shortened line %d,%d to %d,%d shortened by %d,%d is %f,%f %f,%f\n", iX1, iY1, iX2, iY2, iShortenedStart, iShortenedEnd, dX1l, dY1l, dX2l, dY2l);
drawThickLine(dX1l, dY1l, dX2l, dY2l, uiColour, iThickness);
}
}
// Get the minimum x coordinate which would be within the redraw region
int DrawingSurface::getVirtualRedrawMinX()
{
int iMin = convertRealToVirtualXPosition(0);
if (this->m_pCreatorEngine->getRedrawAllScreen())
return iMin;
int iRedrawMin = this->m_pCreatorEngine->getRedrawRectVirtualLeft();
if (iRedrawMin > iMin)
iMin = iRedrawMin;
return iMin;
}
int DrawingSurface::getVirtualRedrawMinY()
{
int iMin = convertRealToVirtualYPosition(0);
if (this->m_pCreatorEngine->getRedrawAllScreen())
return iMin;
int iRedrawMin = this->m_pCreatorEngine->getRedrawRectVirtualTop();
if (iRedrawMin > iMin)
iMin = iRedrawMin;
return iMin;
}
int DrawingSurface::getVirtualRedrawMaxX()
{
int iMax = convertRealToVirtualXPosition(getSurfaceWidth());
if (this->m_pCreatorEngine->getRedrawAllScreen())
return iMax;
int iRedrawMax = this->m_pCreatorEngine->getRedrawRectVirtualRight();
if (iMax > iRedrawMax )
iMax = iRedrawMax;
return iMax;
}
int DrawingSurface::getVirtualRedrawMaxY()
{
int iMax = convertRealToVirtualYPosition(getSurfaceHeight());
if (this->m_pCreatorEngine->getRedrawAllScreen())
return iMax;
int iRedrawMax = this->m_pCreatorEngine->getRedrawRectVirtualBottom();
if (iMax > iRedrawMax )
iMax = iRedrawMax;
return iMax;
}
// Get the minimum x coordinate which would be within the redraw region
int DrawingSurface::getRealRedrawMinX()
{
if (m_pCreatorEngine->getRedrawAllScreen())
return 0;
int iMin = 0;
int iRedrawMin = this->m_pCreatorEngine->getRedrawRectRealLeft();
if (iRedrawMin > iMin)
iMin = iRedrawMin;
return iMin;
}
int DrawingSurface::getRealRedrawMinY()
{
if (m_pCreatorEngine->getRedrawAllScreen())
return 0;
int iMin = 0;
int iRedrawMin = this->m_pCreatorEngine->getRedrawRectRealTop();
if (iRedrawMin > iMin)
iMin = iRedrawMin;
return iMin;
}
int DrawingSurface::getRealRedrawMaxX()
{
if (m_pCreatorEngine->getRedrawAllScreen())
return getSurfaceWidth();
int iMax = getSurfaceWidth();
int iRedrawMax = this->m_pCreatorEngine->getRedrawRectRealRight();
if (iMax > iRedrawMax )
iMax = iRedrawMax;
return iMax;
}
int DrawingSurface::getRealRedrawMaxY()
{
if (m_pCreatorEngine->getRedrawAllScreen())
return getSurfaceHeight();
int iMax = getSurfaceHeight();
int iRedrawMax = this->m_pCreatorEngine->getRedrawRectRealBottom();
if (iMax > iRedrawMax )
iMax = iRedrawMax;
return iMax;
}
/*
Draw an oval on the specified surface - without any scaling or checking etc - BE CAREFUL WITH THIS!.
*/
void DrawingSurface::rawDrawOval(int iX1, int iY1, int iX2, int iY2, unsigned int uiColour)
{
if (iX2 < iX1) { int t = iX1; iX1 = iX2; iX2 = t; }
if (iY2 < iY1) { int t = iY1; iY1 = iY2; iY2 = t; }
double fCentreX = ((double)(iX2 + iX1)) / 2.0;
double fCentreY = ((double)(iY2 + iY1)) / 2.0;
double fXFactor = (double)((iX2 - iX1) * (iX2 - iX1)) / 4.0;
double fYFactor = (double)((iY2 - iY1) * (iY2 - iY1)) / 4.0;
double fDist;
for (int iX = iX1; iX <= iX2; iX++)
for (int iY = iY1; iY <= iY2; iY++)
{
fDist = ((double)iX - fCentreX) * ((double)iX - fCentreX) / fXFactor
+ ((double)iY - fCentreY) * ((double)iY - fCentreY) / fYFactor;
if (fDist <= 1.0)
rawSetPixel(iX, iY, uiColour);
}
}
| 36.85614 | 219 | 0.652862 | chrisjpurdy |
c2269d3f254b29964f062a782a979882a83d184e | 7,457 | cpp | C++ | examples/ex7_ssl_server/ex7_ssl_server.cpp | saarbastler/beast_http_server | bd19f1651324a0fb05ddc27fb6799fd371627e64 | [
"BSD-2-Clause"
] | null | null | null | examples/ex7_ssl_server/ex7_ssl_server.cpp | saarbastler/beast_http_server | bd19f1651324a0fb05ddc27fb6799fd371627e64 | [
"BSD-2-Clause"
] | null | null | null | examples/ex7_ssl_server/ex7_ssl_server.cpp | saarbastler/beast_http_server | bd19f1651324a0fb05ddc27fb6799fd371627e64 | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <server.hpp>
#include <ssl.hpp>
using namespace std;
template<class Request>
auto make_response(const Request & req, const string & user_body){
boost::beast::http::string_body::value_type body(user_body);
auto const body_size = body.size();
boost::beast::http::response<boost::beast::http::string_body> res{
std::piecewise_construct,
std::make_tuple(std::move(body)),
std::make_tuple(boost::beast::http::status::ok, req.version())};
res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(boost::beast::http::field::content_type, "text/html");
res.content_length(body_size);
res.keep_alive(req.keep_alive());
return res;
}
int main()
{
//g++ -c -std=gnu++14 -I../../include -o ex7_ssl_server.o ./ex7_ssl_server.cpp
//g++ -o ex7_ssl_server ex7_ssl_server.o -lboost_system -lboost_thread -lpthread -lboost_regex -licui18n -lssl
//root@x0x0:~# curl --insecure https://localhost --request 'GET' --request-target '/1' --cacert /path/to/int.pem --cert-type PEM --tlsv1.2
//root@x0x0:~# curl --insecure https://localhost --request 'GET' --request-target '/2' --cacert /path/to/int.pem --cert-type PEM --tlsv1.2
//root@x0x0:~# openssl s_client -connect localhost:443 -servername localhost -CAfile /root/certs/int.pem
std::string const cert =
"-----BEGIN CERTIFICATE-----\n"
"MIIDwTCCAimgAwIBAgIBATANBgkqhkiG9w0BAQsFADBAMQswCQYDVQQGEwJVUzEL\n"
"MAkGA1UECAwCQ0ExDjAMBgNVBAoMBUJlYXN0MRQwEgYDVQQHDAtMb3MgQW5nZWxl\n"
"czAeFw0xODA5MDEwOTUzMDJaFw0yMTA5MDEwOTUzMDJaMBQxEjAQBgNVBAMMCWxv\n"
"Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMm2gFNSV49z\n"
"mwSn6qJeh8ABnLy61jBs/jmR53cN0cN0+8vBHrhQum4sCAsFgbiMZ4cJzE4d+g0p\n"
"Y5qnF8N0jeqxGHg7d0YemTCJjvV9PN0esM02Fqd8sS473SEZpkoT5L4RDWaqggVN\n"
"wfFnPeIVNIEE/QshygZyBNBJPqvzwM/buXR17ncQ8kOx0i5VLwrBKowVbG6mBIuF\n"
"O96Vst+/mb0c4Lkrsev7hbjM7MFVjpCDm2zOLTYb4GVGHmqB1KPPPxzPiS+upvG1\n"
"C5UstgJAbgfynIzRfriGTWPjLDoVhuq5aksJDGCjv14ini2LDJrqQ/AVVw0ZF/uh\n"
"VbK/aS+ldD8CAwEAAaNyMHAwCQYDVR0TBAIwADAUBgNVHREEDTALgglsb2NhbGhv\n"
"c3QwEwYDVR0lBAwwCgYIKwYBBQUHAwEwOAYIKwYBBQUHAQEELDAqMCgGCCsGAQUF\n"
"BzABhhxodHRwOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODAvMA0GCSqGSIb3DQEBCwUA\n"
"A4IBgQAkJbfWAkn7G3JZ3h1x3UzEdKOage9KmimbTW68HrVwyqsE057Ix0L3UVCd\n"
"9T1xIeM9SFcsBTpA2mJotWhQak0tGlW9AcJoziRT1c4GvdkDwss0vAPB6XoCSZ9z\n"
"bxyFdQaXRNK25kq60wSq1PTvNMZYYQA7Eusj5lpp1Gz+iS57NBfcq/MxiPB79Ysb\n"
"6h+YkCPsJNx1S2W3qC2d3pIeOg+5lnXL58cj1XPnBgy84webRgPtxufKlVdfG85Z\n"
"cw8a/OeXiCawZQKW5z7DwINsXEtX5cm4hMOlIE9JxaGCUf1yRel/MCT5fKaeSlUt\n"
"4IeGaJvyC5zYiockngaJcCW2H2DieWkgRojfgGCagXQ3rs3bdKncNDg5iuu/7jXc\n"
"TZ4YMoYmt78Z7D+Rjl624omUV2TYp3dU0xrG5Xutab3gJOrUzIn7/vtU+oJ3Kc7a\n"
"Rk544OYp0lFUCgCuWsF9l2nDRcD5QQCDUveww9zQFXgkcGnJ4567Kcq+FlmS7fNo\n"
"kNeiKJA=\n"
"-----END CERTIFICATE-----\n";
std::string const key =
"-----BEGIN PRIVATE KEY-----\n"
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJtoBTUlePc5sE\n"
"p+qiXofAAZy8utYwbP45ked3DdHDdPvLwR64ULpuLAgLBYG4jGeHCcxOHfoNKWOa\n"
"pxfDdI3qsRh4O3dGHpkwiY71fTzdHrDNNhanfLEuO90hGaZKE+S+EQ1mqoIFTcHx\n"
"Zz3iFTSBBP0LIcoGcgTQST6r88DP27l0de53EPJDsdIuVS8KwSqMFWxupgSLhTve\n"
"lbLfv5m9HOC5K7Hr+4W4zOzBVY6Qg5tszi02G+BlRh5qgdSjzz8cz4kvrqbxtQuV\n"
"LLYCQG4H8pyM0X64hk1j4yw6FYbquWpLCQxgo79eIp4tiwya6kPwFVcNGRf7oVWy\n"
"v2kvpXQ/AgMBAAECggEAFW/s4W4N2jQKFIuX9xuex7wkITamDs12kz27YL66PVCQ\n"
"dg4XKrWBqrXJQQqbx7Y8RnC3ItIywfVVHZmGgAJCFuAtXpHLUktsMmlcJSDjOAjL\n"
"93M5IyGwXt6D2MG2F4dXtw9u4ita2B90bihvvjhMtS2HiwhTRS4W7t/p5jJomm5q\n"
"RdWBGv6wqA6qHAMwyp/FoRY7gO4ZNbfCMn+n02A4PQ4fWZ/wIJgg9Ikl5cjinRon\n"
"go6vbFakVr1CEpUJJyNMzSO0oNoOa0SPE90STRxdf+WlrCDjU84NNzjehGxVK2Nm\n"
"KCyYtdaY1pSz2YQ0WczcbxFhYvzMLaRbnceMUY228QKBgQDtLLJ3Q44P1/TI9wSH\n"
"BBiZPamSbwZmw40zYTNHDBQKcyGP07Anw9UiHWJcvWnMSRE/CtGjn4lw02azjukE\n"
"Lx0mKUPdiodOGpr/qzw99lyM7Test8T/9cUR/g/p+lIRc9R1YR+ju6KU90Afv3yL\n"
"z+Dy8K3kfeWmKCnumgxPEazDhwKBgQDZuTwsBLq6eiviMaTL1Rd8SZyHztPETq2I\n"
"knzDRC0ZZ6qpAgfhUhQHLho8i/W93nIUwekO0y3P2ryBwx0t9GdEH2A7/8RRjQEK\n"
"UVztb5Ugki3i3apqX3cPK9KIg6foTEYw4IxZTTjJxBN5BNMTJvQQM2tmfXppr94f\n"
"v+SbkK7niQKBgQCgNPoUX7idcSXzfhA714N6N9HMjVyIm/1MQJMvobQD3wNDsR2j\n"
"rr/QfILN3FCT4qNYr0kuunxPjy0nixhRcDXDakpiYsnE82nR2+wker7HnxFlhPj4\n"
"YR6Oacx8I0++ZDyWUVXa9sr6zw0spN9PXcs4r2T3HCe9FhJFDx/TZUALDwKBgQCU\n"
"9jZkC4xSX5o8tSiCSTY7VAXjqS+cRRRXt5ni43dTxWivH3OSxtxrGTDcMgodMN+u\n"
"sgkpmnTinE6THZKOSYSJyEnIYzLHdQi8LXS+ArTuRvVcHbsl8lD8MUhnHGS5+82e\n"
"TVPZGYt8CEomZ5Weqe0cVIHr6nfhbXE1Gc5oXTI9uQKBgFKbG+08h/UmEhBs78PT\n"
"zVz15vXCD6CCZ/gGBxpDO9SJpVWJgo4m4MmmMn2zQyCJU/7vj4lp6oNsRA3ULdRL\n"
"RbF5vQoY/3bZcyuKc2PfBAUjvKbLAAFF8VtVj6QUj0IgBKkkqumyvVxwYy/1k56R\n"
"mXLnbU9LRnjes0GyZNw2gRBf\n"
"-----END PRIVATE KEY-----\n";
std::string const dh =
"-----BEGIN DH PARAMETERS-----\n"
"MIIBCAKCAQEAw5V8Zv0UXTzjBLBr+Wje5RktwL1K27giAQoZIKfs5MsKqAkaGJOI\n"
"jeThplBGu26wZOxUKa0+aSU780JQY75aOYXqw6trLPC8Ay9ogQP9XzbxyJQPj2lJ\n"
"LBwHnDVwU9xIYmwVBzo5QbVyssxtQlh+XckOARTQ4dz3x5lob9/W0Q6beRWZG7w6\n"
"ruYU2DlZ5HMT2bMJkYV+T1Z6ZBVg8uXjuAvsqjHRJNDvKDPXWeZqHE4I4xFQo5MU\n"
"ua0cgFeqJ9lzwiGKgTnwAswKA/c/XIX/xsCAdL1wp+a+U98loQfS/ZvWTg4Wer88\n"
"18rx/G5U0pwJzRDqNbX2cwl3+3rj8KlsKwIBAg==\n"
"-----END DH PARAMETERS-----\n";
boost::asio::ssl::context ctx{boost::asio::ssl::context::tlsv12};
ctx.set_options(boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::single_dh_use);
ctx.use_certificate_chain(boost::asio::buffer(cert.data(), cert.size()));
ctx.use_private_key(boost::asio::buffer(key.data(), key.size()),
boost::asio::ssl::context::file_format::pem);
ctx.use_tmp_dh(boost::asio::buffer(dh.data(), dh.size()));
//###############################################################################
http::ssl::server my_https_server{ctx};
my_https_server.get("/1", [](auto & req, auto & session){
cout << req << endl; // '/1'
session.do_write(make_response(req, "GET 1\n"));
});
my_https_server.get("/2", [](auto & req, auto & session){
cout << req << endl; // '/2'
session.do_write(make_response(req, "GET 2\n"));
});
my_https_server.all(".*", [](auto & req, auto & session){
cout << req << endl; // 'any'
session.do_write(make_response(req, "error\n"));
});
const auto & address = "127.0.0.1";
uint32_t port = 443;
my_https_server.listen(address, port, [](auto & session){
http::base::out(session.getConnection()->stream().lowest_layer().remote_endpoint().address().to_string() + " connected");
session.do_handshake();
});
http::base::processor::get().register_signals_handler([](int signal){
if(signal == SIGINT)
http::base::out("Interactive attention signal");
else if(signal == SIGTERM)
http::base::out("Termination request");
else
http::base::out("Quit");
http::base::processor::get().stop();
}, std::vector<int>{SIGINT,SIGTERM, SIGQUIT});
uint32_t pool_size = boost::thread::hardware_concurrency();
http::base::processor::get().start(pool_size == 0 ? 4 : pool_size << 1);
http::base::processor::get().wait();
return 0;
}
| 46.899371 | 142 | 0.73488 | saarbastler |
c2313e39bc1107089d98d69060fe05c8e3cdc0c1 | 1,906 | cpp | C++ | Minecraft/Taiga_Biome.cpp | borbrudar/Minecraft_clone | 117fbe94390f96e3a6227129de60c08a5cc2ccdc | [
"MIT"
] | null | null | null | Minecraft/Taiga_Biome.cpp | borbrudar/Minecraft_clone | 117fbe94390f96e3a6227129de60c08a5cc2ccdc | [
"MIT"
] | null | null | null | Minecraft/Taiga_Biome.cpp | borbrudar/Minecraft_clone | 117fbe94390f96e3a6227129de60c08a5cc2ccdc | [
"MIT"
] | null | null | null | #include "Taiga_Biome.h"
void Taiga_Biome::drawBiome(Shader shader, Block_Heavy & data, glm::mat4 model)
{
//draw the trees
for (int i = 0; i < trees.size(); i++) {
for (int j = 0; j < trees[i].part1.size(); j++) {
int x = trees[i].part1[j].x, y = trees[i].part1[j].y, z = trees[i].part1[j].z;
model[3][0] = x;
model[3][1] = y;
model[3][2] = z;
shader.setMat4("model", model);
trees[i].part1[j].draw(shader, data);
if (j == (trees[i].part1.size() - 1)) {
trees[i].setStructure(x, y, z);
for (int k = 0; k < trees[i].part2.size(); k++) {
model[3][0] = trees[i].part2[k].x;
model[3][1] = trees[i].part2[k].y;
model[3][2] = trees[i].part2[k].z;
shader.setMat4("model", model);
trees[i].part2[k].draw(shader, data);
}
}
}
}
}
void Taiga_Biome::setBiomeData(int chunkSize, int modelX, int modelZ, int modelY, std::vector<int>& heights, std::vector<Block>& blocks)
{
//dirt/stone for the surface
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<int> dist(0, 1);
for (int x = 0; x < chunkSize; x++) {
for (int y = 0; y < chunkSize; y++) {
for (int z = 0; z < chunkSize; z++) {
int temp = dist(engine);
if(temp == 0) blocks[x + chunkSize * (y + (z * chunkSize))].type = block_type::type::dirt;
if(temp == 1) blocks[x + chunkSize * (y + (z * chunkSize))].type = block_type::type::stone;
}
}
}
//load the tree positions
std::uniform_int_distribution<int> pos(0, chunkSize - 1);
trees.resize(3);
for (int i = 0; i < trees.size(); i++) {
trees[i].setStructureData(structureType::taiga_tree);
int x = pos(engine), z = pos(engine);
for (int j = 0; j < trees[i].part1.size(); j++) {
trees[i].part1[j].x = x + (modelX * chunkSize);
trees[i].part1[j].z = z + (modelZ * chunkSize);
trees[i].part1[j].y = heights[x + (z * chunkSize)] + modelY + j;
}
}
}
| 30.741935 | 136 | 0.58447 | borbrudar |
ea4d3d64447cc74008b0b64b8ede39197bee2f21 | 1,923 | cpp | C++ | LiveCam/Core/GLSL/VAO.cpp | KanSmith/LiveCam | 8b863f55f08cb3ea5090e417c68ad82ded690743 | [
"MIT"
] | null | null | null | LiveCam/Core/GLSL/VAO.cpp | KanSmith/LiveCam | 8b863f55f08cb3ea5090e417c68ad82ded690743 | [
"MIT"
] | null | null | null | LiveCam/Core/GLSL/VAO.cpp | KanSmith/LiveCam | 8b863f55f08cb3ea5090e417c68ad82ded690743 | [
"MIT"
] | null | null | null | #include <GLSL/VAO.h>
namespace gl {
#if 0
VAO::VAO()
:id(0)
{
}
VAO::~VAO() {
id = 0;
}
bool VAO::setup() {
if(id) {
LC_ERROR(ERR_GL_VAO_ALREADY_SETUP);
return false;
}
glGenVertexArrays(1, &id);
if(!id) {
LC_ERROR(ERR_GL_VAO_CANNOT_CREATE);
return false;
}
return true;
}
void VAO::enableAttributes(VBO<VertexP>& vbo) {
bind();
vbo.bind();
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexP), (GLvoid*)0);
unbind();
}
void VAO::enableAttributes(VBO<VertexPT>& vbo) {
bind();
vbo.bind();
glEnableVertexAttribArray(0); // pos
glEnableVertexAttribArray(1); // tex
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPT), (GLvoid*)0); // pos
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexPT), (GLvoid*)12); // tex
vbo.unbind();
unbind();
}
void VAO::enableAttributes(VBO<VertexCP>& vbo) {
bind();
vbo.bind();
glEnableVertexAttribArray(0); // pos
glEnableVertexAttribArray(2); // col
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexCP), (GLvoid*)16); // pos
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(VertexCP), (GLvoid*)0); // col
vbo.unbind();
unbind();
}
void VAO::enableAttributes(VBO<VertexNP>& vbo) {
bind();
vbo.bind();
glEnableVertexAttribArray(0); // pos
glEnableVertexAttribArray(3); // norm
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexNP), (GLvoid*)12); // pos
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(VertexNP), (GLvoid*)0); // norm
vbo.unbind();
unbind();
}
void VAO::bind() {
if(!id) {
LC_ERROR(ERR_GL_VAO_NOT_SETUP);
return;
}
glBindVertexArray(id);
}
void VAO::unbind() {
glBindVertexArray(0);
}
#endif
} // gl
| 19.424242 | 90 | 0.609984 | KanSmith |
ea51aef431a15015a7cc29613f6b088384c01dec | 4,489 | cpp | C++ | core/src/ConfigData.cpp | aschuman/CoBaB | 59700463859b267f6e37d5694667e3e4110aa70b | [
"MIT"
] | null | null | null | core/src/ConfigData.cpp | aschuman/CoBaB | 59700463859b267f6e37d5694667e3e4110aa70b | [
"MIT"
] | 3 | 2015-11-15T13:24:23.000Z | 2016-03-11T12:27:15.000Z | core/src/ConfigData.cpp | aschuman/CoBaB | 59700463859b267f6e37d5694667e3e4110aa70b | [
"MIT"
] | 3 | 2015-11-10T07:54:45.000Z | 2021-05-11T12:33:12.000Z | #include "ConfigData.h"
#include <QTranslator>
#include <QApplication>
/**
* @brief ConfigData::ConfigData Creates the ConfigData object.
*/
ConfigData::ConfigData() : QSettings("IOSB", "CoBaB"){
Q_INIT_RESOURCE(application);
languages.insert("German", QLocale(QLocale::German));
languages.insert("English", QLocale(QLocale::English));
mTranslator = new QTranslator(0);
}
/**
* @brief ConfigData::instance The instance of ConfigData.
*/
ConfigData* ConfigData::instance = nullptr;
/**
* @brief ConfigData::getInstance This method ensures that there is only one instance of ConfigData.
* @return The only instance of ConfigData.
*/
ConfigData* ConfigData::getInstance() {
if(instance == nullptr) {
instance = new ConfigData();
}
return instance;
}
/**
* @brief ConfigData::getLanguage Loads the language chosen by the user.
* @return The language chosen by the user.
*/
QString ConfigData::getLanguage() {
return QSettings::value("language", "German").toString();
}
/**
* @brief ConfigData::setLanguage Stores the language and sets the translator.
* @param language The language chosen by the user.
*/
void ConfigData::setLanguage(QString language) {
QSettings::setValue("language", language);
if(languages.contains(language)) {
if(mTranslator->load(languages.value(language), QLatin1String("CoBaB"), QLatin1String("_"), QLatin1String(":/resources/translations"))) {
qApp->installTranslator(mTranslator);
}
}
}
/**
* @brief ConfigData::getSoundOn Loads the sound setting chosen by the user.
* @return True if the user wants to hear a notification sound when the search is finished.
*/
bool ConfigData::getSoundOn() {
return QSettings::value("soundOn", false).toBool();
}
/**
* @brief ConfigData::setSoundOn Stores the sound setting chosen by the user.
* @param soundOn True if the user wants to hear a notification sound when the search is finished.
*/
void ConfigData::setSoundOn(bool soundOn) {
QSettings::setValue("soundOn", soundOn);
}
/**
* @brief ConfigData::getHelp Returns the help string in the chosen language.
* @return The help string.
*/
QString ConfigData::getHelp() {
return tr("Bibliothek:\nEnthält die zuletzt verwendeten Datensätze und die Datensätze aus dem Standardordner, der per Kommandozeile übergeben werden kann.\n"
"Per Doppelklick wird der Datensatz ausgewählt, in dem sich das Bild/Video befindet, das als Grundlage für die inhaltsbasierte Suche dienen soll. \n \n"
"Viewer:\nÜber die Buttons 'vorheriges' und 'nächstes' wird das Bild/Video ausgewählt, das als Grundlage für die inhaltsbasierte Suche dienen soll. \n"
"Bei einem Rechtsklick auf das Bild werden die verfügbaren Suchalgorithmen aufgelistet. "
"Fährt man mit der Maus über einen solchen Algorithmus, erscheint eine Beschreibung zu diesem. "
"Durch Klicken auf einen Algorithmus kann mit dem Programm fortgefahren werden. \n"
"In den Bildern werden außerdem, falls vorhanden, Annotationen angezeigt. \n"
"Nach einem Klick auf den Button 'Bereich auswählen' kann ein eigenes Rechteck auf dem Bild gezogen werden. "
"Mit einem Rechtsklick in die Annotation oder das gezogene Rechteck werden die dafür verfügbaren Algorithmen angezeigt. \n\n"
"Parameter:\nNach der Auswahl eines Algorithmus kann man Parameter für diesen festlegen. "
"Außerdem können weitere Datensätze ausgewählt werden, in denen gesucht werden soll. \n \n"
"Bestätigung:\nHier wird die aktuelle Auswahl angezeigt, die dem Algorithmus übergeben wird. \n \n"
"Ergebnisse:\nDie Bilder können als positiv (grüner Kasten, ein Klick auf das Bild), negativ (roter Kasten, zweiter Klick) oder wieder neutral (dritter Klick) bewertet werden.\n"
"Durch einen Klick auf den Button 'Erneut suchen' wird das Feedback an den Algorithmus übermittelt und eine neue verbesserte Suche gestartet.");
}
/**
* @brief ConfigData::getAbout Returns the about string in the chosen language.
* @return The about string.
*/
QString ConfigData::getAbout() {
return tr("CoBaB ermöglicht es, anhand eines ausgewählten Bildes"
" oder Videos eine inhaltsbasierte Suche in Bild- oder Videodaten durchzuführen."
" Als Ergebnis liefert CoBaB eine Auswahl ähnlicher Bilder oder Videos. Durch die Eingabe von Feedback kann diese Auswahl verfeinert werden.\n\n"
"Autoren: Anja Blechinger, Marie Bommersheim, Georgi Georgiev, Tung Nguyen, Vincent Winkler, Violina Zhekova");
}
| 44.89 | 182 | 0.740699 | aschuman |
ea54f68fa64e088280e1531c992ec8d53df920c9 | 1,988 | cpp | C++ | P4612.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | P4612.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | P4612.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | /*
* Author: xiaohei_AWM
* Date:5.3
* Mutto: Face to the weakness, expect for the strength.
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<utility>
#include<functional>
#include<vector>
#include<assert.h>
using namespace std;
#define reg register
#define endfile fclose(stdin);fclose(stdout);
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef std::pair<int,int> pii;
typedef std::pair<ll,ll> pll;
namespace IO{
char buf[1<<15],*S,*T;
inline char gc(){
if (S==T){
T=(S=buf)+fread(buf,1,1<<15,stdin);
if (S==T)return EOF;
}
return *S++;
}
inline int read(){
reg int x;reg bool f;reg char c;
for(f=0;(c=gc())<'0'||c>'9';f=c=='-');
for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0'));
return f?-x:x;
}
inline ll readll(){
reg ll x;reg bool f;reg char c;
for(f=0;(c=gc())<'0'||c>'9';f=c=='-');
for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0'));
return f?-x:x;
}
}
using namespace IO;
struct Rectangle{
int x1, x2, y1, y2;
Rectangle(){}
Rectangle(int x, int y, int p){
x1 = x-p;
x2 = x+p;
y1 = y-p;
y2 = y+p;
}
};
int n, x, y, p;
ll ans = 0;
int main(){
n = read();
x = read(), y = read(), p = read();
Rectangle S(x, y, p);
for(int i = 1; i < n; i++){
x = read(), y = read(), p = read();
Rectangle A(x, y, p);
int D = max(max(A.x1 - S.x2, S.x1 - A.x2), max(A.y1 - S.y2, S.y1 - A.y2));
if(D < 0)
D = 0;
ans += D;
S.x1 -= D;
S.x2 += D;
S.y1 -= D;
S.y2 += D;
Rectangle Part;
Part.x1 = max(S.x1, A.x1);
Part.x2 = min(S.x2, A.x2);
Part.y1 = max(S.y1, A.y1);
Part.y2 = min(S.y2, A.y2);//慢慢移动
S = Part;
}
cout << ans;
return 0;
}
| 23.666667 | 82 | 0.479376 | AndrewWayne |
ea5ce77589e9dcc71190384d6405826e9e895524 | 1,131 | cpp | C++ | Company-Google/393. UTF-8 Validation/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 1 | 2021-11-19T19:58:33.000Z | 2021-11-19T19:58:33.000Z | Company-Google/393. UTF-8 Validation/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | null | null | null | Company-Google/393. UTF-8 Validation/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 2 | 2021-11-26T12:47:27.000Z | 2022-01-13T16:14:46.000Z | //
// main.cpp
// 393. UTF-8 Validation
//
// Created by Jaylen Bian on 7/26/20.
// Copyright © 2020 边俊林. All rights reserved.
//
#include <map>
#include <set>
#include <queue>
#include <string>
#include <stack>
#include <vector>
#include <cstdio>
#include <numeric>
#include <cstdlib>
#include <utility>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Solution:
//
class Solution {
public:
bool validUtf8(vector<int>& data) {
int cnt = 0;
for (int& n: data) {
if (cnt == 0) {
if ((n >> 3) == 0b11110) cnt = 3;
else if ((n >> 4) == 0b1110) cnt = 2;
else if ((n >> 5) == 0b110) cnt = 1;
else if ((n >> 7) == 0b1) return false;
} else {
if ((n >> 6) != 0b10)
return false;
--cnt;
}
}
return cnt == 0;
}
};
int main() {
Solution sol = Solution();
vector<int> data = {197, 130, 1};
bool res = sol.validUtf8(data);
cout << res << endl;
return 0;
}
| 20.563636 | 55 | 0.50221 | Minecodecraft |
ea5ef2d33b7d36eeb530e3e5720301530f805d2e | 280 | cpp | C++ | All_code/57.cpp | jnvshubham7/cpp-programming | 7d00f4a3b97b9308e337c5d3547fd3edd47c5e0b | [
"Apache-2.0"
] | 1 | 2021-12-22T12:37:36.000Z | 2021-12-22T12:37:36.000Z | All_code/57.cpp | jnvshubham7/CPP_Programming | a17c4a42209556495302ca305b7c3026df064041 | [
"Apache-2.0"
] | null | null | null | All_code/57.cpp | jnvshubham7/CPP_Programming | a17c4a42209556495302ca305b7c3026df064041 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int factorial(int n) {
int fact = 1;
for (int v = 1; v <= n; v++) {
fact = fact * v;
}
return fact;
}
return 0;
}
| 14 | 38 | 0.517857 | jnvshubham7 |
ea6304a806f2166c33b63ea65a502beb4a699b6c | 1,051 | cpp | C++ | src/utils/ExpressionManager.cpp | amecky/breakout | b580befabd1226c6c8c26550d5e0e0ca841fe67d | [
"MIT"
] | null | null | null | src/utils/ExpressionManager.cpp | amecky/breakout | b580befabd1226c6c8c26550d5e0e0ca841fe67d | [
"MIT"
] | null | null | null | src/utils/ExpressionManager.cpp | amecky/breakout | b580befabd1226c6c8c26550d5e0e0ca841fe67d | [
"MIT"
] | null | null | null | #include "ExpressionManager.h"
#include <diesel.h>
ExpressionManager::ExpressionManager() {
_vmCtx = vm_create_context();
vm_add_variable(_vmCtx, "TIMER", 0.0f);
vm_add_variable(_vmCtx, "PI", ds::PI);
vm_add_variable(_vmCtx, "TWO_PI", ds::TWO_PI);
}
ExpressionManager::~ExpressionManager() {
vm_destroy_context(_vmCtx);
}
void ExpressionManager::setVariable(const char * name, float value) {
vm_set_variable(_vmCtx, name, value);
}
int ExpressionManager::parse(const char * expression) {
Expression exp;
exp.num = vm_parse(_vmCtx, expression, exp.tokens, 64);
_expressions.push_back(exp);
return _expressions.size() - 1;
}
void ExpressionManager::parse(int expressionID, const char * expression) {
Expression& exp = _expressions[expressionID];
exp.num = vm_parse(_vmCtx, expression, exp.tokens, 64);
}
float ExpressionManager::run(int index) {
Expression& exp = _expressions[index];
float r = 0.0f;
int code = vm_run(_vmCtx, exp.tokens, exp.num, &r);
if (code != 0) {
DBG_LOG("Error: %s", vm_get_error(code));
}
return r;
}
| 26.275 | 74 | 0.725975 | amecky |
ea6cef86f165de40ad583269f5207fea3ec23482 | 1,419 | cpp | C++ | c++/leetcode/0909-Snakes_and_Ladders-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/0909-Snakes_and_Ladders-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/0909-Snakes_and_Ladders-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | // 909 Snakes and Ladders
// https://leetcode.com/problems/snakes-and-ladders
// version: 1; create time: 2020-01-12 11:30:15;
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
const int m = board.size();
if (m == 0) return -1;
const int n = board.size();
if (n == 0) return -1;
const auto calc_index = [&](const int k) {
const int i = m - 1 - (k / n);
const int j = ((k / n) % 2) ? (n - 1 - (k % n)) : (k % n);
return std::make_pair(i, j);
};
vector<bool> visit(m * n, false);
queue<int> bfs;
bfs.push(0);
int steps = 0;
while (!bfs.empty()) {
const int size = bfs.size();
++steps;
for (int i = 0; i < size; ++i) {
const auto k = bfs.front(); bfs.pop();
for (int s = 1; (s <= 6) && (s + k < m * n); ++s) {
const auto index = calc_index(k + s);
const int i = index.first;
const int j = index.second;
const int next = board[i][j] != -1 ? board[i][j] - 1 : k + s;
if (next == m * n - 1) return steps;
if (visit[next]) continue;
visit[next] = true;
bfs.push(next);
}
}
}
return -1;
}
};
| 31.533333 | 81 | 0.41649 | levendlee |
ea7525f81d1d57b3a558ed62d3f5d00b2818ae70 | 2,762 | cpp | C++ | src/Thread.cpp | TheDSCPL/SSRE_2017-2018_group8 | 10a74266fbd9fcdb9a2898427096d80f6430b75e | [
"MIT"
] | null | null | null | src/Thread.cpp | TheDSCPL/SSRE_2017-2018_group8 | 10a74266fbd9fcdb9a2898427096d80f6430b75e | [
"MIT"
] | null | null | null | src/Thread.cpp | TheDSCPL/SSRE_2017-2018_group8 | 10a74266fbd9fcdb9a2898427096d80f6430b75e | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <chrono>
#include <thread>
#include <iostream>
#include <sys/time.h>
#include <string.h>
#include "../headers/Thread.hpp"
using namespace std;
Mutex::Mutex() : mutex(PTHREAD_MUTEX_INITIALIZER) {}
void Mutex::lock() {
pthread_mutex_lock(&mutex);
}
void Mutex::unlock() {
pthread_mutex_unlock(&mutex);
}
bool Mutex::isLocked() {
static Mutex m;
bool ret = false;
m.lock();
int r = pthread_mutex_trylock(&mutex);
if (r == 0) { //could lock so it's not locked
pthread_mutex_unlock(&mutex);
} else if (r == EBUSY)
ret = true;
m.unlock();
return ret;
}
Mutex::~Mutex() {
pthread_mutex_destroy(&mutex);
}
ThreadCondition::ThreadCondition() : condition(PTHREAD_COND_INITIALIZER) {}
void ThreadCondition::wait(Mutex &m) {
pthread_cond_wait(&condition, &m.mutex);
}
void ThreadCondition::timedWait(Mutex &m, long millis) {
struct timeval tv;
gettimeofday(&tv, NULL); //epoch time
timespec t; //epoch target time
t.tv_sec = tv.tv_sec + millis / 1000;
t.tv_nsec = (tv.tv_usec + millis % 1000) * 1000;
pthread_cond_timedwait(&condition, &m.mutex, &t);
}
void ThreadCondition::signal() {
pthread_cond_signal(&condition);
}
void ThreadCondition::broadcast() {
pthread_cond_broadcast(&condition);
}
ThreadCondition::~ThreadCondition() {
pthread_cond_destroy(&condition);
}
Thread::Thread(std::function<void()> f, std::function<void()> os) : routine(f), onStop(os), running(false),
onStopCalledOnLastRun(false) {}
//(std::function<void *(void *)>)[&f](void*)->void*{f(); return nullptr;}
Thread::~Thread() {
//cout << "DELETING THREAD!" << endl;
cancel();
}
void Thread::start() {
onStopCalledOnLastRun = false;
pthread_create(&thread, nullptr, trick, (void *) this);
// if(pthread_detach(thread))
// cerr << "Couldn't detach thread!" << endl;
}
void Thread::usleep(long millis) {
this_thread::sleep_for(chrono::milliseconds(millis));
}
void Thread::_onStop() {
if (onStopCalledOnLastRun)
return;
onStopCalledOnLastRun = true;
onStop();
}
void *Thread::trick(void *c) {//http://stackoverflow.com/a/1151615
((Thread *) c)->run();
return nullptr;
}
void Thread::run() {
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr);
running = true;
routine();
running = false;
_onStop();
}
bool Thread::isRunning() const {
return running;
}
void Thread::join() const {
pthread_join(thread, nullptr);
}
void Thread::cancel() {
running = false;
_onStop();
//cout << "FINISHED CANCELING!" << endl;
pthread_cancel(thread);
pthread_join(thread,nullptr);
} | 22.826446 | 107 | 0.636495 | TheDSCPL |
ea7d8672f124302266848020fc28e0ef2e9c3c59 | 8,997 | cpp | C++ | ScriptHookDotNet/SettingsFile.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 3 | 2021-11-14T20:59:58.000Z | 2021-12-16T16:41:31.000Z | ScriptHookDotNet/SettingsFile.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 2 | 2021-11-29T14:41:23.000Z | 2021-11-30T13:13:51.000Z | ScriptHookDotNet/SettingsFile.cpp | HazardX/gta4_scripthookdotnet | 927b2830952664b63415234541a6c83592e53679 | [
"MIT"
] | 3 | 2021-11-21T12:41:55.000Z | 2021-12-22T16:17:52.000Z | /*
* Copyright (c) 2009-2011 Hazard ([email protected] / twitter.com/HazardX)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"
#include "SettingsFile.h"
#include "ContentCache.h"
#pragma managed
namespace GTA {
//namespace value {
SettingsFile::SettingsFile(String^ Filename) {
pFilename = Filename;
categories = gcnew Collections::Generic::Dictionary<String^,SettingCategory^>();
bChanged = false;
}
SettingsFile^ SettingsFile::Open(String^ Filename) {
return ContentCache::GetINI(Filename);
}
SettingsFile::!SettingsFile() {
if (bChanged) Save();
}
//String^ SettingsFile::Filename::get() {
// return IO::Path::ChangeExtension(script->Filename,"ini");
//}
SettingCategory^ SettingsFile::GetCategory(String^ Name) {
String^ id = Name->ToLower();
if (categories->ContainsKey(id)) {
return categories[id];
} else {
SettingCategory^ cat = gcnew SettingCategory(Name);
categories[id] = cat;
return cat;
}
}
void SettingsFile::Clear() {
categories->Clear();
bChanged = true;
bAddNextLine = false;
}
void SettingsFile::Load() {
Clear();
array<String^>^ Lines = Helper::StringToLines(Helper::FileToString(Filename, System::Text::Encoding::ASCII));
//if (Lines->Length == 0) NetHook::Log("No settings in file '"+Filename+"'!");
CurrentCategory = String::Empty;
for (int i = 0; i < Lines->Length; i++) {
if (!bAddNextLine)
ParseLine(Lines[i]);
else
ParseAddLine(Lines[i]);
}
bChanged = false;
}
void SettingsFile::ParseLine(String^ DataLine) {
try {
DataLine = DataLine->Trim();
if (DataLine->StartsWith("/") || DataLine->StartsWith("'") || DataLine->StartsWith("#")) return;
if (DataLine->StartsWith("[")) {
int sPos = DataLine->IndexOf("]");
if (sPos<=1) return;
CurrentCategory = DataLine->Substring(1,sPos-1);
return;
}
int eq = DataLine->IndexOf("=");
if (eq <= 0) return;
String^ name = DataLine->Substring(0, eq)->Trim();
String^ val;
if (eq < DataLine->Length-1) {
val = DataLine->Substring(eq+1)->Trim();
if (val->EndsWith("\\n\\")) {
pLastValueName = name;
bAddNextLine = true;
if (val->Length > 3)
val = val->Substring(0,val->Length-3);
else
val = String::Empty;
}
val = val->Replace("\\n",Environment::NewLine);
val = val->Replace("#\\#n#","\\n");
} else {
val = String::Empty;
}
//values->Add(name->ToLower(), val);
GetCategory(CurrentCategory)->SetValue(name, val);
//NetHook::Log("Found setting '"+name+"' with value '"+val+"'!");
} catchErrors("Error in setting file '"+Filename+"'",)//catch(...) {}
}
void SettingsFile::ParseAddLine(String^ DataLine) {
bAddNextLine = false;
try {
DataLine = DataLine->Trim();
if (DataLine->Length > 0) {
if (DataLine->EndsWith("\\n\\")) {
//pLastValueName = name;
bAddNextLine = true;
if (DataLine->Length > 3)
DataLine = DataLine->Substring(0,DataLine->Length-3);
else
DataLine = String::Empty;
}
DataLine = DataLine->Replace("\\n",Environment::NewLine);
DataLine = DataLine->Replace("#\\#n#","\\n");
} else {
DataLine = String::Empty;
}
SetValue(CurrentCategory, pLastValueName, GetValueString(pLastValueName, CurrentCategory, String::Empty) + Environment::NewLine + DataLine);
} catchErrors("Error in setting file '"+Filename+"'",)//catch(...) {}
}
bool SettingsFile::Save() {
if (!bChanged) return true;
if (SaveCopyTo(Filename)) {
bChanged = false;
return true;
} else {
return false;
}
}
bool SettingsFile::SaveCopyTo(String^ Filename) {
System::Text::StringBuilder^ sb = gcnew System::Text::StringBuilder();
array<String^>^ cats = GetCategoryNames();
for (int i = 0; i < cats->Length; i++) {
SaveCategory(sb, cats[i]);
}
return Helper::StringToFile(Filename, sb->ToString(), System::Text::Encoding::ASCII);
}
void SettingsFile::SaveCategory(System::Text::StringBuilder^ sb, String^ CategoryName) {
array<String^>^ vals = GetValueNames(CategoryName);
if (vals->Length == 0) return;
String^ val;
sb->AppendLine();
if (CategoryName->Length > 0) sb->AppendLine("[" + CategoryName + "]");
for (int i = 0; i < vals->Length; i++) {
val = GetValueString(vals[i], CategoryName, String::Empty);
val = val->Replace("\\n","#\\#n#");
val = val->Replace("\r",String::Empty);
val = val->Replace("\n","\\n");
sb->AppendLine(vals[i] + "=" + val);
}
}
array<String^>^ SettingsFile::GetCategoryNames() {
List<String^>^ list = gcnew List<String^>();
//list->Add(String::Empty);
for each (KeyValuePair<String^,SettingCategory^> kvp in categories) {
if (kvp.Key->Length > 0) list->Add(kvp.Value->Name);
}
list->Sort();
list->Insert(0, String::Empty);
return list->ToArray();
}
array<String^>^ SettingsFile::GetValueNames(String^ Category) {
return GetCategory(Category)->GetValueNames();
}
String^ SettingsFile::GetValueString(String^ OptionName, String^ Category, String^ DefaultValue) {
return GetCategory(Category)->GetValue(OptionName,DefaultValue);
}
String^ SettingsFile::GetValueString(String^ OptionName, String^ Category) {
return GetValueString(OptionName, Category, String::Empty);
//OptionName = OptionName->ToLower();
//if (!values->ContainsKey(OptionName)) return DefaultValue;
//return values[OptionName];
}
String^ SettingsFile::GetValueString(String^ OptionName) {
return GetValueString(OptionName, String::Empty, String::Empty);
}
int SettingsFile::GetValueInteger(String^ OptionName, String^ Category, int DefaultValue) {
String^ val = GetValueString(OptionName, Category, String::Empty);
return Helper::StringToInteger(val, DefaultValue);
}
float SettingsFile::GetValueFloat(String^ OptionName, String^ Category, float DefaultValue) {
String^ val = GetValueString(OptionName, Category, String::Empty);
return Helper::StringToFloat(val, DefaultValue);
}
bool SettingsFile::GetValueBool(String^ OptionName, String^ Category, bool DefaultValue) {
String^ val = GetValueString(OptionName, Category, String::Empty);
return Helper::StringToBoolean(val, DefaultValue);
}
Vector3 SettingsFile::GetValueVector3(String^ OptionName, String^ Category, Vector3 DefaultValue) {
String^ val = GetValueString(OptionName, Category, String::Empty);
return Helper::StringToVector3(val, DefaultValue);
}
Windows::Forms::Keys SettingsFile::GetValueKey(String^ OptionName, String^ Category, Windows::Forms::Keys DefaultValue) {
String^ val = GetValueString(OptionName, Category, String::Empty);
//if (val->Length == 0) NetHook::Log("Requested setting '"+OptionName+"' not found!");
return Helper::StringToKey(val, DefaultValue);
}
GTA::Model SettingsFile::GetValueModel(String^ OptionName, String^ Category, GTA::Model DefaultValue) {
String^ val = GetValueString(OptionName, Category, String::Empty);
return Helper::StringToModel(val,DefaultValue);
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, String^ Value) {
GetCategory(Category)->SetValue(OptionName, Value);
bChanged = true;
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, Vector3 Value) {
SetValue(OptionName, Category, Value.ToString(", ", 4));
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, bool Value) {
SetValue(OptionName, Category, Value.ToString());
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, float Value) {
SetValue(OptionName, Category, Helper::FloatToString(Value,4));
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, int Value) {
SetValue(OptionName, Category, Value.ToString());
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, Windows::Forms::Keys Value) {
SetValue(OptionName, Category, Value.ToString());
}
void SettingsFile::SetValue(String^ OptionName, String^ Category, GTA::Model Value) {
SetValue(OptionName, Category, Value.ToString());
}
//}
} | 35.702381 | 143 | 0.691342 | HazardX |
ea87fcf473d7ffc76b62a509b1dc7059f92b7edf | 640 | cpp | C++ | competitive programming/codeforces/486A - Calculating Function.cpp | sureshmangs/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 16 | 2020-06-02T19:22:45.000Z | 2022-02-05T10:35:28.000Z | competitive programming/codeforces/486A - Calculating Function.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | null | null | null | competitive programming/codeforces/486A - Calculating Function.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 2 | 2020-08-27T17:40:06.000Z | 2022-02-05T10:33:52.000Z | /*
For a positive integer n let's define a function f:
f(n)?=??-?1?+?2?-?3?+?..?+?(?-?1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1?=?n?=?1015).
Output
Print f(n) in a single line.
Examples
inputCopy
4
outputCopy
2
inputCopy
5
outputCopy
-3
Note
f(4)?=??-?1?+?2?-?3?+?4?=?2
f(5)?=??-?1?+?2?-?3?+?4?-?5?=??-?3
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n;
cin >> n;
if (n % 2) {
cout << - (n + 1) / 2;
} else cout << n / 2;
return 0;
}
| 13.061224 | 63 | 0.551563 | sureshmangs |
ea88234b0e97b18027441b56582f5a64b831d84b | 295 | cpp | C++ | CPP files/win.cpp | jjang32/RPS | 2ce861f461f440ac9fadfbb7a1d3676d3c8a9f42 | [
"MIT"
] | null | null | null | CPP files/win.cpp | jjang32/RPS | 2ce861f461f440ac9fadfbb7a1d3676d3c8a9f42 | [
"MIT"
] | null | null | null | CPP files/win.cpp | jjang32/RPS | 2ce861f461f440ac9fadfbb7a1d3676d3c8a9f42 | [
"MIT"
] | null | null | null | #include "win.h"
#include "ui_win.h"
#include "mainwindow.h"
Win::Win(QWidget *parent) :
QDialog(parent),
ui(new Ui::Win)
{
ui->setupUi(this);
}
Win::~Win()
{
delete ui;
}
void Win::on_retry_clicked()
{
MainWindow *mainwindow = new MainWindow();
mainwindow->show();
}
| 13.409091 | 46 | 0.616949 | jjang32 |
ea8d52382b0b5936a612770af237ad24a8b2b2be | 8,899 | cpp | C++ | src/dpp/dispatcher.cpp | luizstudios/DPP | ea546cd10a06a23b62d1667c26a909cd59ca6100 | [
"Apache-2.0"
] | null | null | null | src/dpp/dispatcher.cpp | luizstudios/DPP | ea546cd10a06a23b62d1667c26a909cd59ca6100 | [
"Apache-2.0"
] | null | null | null | src/dpp/dispatcher.cpp | luizstudios/DPP | ea546cd10a06a23b62d1667c26a909cd59ca6100 | [
"Apache-2.0"
] | 1 | 2021-09-26T18:36:18.000Z | 2021-09-26T18:36:18.000Z | /************************************************************************************
*
* D++, A Lightweight C++ library for Discord
*
* Copyright 2021 Craig Edwards and D++ contributors
* (https://github.com/brainboxdotcc/DPP/graphs/contributors)
*
* 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 <dpp/discord.h>
#include <dpp/slashcommand.h>
#include <dpp/dispatcher.h>
#include <dpp/cluster.h>
#include <dpp/fmt/format.h>
#include <variant>
namespace dpp {
event_dispatch_t::event_dispatch_t(discord_client* client, const std::string &raw) : from(client), raw_event(raw)
{
}
guild_join_request_delete_t::guild_join_request_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
stage_instance_create_t::stage_instance_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
stage_instance_delete_t::stage_instance_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
log_t::log_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_state_update_t::voice_state_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
interaction_create_t::interaction_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
void interaction_create_t::reply(interaction_response_type t, const message & m) const
{
from->creator->interaction_response_create(this->command.id, this->command.token, dpp::interaction_response(t, m));
}
void interaction_create_t::reply(interaction_response_type t, const std::string & mt) const
{
this->reply(t, dpp::message(this->command.channel_id, mt, mt_application_command));
}
const command_value& interaction_create_t::get_parameter(const std::string& name) const
{
/* Dummy STATIC return value for unknown options so we arent returning a value off the stack */
static command_value dummy_value = {};
const command_interaction& ci = std::get<command_interaction>(command.data);
for (auto i = ci.options.begin(); i != ci.options.end(); ++i) {
if (i->name == name) {
return i->value;
}
}
return dummy_value;
}
button_click_t::button_click_t(discord_client* client, const std::string &raw) : interaction_create_t(client, raw)
{
}
const command_value& button_click_t::get_parameter(const std::string& name) const
{
/* Buttons don't have parameters, so override this */
static command_value dummy_b_value = {};
return dummy_b_value;
}
guild_delete_t::guild_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
channel_delete_t::channel_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
channel_update_t::channel_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
ready_t::ready_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_delete_t::message_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
application_command_delete_t::application_command_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
application_command_create_t::application_command_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
resumed_t::resumed_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_role_create_t::guild_role_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
typing_start_t::typing_start_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_reaction_add_t::message_reaction_add_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_reaction_remove_t::message_reaction_remove_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_create_t::guild_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
channel_create_t::channel_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_reaction_remove_emoji_t::message_reaction_remove_emoji_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_delete_bulk_t::message_delete_bulk_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_role_update_t::guild_role_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_role_delete_t::guild_role_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
channel_pins_update_t::channel_pins_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_reaction_remove_all_t::message_reaction_remove_all_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_server_update_t::voice_server_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_emojis_update_t::guild_emojis_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
presence_update_t::presence_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
webhooks_update_t::webhooks_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_member_add_t::guild_member_add_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
invite_delete_t::invite_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_update_t::guild_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_integrations_update_t::guild_integrations_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_member_update_t::guild_member_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
application_command_update_t::application_command_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
invite_create_t::invite_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_update_t::message_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
user_update_t::user_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
message_create_t::message_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_ban_add_t::guild_ban_add_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_ban_remove_t::guild_ban_remove_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
integration_create_t::integration_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
integration_update_t::integration_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
integration_delete_t::integration_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_member_remove_t::guild_member_remove_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
guild_members_chunk_t::guild_members_chunk_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_buffer_send_t::voice_buffer_send_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_user_talking_t::voice_user_talking_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_ready_t::voice_ready_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_receive_t::voice_receive_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
voice_track_marker_t::voice_track_marker_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw)
{
}
};
| 32.126354 | 144 | 0.766041 | luizstudios |
ea8e774c6d9ee684545b00450bf4bca5662de336 | 2,010 | hpp | C++ | include/vcd/test/header.hpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 1 | 2019-04-30T17:56:23.000Z | 2019-04-30T17:56:23.000Z | include/vcd/test/header.hpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | null | null | null | include/vcd/test/header.hpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 4 | 2018-08-01T08:32:00.000Z | 2019-12-18T06:34:33.000Z | // ============================================================================
// Copyright 2018 Paul le Roux and Calvin Maree
//
// 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.
// ============================================================================
#ifndef LIBVCD_TEST_HEADER_HPP
#define LIBVCD_TEST_HEADER_HPP
#include "./scope.hpp"
#include "vcd/types/enums.hpp"
#include "vcd/types/header_reader.hpp"
namespace VCD::Test {
struct TestHeader {
std::optional<VCD::TimeScale> time_scale;
std::optional<std::string> date;
std::optional<std::string> version;
std::optional<TestScope> root_scope;
};
void read_in_test_header(VCD::HeaderReader &reader, TestHeader &test);
} // namespace VCD::Test
#endif // LIBVCD_TEST_HEADER_HPP
| 40.2 | 79 | 0.706965 | qedalab |
ea95e1ac0c66d504220f720ff6bdbb4f53d8f4e0 | 1,290 | cpp | C++ | DFS/RangeSumBST.cpp | karan2808/Cpp | 595f536e33505c5fd079b709d6370bf888043fb3 | [
"MIT"
] | 1 | 2021-01-31T03:43:59.000Z | 2021-01-31T03:43:59.000Z | DFS/RangeSumBST.cpp | karan2808/Cpp | 595f536e33505c5fd079b709d6370bf888043fb3 | [
"MIT"
] | null | null | null | DFS/RangeSumBST.cpp | karan2808/Cpp | 595f536e33505c5fd079b709d6370bf888043fb3 | [
"MIT"
] | 1 | 2021-01-25T14:27:08.000Z | 2021-01-25T14:27:08.000Z | #include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode()
{
val = 0;
left = nullptr;
right = nullptr;
}
TreeNode(int x)
{
val = x;
left = nullptr;
right = nullptr;
}
TreeNode(int x, TreeNode *left, TreeNode *right)
{
val = x;
this->left = left;
this->right = right;
}
};
class Solution
{
public:
int rangeSumBST(TreeNode *root, int low, int high)
{
if (!root)
return 0;
int sum = 0;
// if the root value is within range, set sum to root value
if (root->val >= low && root->val <= high)
sum = root->val;
// add sum of left side and right side to the current sum
sum += rangeSumBST(root->left, low, high);
sum += rangeSumBST(root->right, low, high);
return sum;
}
};
int main()
{
Solution mySol;
TreeNode *root = new TreeNode(10, new TreeNode(5), new TreeNode(15));
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(7);
root->right->right = new TreeNode(18);
cout << "The range sum of the BST between 7 and 15: " << mySol.rangeSumBST(root, 7, 15) << endl;
return 0;
} | 22.631579 | 100 | 0.542636 | karan2808 |
ea9635dcef6773bb10aa9d56672b48364e959e6e | 939 | cpp | C++ | old/src/riscv/Value.cpp | ClasSun9/riscv-dynamic-taint-analysis | 8a96f5ea8d07580315253dc074f60955fc633da9 | [
"MIT"
] | null | null | null | old/src/riscv/Value.cpp | ClasSun9/riscv-dynamic-taint-analysis | 8a96f5ea8d07580315253dc074f60955fc633da9 | [
"MIT"
] | null | null | null | old/src/riscv/Value.cpp | ClasSun9/riscv-dynamic-taint-analysis | 8a96f5ea8d07580315253dc074f60955fc633da9 | [
"MIT"
] | null | null | null | # include "Value.hpp"
namespace riscv {
int8_t SignedValue::As8() {
return static_cast<int8_t>(_value);
}
int16_t SignedValue::As16() {
return static_cast<int16_t>(_value);
}
int32_t SignedValue::As32() {
return static_cast<int32_t>(_value);
}
int64_t SignedValue::As64() {
return _value;
}
SignedValue::SignedValue(int64_t value) : _value(value) { }
uint8_t UnsignedValue::As8() {
return static_cast<uint8_t>(_value);
}
uint16_t UnsignedValue::As16() {
return static_cast<uint16_t>(_value);
}
uint32_t UnsignedValue::As32() {
return static_cast<uint32_t>(_value);
}
uint64_t UnsignedValue::As64() {
return _value;
}
UnsignedValue::UnsignedValue(uint64_t value) : _value(value) { }
SignedValue Value::AsSigned() {
return SignedValue(static_cast<int64_t>(_value));
}
UnsignedValue Value::AsUnsigned() {
return UnsignedValue(_value);
}
Value::Value(uint64_t value) : _value(value) { }
} | 18.411765 | 64 | 0.7082 | ClasSun9 |
ea9d4310af354771c1c8338250f75c367b6b6e32 | 33,490 | hpp | C++ | include/lfd/GenericDescriptor.hpp | waterben/LineExtraction | d247de45417a1512a3bf5d0ffcd630d40ffb8798 | [
"MIT"
] | 1 | 2020-06-12T13:30:56.000Z | 2020-06-12T13:30:56.000Z | include/lfd/GenericDescriptor.hpp | waterben/LineExtraction | d247de45417a1512a3bf5d0ffcd630d40ffb8798 | [
"MIT"
] | null | null | null | include/lfd/GenericDescriptor.hpp | waterben/LineExtraction | d247de45417a1512a3bf5d0ffcd630d40ffb8798 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
// C by Benjamin Wassermann
//
#ifndef _LFD_GENERICDESCRIPTOR_HPP_
#define _LFD_GENERICDESCRIPTOR_HPP_
#ifdef __cplusplus
#include <vector>
#include <geometry/line.hpp>
#include <utility/mean.hpp>
#include <lfd/FeatureDescriptor.hpp>
#include <opencv2/imgproc/imgproc.hpp>
namespace lsfm {
template<class FT>
struct RotationAlign {
static inline void apply(const Line<FT>& line, const Vec2<FT> &p, Vec2<FT>& ret) {
set(ret, line.project(p), line.normalProject(p));
}
static inline Vec2<FT> apply(const Line<FT>& line, const Vec2<FT> &p) {
return Vec2<FT>(line.project(p),line.normalProject(p));
}
};
template<class FT>
struct NoAlign {
static inline void apply(const Line<FT>& line, const Vec2<FT> &p, Vec2<FT> &ret) {
ret = p;
}
static inline Vec2<FT> apply(const Line<FT>& line, const Vec2<FT> &p) {
return p;
}
};
// Generic Feature Descriptor
template<class FT, int cn>
struct GenericDescritpor {
GenericDescritpor() {}
GenericDescritpor(const FT *d) : data() {
memcopy(data,d,sizeof(FT) * cn);
}
FT data[cn];
inline FT distance(const GenericDescritpor<FT,cn>& rhs) const {
return static_cast<FT>(norm(cv::_InputArray(data,cn), cv::_InputArray(rhs.data,cn), cv::NORM_L2));
}
//! compute distance between two descriptors (static version)
static inline FT distance(const GenericDescritpor<FT,cn>& lhs, const GenericDescritpor<FT,cn>& rhs) {
return static_cast<FT>(norm(cv::_InputArray(lhs.ata,cn), cv::_InputArray(rhs.data,cn), cv::NORM_L2));
}
static inline int size() {
return cn;
}
std::string name() const {
return "GENERIC";
}
};
// Creator Helper for intensity images using interpolator
template<class FT, uint size = 3, uint step = 2, class Interpolator = FastRoundNearestInterpolator<FT, uchar>>
struct GchImgInterpolate {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 2;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &img = data[0];
// get line length (floor)
uint length = static_cast<uint>(line.length());
if (length < 1)
length = 1;
// get current line direction
cv::Point_<FT> dL = line.direction();
cv::Point_<FT> dN(-dL.y,dL.x);
dN *= step * stepDir;
dL *= lstep;
// coordinates
cv::Point_<FT> sCor0, sCor;
FT sum, sum2, val;
// convert upper left pos in line coords to local coords (rotate + translate)
sCor0 = line.line2world(cv::Point_<FT>(-((static_cast<FT>(length) - 1) / 2), static_cast<FT>(beg)), line.centerPoint());
int lineSteps = static_cast<int>(length / lstep);
FT norm = static_cast<FT>(1.0 / (lineSteps * numBands));
for (int i = 0; i != numBands; ++i) {
sCor = sCor0;
sum = 0;
sum2 = 0;
for (int j = 0; j < lineSteps; ++j) {
// access value in mat
val = Interpolator::get(img, sCor);
//std::cout << sCor << std::endl;
sum += val;
sum2 += val*val;
// next pixel in line dir
sCor += dL;
}
// next row
sCor0 += dN;
// compute mean
dst[0] = val = sum * norm;
// compute variance
dst[numBands] = std::sqrt(sum2 * norm - val*val);
++dst;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("img"));
return ret;
}
};
// Creator Helper for intensity images using interpolator
template<class FT, uint size = 3, uint step = 2, class Mean = FastMean<FT, uchar>>
struct GchImgMean {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 2;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &img = data[0];
LineSegment<FT> l = line;
l.translateOrtho(beg);
stepDir *= step;
FT norm = static_cast<FT>(1.0 / numBands), variance, mean;
for (int i = 0; i != numBands; ++i) {
mean = Mean::process(variance, img, l, lstep);
// compute mean
dst[0] = mean * norm;
// compute variance
dst[numBands] = std::sqrt(variance * norm);
++dst;
// next row
l.translateOrtho(stepDir);
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("img"));
return ret;
}
};
// Creator Helper for intensity images using iterator
template<class FT, uint size = 3, uint step = 2, class MT = uchar>
struct GchImgIterate {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 2;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &img = data[0];
LineSegment<FT> l = line;
l.translateOrtho(beg);
cv::Point_<FT> ps, pe;
FT sum, sum2, val;
for (int i = 0; i != numBands; ++i) {
sum = 0;
sum2 = 0;
ps = l.startPoint();
pe = l.endPoint();
cv::LineIterator it(img, cv::Point(static_cast<int>(std::round(ps.x)),static_cast<int>(std::round(ps.y))),
cv::Point(static_cast<int>(std::round(pe.x)),static_cast<int>(std::round(pe.y))));
for (int j = 0; j < it.count; ++j, ++it) {
// access value in mat
val = img.at<MT>(it.pos());
sum += val;
sum2 += val*val;
}
// next row
l.translateOrtho(step * stepDir);
// compute mean
dst[0] = val = sum / (it.count * numBands);
// compute variance
dst[numBands] = std::sqrt(sum2 / (it.count * numBands) - val*val);
++dst;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("img"));
return ret;
}
};
// Creator Helper for gradient using interpolator
template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class Interpolator = FastRoundNearestInterpolator<FT, short>>
struct GchGradInterpolate {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 8;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &dx = data[0];
const cv::Mat &dy = data[1];
// get line length (floor)
uint length = static_cast<uint>(line.length());
if (length < 1)
length = 1;
// get current line direction
cv::Point_<FT> dL = line.direction();
cv::Point_<FT> dN(-dL.y,dL.x);
dN *= step * stepDir;
dL *= lstep;
// coordinates
cv::Point_<FT> sCor0, sCor, val;
FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, tmp;
// convert upper left pos in line coords to local coords (rotate + translate)
sCor0 = line.line2world(cv::Point_<FT>(-((static_cast<FT>(length) - 1) / 2), static_cast<FT>(beg)), line.centerPoint());
int lineSteps = static_cast<int>(length / lstep);
FT norm = static_cast<FT>(1.0 / (lineSteps * numBands));
for (int i = 0; i != numBands; ++i) {
sCor = sCor0;
sumXP = sumXN = sumYP = sumYN = 0;
sum2XP = sum2XN = sum2YP = sum2YN = 0;
for (int j = 0; j < lineSteps; ++j) {
// access value in grad and do alignment
Align::apply(line,cv::Point_<FT>(Interpolator::get(dx, sCor), Interpolator::get(dy, sCor)),val);
if (val.x < 0) {
sumXN -= val.x;
sum2XN += val.x*val.x;
} else {
sumXP += val.x;
sum2XP += val.x*val.x;
}
if (val.y < 0) {
sumYN -= val.y;
sum2YN += val.y*val.y;
} else {
sumYP += val.y;
sum2YP += val.y*val.y;
}
// next pixel in line dir
sCor += dL;
}
// next row
sCor0 += dN;
// compute mean and compute variance
dst[0] = tmp = sumXP * norm;
dst[4] = std::sqrt(sum2XP * norm - tmp*tmp);
dst[1] = tmp = sumXN * norm;
dst[5] = std::sqrt(sum2XN * norm - tmp*tmp);
dst[2] = tmp = sumYP * norm;
dst[6] = std::sqrt(sum2YP * norm - tmp*tmp);
dst[3] = tmp = sumYN * norm;
dst[7] = std::sqrt(sum2YN * norm - tmp*tmp);
dst += 8;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("gx"));
ret.push_back(std::string("gy"));
return ret;
}
};
// Creator Helper for intensity images using interator
template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class Mean = FastMean<FT, short>>
struct GchGradMean {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 8;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &dx = data[0];
const cv::Mat &dy = data[1];
LineSegment<FT> l = line;
l.translateOrtho(beg);
stepDir *= step;
cv::Point_<FT> p;
FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, tmp, norm;
std::vector<FT> valX, valY;
size_t n;
for (int i = 0; i != numBands; ++i) {
sumXP = sumXN = sumYP = sumYN = 0;
sum2XP = sum2XN = sum2YP = sum2YN = 0;
Mean::process(valX,dx,l,lstep);
Mean::process(valY,dy,l,lstep);
n = valX.size();
for (int j = 0; j < n; ++j) {
// access value in grad and do alignment
Align::apply(l,cv::Point_<FT>(valX[j],valY[j]),p);
if (p.x < 0) {
sumXN -= p.x;
sum2XN += p.x*p.x;
} else {
sumXP += p.x;
sum2XP += p.x*p.x;
}
if (p.y < 0) {
sumYN -= p.y;
sum2YN += p.y*p.y;
} else {
sumYP += p.y;
sum2YP += p.y*p.y;
}
}
// next row
l.translateOrtho(stepDir);
norm = static_cast<FT>(1) / (n * numBands);
// compute mean and compute variance
dst[0] = tmp = sumXP * norm;
dst[4] = std::sqrt(sum2XP * norm - tmp*tmp);
dst[1] = tmp = sumXN * norm;
dst[5] = std::sqrt(sum2XN * norm - tmp*tmp);
dst[2] = tmp = sumYP * norm;
dst[6] = std::sqrt(sum2YP * norm - tmp*tmp);
dst[3] = tmp = sumYN * norm;
dst[7] = std::sqrt(sum2YN * norm - tmp*tmp);
dst += 8;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("gx"));
ret.push_back(std::string("gy"));
return ret;
}
};
// Creator Helper for intensity images using interator
template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class MT = short>
struct GchGradIterate {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 8;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &dx = data[0];
const cv::Mat &dy = data[1];
LineSegment<FT> l = line;
l.translateOrtho(beg);
cv::Point_<FT> ps, pe;
FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, tmp;
for (int i = 0; i != numBands; ++i) {
sumXP = sumXN = sumYP = sumYN = 0;
sum2XP = sum2XN = sum2YP = sum2YN = 0;
ps = l.startPoint();
pe = l.endPoint();
cv::LineIterator it(dx, cv::Point(static_cast<int>(std::round(ps.x)),static_cast<int>(std::round(ps.y))),
cv::Point(static_cast<int>(std::round(pe.x)),static_cast<int>(std::round(pe.y))));
for (int j = 0; j < it.count; ++j, ++it) {
// access value in grad and do alignment
Align::apply(l,cv::Point_<FT>(dx.at<MT>(it.pos()),dy.at<MT>(it.pos())),ps);
if (ps.x < 0) {
sumXN -= ps.x;
sum2XN += ps.x*ps.x;
} else {
sumXP += ps.x;
sum2XP += ps.x*ps.x;
}
if (ps.y < 0) {
sumYN -= ps.y;
sum2YN += ps.y*ps.y;
} else {
sumYP += ps.y;
sum2YP += ps.y*ps.y;
}
}
// next row
l.translateOrtho(step * stepDir);
// compute mean and compute variance
dst[0] = tmp = sumXP / (it.count * numBands);
dst[4] = std::sqrt(sum2XP/(it.count * numBands) - tmp*tmp);
dst[1] = tmp = sumXN / (it.count * numBands);
dst[5] = std::sqrt(sum2XN/(it.count * numBands) - tmp*tmp);
dst[2] = tmp = sumYP / (it.count * numBands);
dst[6] = std::sqrt(sum2YP/(it.count * numBands) - tmp*tmp);
dst[3] = tmp = sumYN / (it.count * numBands);
dst[7] = std::sqrt(sum2YN/(it.count * numBands) - tmp*tmp);
dst += 8;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("gx"));
ret.push_back(std::string("gy"));
return ret;
}
};
// Creator Helper for gradient and image using interpolator
template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class InterpolatorG = FastRoundNearestInterpolator<FT, short>, class InterpolatorI = FastRoundNearestInterpolator<FT, uchar>>
struct GchGradImgInterpolate {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 10;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &dx = data[0];
const cv::Mat &dy = data[1];
const cv::Mat &img = data[2];
// get line length (floor)
uint length = static_cast<uint>(line.length());
if (length < 1)
length = 1;
// get current line direction
Vec2<FT> dL = line.direction();
Vec2<FT> dN(-dL.y(),dL.x());
dN *= step * stepDir;
dL *= lstep;
// coordinates
Vec2<FT> sCor0, sCor, val;
FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, sum, sum2, tmp;
// convert upper left pos in line coords to local coords (rotate + translate)
sCor0 = line.line2world(Vec2<FT>(-((static_cast<FT>(length) - 1) / 2), static_cast<FT>(beg)), line.centerPoint());
int lineSteps = static_cast<int>(length / lstep);
FT norm = static_cast<FT>(1.0 / (lineSteps * numBands));
for (int i = 0; i != numBands; ++i) {
sCor = sCor0;
sumXP = sumXN = sumYP = sumYN = sum = 0;
sum2XP = sum2XN = sum2YP = sum2YN = sum2 = 0;
for (int j = 0; j < lineSteps; ++j) {
// access value in grad and do alignment
Align::apply(line,Vec2<FT>(InterpolatorG::get(dx, sCor), InterpolatorG::get(dy, sCor)),val);
if (val.x() < 0) {
sumXN -= val.x();
sum2XN += val.x()*val.x();
} else {
sumXP += val.x();
sum2XP += val.x()*val.x();
}
if (val.y() < 0) {
sumYN -= val.y();
sum2YN += val.y()*val.y();
} else {
sumYP += val.y();
sum2YP += val.y()*val.y();
}
tmp = InterpolatorI::get(img, sCor);
sum += tmp;
sum2 += tmp * tmp;
// next pixel in line dir
sCor += dL;
}
// next row
sCor0 += dN;
// compute mean and compute variance of grad
dst[0] = tmp = sumXP * norm;
dst[5] = std::sqrt(sum2XP * norm - tmp*tmp);
dst[1] = tmp = sumXN * norm;
dst[6] = std::sqrt(sum2XN * norm - tmp*tmp);
dst[2] = tmp = sumYP * norm;
dst[7] = std::sqrt(sum2YP * norm - tmp*tmp);
dst[3] = tmp = sumYN * norm;
dst[8] = std::sqrt(sum2YN * norm - tmp*tmp);
// compute mean and compute variance of img
tmp = sum * norm;
dst[4] = tmp * 2;
dst[9] = std::sqrt(sum2 * norm - tmp*tmp) * 2;
dst += 10;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("gx"));
ret.push_back(std::string("gy"));
ret.push_back(std::string("img"));
return ret;
}
};
// Creator Helper for intensity images using interator
template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class MeanG = FastMean<FT, short>, class MeanI = FastMean<FT, uchar>>
struct GchGradImgMean {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 8;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &dx = data[0];
const cv::Mat &dy = data[1];
const cv::Mat &img = data[2];
LineSegment<FT> l = line;
l.translateOrtho(beg);
stepDir *= step;
cv::Point_<FT> p;
FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, sum, sum2, tmp, norm;
std::vector<FT> valX, valY, valI;
size_t n;
for (int i = 0; i != numBands; ++i) {
sumXP = sumXN = sumYP = sumYN = sum = 0;
sum2XP = sum2XN = sum2YP = sum2YN = sum2 = 0;
MeanG::process(valX,dx,l,lstep);
MeanG::process(valY,dy,l,lstep);
MeanI::process(valI,img,l,lstep);
n = valX.size();
for (int j = 0; j < n; ++j) {
// access value in grad and do alignment
Align::apply(l,cv::Point_<FT>(valX[j],valY[j]),p);
if (p.x < 0) {
sumXN -= p.x;
sum2XN += p.x*p.x;
} else {
sumXP += p.x;
sum2XP += p.x*p.x;
}
if (p.y < 0) {
sumYN -= p.y;
sum2YN += p.y*p.y;
} else {
sumYP += p.y;
sum2YP += p.y*p.y;
}
tmp = valI[j];
sum += tmp;
sum2 += tmp * tmp;
}
// next row
l.translateOrtho(stepDir);
norm = static_cast<FT>(1) / (n * numBands);
// compute mean and compute variance
dst[0] = tmp = sumXP * norm;
dst[5] = std::sqrt(sum2XP * norm - tmp*tmp);
dst[1] = tmp = sumXN * norm;
dst[6] = std::sqrt(sum2XN * norm - tmp*tmp);
dst[2] = tmp = sumYP * norm;
dst[7] = std::sqrt(sum2YP * norm - tmp*tmp);
dst[3] = tmp = sumYN * norm;
dst[9] = std::sqrt(sum2YN * norm - tmp*tmp);
// compute mean and compute variance of img
tmp = sum * norm;
dst[4] = tmp * 2;
dst[9] = std::sqrt(sum2 * norm - tmp*tmp) * 2;
dst += 10;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("gx"));
ret.push_back(std::string("gy"));
ret.push_back(std::string("img"));
return ret;
}
};
// Creator Helper for intensity images using interator
template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class MTG = short, class MTI = uchar>
struct GchGradImgIterate {
static constexpr int numBands = size / step + (size % step ? 1 : 0);
static constexpr int dscSize = numBands * 10;
static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) {
const cv::Mat &dx = data[0];
const cv::Mat &dy = data[1];
const cv::Mat &img = data[2];
LineSegment<FT> l = line;
l.translateOrtho(beg);
cv::Point_<FT> ps, pe;
FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, sum, sum2, tmp;
for (int i = 0; i != numBands; ++i) {
sumXP = sumXN = sumYP = sumYN = sum = 0;
sum2XP = sum2XN = sum2YP = sum2YN = sum2 = 0;
ps = l.startPoint();
pe = l.endPoint();
cv::LineIterator it(dx, cv::Point(static_cast<int>(std::round(ps.x)),static_cast<int>(std::round(ps.y))),
cv::Point(static_cast<int>(std::round(pe.x)),static_cast<int>(std::round(pe.y))));
for (int j = 0; j < it.count; ++j, ++it) {
// access value in grad and do alignment
Align::apply(l,cv::Point_<FT>(dx.at<MTG>(it.pos()),dy.at<MTG>(it.pos())),ps);
if (ps.x < 0) {
sumXN -= ps.x;
sum2XN += ps.x*ps.x;
} else {
sumXP += ps.x;
sum2XP += ps.x*ps.x;
}
if (ps.y < 0) {
sumYN -= ps.y;
sum2YN += ps.y*ps.y;
} else {
sumYP += ps.y;
sum2YP += ps.y*ps.y;
}
tmp = img.at<MTI>(it.pos());
sum += tmp;
sum2 += tmp * tmp;
}
// next row
l.translateOrtho(step * stepDir);
// compute mean and compute variance of grad
dst[0] = tmp = sumXP / (it.count * numBands);
dst[5] = std::sqrt(sum2XP/(it.count * numBands) - tmp*tmp);
dst[1] = tmp = sumXN / (it.count * numBands);
dst[6] = std::sqrt(sum2XN/(it.count * numBands) - tmp*tmp);
dst[2] = tmp = sumYP / (it.count * numBands);
dst[7] = std::sqrt(sum2YP/(it.count * numBands) - tmp*tmp);
dst[3] = tmp = sumYN / (it.count * numBands);
dst[8] = std::sqrt(sum2YN/(it.count * numBands) - tmp*tmp);
// compute mean and compute variance of img
tmp = sum / (it.count * numBands);
dst[4] = tmp * 2;
dst[9] = std::sqrt(sum2/(it.count * numBands) - tmp*tmp) * 2;
dst += 10;
}
}
static std::vector<std::string> inputData() {
std::vector<std::string> ret;
ret.push_back(std::string("gx"));
ret.push_back(std::string("gy"));
ret.push_back(std::string("img"));
return ret;
}
};
// Generic Feature Descriptor creator for gradient
template<class FT, class GT = LineSegment<FT>, class Helper = GchImgInterpolate<FT>>
class FdcGeneric : public Fdc<FT, GT, GenericDescritpor<FT,Helper::dscSize>> {
public:
typedef typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr FdcPtr;
typedef typename FdcObj <FT, GT, GenericDescritpor<FT,Helper::dscSize>>::Ptr CustomFdcPtr;
typedef typename FdcMat < FT, GT>::Ptr SimpleFdcPtr;
typedef GenericDescritpor<FT,Helper::dscSize> descriptor_type;
FdcGeneric(const MatMap& data, FT pos = -1, FT stepDir = 1, FT lstep = 1)
: pos_(pos), stepDir_(stepDir), lstep_(lstep) {
data_.resize(Helper::inputData().size());
this->setData(data);
}
static FdcPtr createFdc(const MatMap& data, FT pos = -1, FT stepDir = 1, FT lstep = 1) {
return FdcPtr(new FdcGeneric<FT, GT, Helper>(data, pos, stepDir, lstep));
}
using FdcMatI<FT, GT>::create;
using FdcObjI<FT, GT, GenericDescritpor<FT,Helper::dscSize>>::create;
//! create single descriptor from single geometric object
virtual void create(const GT& input, descriptor_type& dst) {
Helper::create(data_.data(), input, dst.data, pos_, stepDir_, lstep_);
}
//! create single simple descriptor from geometric object
virtual void create(const GT& input, cv::Mat& dst) {
if (dst.empty() || dst.cols != descriptor_type::size())
dst.create(1, descriptor_type::size(), cv::DataType<FT>::type);
Helper::create(data_.data(), input, dst.template ptr<FT>(), pos_, stepDir_, lstep_);
}
//! get size of single descriptor (cols in cv::Mat)
virtual size_t size() const {
return static_cast<size_t>(descriptor_type::size());
}
//! allow to set internal processing data after init
virtual void setData(const MatMap& data) {
MatMap::const_iterator f;
auto input = Helper::inputData();
for (size_t i = 0; i != input.size(); ++i) {
f = data.find(input[i]);
if (f != data.end())
data_[i] = f->second;
}
}
// input
std::vector<cv::Mat> data_;
FT pos_, stepDir_, lstep_;
protected:
virtual void create(const GT& input, FT* dst) {
Helper::create(data_.data(), input, dst, pos_, stepDir_, lstep_);
}
};
template<class FT, class GT = LineSegment<FT>, class Helper = GchImgInterpolate<FT>>
typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr createGenericFdc(const cv::Mat& img, FT pos = -1, FT stepDir = 1, FT lstep = 1) {
MatMap tmp;
tmp["img"] = img;
return typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr(new FdcGeneric<FT, GT, Helper>(tmp, pos, stepDir, lstep));
}
template<class FT, class GT = LineSegment<FT>, class Helper = GchGradInterpolate<FT>>
typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr createGenericFdc(const cv::Mat& gx, const cv::Mat& gy, FT pos = -1, FT stepDir = 1, FT lstep = 1) {
MatMap tmp;
tmp["gx"] = gx;
tmp["gy"] = gy;
return typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr(new FdcGeneric<FT, GT, Helper>(tmp, pos, stepDir, lstep));
}
template<class FT, class GT = LineSegment<FT>, class Helper = GchGradImgInterpolate<FT>>
typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr createGenericFdc(const cv::Mat& gx, const cv::Mat& gy, const cv::Mat& img, FT pos = -1, FT stepDir = 1, FT lstep = 1) {
MatMap tmp;
tmp["gx"] = gx;
tmp["gy"] = gy;
tmp["img"] = img;
return typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr(new FdcGeneric<FT, GT, Helper>(tmp, pos, stepDir, lstep));
}
}
#endif
#endif
| 40.742092 | 212 | 0.478173 | waterben |
eaa157c6d083c996a9d2b3fc57a64871f43db283 | 15,614 | cpp | C++ | projects/atLib/source/IO/Mesh/atFBXReader.cpp | mbatc/atLib | 7e3a69515f504a05a312d234291f02863e291631 | [
"MIT"
] | 1 | 2019-09-17T18:02:16.000Z | 2019-09-17T18:02:16.000Z | projects/atLib/source/IO/Mesh/atFBXReader.cpp | mbatc/atLib | 7e3a69515f504a05a312d234291f02863e291631 | [
"MIT"
] | null | null | null | projects/atLib/source/IO/Mesh/atFBXReader.cpp | mbatc/atLib | 7e3a69515f504a05a312d234291f02863e291631 | [
"MIT"
] | null | null | null | #include "atFBXParser.h"
#include "atFBXCommon.h"
#include "atHashMap.h"
struct _atFbxParseContext
{
atMesh *pMesh;
// Node ptr to bone index
atHashMap<int64_t, int64_t> boneLookup;
int64_t poseID = -1; // ID of the active pos
};
FbxAMatrix _GetGeometry(FbxNode *pNode)
{
FbxDouble3 pivotTrans = pNode->GetGeometricTranslation(FbxNode::eSourcePivot);
FbxDouble3 pivotRot = pNode->GetGeometricRotation(FbxNode::eSourcePivot);
FbxDouble3 pivotScl = pNode->GetGeometricScaling(FbxNode::eSourcePivot);
return FbxAMatrix(pivotTrans, pivotRot, pivotScl);
}
template<typename T> int64_t _GetMappedIndex(T *pElementArray, const int64_t &controlPoint, const int64_t &polyVert, const int64_t &polyIdx)
{
if (!pElementArray)
return -1;
// Get the base index
int64_t indirectIdx = -1;
switch (pElementArray->GetMappingMode())
{
case FbxGeometryElement::eByPolygonVertex: indirectIdx = polyVert; break;
case FbxGeometryElement::eByControlPoint: indirectIdx = controlPoint; break;
case FbxGeometryElement::eByPolygon: indirectIdx = polyIdx; break;
}
int64_t directIdx = indirectIdx;
// Convert indirect index to a direct index
if (pElementArray->GetReferenceMode() != FbxGeometryElement::eDirect)
directIdx = pElementArray->GetIndexArray().GetAt((int)indirectIdx);
return directIdx;
}
template<typename Vec, typename T> Vec _ExtractElements(T *pElementArray, const int64_t &controlPoint, const int64_t &polyVert, const int64_t &polyIdx)
{
typedef decltype(pElementArray->GetDirectArray().GetAt(0)) FbxElement; // Fbx element array item type
int64_t directIdx = _GetMappedIndex(pElementArray, controlPoint, polyVert, polyIdx);
// Get the item from the element array
FbxElement item = pElementArray->GetDirectArray().GetAt((int)directIdx);
Vec ret = { 0 };
for (int64_t i = 0; i < Vec::ElementCount; ++i)
ret[i] = item[(int)i];
return ret;
}
static void _LoadTextures(const char *name, FbxSurfaceMaterial *pMaterial, atVector<atFilename> *pTextures)
{
FbxProperty prop = pMaterial->FindProperty(name);
for (int64_t i = 0; i < prop.GetSrcObjectCount<FbxTexture>(); ++i)
{
FbxFileTexture *pTex = prop.GetSrcObject<FbxFileTexture>((int)i);
if (pTex)
pTextures->push_back(pTex->GetFileName());
}
}
static atVec4D _GetColour(const FbxPropertyT<FbxDouble3> &colour, const double &factor)
{
FbxDouble3 val = colour.Get();
return atVec4D(val[0], val[1], val[2], factor);
}
static atVec4D _GetColour(const FbxPropertyT<FbxDouble3> &colour, const FbxPropertyT<FbxDouble> &factor)
{
return _GetColour(colour, factor.Get());
}
static atMaterial _LoadMaterial(FbxSurfaceMaterial *pMaterial)
{
atMaterial mat;
mat.m_name = pMaterial->GetName();
bool isPhong = pMaterial->GetClassId() == FbxSurfacePhong::ClassId;
bool isLambert = isPhong || pMaterial->GetClassId() == FbxSurfaceLambert::ClassId;
if (isLambert)
{
FbxSurfaceLambert *pLambert = (FbxSurfaceLambert*)pMaterial;
mat.m_cDiffuse = _GetColour(pLambert->Diffuse, pLambert->DiffuseFactor);
mat.m_cAmbient = _GetColour(pLambert->Ambient, pLambert->AmbientFactor);
mat.m_alpha = pLambert->TransparencyFactor.Get();
_LoadTextures(FbxSurfaceMaterial::sDiffuse, pMaterial, &mat.m_tDiffuse);
_LoadTextures(FbxSurfaceMaterial::sAmbientFactor, pMaterial, &mat.m_tAmbient);
_LoadTextures(FbxSurfaceMaterial::sTransparencyFactor, pMaterial, &mat.m_tAlpha);
_LoadTextures(FbxSurfaceMaterial::sDisplacementFactor, pMaterial, &mat.m_tDisplacement);
}
if (isPhong)
{
FbxSurfacePhong *pPhong = (FbxSurfacePhong*)pMaterial;
mat.m_cSpecular = _GetColour(pPhong->Specular, pPhong->SpecularFactor);
mat.m_specularPower = pPhong->SpecularFactor;
_LoadTextures(FbxSurfaceMaterial::sSpecular, pMaterial, &mat.m_tSpecular);
}
return mat;
}
static bool _ParseDeformer(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh, FbxSkin *pSkin)
{
if (!pSkin)
return false;
FbxAMatrix geom = _GetGeometry(pNode);
for (int64_t clusterIndex = 0; clusterIndex < (int64_t)pSkin->GetClusterCount(); ++clusterIndex)
{
FbxCluster *pCluster = pSkin->GetCluster((int)clusterIndex);
int64_t *pBoneID = pCtx->boneLookup.TryGet((int64_t)pCluster->GetLink());
if (!pBoneID)
continue;
if (pCtx->poseID == -1)
{
pCtx->poseID = pCtx->pMesh->m_skeleton.GetPoseCount();
pCtx->pMesh->m_skeleton.AddPose(false);
}
atPose &pose = pCtx->pMesh->m_skeleton.GetPose(pCtx->poseID);
atMesh::VertexDeformer deformer;
FbxAMatrix clusterTransform;
FbxAMatrix bonePoseTransform;
FbxAMatrix associateMatrix;
pCluster->GetTransformAssociateModelMatrix(associateMatrix);
pCluster->GetTransformLinkMatrix(bonePoseTransform);
pCluster->GetTransformMatrix(clusterTransform);
// Set the cluster transform
atAssign(deformer.transform, clusterTransform * geom);
deformer.inverseTransform = deformer.transform.Inverse();
// Set the bone bind position
pose.SetTransform(*pBoneID, atAssign<atMat4D>(bonePoseTransform));
deformer.boneID = *pBoneID;
int *pIndices = pCluster->GetControlPointIndices();
double *pWeights = pCluster->GetControlPointWeights();
for (int64_t vert = 0; vert < (int64_t)pCluster->GetControlPointIndicesCount(); ++vert)
{
deformer.vertices.push_back(pIndices[vert]);
deformer.weights.push_back(pWeights[vert]);
}
pCtx->pMesh->m_deformationGroups.push_back(deformer);
}
return true;
}
static bool _ParseDeformer(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh, FbxVertexCacheDeformer *pCache)
{
if (!pCache)
return false;
atUnused(pCtx, pNode, pFbxMesh, pCache);
return false;
}
static bool _ParseDeformer(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh, FbxBlendShape *pBlend)
{
if (!pBlend)
return false;
atUnused(pCtx, pNode, pFbxMesh, pBlend);
return false;
}
static void _ParseMesh(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh)
{
atMesh mesh;
// Copy control points
mesh.m_positions.reserve(pFbxMesh->GetControlPointsCount());
for (const FbxVector4 &pos : atIterate(pFbxMesh->GetControlPoints(), pFbxMesh->GetControlPointsCount()))
mesh.m_positions.push_back(atVec3D(pos[0], pos[1], pos[2]));
// Get geometry element arrays
FbxGeometryElementNormal *pNormals = pFbxMesh->GetElementNormal();
FbxGeometryElementUV *pUVs = pFbxMesh->GetElementUV();
FbxGeometryElementVertexColor *pVertexColor = pFbxMesh->GetElementVertexColor();
FbxGeometryElementMaterial *pMaterials = pFbxMesh->GetElementMaterial();
// Extract geometry elements
int64_t polyVertIndex = 0;
int64_t polyCount = pFbxMesh->GetPolygonCount();
atVector<int64_t> materialLookup;
mesh.m_materials.reserve(pNode->GetMaterialCount());
materialLookup.resize(pNode->GetMaterialCount(), -1);
int64_t defaultMaterial = -1;
for (int64_t polygonIdx = 0; polygonIdx < polyCount; ++polygonIdx)
{
atMesh::Triangle tri;
int64_t materialID = _GetMappedIndex(pMaterials, pFbxMesh->GetPolygonVertex((int)polygonIdx, 0), polyVertIndex, polygonIdx);
if (materialID != -1)
{
int64_t &index = materialLookup[materialID];
if (index == -1)
{ // Material has not been loaded yet
index = mesh.m_materials.size();
mesh.m_materials.push_back(_LoadMaterial(pNode->GetMaterial((int)materialID)));
}
tri.mat = index;
}
else
{
if (defaultMaterial == -1)
{
defaultMaterial = mesh.m_materials.size();
mesh.m_materials.emplace_back();
}
tri.mat = defaultMaterial;
}
int64_t vertCount = pFbxMesh->GetPolygonSize((int)polygonIdx);
for (int64_t vertIdx = 0; vertIdx < vertCount; ++vertIdx)
{
int64_t controlPointIdx = pFbxMesh->GetPolygonVertex((int)polygonIdx, (int)vertIdx);
tri.verts[vertIdx].position = controlPointIdx;
if (pNormals)
{
tri.verts[vertIdx].normal = mesh.m_normals.size();
mesh.m_normals.push_back(_ExtractElements<atVec3D>(pNormals, controlPointIdx, polyVertIndex, polygonIdx));
}
if (pUVs)
{
tri.verts[vertIdx].texCoord = mesh.m_texCoords.size();
mesh.m_texCoords.push_back(_ExtractElements<atVec2D>(pUVs, controlPointIdx, polyVertIndex, polygonIdx));
}
if (pVertexColor)
{
tri.verts[vertIdx].color = mesh.m_colors.size();
mesh.m_colors.push_back(_ExtractElements<atVec4D>(pVertexColor, controlPointIdx, polyVertIndex, polygonIdx));
}
++polyVertIndex;
}
mesh.m_triangles.push_back(tri);
}
for (int64_t i = 0; i < (int64_t)pFbxMesh->GetDeformerCount(); ++i)
{
if (!_ParseDeformer(pCtx, pNode, pFbxMesh, (FbxSkin*)pFbxMesh->GetDeformer((int)i, FbxDeformer::eSkin)))
if (!_ParseDeformer(pCtx, pNode, pFbxMesh, (FbxVertexCacheDeformer*)pFbxMesh->GetDeformer((int)i, FbxDeformer::eVertexCache)))
if (!_ParseDeformer(pCtx, pNode, pFbxMesh, (FbxBlendShape*)pFbxMesh->GetDeformer((int)i, FbxDeformer::eBlendShape)))
continue;
}
FbxAMatrix pivot = _GetGeometry(pNode);
mesh.SpatialTransform(atAssign<atMat4D>(pNode->EvaluateGlobalTransform() * pivot));
atAssign(pCtx->pMesh->m_skeleton.Get(atHierarchy_RootNodeID).localTransform, pivot);
pCtx->pMesh->Combine(mesh);
}
static void _ParseSkeleton(_atFbxParseContext *pCtx, FbxNode *pNode, FbxSkeleton *pFbxSkeleton)
{
int64_t *pParentBone = pCtx->boneLookup.TryGet((int64_t)pNode->GetParent());
atBone bone;
bone.name = pNode->GetName();
bool isRoot = pFbxSkeleton->IsSkeletonRoot();
FbxAMatrix localTransform = pNode->EvaluateLocalTransform();
FbxAMatrix globalTransform = pNode->EvaluateGlobalTransform();
atAssign(bone.localTransform, localTransform);
atAssign(bone.globalTransform, globalTransform);
bone.modified = true;
int64_t boneID = pCtx->pMesh->m_skeleton.Add(bone, pParentBone ? *pParentBone : atHierarchy_RootNodeID);
pCtx->boneLookup.Add((int64_t)pNode, boneID);
}
static void _ParsePatch(_atFbxParseContext *pCtx, FbxNode *pNode, FbxPatch *pFbxPatch)
{
}
static void _ParseShape(_atFbxParseContext *pCtx, FbxNode *pNode, FbxShape *pFbxShape)
{
}
static void _ParseNurbs(_atFbxParseContext *pCtx, FbxNode *pNode, FbxNurbs *pFbxNurbs)
{
}
static void _ParseNode(_atFbxParseContext *pCtx, FbxNode *pNode, const FbxNodeAttribute::EType &type = FbxNodeAttribute::eUnknown)
{
for (int64_t i = 0; i < (int64_t)pNode->GetNodeAttributeCount(); ++i)
{
FbxNodeAttribute *pAttribute = pNode->GetNodeAttributeByIndex((int)i);
FbxNodeAttribute::EType attrType = pAttribute->GetAttributeType();
if (type != FbxNodeAttribute::eUnknown && attrType != type)
continue;
switch (pAttribute->GetAttributeType())
{
case FbxNodeAttribute::eMesh: _ParseMesh(pCtx, pNode, (FbxMesh*)pAttribute); break;
case FbxNodeAttribute::eNurbs: _ParseNurbs(pCtx, pNode, (FbxNurbs*)pAttribute); break;
case FbxNodeAttribute::ePatch: _ParsePatch(pCtx, pNode, (FbxPatch*)pAttribute); break;
case FbxNodeAttribute::eShape: _ParseShape(pCtx, pNode, (FbxShape*)pAttribute); break;
case FbxNodeAttribute::eSkeleton: _ParseSkeleton(pCtx, pNode, (FbxSkeleton*)pAttribute); break;
default: break;
}
}
for (int64_t i = 0; i < (int64_t)pNode->GetChildCount(); ++i)
_ParseNode(pCtx, pNode->GetChild((int)i), type);
}
static atAnimationCurve _ConvertCurve(FbxAnimCurve *pFbxCurve, const double &factor = 1)
{
if (!pFbxCurve)
return atAnimationCurve();
atAnimationCurve converted;
int keyCount = pFbxCurve->KeyGetCount();
for (int i = 0; i < keyCount; ++i)
{
FbxAnimCurveKey fbxKey = pFbxCurve->KeyGet(i);
atAnimationKey key;
key.SetValue(fbxKey.GetValue() * factor);
switch (fbxKey.GetInterpolation())
{
case FbxAnimCurveDef::eInterpolationConstant: key.SetInterpolation(atAnimationKey::Constant); break;
case FbxAnimCurveDef::eInterpolationLinear: key.SetInterpolation(atAnimationKey::Linear); break;
case FbxAnimCurveDef::eInterpolationCubic: key.SetInterpolation(atAnimationKey::Cubic); break;
}
converted.SetKey(atMilliSeconds(fbxKey.GetTime().GetMilliSeconds()), key);
}
return converted;
}
static void _ExtractCurveXYZ(FbxProperty *pProp, FbxAnimLayer *pLayer, atAnimationCurve *pCurveX = nullptr, atAnimationCurve *pCurveY = nullptr, atAnimationCurve *pCurveZ = nullptr, const double &factor = 1)
{
if (pCurveX) *pCurveX = _ConvertCurve(pProp->GetCurve(pLayer, FBXSDK_CURVENODE_COMPONENT_X), factor);
if (pCurveY) *pCurveY = _ConvertCurve(pProp->GetCurve(pLayer, FBXSDK_CURVENODE_COMPONENT_Y), factor);
if (pCurveZ) *pCurveZ = _ConvertCurve(pProp->GetCurve(pLayer, FBXSDK_CURVENODE_COMPONENT_Z), factor);
}
static void _ParseAnimations(_atFbxParseContext *pCtx, FbxScene *pScene)
{
int numStacks = pScene->GetSrcObjectCount<FbxAnimStack>();
for (int stackIdx = 0; stackIdx < numStacks; ++stackIdx)
{
FbxAnimStack *pStack = pScene->GetSrcObject<FbxAnimStack>(stackIdx);
int numLayers = pStack->GetMemberCount<FbxAnimLayer>();
atMesh::AnimTake take;
take.anim.SetName(pStack->GetName());
take.startTime = atMilliSeconds(pStack->GetLocalTimeSpan().GetStart().GetMilliSeconds());
take.endTime = atMilliSeconds(pStack->GetLocalTimeSpan().GetStop().GetMilliSeconds());
int64_t animGroupID = pCtx->pMesh->m_takes.size();
for (int layerIdx = 0; layerIdx < numLayers; ++layerIdx)
{
// For each layer extract the animations for the bones
FbxAnimLayer *pLayer = pStack->GetMember<FbxAnimLayer>(layerIdx);
for (const atKeyValue<int64_t, int64_t> &kvp : pCtx->boneLookup)
{
int64_t animID = take.anim.AddAnimation();
atAnimation *pAnimation = take.anim.GetAnimation(animID);
FbxNode *pFbxBone = (FbxNode*)kvp.m_key;
_ExtractCurveXYZ(&pFbxBone->LclTranslation, pLayer,
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_TranslationX),
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_TranslationY),
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_TranslationZ));
_ExtractCurveXYZ(&pFbxBone->LclRotation, pLayer,
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_RotationX),
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_RotationY),
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_RotationZ), atPi / 180.0);
_ExtractCurveXYZ(&pFbxBone->LclScaling, pLayer,
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_ScaleX),
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_ScaleY),
pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_ScaleZ));
take.links.Add(kvp.m_val, animID);
}
}
pCtx->pMesh->m_takes.push_back(take);
}
}
bool atFBXReader::Read(const atFilename &file, atMesh *pMesh)
{
// Clear the mesh
*pMesh = atMesh();
// Load the FBXScene
atFBXCommon fbx;
FbxScene *pScene = fbx.Import(file);
// Triangulate the meshes
FbxGeometryConverter converter(fbx.GetManager());
converter.Triangulate(pScene, true);
if (!pScene)
return false;
// Create a fresh FBX mesh parser context
_atFbxParseContext ctx;
ctx.pMesh = pMesh;
// Only skeletons and meshes are supported so far
_ParseNode(&ctx, pScene->GetRootNode(), FbxNodeAttribute::eSkeleton);
_ParseNode(&ctx, pScene->GetRootNode(), FbxNodeAttribute::eMesh);
// Extract animations after loading the geometry
_ParseAnimations(&ctx, pScene);
return true;
}
| 35.486364 | 207 | 0.723389 | mbatc |
eaa35451e1076cf3995c60c038e843d3042dd589 | 5,278 | inl | C++ | TwitchQt/twitchvideoreply.inl | jkbz64/TwitchQt | 9bfddd9b48eea9eb25ae5f05239c0739c0bdfb12 | [
"MIT"
] | 9 | 2019-09-16T22:28:43.000Z | 2022-03-06T22:57:56.000Z | TwitchQt/twitchvideoreply.inl | jkbz64/TwitchQt | 9bfddd9b48eea9eb25ae5f05239c0739c0bdfb12 | [
"MIT"
] | 5 | 2020-10-11T15:01:09.000Z | 2021-10-11T05:39:28.000Z | TwitchQt/twitchvideoreply.inl | jkbz64/TwitchQt | 9bfddd9b48eea9eb25ae5f05239c0739c0bdfb12 | [
"MIT"
] | 2 | 2020-10-11T14:38:24.000Z | 2020-10-11T14:45:34.000Z |
inline void VideoReply::parseData(const JSON& json)
{
if (json.find("data") != json.end()) {
const auto& data = json["data"];
if (!data.empty()) {
const auto& video = data.front();
QList<MutedSegment> mutedSegmentsList;
if (video.find("muted_segments") != video.end()) {
const auto& mutedSegments = video["muted_segments"];
for (const auto& segment : mutedSegments) {
if (segment.find("duration") == segment.end()) {
continue;
}
MutedSegment ms;
ms.duration = segment.value("duration", -1);
ms.offset = segment.value("offset", -1);
mutedSegmentsList.append(ms);
}
}
QString typeStr = video["type"];
Video::VideoType type;
if (typeStr == "upload")
type = Video::VideoType::Upload;
else if (typeStr == "archive")
type = Video::VideoType::Archive;
else if (typeStr == "highlight")
type = Video::VideoType::Highlight;
QString createdAt = video["created_at"];
QString publishedAt = video["published_at"];
m_data.setValue(Video{video.value("id", QString("-1")),
video.value("stream_id", QString("-1")),
video.value("user_id", QString("-1")),
video.value("user_login", QString("")),
video.value("user_name", QString("")),
video.value("title", QString()),
video.value("description", QString("")),
QDateTime::fromString(createdAt, Qt::ISODate),
QDateTime::fromString(publishedAt, Qt::ISODate),
video.value("url", QString("")),
video.value("thumbnail_url", QString("")),
video.value("viewable", QString("")),
video.value("view_count", -1),
video.value("language", QString("")),
type,
video.value("duration", QString("")),
mutedSegmentsList});
} else {
// ???
}
}
}
inline void VideosReply::parseData(const JSON& json)
{
Videos videos;
if (json.find("data") != json.end()) {
const auto& data = json["data"];
for (const auto& video : data) {
QList<MutedSegment> mutedSegmentsList;
if (video.find("muted_segments") != video.end()) {
const auto& mutedSegments = video["muted_segments"];
for (const auto& segment : mutedSegments) {
if (segment.find("duration") == segment.end()) {
continue;
}
MutedSegment ms;
ms.duration = segment.value("duration", -1);
ms.offset = segment.value("offset", -1);
mutedSegmentsList.append(ms);
}
}
QString typeStr = video["type"];
Video::VideoType type;
if (typeStr == "upload")
type = Video::VideoType::Upload;
else if (typeStr == "archive")
type = Video::VideoType::Archive;
else if (typeStr == "highlight")
type = Video::VideoType::Highlight;
QString createdAt = video["created_at"];
QString publishedAt = video["published_at"];
videos.push_back({video.value("id", QString("-1")),
video.value("stream_id", QString("-1")),
video.value("user_id", QString("-1")),
video.value("user_login", QString("")),
video.value("user_name", QString("")),
video.value("title", QString()),
video.value("description", QString("")),
QDateTime::fromString(createdAt, Qt::ISODate),
QDateTime::fromString(publishedAt, Qt::ISODate),
video.value("url", QString("")),
video.value("thumbnail_url", QString("")),
video.value("viewable", QString("")),
video.value("view_count", -1),
video.value("language", QString("")),
type,
video.value("duration", QString("")),
mutedSegmentsList});
}
}
m_data.setValue(videos);
}
inline int VideosReply::combinedViewerCount() const
{
return m_combinedViewerCount;
}
inline Twitch::Video Twitch::VideoReply::video()
{
return m_data.value<Twitch::Video>();
}
inline Twitch::Videos Twitch::VideosReply::videos()
{
return m_data.value<Twitch::Videos>();
}
| 41.559055 | 82 | 0.448844 | jkbz64 |
eaa463011f86ef63641021cc9893c2f867c3b735 | 140 | cpp | C++ | synthesizer/lang/macro/lowercase.cpp | SleepyToDeath/NetQRE | 0176a31afa45faa4877974a4a0575a4e60534090 | [
"MIT"
] | 2 | 2021-03-30T15:25:44.000Z | 2021-05-14T07:22:25.000Z | synthesizer/lang/macro/lowercase.cpp | SleepyToDeath/NetQRE | 0176a31afa45faa4877974a4a0575a4e60534090 | [
"MIT"
] | null | null | null | synthesizer/lang/macro/lowercase.cpp | SleepyToDeath/NetQRE | 0176a31afa45faa4877974a4a0575a4e60534090 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
for (char c='a'; c<='z'; c++)
cout<<"[ \""<<c<<"\" ], ";
cout<<"[ \"\\c\" ]";
}
| 12.727273 | 30 | 0.435714 | SleepyToDeath |
eaa70dd8d8b82f080b7e5fdcd4f02e19749a841e | 10,254 | cpp | C++ | Framework/Util/Thread.cpp | dengwenyi88/Deferred_Lighting | b45b6590150a3119b0c2365f4795d93b3b4f0748 | [
"MIT"
] | 110 | 2017-06-23T17:12:28.000Z | 2022-02-22T19:11:38.000Z | RunTest/Framework3/Util/Thread.cpp | dtrebilco/ECSAtto | 86a04f0bdc521c79f758df94250c1898c39213c8 | [
"MIT"
] | null | null | null | RunTest/Framework3/Util/Thread.cpp | dtrebilco/ECSAtto | 86a04f0bdc521c79f758df94250c1898c39213c8 | [
"MIT"
] | 3 | 2018-02-12T00:16:18.000Z | 2018-02-18T11:12:35.000Z |
/* * * * * * * * * * * * * Author's note * * * * * * * * * * * *\
* _ _ _ _ _ _ _ _ _ _ _ _ *
* |_| |_| |_| |_| |_|_ _|_| |_| |_| _|_|_|_|_| *
* |_|_ _ _|_| |_| |_| |_|_|_|_|_| |_| |_| |_|_ _ _ *
* |_|_|_|_|_| |_| |_| |_| |_| |_| |_| |_| |_|_|_|_ *
* |_| |_| |_|_ _ _|_| |_| |_| |_|_ _ _|_| _ _ _ _|_| *
* |_| |_| |_|_|_| |_| |_| |_|_|_| |_|_|_|_| *
* *
* http://www.humus.name *
* *
* This file is a part of the work done by Humus. You are free to *
* use the code in any way you like, modified, unmodified or copied *
* into your own work. However, I expect you to respect these points: *
* - If you use this file and its contents unmodified, or use a major *
* part of this file, please credit the author and leave this note. *
* - For use in anything commercial, please request my approval. *
* - Share your work and ideas too as much as you can. *
* *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Thread.h"
#ifdef _WIN32
ThreadHandle createThread(ThreadProc startProc, void *param){
return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) startProc, param, 0, NULL);
}
void deleteThread(ThreadHandle thread){
CloseHandle(thread);
}
void waitOnThread(const ThreadHandle threadID){
WaitForSingleObject(threadID, INFINITE);
}
void waitOnAllThreads(const ThreadHandle *threads, const int nThreads){
WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE);
}
void waitOnAnyThread(const ThreadHandle *threads, const int nThreads){
WaitForMultipleObjects(nThreads, threads, FALSE, INFINITE);
}
void createMutex(Mutex &mutex){
mutex = CreateMutex(NULL, FALSE, NULL);
}
void deleteMutex(Mutex &mutex){
CloseHandle(mutex);
}
void lockMutex(Mutex &mutex){
WaitForSingleObject(mutex, INFINITE);
}
void unlockMutex(Mutex &mutex){
ReleaseMutex(mutex);
}
void createCondition(Condition &condition){
condition.waiters_count = 0;
condition.was_broadcast = false;
condition.sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
InitializeCriticalSection(&condition.waiters_count_lock);
condition.waiters_done = CreateEvent(NULL, FALSE, FALSE, NULL);
}
void deleteCondition(Condition &condition){
CloseHandle(condition.sema);
DeleteCriticalSection(&condition.waiters_count_lock);
CloseHandle(condition.waiters_done);
}
void waitCondition(Condition &condition, Mutex &mutex){
EnterCriticalSection(&condition.waiters_count_lock);
condition.waiters_count++;
LeaveCriticalSection(&condition.waiters_count_lock);
SignalObjectAndWait(mutex, condition.sema, INFINITE, FALSE);
EnterCriticalSection(&condition.waiters_count_lock);
// We're no longer waiting...
condition.waiters_count--;
// Check to see if we're the last waiter after broadcast.
bool last_waiter = condition.was_broadcast && (condition.waiters_count == 0);
LeaveCriticalSection(&condition.waiters_count_lock);
// If we're the last waiter thread during this particular broadcast then let all the other threads proceed.
if (last_waiter){
// This call atomically signals the <waiters_done> event and waits until
// it can acquire the <mutex>. This is required to ensure fairness.
SignalObjectAndWait(condition.waiters_done, mutex, INFINITE, FALSE);
} else {
// Always regain the external mutex since that's the guarantee we give to our callers.
WaitForSingleObject(mutex, INFINITE);
}
}
void signalCondition(Condition &condition){
EnterCriticalSection(&condition.waiters_count_lock);
bool have_waiters = (condition.waiters_count > 0);
LeaveCriticalSection(&condition.waiters_count_lock);
// If there aren't any waiters, then this is a no-op.
if (have_waiters){
ReleaseSemaphore(condition.sema, 1, 0);
}
}
void broadcastCondition(Condition &condition){
// This is needed to ensure that <waiters_count> and <was_broadcast> are consistent relative to each other.
EnterCriticalSection(&condition.waiters_count_lock);
bool have_waiters = false;
if (condition.waiters_count > 0){
// We are broadcasting, even if there is just one waiter...
// Record that we are broadcasting, which helps optimize
// <pthread_cond_wait> for the non-broadcast case.
condition.was_broadcast = true;
have_waiters = true;
}
if (have_waiters){
// Wake up all the waiters atomically.
ReleaseSemaphore(condition.sema, condition.waiters_count, 0);
LeaveCriticalSection(&condition.waiters_count_lock);
// Wait for all the awakened threads to acquire the counting semaphore.
WaitForSingleObject(condition.waiters_done, INFINITE);
// This assignment is okay, even without the <waiters_count_lock> held
// because no other waiter threads can wake up to access it.
condition.was_broadcast = false;
} else {
LeaveCriticalSection(&condition.waiters_count_lock);
}
}
#else
ThreadHandle createThread(ThreadProc startProc, void *param){
pthread_t th;
pthread_create(&th, NULL, (void *(*)(void *)) startProc, param);
return th;
}
void deleteThread(ThreadHandle thread){
}
void waitOnThread(const ThreadHandle threadID){
pthread_join(threadID, NULL);
}
void createMutex(Mutex &mutex){
pthread_mutex_init(&mutex, NULL);
}
void deleteMutex(Mutex &mutex){
pthread_mutex_destroy(&mutex);
}
void lockMutex(Mutex &mutex){
pthread_mutex_lock(&mutex);
}
void unlockMutex(Mutex &mutex){
pthread_mutex_unlock(&mutex);
}
void createCondition(Condition &condition){
pthread_cond_init(&condition, NULL);
}
void deleteCondition(Condition &condition){
pthread_cond_destroy(&condition);
}
void waitCondition(Condition &condition, Mutex &mutex){
pthread_cond_wait(&condition, &mutex);
}
void signalCondition(Condition &condition){
pthread_cond_signal(&condition);
}
void broadcastCondition(Condition &condition){
pthread_cond_broadcast(&condition);
}
#endif
//#include <stdio.h>
struct ThreadParam {
Thread *thread;
int threadInstance;
};
#ifdef _WIN32
DWORD WINAPI threadStarter(void *param){
// ((Thread *) startFunc)->mainFunc(0);
Thread *thread = ((ThreadParam *) param)->thread;
int instance = ((ThreadParam *) param)->threadInstance;
delete param;
thread->mainFunc(instance);
return 0;
}
void Thread::startThreads(const int threadCount){
nThreads = threadCount;
threadHandles = new HANDLE[threadCount];
threadIDs = new DWORD[threadCount];
for (int i = 0; i < threadCount; i++){
ThreadParam *param = new ThreadParam;
param->thread = this;
param->threadInstance = i;
threadHandles[i] = CreateThread(NULL, 0, threadStarter, param, 0, &threadIDs[i]);
}
}
void Thread::postMessage(const int thread, const int message, void *data, const int size){
int msg = WM_USER + message;
int start, end;
if (thread < 0){
start = 0;
end = nThreads;
} else {
start = thread;
end = start + 1;
}
for (int i = start; i < end; i++){
char *msgData = new char[size];
memcpy(msgData, data, size);
while (!PostThreadMessage(threadIDs[i], msg, size, (LPARAM) msgData)){
//printf("PostThreadMessage failed\n");
Sleep(1);
}
}
}
void Thread::mainFunc(const int thread){
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0){
processMessage(thread, msg.message - WM_USER, (void *) msg.lParam, (const int) msg.wParam);
}
}
void Thread::waitForExit(){
delete threadIDs;
// WaitForSingleObject(threadHandle, INFINITE);
WaitForMultipleObjects(nThreads, threadHandles, TRUE, INFINITE);
delete threadHandles;
}
#else
#include <string.h>
void *threadStarter(void *param){
ThreadParam *tp = (ThreadParam *) param;
Thread *thread = tp->thread;
int instance = tp->threadInstance;
delete tp;
thread->mainFunc(instance);
return NULL;
}
void Thread::startThreads(const int threadCount){
/*
first = last = NULL;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&pending, NULL);
pthread_create(&thread, NULL, threadStarter, this);
*/
nThreads = threadCount;
queues = new MessageQueue[threadCount];
threadHandles = new pthread_t[threadCount];
for (int i = 0; i < threadCount; i++){
queues[i].first = NULL;
queues[i].last = NULL;
pthread_mutex_init(&queues[i].mutex, NULL);
pthread_cond_init(&queues[i].pending, NULL);
ThreadParam *param = new ThreadParam;
param->thread = this;
param->threadInstance = i;
pthread_create(&threadHandles[i], NULL, threadStarter, param);
}
}
void Thread::postMessage(const int thread, const int message, void *data, const int size){
int start, end;
if (thread < 0){
start = 0;
end = nThreads;
} else {
start = thread;
end = start + 1;
}
for (int i = start; i < end; i++){
MessageQueue *queue = queues + i;
pthread_mutex_lock(&queue->mutex);
Message *msg = new Message;
msg->message = message;
if (data){
msg->data = new char[size];
memcpy(msg->data, data, size);
} else {
msg->data = NULL;
}
msg->size = size;
msg->next = NULL;
if (queue->first == NULL){
queue->first = queue->last = msg;
} else {
queue->last->next = msg;
queue->last = msg;
}
pthread_mutex_unlock(&queue->mutex);
pthread_cond_signal(&queue->pending);
}
}
void Thread::mainFunc(const int thread){
bool done = false;
do {
Message *msg = getMessage(thread);
if (msg->message < 0){
done = true;
} else {
processMessage(thread, msg->message, msg->data, msg->size);
}
delete msg->data;
delete msg;
} while (!done);
pthread_mutex_destroy(&queues[thread].mutex);
pthread_cond_destroy(&queues[thread].pending);
// printf("Done\n");
}
void Thread::waitForExit(){
for (int i = 0; i < nThreads; i++){
pthread_join(threadHandles[i], NULL);
}
}
Message *Thread::getMessage(const int thread){
MessageQueue *queue = queues + thread;
pthread_mutex_lock(&queue->mutex);
while (queue->first == NULL){
pthread_cond_wait(&queue->pending, &queue->mutex);
}
Message *ret = queue->first;
queue->first = queue->first->next;
if (queue->first == NULL) queue->last = NULL;
pthread_mutex_unlock(&queue->mutex);
return ret;
}
#endif // !_WIN32
| 25.444169 | 108 | 0.676712 | dengwenyi88 |
eaa7ce23241ef9d19e386ea6aaeb0caa567a66d4 | 231 | cpp | C++ | test/llvm_test_code/call_graphs/global_ctor_dtor_4.cpp | ga0/phasar | b9ecb9a1f0353501376021fab67057a713fa70dc | [
"MIT"
] | 581 | 2018-06-10T10:37:55.000Z | 2022-03-30T14:56:53.000Z | test/llvm_test_code/call_graphs/global_ctor_dtor_4.cpp | meret-boe/phasar | 2b394d5611b107e4fd3d8eec37f26abca8ef1e9a | [
"MIT"
] | 172 | 2018-06-13T12:33:26.000Z | 2022-03-26T07:21:41.000Z | test/llvm_test_code/call_graphs/global_ctor_dtor_4.cpp | meret-boe/phasar | 2b394d5611b107e4fd3d8eec37f26abca8ef1e9a | [
"MIT"
] | 137 | 2018-06-10T10:31:14.000Z | 2022-03-06T11:53:56.000Z | __attribute__((constructor)) void before_main();
__attribute__((destructor)) void after_main();
void before_main() {}
void after_main() {}
struct S {
int data;
S(int data) : data(data) {}
~S() {}
};
S s(0);
int main() {}
| 14.4375 | 48 | 0.632035 | ga0 |
eaabbda163a454e1416e67830d8336efb40a3bad | 1,476 | cpp | C++ | VC2010Samples/MFC/Visual C++ 2008 Feature Pack/RollupPane/InfoBar.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2010Samples/MFC/Visual C++ 2008 Feature Pack/RollupPane/InfoBar.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2010Samples/MFC/Visual C++ 2008 Feature Pack/RollupPane/InfoBar.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "RollupPane.h"
#include "InfoBar.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CInfoBar
CInfoBar::CInfoBar()
{
}
CInfoBar::~CInfoBar()
{
}
BEGIN_MESSAGE_MAP(CInfoBar, CDockablePane)
//{{AFX_MSG_MAP(CInfoBar)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CInfoBar message handlers
void CInfoBar::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rectClient;
GetClientRect (rectClient);
dc.FillSolidRect (rectClient, ::GetSysColor (COLOR_3DHILIGHT));
dc.Draw3dRect (rectClient, ::GetSysColor (COLOR_3DSHADOW),
::GetSysColor (COLOR_3DLIGHT));
dc.SetBkMode (TRANSPARENT);
dc.SetTextColor (::GetSysColor (COLOR_BTNTEXT));
CFont* pOldFont = (CFont*) dc.SelectStockObject (DEFAULT_GUI_FONT);
CString str = _T("Information...");
dc.TextOut (10, 10, str);
dc.SelectObject (pOldFont);
}
| 23.428571 | 77 | 0.667344 | alonmm |
eaaee55d560d16a2957b2c5fb53f02afae059dec | 2,406 | cpp | C++ | src/zmqConsumerPoll.cpp | tompatman/zmqplus | efea491f2e9ca8f531ec7e102564fb56b1d62e0f | [
"MIT"
] | null | null | null | src/zmqConsumerPoll.cpp | tompatman/zmqplus | efea491f2e9ca8f531ec7e102564fb56b1d62e0f | [
"MIT"
] | null | null | null | src/zmqConsumerPoll.cpp | tompatman/zmqplus | efea491f2e9ca8f531ec7e102564fb56b1d62e0f | [
"MIT"
] | null | null | null | /*
* zmqConsumerPoll.cpp
*
* Created on: May 31, 2013
* Author: service
*/
#include "../include/zmqConsumerPoll.h"
using std::string;
zmqConsumerPoll::zmqConsumerPoll(ppcLogger *log, uint num_consumers_to_poll, int timeout_ms)
: _log(log)
, _num_consumers(num_consumers_to_poll)
, _timeout_ms(timeout_ms)
{
_items = (zmq::pollitem_t *) new zmq::pollitem_t[_num_consumers];
}
zmqConsumerPoll::~zmqConsumerPoll()
{
delete[] _items;
}
void zmqConsumerPoll::Add(iConsumer *a_consumer)
{
uint idx = _consumer_list.size();
poco_assert(idx < _num_consumers);
_consumer_list.push_back(a_consumer);
_items[idx].events = ZMQ_POLLIN;
_items[idx].fd = 0;
_items[idx].socket = a_consumer->get_sub_socket_for_poll();
}
int zmqConsumerPoll::Poll()
{
poco_assert(_consumer_list.size() == _num_consumers);
int number_signaled = zmq::poll(_items, _num_consumers, _timeout_ms);
if(number_signaled > 0) // Any updates
{
int count = 0;
for (uint i = 0; i < _num_consumers; ++i)
{
if(_items[i].revents & ZMQ_POLLIN)
{
if(!_consumer_list[i]->update_data_share())
_items[i].revents = 0; // Remove the signal if it does not return true.
count++;
}
}
poco_assert(count == number_signaled); // Better be the same.
}
if(number_signaled < 0)
{
_log->log(LG_ERR, "zmq::poll returned error[%d]:", zmq_errno(), zmq_strerror(zmq_errno()));
throw Poco::RuntimeException(string("zmq::poll returned error[]:") + zmq_strerror(zmq_errno()));
}
return number_signaled;
}
bool zmqConsumerPoll::WasSignaled(uint consumer_idx)
{
poco_assert(consumer_idx < _num_consumers);
return (_items[consumer_idx].revents & ZMQ_POLLIN);
}
bool zmqConsumerPoll::WasSignaled(iConsumer *a_consumer)
{
bool was_signaled = false;
uint i = 0;
for (; i < _num_consumers; ++i)
{
if(_consumer_list[i] == a_consumer)
{
was_signaled = (_items[i].revents & ZMQ_POLLIN);
break;
}
}
if(i == _num_consumers)
{
_log->log(LG_ERR, "The consumer was not found in the list!");
throw Poco::RuntimeException("WasSignaled() : The consumer was not found in the list!");
}
return was_signaled;
}
| 23.588235 | 112 | 0.620116 | tompatman |
eaaf2f4745d98ff1b2d861e75db041301a3a0122 | 2,341 | cpp | C++ | midterm_mbghazi.cpp | mbghazi/Data-Structures | 4703488686d2a78267fcd5a6adcbeda36ac10703 | [
"MIT"
] | null | null | null | midterm_mbghazi.cpp | mbghazi/Data-Structures | 4703488686d2a78267fcd5a6adcbeda36ac10703 | [
"MIT"
] | null | null | null | midterm_mbghazi.cpp | mbghazi/Data-Structures | 4703488686d2a78267fcd5a6adcbeda36ac10703 | [
"MIT"
] | null | null | null | /*
** PROGRAM: Matrix Multiply
**
** PURPOSE: This is a simple matrix multiply program.
** It will compute the product
**
** C = A * B
**
** A and B are set to constant matrices so we
** can make a quick test of the multiplication.
**
** USAGE: Right now, I hardwire the martix dimensions.
** later, I'll take them from the command line.
**
** HISTORY: Written by Tim Mattson, Nov 1999.
*/
#include <iostream>
#include <omp.h>
using namespace std;
#define ORDER 500
#define AVAL 3.0
#define BVAL 5.0
#define TOL 0.001
#define Ndim ORDER
#define Pdim ORDER
#define Mdim ORDER
#define NUM_THREADS 4//added
int main(int argc, char **argv)
{
double A[Ndim][Pdim], B[Pdim][Mdim], C[Ndim][Mdim];
int i,j,k;
//double *A, *B, *C,
double cval, tmp, err, errsq;
double dN, mflops;
double start_time, run_time;
double sum;
omp_set_num_threads(NUM_THREADS);
start_time = omp_get_wtime();
/* Initialize matrices */
for (i=0; i<Ndim; i++)
for (j=0; j<Pdim; j++)
A[i][j] = AVAL;
for (i=0; i<Pdim; i++)
for (j=0; j<Mdim; j++)
B[i][j] = BVAL;
for (i=0; i<Ndim; i++)
for (j=0; j<Mdim; j++)
C[i][j] = 0.0;
/* Do the matrix product */
#pragma parallel for schedule(dynamic) lastprivate(sum) red(-tmp)
for (i=0; i<Ndim; i++){
//added
//#pragma parallel for
for (j=0; j<Mdim; j++){
tmp = 0.0;
//#pragma parallel for schedule(dynamic) lastprivate(tmp)
for(k=0;k<Pdim;k++){
/* C(i,j) = sum(over k) A(i,k) * B(k,j) */
tmp += A[i][k] * B[k][j];
}
C[i][j] = tmp;
sum += tmp;
}
}
/* Check the answer */
cout << "Summary is " << sum << endl;
cval = Pdim * AVAL * BVAL;
errsq = 0.0;
for (i=0; i<Ndim; i++){
for (j=0; j<Mdim; j++){
err = C[i][j] - cval;
errsq += err * err;
}
}
errsq += sum - cval*Ndim*Mdim;
if (errsq > TOL)
cout << "Errors in multiplication: "<< errsq<< endl;
else
cout << "Hey, it worked! Error is: " << errsq << endl;
run_time = omp_get_wtime() - start_time;
cout << "Order " << ORDER << " multiplication in " << run_time << " seconds "<< endl;
dN = (double)ORDER;
mflops = 2.0 * dN * dN * dN/(1000000.0* run_time);
cout << "Order " << " multiplication at " << mflops << " mflops" << endl;
cout << "All done "<< endl;
return 0;
}
| 22.509615 | 86 | 0.564289 | mbghazi |
eab068770436f9db993275b1ce35ad8d8dba1c8d | 1,444 | cc | C++ | src/boson/test/queues_weakrb.cc | duckie/boson | f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a | [
"MIT"
] | 174 | 2016-10-10T12:47:01.000Z | 2022-03-09T16:06:59.000Z | src/boson/test/queues_weakrb.cc | duckie/boson | f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a | [
"MIT"
] | 5 | 2017-02-01T21:30:14.000Z | 2018-09-09T10:02:00.000Z | src/boson/test/queues_weakrb.cc | duckie/boson | f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a | [
"MIT"
] | 13 | 2016-10-10T12:19:14.000Z | 2021-12-04T08:23:26.000Z | #include <iostream>
#include <limits>
#include <random>
#include <thread>
#include "boson/queues/weakrb.h"
#include "catch.hpp"
TEST_CASE("Queues - WeakRB - serial random integers", "[queues][weakrb]") {
constexpr size_t const sample_size = 1e4;
std::random_device seed;
std::mt19937_64 generator{seed()};
std::uniform_int_distribution<int> distribution(std::numeric_limits<int>::min(),
std::numeric_limits<int>::max());
std::vector<int> sample;
sample.reserve(sample_size);
for (size_t index = 0; index < sample_size; ++index)
sample.emplace_back(distribution(generator));
// Create the buffer
std::vector<int> destination;
destination.reserve(sample_size);
boson::queues::weakrb<int> queue(1);
std::thread t1([&sample, &queue]() {
for (auto v : sample) {
bool success = false;
int value = v;
// Ugly spin lock, osef
while (!success) {
success = queue.write(value);
std::this_thread::yield();
}
}
});
std::thread t2([&destination, &queue]() {
for (size_t index = 0; index < sample_size; ++index) {
bool success = false;
int result{};
// Ugly spin lock, osef
while (!success) {
success = queue.read(result);
std::this_thread::yield();
}
destination.emplace_back(result);
}
});
t1.join();
t2.join();
CHECK(sample == destination);
}
| 25.333333 | 83 | 0.605956 | duckie |
eab334692c7e899abd7ef97fc35637752d552cba | 64,611 | cpp | C++ | src/slg/film/film.cpp | DavidBluecame/LuxRays | be0f5228b8b65268278a6c6a1c98564ebdc27c05 | [
"Apache-2.0"
] | null | null | null | src/slg/film/film.cpp | DavidBluecame/LuxRays | be0f5228b8b65268278a6c6a1c98564ebdc27c05 | [
"Apache-2.0"
] | null | null | null | src/slg/film/film.cpp | DavidBluecame/LuxRays | be0f5228b8b65268278a6c6a1c98564ebdc27c05 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright 1998-2015 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxRender. *
* *
* 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 <limits>
#include <algorithm>
#include <exception>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/imagebuf.h>
OIIO_NAMESPACE_USING
#include "luxrays/core/geometry/point.h"
#include "luxrays/utils/properties.h"
#include "slg/film/film.h"
#include "slg/film/filters/gaussian.h"
#include "slg/editaction.h"
using namespace std;
using namespace luxrays;
using namespace slg;
typedef unsigned char BYTE;
//------------------------------------------------------------------------------
// FilmOutput
//------------------------------------------------------------------------------
void FilmOutputs::Add(const FilmOutputType type, const string &fileName,
const Properties *p) {
types.push_back(type);
fileNames.push_back(fileName);
if (p)
props.push_back(*p);
else
props.push_back(Properties());
}
//------------------------------------------------------------------------------
// Film
//------------------------------------------------------------------------------
Film::Film(const u_int w, const u_int h) {
initialized = false;
width = w;
height = h;
radianceGroupCount = 1;
channel_ALPHA = NULL;
channel_RGB_TONEMAPPED = NULL;
channel_DEPTH = NULL;
channel_POSITION = NULL;
channel_GEOMETRY_NORMAL = NULL;
channel_SHADING_NORMAL = NULL;
channel_MATERIAL_ID = NULL;
channel_DIRECT_DIFFUSE = NULL;
channel_DIRECT_GLOSSY = NULL;
channel_EMISSION = NULL;
channel_INDIRECT_DIFFUSE = NULL;
channel_INDIRECT_GLOSSY = NULL;
channel_INDIRECT_SPECULAR = NULL;
channel_DIRECT_SHADOW_MASK = NULL;
channel_INDIRECT_SHADOW_MASK = NULL;
channel_UV = NULL;
channel_RAYCOUNT = NULL;
channel_IRRADIANCE = NULL;
convTest = NULL;
enabledOverlappedScreenBufferUpdate = true;
rgbTonemapUpdate = true;
imagePipeline = NULL;
filter = NULL;
filterLUTs = NULL;
SetFilter(new GaussianFilter(1.5f, 1.5f, 2.f));
}
Film::~Film() {
delete imagePipeline;
delete convTest;
for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i)
delete channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i];
for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i)
delete channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i];
delete channel_ALPHA;
delete channel_RGB_TONEMAPPED;
delete channel_DEPTH;
delete channel_POSITION;
delete channel_GEOMETRY_NORMAL;
delete channel_SHADING_NORMAL;
delete channel_MATERIAL_ID;
delete channel_DIRECT_DIFFUSE;
delete channel_DIRECT_GLOSSY;
delete channel_EMISSION;
delete channel_INDIRECT_DIFFUSE;
delete channel_INDIRECT_GLOSSY;
delete channel_INDIRECT_SPECULAR;
for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i)
delete channel_MATERIAL_ID_MASKs[i];
delete channel_DIRECT_SHADOW_MASK;
delete channel_INDIRECT_SHADOW_MASK;
delete channel_UV;
delete channel_RAYCOUNT;
for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i)
delete channel_BY_MATERIAL_IDs[i];
delete channel_IRRADIANCE;
delete filterLUTs;
delete filter;
}
void Film::AddChannel(const FilmChannelType type, const Properties *prop) {
if (initialized)
throw runtime_error("It is only possible to add a channel to a Film before initialization");
channels.insert(type);
switch (type) {
case MATERIAL_ID_MASK: {
const u_int id = prop->Get(Property("id")(255)).Get<u_int>();
if (count(maskMaterialIDs.begin(), maskMaterialIDs.end(), id) == 0)
maskMaterialIDs.push_back(id);
break;
}
case BY_MATERIAL_ID: {
const u_int id = prop->Get(Property("id")(255)).Get<u_int>();
if (count(byMaterialIDs.begin(), byMaterialIDs.end(), id) == 0)
byMaterialIDs.push_back(id);
break;
}
default:
break;
}
}
void Film::RemoveChannel(const FilmChannelType type) {
if (initialized)
throw runtime_error("It is only possible to remove a channel from a Film before initialization");
channels.erase(type);
}
void Film::Init() {
if (initialized)
throw runtime_error("A Film can not be initialized multiple times");
initialized = true;
Resize(width, height);
}
void Film::Resize(const u_int w, const u_int h) {
width = w;
height = h;
pixelCount = w * h;
delete convTest;
convTest = NULL;
// Delete all already allocated channels
for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i)
delete channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i];
channel_RADIANCE_PER_PIXEL_NORMALIZEDs.clear();
for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i)
delete channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i];
channel_RADIANCE_PER_SCREEN_NORMALIZEDs.clear();
delete channel_ALPHA;
delete channel_RGB_TONEMAPPED;
delete channel_DEPTH;
delete channel_POSITION;
delete channel_GEOMETRY_NORMAL;
delete channel_SHADING_NORMAL;
delete channel_MATERIAL_ID;
delete channel_DIRECT_DIFFUSE;
delete channel_DIRECT_GLOSSY;
delete channel_EMISSION;
delete channel_INDIRECT_DIFFUSE;
delete channel_INDIRECT_GLOSSY;
delete channel_INDIRECT_SPECULAR;
for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i)
delete channel_MATERIAL_ID_MASKs[i];
channel_MATERIAL_ID_MASKs.clear();
delete channel_DIRECT_SHADOW_MASK;
delete channel_INDIRECT_SHADOW_MASK;
delete channel_UV;
delete channel_RAYCOUNT;
for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i)
delete channel_BY_MATERIAL_IDs[i];
channel_BY_MATERIAL_IDs.clear();
delete channel_IRRADIANCE;
// Allocate all required channels
hasDataChannel = false;
hasComposingChannel = false;
if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) {
channel_RADIANCE_PER_PIXEL_NORMALIZEDs.resize(radianceGroupCount, NULL);
for (u_int i = 0; i < radianceGroupCount; ++i) {
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i] = new GenericFrameBuffer<4, 1, float>(width, height);
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->Clear();
}
}
if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) {
channel_RADIANCE_PER_SCREEN_NORMALIZEDs.resize(radianceGroupCount, NULL);
for (u_int i = 0; i < radianceGroupCount; ++i) {
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i] = new GenericFrameBuffer<3, 0, float>(width, height);
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->Clear();
}
}
if (HasChannel(ALPHA)) {
channel_ALPHA = new GenericFrameBuffer<2, 1, float>(width, height);
channel_ALPHA->Clear();
}
if (HasChannel(RGB_TONEMAPPED)) {
channel_RGB_TONEMAPPED = new GenericFrameBuffer<3, 0, float>(width, height);
channel_RGB_TONEMAPPED->Clear();
convTest = new ConvergenceTest(width, height);
}
if (HasChannel(DEPTH)) {
channel_DEPTH = new GenericFrameBuffer<1, 0, float>(width, height);
channel_DEPTH->Clear(numeric_limits<float>::infinity());
hasDataChannel = true;
}
if (HasChannel(POSITION)) {
channel_POSITION = new GenericFrameBuffer<3, 0, float>(width, height);
channel_POSITION->Clear(numeric_limits<float>::infinity());
hasDataChannel = true;
}
if (HasChannel(GEOMETRY_NORMAL)) {
channel_GEOMETRY_NORMAL = new GenericFrameBuffer<3, 0, float>(width, height);
channel_GEOMETRY_NORMAL->Clear(numeric_limits<float>::infinity());
hasDataChannel = true;
}
if (HasChannel(SHADING_NORMAL)) {
channel_SHADING_NORMAL = new GenericFrameBuffer<3, 0, float>(width, height);
channel_SHADING_NORMAL->Clear(numeric_limits<float>::infinity());
hasDataChannel = true;
}
if (HasChannel(MATERIAL_ID)) {
channel_MATERIAL_ID = new GenericFrameBuffer<1, 0, u_int>(width, height);
channel_MATERIAL_ID->Clear(numeric_limits<u_int>::max());
hasDataChannel = true;
}
if (HasChannel(DIRECT_DIFFUSE)) {
channel_DIRECT_DIFFUSE = new GenericFrameBuffer<4, 1, float>(width, height);
channel_DIRECT_DIFFUSE->Clear();
hasComposingChannel = true;
}
if (HasChannel(DIRECT_GLOSSY)) {
channel_DIRECT_GLOSSY = new GenericFrameBuffer<4, 1, float>(width, height);
channel_DIRECT_GLOSSY->Clear();
hasComposingChannel = true;
}
if (HasChannel(EMISSION)) {
channel_EMISSION = new GenericFrameBuffer<4, 1, float>(width, height);
channel_EMISSION->Clear();
hasComposingChannel = true;
}
if (HasChannel(INDIRECT_DIFFUSE)) {
channel_INDIRECT_DIFFUSE = new GenericFrameBuffer<4, 1, float>(width, height);
channel_INDIRECT_DIFFUSE->Clear();
hasComposingChannel = true;
}
if (HasChannel(INDIRECT_GLOSSY)) {
channel_INDIRECT_GLOSSY = new GenericFrameBuffer<4, 1, float>(width, height);
channel_INDIRECT_GLOSSY->Clear();
hasComposingChannel = true;
}
if (HasChannel(INDIRECT_SPECULAR)) {
channel_INDIRECT_SPECULAR = new GenericFrameBuffer<4, 1, float>(width, height);
channel_INDIRECT_SPECULAR->Clear();
hasComposingChannel = true;
}
if (HasChannel(MATERIAL_ID_MASK)) {
for (u_int i = 0; i < maskMaterialIDs.size(); ++i) {
GenericFrameBuffer<2, 1, float> *buf = new GenericFrameBuffer<2, 1, float>(width, height);
buf->Clear();
channel_MATERIAL_ID_MASKs.push_back(buf);
}
hasComposingChannel = true;
}
if (HasChannel(DIRECT_SHADOW_MASK)) {
channel_DIRECT_SHADOW_MASK = new GenericFrameBuffer<2, 1, float>(width, height);
channel_DIRECT_SHADOW_MASK->Clear();
hasComposingChannel = true;
}
if (HasChannel(INDIRECT_SHADOW_MASK)) {
channel_INDIRECT_SHADOW_MASK = new GenericFrameBuffer<2, 1, float>(width, height);
channel_INDIRECT_SHADOW_MASK->Clear();
hasComposingChannel = true;
}
if (HasChannel(UV)) {
channel_UV = new GenericFrameBuffer<2, 0, float>(width, height);
channel_UV->Clear(numeric_limits<float>::infinity());
hasDataChannel = true;
}
if (HasChannel(RAYCOUNT)) {
channel_RAYCOUNT = new GenericFrameBuffer<1, 0, float>(width, height);
channel_RAYCOUNT->Clear();
hasDataChannel = true;
}
if (HasChannel(BY_MATERIAL_ID)) {
for (u_int i = 0; i < byMaterialIDs.size(); ++i) {
GenericFrameBuffer<4, 1, float> *buf = new GenericFrameBuffer<4, 1, float>(width, height);
buf->Clear();
channel_BY_MATERIAL_IDs.push_back(buf);
}
hasComposingChannel = true;
}
if (HasChannel(IRRADIANCE)) {
channel_IRRADIANCE = new GenericFrameBuffer<4, 1, float>(width, height);
channel_IRRADIANCE->Clear();
hasComposingChannel = true;
}
// Initialize the stats
statsTotalSampleCount = 0.0;
statsAvgSampleSec = 0.0;
statsStartSampleTime = WallClockTime();
}
void Film::SetFilter(Filter *flt) {
delete filterLUTs;
filterLUTs = NULL;
delete filter;
filter = flt;
if (filter) {
const u_int size = Max<u_int>(4, Max(filter->xWidth, filter->yWidth) + 1);
filterLUTs = new FilterLUTs(*filter, size);
}
}
void Film::Reset() {
if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) {
for (u_int i = 0; i < radianceGroupCount; ++i)
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->Clear();
}
if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) {
for (u_int i = 0; i < radianceGroupCount; ++i)
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->Clear();
}
if (HasChannel(ALPHA))
channel_ALPHA->Clear();
if (HasChannel(DEPTH))
channel_DEPTH->Clear(numeric_limits<float>::infinity());
if (HasChannel(POSITION))
channel_POSITION->Clear(numeric_limits<float>::infinity());
if (HasChannel(GEOMETRY_NORMAL))
channel_GEOMETRY_NORMAL->Clear(numeric_limits<float>::infinity());
if (HasChannel(SHADING_NORMAL))
channel_SHADING_NORMAL->Clear(numeric_limits<float>::infinity());
if (HasChannel(MATERIAL_ID))
channel_MATERIAL_ID->Clear(numeric_limits<float>::max());
if (HasChannel(DIRECT_DIFFUSE))
channel_DIRECT_DIFFUSE->Clear();
if (HasChannel(DIRECT_GLOSSY))
channel_DIRECT_GLOSSY->Clear();
if (HasChannel(EMISSION))
channel_EMISSION->Clear();
if (HasChannel(INDIRECT_DIFFUSE))
channel_INDIRECT_DIFFUSE->Clear();
if (HasChannel(INDIRECT_GLOSSY))
channel_INDIRECT_GLOSSY->Clear();
if (HasChannel(INDIRECT_SPECULAR))
channel_INDIRECT_SPECULAR->Clear();
if (HasChannel(MATERIAL_ID_MASK)) {
for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i)
channel_MATERIAL_ID_MASKs[i]->Clear();
}
if (HasChannel(DIRECT_SHADOW_MASK))
channel_DIRECT_SHADOW_MASK->Clear();
if (HasChannel(INDIRECT_SHADOW_MASK))
channel_INDIRECT_SHADOW_MASK->Clear();
if (HasChannel(UV))
channel_UV->Clear();
if (HasChannel(RAYCOUNT))
channel_RAYCOUNT->Clear();
if (HasChannel(BY_MATERIAL_ID)) {
for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i)
channel_BY_MATERIAL_IDs[i]->Clear();
}
if (HasChannel(IRRADIANCE))
channel_IRRADIANCE->Clear();
// convTest has to be reset explicitly
statsTotalSampleCount = 0.0;
statsAvgSampleSec = 0.0;
statsStartSampleTime = WallClockTime();
}
void Film::AddFilm(const Film &film,
const u_int srcOffsetX, const u_int srcOffsetY,
const u_int srcWidth, const u_int srcHeight,
const u_int dstOffsetX, const u_int dstOffsetY) {
statsTotalSampleCount += film.statsTotalSampleCount;
if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && film.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) {
for (u_int i = 0; i < Min(radianceGroupCount, film.radianceGroupCount); ++i) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED) && film.HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) {
for (u_int i = 0; i < Min(radianceGroupCount, film.radianceGroupCount); ++i) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(ALPHA) && film.HasChannel(ALPHA)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_ALPHA->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_ALPHA->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(POSITION) && film.HasChannel(POSITION)) {
if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) {
// Used DEPTH information to merge Films
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) {
const float *srcPixel = film.channel_POSITION->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_POSITION->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
} else {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_POSITION->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_POSITION->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(GEOMETRY_NORMAL) && film.HasChannel(GEOMETRY_NORMAL)) {
if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) {
// Used DEPTH information to merge Films
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) {
const float *srcPixel = film.channel_GEOMETRY_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_GEOMETRY_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
} else {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_GEOMETRY_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_GEOMETRY_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(SHADING_NORMAL) && film.HasChannel(SHADING_NORMAL)) {
if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) {
// Used DEPTH information to merge Films
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) {
const float *srcPixel = film.channel_SHADING_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_SHADING_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
} else {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_SHADING_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_SHADING_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(MATERIAL_ID) && film.HasChannel(MATERIAL_ID)) {
if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) {
// Used DEPTH information to merge Films
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) {
const u_int *srcPixel = film.channel_MATERIAL_ID->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_MATERIAL_ID->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
} else {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const u_int *srcPixel = film.channel_MATERIAL_ID->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_MATERIAL_ID->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(DIRECT_DIFFUSE) && film.HasChannel(DIRECT_DIFFUSE)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_DIRECT_DIFFUSE->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_DIRECT_DIFFUSE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(DIRECT_GLOSSY) && film.HasChannel(DIRECT_GLOSSY)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_DIRECT_GLOSSY->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_DIRECT_GLOSSY->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(EMISSION) && film.HasChannel(EMISSION)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_EMISSION->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_EMISSION->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(INDIRECT_DIFFUSE) && film.HasChannel(INDIRECT_DIFFUSE)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_INDIRECT_DIFFUSE->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_INDIRECT_DIFFUSE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(INDIRECT_GLOSSY) && film.HasChannel(INDIRECT_GLOSSY)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_INDIRECT_GLOSSY->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_INDIRECT_GLOSSY->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(INDIRECT_SPECULAR) && film.HasChannel(INDIRECT_SPECULAR)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_INDIRECT_SPECULAR->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_INDIRECT_SPECULAR->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(MATERIAL_ID_MASK) && film.HasChannel(MATERIAL_ID_MASK)) {
for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) {
for (u_int j = 0; j < film.maskMaterialIDs.size(); ++j) {
if (maskMaterialIDs[i] == film.maskMaterialIDs[j]) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_MATERIAL_ID_MASKs[j]->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_MATERIAL_ID_MASKs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
}
}
if (HasChannel(DIRECT_SHADOW_MASK) && film.HasChannel(DIRECT_SHADOW_MASK)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_DIRECT_SHADOW_MASK->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_DIRECT_SHADOW_MASK->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(INDIRECT_SHADOW_MASK) && film.HasChannel(INDIRECT_SHADOW_MASK)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_INDIRECT_SHADOW_MASK->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_INDIRECT_SHADOW_MASK->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(UV) && film.HasChannel(UV)) {
if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) {
// Used DEPTH information to merge Films
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) {
const float *srcPixel = film.channel_UV->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_UV->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
} else {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_UV->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_UV->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
if (HasChannel(RAYCOUNT) && film.HasChannel(RAYCOUNT)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_RAYCOUNT->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_RAYCOUNT->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
if (HasChannel(BY_MATERIAL_ID) && film.HasChannel(BY_MATERIAL_ID)) {
for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) {
for (u_int j = 0; j < film.byMaterialIDs.size(); ++j) {
if (byMaterialIDs[i] == film.byMaterialIDs[j]) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_BY_MATERIAL_IDs[j]->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_BY_MATERIAL_IDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
}
}
if (HasChannel(IRRADIANCE) && film.HasChannel(IRRADIANCE)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_IRRADIANCE->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_IRRADIANCE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
// NOTE: update DEPTH channel last because it is used to merge other channels
if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) {
for (u_int y = 0; y < srcHeight; ++y) {
for (u_int x = 0; x < srcWidth; ++x) {
const float *srcPixel = film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y);
channel_DEPTH->MinPixel(dstOffsetX + x, dstOffsetY + y, srcPixel);
}
}
}
}
u_int Film::GetChannelCount(const FilmChannelType type) const {
switch (type) {
case RADIANCE_PER_PIXEL_NORMALIZED:
return channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size();
case RADIANCE_PER_SCREEN_NORMALIZED:
return channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size();
case ALPHA:
return channel_ALPHA ? 1 : 0;
case RGB_TONEMAPPED:
return channel_RGB_TONEMAPPED ? 1 : 0;
case DEPTH:
return channel_DEPTH ? 1 : 0;
case POSITION:
return channel_POSITION ? 1 : 0;
case GEOMETRY_NORMAL:
return channel_GEOMETRY_NORMAL ? 1 : 0;
case SHADING_NORMAL:
return channel_SHADING_NORMAL ? 1 : 0;
case MATERIAL_ID:
return channel_MATERIAL_ID ? 1 : 0;
case DIRECT_DIFFUSE:
return channel_DIRECT_DIFFUSE ? 1 : 0;
case DIRECT_GLOSSY:
return channel_DIRECT_GLOSSY ? 1 : 0;
case EMISSION:
return channel_EMISSION ? 1 : 0;
case INDIRECT_DIFFUSE:
return channel_INDIRECT_DIFFUSE ? 1 : 0;
case INDIRECT_GLOSSY:
return channel_INDIRECT_GLOSSY ? 1 : 0;
case INDIRECT_SPECULAR:
return channel_INDIRECT_SPECULAR ? 1 : 0;
case MATERIAL_ID_MASK:
return channel_MATERIAL_ID_MASKs.size();
case DIRECT_SHADOW_MASK:
return channel_DIRECT_SHADOW_MASK ? 1 : 0;
case INDIRECT_SHADOW_MASK:
return channel_INDIRECT_SHADOW_MASK ? 1 : 0;
case UV:
return channel_UV ? 1 : 0;
case RAYCOUNT:
return channel_RAYCOUNT ? 1 : 0;
case BY_MATERIAL_ID:
return channel_BY_MATERIAL_IDs.size();
case IRRADIANCE:
return channel_IRRADIANCE ? 1 : 0;
default:
throw runtime_error("Unknown FilmOutputType in Film::GetChannelCount>(): " + ToString(type));
}
}
size_t Film::GetOutputSize(const FilmOutputs::FilmOutputType type) const {
switch (type) {
case FilmOutputs::RGB:
return 3 * pixelCount;
case FilmOutputs::RGBA:
return 4 * pixelCount;
case FilmOutputs::RGB_TONEMAPPED:
return 3 * pixelCount;
case FilmOutputs::RGBA_TONEMAPPED:
return 4 * pixelCount;
case FilmOutputs::ALPHA:
return pixelCount;
case FilmOutputs::DEPTH:
return pixelCount;
case FilmOutputs::POSITION:
return 3 * pixelCount;
case FilmOutputs::GEOMETRY_NORMAL:
return 3 * pixelCount;
case FilmOutputs::SHADING_NORMAL:
return 3 * pixelCount;
case FilmOutputs::MATERIAL_ID:
return pixelCount;
case FilmOutputs::DIRECT_DIFFUSE:
return 3 * pixelCount;
case FilmOutputs::DIRECT_GLOSSY:
return 3 * pixelCount;
case FilmOutputs::EMISSION:
return 3 * pixelCount;
case FilmOutputs::INDIRECT_DIFFUSE:
return 3 * pixelCount;
case FilmOutputs::INDIRECT_GLOSSY:
return 3 * pixelCount;
case FilmOutputs::INDIRECT_SPECULAR:
return 3 * pixelCount;
case FilmOutputs::MATERIAL_ID_MASK:
return pixelCount;
case FilmOutputs::DIRECT_SHADOW_MASK:
return pixelCount;
case FilmOutputs::INDIRECT_SHADOW_MASK:
return pixelCount;
case FilmOutputs::RADIANCE_GROUP:
return 3 * pixelCount;
case FilmOutputs::UV:
return 2 * pixelCount;
case FilmOutputs::RAYCOUNT:
return pixelCount;
case FilmOutputs::BY_MATERIAL_ID:
return 3 * pixelCount;
case FilmOutputs::IRRADIANCE:
return 3 * pixelCount;
default:
throw runtime_error("Unknown FilmOutputType in Film::GetOutputSize(): " + ToString(type));
}
}
bool Film::HasOutput(const FilmOutputs::FilmOutputType type) const {
switch (type) {
case FilmOutputs::RGB:
return HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED);
case FilmOutputs::RGB_TONEMAPPED:
return HasChannel(RGB_TONEMAPPED);
case FilmOutputs::RGBA:
return (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) && HasChannel(ALPHA);
case FilmOutputs::RGBA_TONEMAPPED:
return HasChannel(RGB_TONEMAPPED) && HasChannel(ALPHA);
case FilmOutputs::ALPHA:
return HasChannel(ALPHA);
case FilmOutputs::DEPTH:
return HasChannel(DEPTH);
case FilmOutputs::POSITION:
return HasChannel(POSITION);
case FilmOutputs::GEOMETRY_NORMAL:
return HasChannel(GEOMETRY_NORMAL);
case FilmOutputs::SHADING_NORMAL:
return HasChannel(SHADING_NORMAL);
case FilmOutputs::MATERIAL_ID:
return HasChannel(MATERIAL_ID);
case FilmOutputs::DIRECT_DIFFUSE:
return HasChannel(DIRECT_DIFFUSE);
case FilmOutputs::DIRECT_GLOSSY:
return HasChannel(DIRECT_GLOSSY);
case FilmOutputs::EMISSION:
return HasChannel(EMISSION);
case FilmOutputs::INDIRECT_DIFFUSE:
return HasChannel(INDIRECT_DIFFUSE);
case FilmOutputs::INDIRECT_GLOSSY:
return HasChannel(INDIRECT_GLOSSY);
case FilmOutputs::INDIRECT_SPECULAR:
return HasChannel(INDIRECT_SPECULAR);
case FilmOutputs::MATERIAL_ID_MASK:
return HasChannel(MATERIAL_ID_MASK);
case FilmOutputs::DIRECT_SHADOW_MASK:
return HasChannel(DIRECT_SHADOW_MASK);
case FilmOutputs::INDIRECT_SHADOW_MASK:
return HasChannel(INDIRECT_SHADOW_MASK);
case FilmOutputs::RADIANCE_GROUP:
return true;
case FilmOutputs::UV:
return HasChannel(UV);
case FilmOutputs::RAYCOUNT:
return HasChannel(RAYCOUNT);
case FilmOutputs::BY_MATERIAL_ID:
return HasChannel(BY_MATERIAL_ID);
case FilmOutputs::IRRADIANCE:
return HasChannel(IRRADIANCE);
default:
throw runtime_error("Unknown film output type in Film::HasOutput(): " + ToString(type));
}
}
void Film::Output(const FilmOutputs &filmOutputs) {
for (u_int i = 0; i < filmOutputs.GetCount(); ++i)
Output(filmOutputs.GetType(i), filmOutputs.GetFileName(i), &filmOutputs.GetProperties(i));
}
void Film::Output(const FilmOutputs::FilmOutputType type, const string &fileName,
const Properties *props) {
u_int maskMaterialIDsIndex = 0;
u_int byMaterialIDsIndex = 0;
u_int radianceGroupIndex = 0;
u_int channelCount = 3;
switch (type) {
case FilmOutputs::RGB:
if (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED))
return;
break;
case FilmOutputs::RGB_TONEMAPPED:
if (!HasChannel(RGB_TONEMAPPED))
return;
ExecuteImagePipeline();
break;
case FilmOutputs::RGBA:
if ((!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(ALPHA))
return;
channelCount = 4;
break;
case FilmOutputs::RGBA_TONEMAPPED:
if (!HasChannel(RGB_TONEMAPPED) || !HasChannel(ALPHA))
return;
ExecuteImagePipeline();
channelCount = 4;
break;
case FilmOutputs::ALPHA:
if (!HasChannel(ALPHA))
return;
channelCount = 1;
break;
case FilmOutputs::DEPTH:
if (!HasChannel(DEPTH))
return;
channelCount = 1;
break;
case FilmOutputs::POSITION:
if (!HasChannel(POSITION))
return;
break;
case FilmOutputs::GEOMETRY_NORMAL:
if (!HasChannel(GEOMETRY_NORMAL))
return;
break;
case FilmOutputs::SHADING_NORMAL:
if (!HasChannel(SHADING_NORMAL))
return;
break;
case FilmOutputs::MATERIAL_ID:
if (!HasChannel(MATERIAL_ID))
return;
break;
case FilmOutputs::DIRECT_DIFFUSE:
if (!HasChannel(DIRECT_DIFFUSE))
return;
break;
case FilmOutputs::DIRECT_GLOSSY:
if (!HasChannel(DIRECT_GLOSSY))
return;
break;
case FilmOutputs::EMISSION:
if (!HasChannel(EMISSION))
return;
break;
case FilmOutputs::INDIRECT_DIFFUSE:
if (!HasChannel(INDIRECT_DIFFUSE))
return;
break;
case FilmOutputs::INDIRECT_GLOSSY:
if (!HasChannel(INDIRECT_GLOSSY))
return;
break;
case FilmOutputs::INDIRECT_SPECULAR:
if (!HasChannel(INDIRECT_SPECULAR))
return;
break;
case FilmOutputs::MATERIAL_ID_MASK:
if (HasChannel(MATERIAL_ID_MASK) && props) {
channelCount = 1;
// Look for the material mask ID index
const u_int id = props->Get(Property("id")(255)).Get<u_int>();
bool found = false;
for (u_int i = 0; i < maskMaterialIDs.size(); ++i) {
if (maskMaterialIDs[i] == id) {
maskMaterialIDsIndex = i;
found = true;
break;
}
}
if (!found)
return;
} else
return;
break;
case FilmOutputs::DIRECT_SHADOW_MASK:
if (!HasChannel(DIRECT_SHADOW_MASK))
return;
channelCount = 1;
break;
case FilmOutputs::INDIRECT_SHADOW_MASK:
if (!HasChannel(INDIRECT_SHADOW_MASK))
return;
channelCount = 1;
break;
case FilmOutputs::RADIANCE_GROUP:
if (!props)
return;
radianceGroupIndex = props->Get(Property("id")(0)).Get<u_int>();
if (radianceGroupIndex >= radianceGroupCount)
return;
break;
case FilmOutputs::UV:
if (!HasChannel(UV))
return;
break;
case FilmOutputs::RAYCOUNT:
if (!HasChannel(RAYCOUNT))
return;
channelCount = 1;
break;
case FilmOutputs::BY_MATERIAL_ID:
if (HasChannel(BY_MATERIAL_ID) && props) {
// Look for the material mask ID index
const u_int id = props->Get(Property("id")(255)).Get<u_int>();
bool found = false;
for (u_int i = 0; i < byMaterialIDs.size(); ++i) {
if (byMaterialIDs[i] == id) {
byMaterialIDsIndex = i;
found = true;
break;
}
}
if (!found)
return;
} else
return;
break;
case FilmOutputs::IRRADIANCE:
if (!HasChannel(IRRADIANCE))
return;
break;
default:
throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type));
}
ImageBuf buffer;
SLG_LOG("Outputting film: " << fileName << " type: " << ToString(type));
if (type == FilmOutputs::MATERIAL_ID) {
// For material IDs we must copy into int buffer first or risk screwing up the ID
ImageSpec spec(width, height, channelCount, TypeDesc::UINT8);
buffer.reset(spec);
for (ImageBuf::ConstIterator<BYTE> it(buffer); !it.done(); ++it) {
u_int x = it.x();
u_int y = it.y();
BYTE *pixel = (BYTE *)buffer.pixeladdr(x, y, 0);
y = height - y - 1;
if (pixel == NULL)
throw runtime_error("Error while unpacking film data, could not address buffer!");
const u_int *src = channel_MATERIAL_ID->GetPixel(x, y);
pixel[0] = (BYTE)src[0];
pixel[1] = (BYTE)src[1];
pixel[2] = (BYTE)src[2];
}
} else {
// OIIO 1 channel EXR output is apparently not working, I write 3 channels as
// temporary workaround
// For all others copy into float buffer first and let OIIO figure out the conversion on write
ImageSpec spec(width, height, (channelCount == 1) ? 3 : channelCount, TypeDesc::FLOAT);
buffer.reset(spec);
for (ImageBuf::ConstIterator<float> it(buffer); !it.done(); ++it) {
u_int x = it.x();
u_int y = it.y();
float *pixel = (float *)buffer.pixeladdr(x, y, 0);
y = height - y - 1;
if (pixel == NULL)
throw runtime_error("Error while unpacking film data, could not address buffer!");
switch (type) {
case FilmOutputs::RGB: {
// Accumulate all light groups
GetPixelFromMergedSampleBuffers(x, y, pixel);
break;
}
case FilmOutputs::RGB_TONEMAPPED: {
channel_RGB_TONEMAPPED->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::RGBA: {
// Accumulate all light groups
GetPixelFromMergedSampleBuffers(x, y, pixel);
channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]);
break;
}
case FilmOutputs::RGBA_TONEMAPPED: {
channel_RGB_TONEMAPPED->GetWeightedPixel(x, y, pixel);
channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]);
break;
}
case FilmOutputs::ALPHA: {
channel_ALPHA->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DEPTH: {
channel_DEPTH->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::POSITION: {
channel_POSITION->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::GEOMETRY_NORMAL: {
channel_GEOMETRY_NORMAL->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::SHADING_NORMAL: {
channel_SHADING_NORMAL->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DIRECT_DIFFUSE: {
channel_DIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DIRECT_GLOSSY: {
channel_DIRECT_GLOSSY->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::EMISSION: {
channel_EMISSION->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_DIFFUSE: {
channel_INDIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_GLOSSY: {
channel_INDIRECT_GLOSSY->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_SPECULAR: {
channel_INDIRECT_SPECULAR->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::MATERIAL_ID_MASK: {
channel_MATERIAL_ID_MASKs[maskMaterialIDsIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::DIRECT_SHADOW_MASK: {
channel_DIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::INDIRECT_SHADOW_MASK: {
channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::RADIANCE_GROUP: {
// Accumulate all light groups
if (radianceGroupIndex < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size())
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel);
if (radianceGroupIndex < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size())
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::UV: {
channel_UV->GetWeightedPixel(x, y, pixel);
pixel[2] = 0.f;
break;
}
case FilmOutputs::RAYCOUNT: {
channel_RAYCOUNT->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::BY_MATERIAL_ID: {
channel_BY_MATERIAL_IDs[byMaterialIDsIndex]->GetWeightedPixel(x, y, pixel);
break;
}
case FilmOutputs::IRRADIANCE: {
channel_IRRADIANCE->GetWeightedPixel(x, y, pixel);
break;
}
default:
throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type));
}
// OIIO 1 channel EXR output is apparently not working, I write 3 channels as
// temporary workaround
if (channelCount == 1) {
pixel[1] = pixel[0];
pixel[2] = pixel[0];
}
}
}
buffer.write(fileName);
}
template<> const float *Film::GetChannel<float>(const FilmChannelType type, const u_int index) {
switch (type) {
case RADIANCE_PER_PIXEL_NORMALIZED:
return channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->GetPixels();
case RADIANCE_PER_SCREEN_NORMALIZED:
return channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->GetPixels();
case ALPHA:
return channel_ALPHA->GetPixels();
case RGB_TONEMAPPED: {
ExecuteImagePipeline();
return channel_RGB_TONEMAPPED->GetPixels();
}
case DEPTH:
return channel_DEPTH->GetPixels();
case POSITION:
return channel_POSITION->GetPixels();
case GEOMETRY_NORMAL:
return channel_GEOMETRY_NORMAL->GetPixels();
case SHADING_NORMAL:
return channel_SHADING_NORMAL->GetPixels();
case DIRECT_DIFFUSE:
return channel_DIRECT_DIFFUSE->GetPixels();
case DIRECT_GLOSSY:
return channel_DIRECT_GLOSSY->GetPixels();
case EMISSION:
return channel_EMISSION->GetPixels();
case INDIRECT_DIFFUSE:
return channel_INDIRECT_DIFFUSE->GetPixels();
case INDIRECT_GLOSSY:
return channel_INDIRECT_GLOSSY->GetPixels();
case INDIRECT_SPECULAR:
return channel_INDIRECT_SPECULAR->GetPixels();
case MATERIAL_ID_MASK:
return channel_MATERIAL_ID_MASKs[index]->GetPixels();
case DIRECT_SHADOW_MASK:
return channel_DIRECT_SHADOW_MASK->GetPixels();
case INDIRECT_SHADOW_MASK:
return channel_INDIRECT_SHADOW_MASK->GetPixels();
case UV:
return channel_UV->GetPixels();
case RAYCOUNT:
return channel_RAYCOUNT->GetPixels();
case BY_MATERIAL_ID:
return channel_BY_MATERIAL_IDs[index]->GetPixels();
case IRRADIANCE:
return channel_IRRADIANCE->GetPixels();
default:
throw runtime_error("Unknown FilmOutputType in Film::GetChannel<float>(): " + ToString(type));
}
}
template<> const u_int *Film::GetChannel<u_int>(const FilmChannelType type, const u_int index) {
switch (type) {
case MATERIAL_ID:
return channel_MATERIAL_ID->GetPixels();
default:
throw runtime_error("Unknown FilmOutputType in Film::GetChannel<u_int>(): " + ToString(type));
}
}
template<> void Film::GetOutput<float>(const FilmOutputs::FilmOutputType type, float *buffer, const u_int index) {
switch (type) {
case FilmOutputs::RGB: {
for (u_int i = 0; i < pixelCount; ++i)
GetPixelFromMergedSampleBuffers(i, &buffer[i * 3]);
break;
}
case FilmOutputs::RGB_TONEMAPPED:
ExecuteImagePipeline();
copy(channel_RGB_TONEMAPPED->GetPixels(), channel_RGB_TONEMAPPED->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::RGBA: {
for (u_int i = 0; i < pixelCount; ++i) {
const u_int offset = i * 4;
GetPixelFromMergedSampleBuffers(i, &buffer[offset]);
channel_ALPHA->GetWeightedPixel(i, &buffer[offset + 3]);
}
break;
}
case FilmOutputs::RGBA_TONEMAPPED: {
ExecuteImagePipeline();
float *srcRGB = channel_RGB_TONEMAPPED->GetPixels();
float *dst = buffer;
for (u_int i = 0; i < pixelCount; ++i) {
*dst++ = *srcRGB++;
*dst++ = *srcRGB++;
*dst++ = *srcRGB++;
channel_ALPHA->GetWeightedPixel(i, dst++);
}
break;
}
case FilmOutputs::ALPHA: {
for (u_int i = 0; i < pixelCount; ++i)
channel_ALPHA->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::DEPTH:
copy(channel_DEPTH->GetPixels(), channel_DEPTH->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::POSITION:
copy(channel_POSITION->GetPixels(), channel_POSITION->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::GEOMETRY_NORMAL:
copy(channel_GEOMETRY_NORMAL->GetPixels(), channel_GEOMETRY_NORMAL->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::SHADING_NORMAL:
copy(channel_SHADING_NORMAL->GetPixels(), channel_SHADING_NORMAL->GetPixels() + pixelCount * 3, buffer);
break;
case FilmOutputs::DIRECT_DIFFUSE: {
for (u_int i = 0; i < pixelCount; ++i)
channel_DIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::DIRECT_GLOSSY: {
for (u_int i = 0; i < pixelCount; ++i)
channel_DIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::EMISSION: {
for (u_int i = 0; i < pixelCount; ++i)
channel_EMISSION->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::INDIRECT_DIFFUSE: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::INDIRECT_GLOSSY: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::INDIRECT_SPECULAR: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_SPECULAR->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::MATERIAL_ID_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_MATERIAL_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::DIRECT_SHADOW_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_DIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::INDIRECT_SHADOW_MASK: {
for (u_int i = 0; i < pixelCount; ++i)
channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]);
break;
}
case FilmOutputs::RADIANCE_GROUP: {
fill(buffer, buffer + 3 * pixelCount, 0.f);
if (index < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) {
float *dst = buffer;
for (u_int i = 0; i < pixelCount; ++i) {
Spectrum c;
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->AccumulateWeightedPixel(i, c.c);
*dst++ += c.c[0];
*dst++ += c.c[1];
*dst++ += c.c[2];
}
}
if (index < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) {
float *dst = buffer;
for (u_int i = 0; i < pixelCount; ++i) {
Spectrum c;
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->AccumulateWeightedPixel(i, c.c);
*dst++ += c.c[0];
*dst++ += c.c[1];
*dst++ += c.c[2];
}
}
break;
}
case FilmOutputs::UV:
copy(channel_UV->GetPixels(), channel_UV->GetPixels() + pixelCount * 2, buffer);
break;
case FilmOutputs::RAYCOUNT:
copy(channel_RAYCOUNT->GetPixels(), channel_RAYCOUNT->GetPixels() + pixelCount, buffer);
break;
case FilmOutputs::BY_MATERIAL_ID: {
for (u_int i = 0; i < pixelCount; ++i)
channel_BY_MATERIAL_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]);
break;
}
case FilmOutputs::IRRADIANCE: {
for (u_int i = 0; i < pixelCount; ++i)
channel_IRRADIANCE->GetWeightedPixel(i, &buffer[i]);
break;
}
default:
throw runtime_error("Unknown film output type in Film::GetOutput<float>(): " + ToString(type));
}
}
template<> void Film::GetOutput<u_int>(const FilmOutputs::FilmOutputType type, u_int *buffer, const u_int index) {
switch (type) {
case FilmOutputs::MATERIAL_ID:
copy(channel_MATERIAL_ID->GetPixels(), channel_MATERIAL_ID->GetPixels() + pixelCount, buffer);
break;
default:
throw runtime_error("Unknown film output type in Film::GetOutput<u_int>(): " + ToString(type));
}
}
void Film::GetPixelFromMergedSampleBuffers(const u_int index, float *c) const {
c[0] = 0.f;
c[1] = 0.f;
c[2] = 0.f;
for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i)
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AccumulateWeightedPixel(index, c);
if (channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size() > 0) {
const float factor = statsTotalSampleCount / pixelCount;
for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) {
const float *src = channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(index);
c[0] += src[0] * factor;
c[1] += src[1] * factor;
c[2] += src[2] * factor;
}
}
}
void Film::ExecuteImagePipeline() {
if (!rgbTonemapUpdate ||
(!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) ||
!HasChannel(RGB_TONEMAPPED)) {
// Nothing to do
return;
}
// Merge all buffers
Spectrum *p = (Spectrum *)channel_RGB_TONEMAPPED->GetPixels();
const u_int pixelCount = width * height;
vector<bool> frameBufferMask(pixelCount, false);
MergeSampleBuffers(p, frameBufferMask);
// Apply the image pipeline if I have one
if (imagePipeline)
imagePipeline->Apply(*this, p, frameBufferMask);
}
void Film::MergeSampleBuffers(Spectrum *p, vector<bool> &frameBufferMask) const {
const u_int pixelCount = width * height;
// Merge RADIANCE_PER_PIXEL_NORMALIZED and RADIANCE_PER_SCREEN_NORMALIZED buffers
if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) {
for (u_int i = 0; i < radianceGroupCount; ++i) {
for (u_int j = 0; j < pixelCount; ++j) {
const float *sp = channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->GetPixel(j);
if (sp[3] > 0.f) {
if (frameBufferMask[j])
p[j] += Spectrum(sp) / sp[3];
else
p[j] = Spectrum(sp) / sp[3];
frameBufferMask[j] = true;
}
}
}
}
if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) {
const float factor = pixelCount / statsTotalSampleCount;
for (u_int i = 0; i < radianceGroupCount; ++i) {
for (u_int j = 0; j < pixelCount; ++j) {
const Spectrum s(channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(j));
if (!s.Black()) {
if (frameBufferMask[j])
p[j] += s * factor;
else
p[j] = s * factor;
frameBufferMask[j] = true;
}
}
}
}
if (!enabledOverlappedScreenBufferUpdate) {
for (u_int i = 0; i < pixelCount; ++i) {
if (!frameBufferMask[i])
p[i] = Spectrum();
}
}
}
void Film::AddSampleResultColor(const u_int x, const u_int y,
const SampleResult &sampleResult, const float weight) {
if ((channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) {
for (u_int i = 0; i < Min(sampleResult.radiancePerPixelNormalized.size(), channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()); ++i) {
if (sampleResult.radiancePerPixelNormalized[i].IsNaN() || sampleResult.radiancePerPixelNormalized[i].IsInf())
continue;
channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AddWeightedPixel(x, y, sampleResult.radiancePerPixelNormalized[i].c, weight);
}
}
// Faster than HasChannel(channel_RADIANCE_PER_SCREEN_NORMALIZED)
if ((channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) {
for (u_int i = 0; i < Min(sampleResult.radiancePerScreenNormalized.size(), channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()); ++i) {
if (sampleResult.radiancePerScreenNormalized[i].IsNaN() || sampleResult.radiancePerScreenNormalized[i].IsInf())
continue;
channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->AddWeightedPixel(x, y, sampleResult.radiancePerScreenNormalized[i].c, weight);
}
}
// Faster than HasChannel(ALPHA)
if (channel_ALPHA && sampleResult.HasChannel(ALPHA))
channel_ALPHA->AddWeightedPixel(x, y, &sampleResult.alpha, weight);
if (hasComposingChannel) {
// Faster than HasChannel(DIRECT_DIFFUSE)
if (channel_DIRECT_DIFFUSE && sampleResult.HasChannel(DIRECT_DIFFUSE))
channel_DIRECT_DIFFUSE->AddWeightedPixel(x, y, sampleResult.directDiffuse.c, weight);
// Faster than HasChannel(DIRECT_GLOSSY)
if (channel_DIRECT_GLOSSY && sampleResult.HasChannel(DIRECT_GLOSSY))
channel_DIRECT_GLOSSY->AddWeightedPixel(x, y, sampleResult.directGlossy.c, weight);
// Faster than HasChannel(EMISSION)
if (channel_EMISSION && sampleResult.HasChannel(EMISSION))
channel_EMISSION->AddWeightedPixel(x, y, sampleResult.emission.c, weight);
// Faster than HasChannel(INDIRECT_DIFFUSE)
if (channel_INDIRECT_DIFFUSE && sampleResult.HasChannel(INDIRECT_DIFFUSE))
channel_INDIRECT_DIFFUSE->AddWeightedPixel(x, y, sampleResult.indirectDiffuse.c, weight);
// Faster than HasChannel(INDIRECT_GLOSSY)
if (channel_INDIRECT_GLOSSY && sampleResult.HasChannel(INDIRECT_GLOSSY))
channel_INDIRECT_GLOSSY->AddWeightedPixel(x, y, sampleResult.indirectGlossy.c, weight);
// Faster than HasChannel(INDIRECT_SPECULAR)
if (channel_INDIRECT_SPECULAR && sampleResult.HasChannel(INDIRECT_SPECULAR))
channel_INDIRECT_SPECULAR->AddWeightedPixel(x, y, sampleResult.indirectSpecular.c, weight);
// This is MATERIAL_ID_MASK and BY_MATERIAL_ID
if (sampleResult.HasChannel(MATERIAL_ID)) {
// MATERIAL_ID_MASK
for (u_int i = 0; i < maskMaterialIDs.size(); ++i) {
float pixel[2];
pixel[0] = (sampleResult.materialID == maskMaterialIDs[i]) ? weight : 0.f;
pixel[1] = weight;
channel_MATERIAL_ID_MASKs[i]->AddPixel(x, y, pixel);
}
// BY_MATERIAL_ID
if ((channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) {
for (u_int index = 0; index < byMaterialIDs.size(); ++index) {
Spectrum c;
if (sampleResult.materialID == byMaterialIDs[index]) {
// Merge all radiance groups
for (u_int i = 0; i < Min(sampleResult.radiancePerPixelNormalized.size(), channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()); ++i) {
if (sampleResult.radiancePerPixelNormalized[i].IsNaN() || sampleResult.radiancePerPixelNormalized[i].IsInf())
continue;
c += sampleResult.radiancePerPixelNormalized[i];
}
}
channel_BY_MATERIAL_IDs[index]->AddWeightedPixel(x, y, c.c, weight);
}
}
}
// Faster than HasChannel(DIRECT_SHADOW)
if (channel_DIRECT_SHADOW_MASK && sampleResult.HasChannel(DIRECT_SHADOW_MASK))
channel_DIRECT_SHADOW_MASK->AddWeightedPixel(x, y, &sampleResult.directShadowMask, weight);
// Faster than HasChannel(INDIRECT_SHADOW_MASK)
if (channel_INDIRECT_SHADOW_MASK && sampleResult.HasChannel(INDIRECT_SHADOW_MASK))
channel_INDIRECT_SHADOW_MASK->AddWeightedPixel(x, y, &sampleResult.indirectShadowMask, weight);
// Faster than HasChannel(IRRADIANCE)
if (channel_IRRADIANCE && sampleResult.HasChannel(IRRADIANCE))
channel_IRRADIANCE->AddWeightedPixel(x, y, sampleResult.irradiance.c, weight);
}
}
void Film::AddSampleResultData(const u_int x, const u_int y,
const SampleResult &sampleResult) {
bool depthWrite = true;
// Faster than HasChannel(DEPTH)
if (channel_DEPTH && sampleResult.HasChannel(DEPTH))
depthWrite = channel_DEPTH->MinPixel(x, y, &sampleResult.depth);
if (depthWrite) {
// Faster than HasChannel(POSITION)
if (channel_POSITION && sampleResult.HasChannel(POSITION))
channel_POSITION->SetPixel(x, y, &sampleResult.position.x);
// Faster than HasChannel(GEOMETRY_NORMAL)
if (channel_GEOMETRY_NORMAL && sampleResult.HasChannel(GEOMETRY_NORMAL))
channel_GEOMETRY_NORMAL->SetPixel(x, y, &sampleResult.geometryNormal.x);
// Faster than HasChannel(SHADING_NORMAL)
if (channel_SHADING_NORMAL && sampleResult.HasChannel(SHADING_NORMAL))
channel_SHADING_NORMAL->SetPixel(x, y, &sampleResult.shadingNormal.x);
// Faster than HasChannel(MATERIAL_ID)
if (channel_MATERIAL_ID && sampleResult.HasChannel(MATERIAL_ID))
channel_MATERIAL_ID->SetPixel(x, y, &sampleResult.materialID);
// Faster than HasChannel(UV)
if (channel_UV && sampleResult.HasChannel(UV))
channel_UV->SetPixel(x, y, &sampleResult.uv.u);
}
if (channel_RAYCOUNT && sampleResult.HasChannel(RAYCOUNT))
channel_RAYCOUNT->AddPixel(x, y, &sampleResult.rayCount);
}
void Film::AddSample(const u_int x, const u_int y,
const SampleResult &sampleResult, const float weight) {
AddSampleResultColor(x, y, sampleResult, weight);
if (hasDataChannel)
AddSampleResultData(x, y, sampleResult);
}
void Film::SplatSample(const SampleResult &sampleResult, const float weight) {
if (!filter) {
const int x = Ceil2Int(sampleResult.filmX - .5f);
const int y = Ceil2Int(sampleResult.filmY - .5f);
if ((x >= 0) && (x < (int)width) && (y >= 0) && (y < (int)height)) {
AddSampleResultColor(x, y, sampleResult, weight);
if (hasDataChannel)
AddSampleResultData(x, y, sampleResult);
}
} else {
//----------------------------------------------------------------------
// Add all data related information (not filtered)
//----------------------------------------------------------------------
if (hasDataChannel) {
const int x = Ceil2Int(sampleResult.filmX - .5f);
const int y = Ceil2Int(sampleResult.filmY - .5f);
if ((x >= 0.f) && (x < (int)width) && (y >= 0.f) && (y < (int)height))
AddSampleResultData(x, y, sampleResult);
}
//----------------------------------------------------------------------
// Add all color related information (filtered)
//----------------------------------------------------------------------
// Compute sample's raster extent
const float dImageX = sampleResult.filmX - .5f;
const float dImageY = sampleResult.filmY - .5f;
const FilterLUT *filterLUT = filterLUTs->GetLUT(dImageX - floorf(sampleResult.filmX), dImageY - floorf(sampleResult.filmY));
const float *lut = filterLUT->GetLUT();
const int x0 = Ceil2Int(dImageX - filter->xWidth);
const int x1 = x0 + filterLUT->GetWidth();
const int y0 = Ceil2Int(dImageY - filter->yWidth);
const int y1 = y0 + filterLUT->GetHeight();
for (int iy = y0; iy < y1; ++iy) {
if (iy < 0) {
lut += filterLUT->GetWidth();
continue;
} else if(iy >= (int)height)
break;
for (int ix = x0; ix < x1; ++ix) {
const float filterWeight = *lut++;
if ((ix < 0) || (ix >= (int)width))
continue;
const float filteredWeight = weight * filterWeight;
AddSampleResultColor(ix, iy, sampleResult, filteredWeight);
}
}
}
}
void Film::ResetConvergenceTest() {
if (convTest)
convTest->Reset();
}
u_int Film::RunConvergenceTest() {
// Required in order to have a valid convergence test
ExecuteImagePipeline();
return convTest->Test((const float *)channel_RGB_TONEMAPPED->GetPixels());
}
Film::FilmChannelType Film::String2FilmChannelType(const std::string &type) {
if (type == "RADIANCE_PER_PIXEL_NORMALIZED")
return RADIANCE_PER_PIXEL_NORMALIZED;
else if (type == "RADIANCE_PER_SCREEN_NORMALIZED")
return RADIANCE_PER_SCREEN_NORMALIZED;
else if (type == "ALPHA")
return ALPHA;
else if (type == "DEPTH")
return DEPTH;
else if (type == "POSITION")
return POSITION;
else if (type == "GEOMETRY_NORMAL")
return GEOMETRY_NORMAL;
else if (type == "SHADING_NORMAL")
return SHADING_NORMAL;
else if (type == "MATERIAL_ID")
return MATERIAL_ID;
else if (type == "DIRECT_DIFFUSE")
return DIRECT_DIFFUSE;
else if (type == "DIRECT_GLOSSY")
return DIRECT_GLOSSY;
else if (type == "EMISSION")
return EMISSION;
else if (type == "INDIRECT_DIFFUSE")
return INDIRECT_DIFFUSE;
else if (type == "INDIRECT_GLOSSY")
return INDIRECT_GLOSSY;
else if (type == "INDIRECT_SPECULAR")
return INDIRECT_SPECULAR;
else if (type == "INDIRECT_SPECULAR")
return INDIRECT_SPECULAR;
else if (type == "MATERIAL_ID_MASK")
return MATERIAL_ID_MASK;
else if (type == "DIRECT_SHADOW_MASK")
return DIRECT_SHADOW_MASK;
else if (type == "INDIRECT_SHADOW_MASK")
return INDIRECT_SHADOW_MASK;
else if (type == "UV")
return UV;
else if (type == "RAYCOUNT")
return RAYCOUNT;
else if (type == "BY_MATERIAL_ID")
return BY_MATERIAL_ID;
else if (type == "IRRADIANCE")
return IRRADIANCE;
else
throw runtime_error("Unknown film output type in Film::String2FilmChannelType(): " + type);
}
const std::string Film::FilmChannelType2String(const Film::FilmChannelType type) {
switch (type) {
case Film::RADIANCE_PER_PIXEL_NORMALIZED:
return "RADIANCE_PER_PIXEL_NORMALIZED";
case Film::RADIANCE_PER_SCREEN_NORMALIZED:
return "RADIANCE_PER_SCREEN_NORMALIZED";
case Film::ALPHA:
return "ALPHA";
case Film::DEPTH:
return "DEPTH";
case Film::POSITION:
return "POSITION";
case Film::GEOMETRY_NORMAL:
return "GEOMETRY_NORMAL";
case Film::SHADING_NORMAL:
return "SHADING_NORMAL";
case Film::MATERIAL_ID:
return "MATERIAL_ID";
case Film::DIRECT_DIFFUSE:
return "DIRECT_DIFFUSE";
case Film::DIRECT_GLOSSY:
return "DIRECT_GLOSSY";
case Film::EMISSION:
return "EMISSION";
case Film::INDIRECT_DIFFUSE:
return "INDIRECT_DIFFUSE";
case Film::INDIRECT_GLOSSY:
return "INDIRECT_GLOSSY";
case Film::INDIRECT_SPECULAR:
return "INDIRECT_SPECULAR";
case Film::MATERIAL_ID_MASK:
return "MATERIAL_ID_MASK";
case Film::DIRECT_SHADOW_MASK:
return "DIRECT_SHADOW_MASK";
case Film::INDIRECT_SHADOW_MASK:
return "INDIRECT_SHADOW_MASK";
case Film::UV:
return "UV";
case Film::RAYCOUNT:
return "RAYCOUNT";
case Film::BY_MATERIAL_ID:
return "BY_MATERIAL_ID";
case Film::IRRADIANCE:
return "IRRADIANCE";
default:
throw runtime_error("Unknown film output type in Film::FilmChannelType2String(): " + ToString(type));
}
}
template<> void Film::load<boost::archive::binary_iarchive>(boost::archive::binary_iarchive &ar,
const u_int version) {
ar >> channel_RADIANCE_PER_PIXEL_NORMALIZEDs;
ar >> channel_RADIANCE_PER_SCREEN_NORMALIZEDs;
ar >> channel_ALPHA;
ar >> channel_RGB_TONEMAPPED;
ar >> channel_DEPTH;
ar >> channel_POSITION;
ar >> channel_GEOMETRY_NORMAL;
ar >> channel_SHADING_NORMAL;
ar >> channel_MATERIAL_ID;
ar >> channel_DIRECT_DIFFUSE;
ar >> channel_DIRECT_GLOSSY;
ar >> channel_EMISSION;
ar >> channel_INDIRECT_DIFFUSE;
ar >> channel_INDIRECT_GLOSSY;
ar >> channel_INDIRECT_SPECULAR;
ar >> channel_MATERIAL_ID_MASKs;
ar >> channel_DIRECT_SHADOW_MASK;
ar >> channel_INDIRECT_SHADOW_MASK;
ar >> channel_UV;
ar >> channel_RAYCOUNT;
ar >> channel_BY_MATERIAL_IDs;
ar >> channel_IRRADIANCE;
ar >> channels;
ar >> width;
ar >> height;
ar >> pixelCount;
ar >> radianceGroupCount;
ar >> maskMaterialIDs;
ar >> byMaterialIDs;
ar >> statsTotalSampleCount;
ar >> statsStartSampleTime;
ar >> statsAvgSampleSec;
ar >> imagePipeline;
ar >> convTest;
ar >> filter;
// filterLUTs is re-built at load time
if (filter) {
const u_int size = Max<u_int>(4, Max(filter->xWidth, filter->yWidth) + 1);
filterLUTs = new FilterLUTs(*filter, size);
} else
filterLUTs = NULL;
ar >> initialized;
ar >> enabledOverlappedScreenBufferUpdate;
ar >> rgbTonemapUpdate;
}
template<> void Film::save<boost::archive::binary_oarchive>(boost::archive::binary_oarchive &ar,
const u_int version) const {
ar << channel_RADIANCE_PER_PIXEL_NORMALIZEDs;
ar << channel_RADIANCE_PER_SCREEN_NORMALIZEDs;
ar << channel_ALPHA;
ar << channel_RGB_TONEMAPPED;
ar << channel_DEPTH;
ar << channel_POSITION;
ar << channel_GEOMETRY_NORMAL;
ar << channel_SHADING_NORMAL;
ar << channel_MATERIAL_ID;
ar << channel_DIRECT_DIFFUSE;
ar << channel_DIRECT_GLOSSY;
ar << channel_EMISSION;
ar << channel_INDIRECT_DIFFUSE;
ar << channel_INDIRECT_GLOSSY;
ar << channel_INDIRECT_SPECULAR;
ar << channel_MATERIAL_ID_MASKs;
ar << channel_DIRECT_SHADOW_MASK;
ar << channel_INDIRECT_SHADOW_MASK;
ar << channel_UV;
ar << channel_RAYCOUNT;
ar << channel_BY_MATERIAL_IDs;
ar << channel_IRRADIANCE;
ar << channels;
ar << width;
ar << height;
ar << pixelCount;
ar << radianceGroupCount;
ar << maskMaterialIDs;
ar << byMaterialIDs;
ar << statsTotalSampleCount;
ar << statsStartSampleTime;
ar << statsAvgSampleSec;
ar << imagePipeline;
ar << convTest;
ar << filter;
// filterLUTs is re-built at load time
ar << initialized;
ar << enabledOverlappedScreenBufferUpdate;
ar << rgbTonemapUpdate;
}
//------------------------------------------------------------------------------
// SampleResult
//------------------------------------------------------------------------------
void SampleResult::AddEmission(const u_int lightID, const Spectrum &pathThroughput,
const Spectrum &incomingRadiance) {
const Spectrum radiance = pathThroughput * incomingRadiance;
radiancePerPixelNormalized[lightID] += radiance;
if (firstPathVertex)
emission += radiance;
else {
indirectShadowMask = 0.f;
if (firstPathVertexEvent & DIFFUSE)
indirectDiffuse += radiance;
else if (firstPathVertexEvent & GLOSSY)
indirectGlossy += radiance;
else if (firstPathVertexEvent & SPECULAR)
indirectSpecular += radiance;
}
}
void SampleResult::AddDirectLight(const u_int lightID, const BSDFEvent bsdfEvent,
const Spectrum &pathThroughput, const Spectrum &incomingRadiance, const float lightScale) {
const Spectrum radiance = pathThroughput * incomingRadiance;
radiancePerPixelNormalized[lightID] += radiance;
if (firstPathVertex) {
// directShadowMask is supposed to be initialized to 1.0
directShadowMask = Max(0.f, directShadowMask - lightScale);
if (bsdfEvent & DIFFUSE)
directDiffuse += radiance;
else
directGlossy += radiance;
} else {
// indirectShadowMask is supposed to be initialized to 1.0
indirectShadowMask = Max(0.f, indirectShadowMask - lightScale);
if (firstPathVertexEvent & DIFFUSE)
indirectDiffuse += radiance;
else if (firstPathVertexEvent & GLOSSY)
indirectGlossy += radiance;
else if (firstPathVertexEvent & SPECULAR)
indirectSpecular += radiance;
irradiance += irradiancePathThroughput * incomingRadiance;
}
}
void SampleResult::AddSampleResult(std::vector<SampleResult> &sampleResults,
const float filmX, const float filmY,
const Spectrum &radiancePPN,
const float alpha) {
assert(!radiancePPN.IsInf() || !radiancePPN.IsNaN());
assert(!isinf(alpha) || !isnan(alpha));
const u_int size = sampleResults.size();
sampleResults.resize(size + 1);
sampleResults[size].Init(Film::RADIANCE_PER_PIXEL_NORMALIZED | Film::ALPHA, 1);
sampleResults[size].filmX = filmX;
sampleResults[size].filmY = filmY;
sampleResults[size].radiancePerPixelNormalized[0] = radiancePPN;
sampleResults[size].alpha = alpha;
}
void SampleResult::AddSampleResult(std::vector<SampleResult> &sampleResults,
const float filmX, const float filmY,
const Spectrum &radiancePSN) {
assert(!radiancePSN.IsInf() || !radiancePSN.IsNaN());
const u_int size = sampleResults.size();
sampleResults.resize(size + 1);
sampleResults[size].Init(Film::RADIANCE_PER_SCREEN_NORMALIZED, 1);
sampleResults[size].filmX = filmX;
sampleResults[size].filmY = filmY;
sampleResults[size].radiancePerScreenNormalized[0] = radiancePSN;
}
| 33.339009 | 136 | 0.693148 | DavidBluecame |
eab95df009eeed45149bf914d5a1f84f0370f35c | 934 | cpp | C++ | src/071.simplify_path/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2016-07-02T17:44:10.000Z | 2016-07-02T17:44:10.000Z | src/071.simplify_path/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | null | null | null | src/071.simplify_path/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2019-12-21T04:57:15.000Z | 2019-12-21T04:57:15.000Z | class Solution {
public:
string simplifyPath(string path) {
stack<string> s;
string ans;
int len = path.length();
if (len == 0) return ans;
int start, end;
for (int i = 0; i < len; i++) {
if (i > 0 && path[i] != '/' && path[i - 1] == '/') {
start = i - 1;
}
if (path[i] != '/' && ((i + 1 < len && path[i + 1] == '/') || (i == len - 1))) {
end = i;
string tmp = path.substr(start, end - start + 1);
if (tmp == "/.") continue;
else if (tmp == "/..") {
if (!s.empty()) s.pop();
}
else {
s.push(tmp);
}
}
}
while(!s.empty()) {
ans = s.top() + ans;
s.pop();
}
if (ans == "") ans = "/";
return ans;
}
};
| 28.30303 | 92 | 0.313704 | cloudzfy |
eab9870e3fd5d0d35a46824b7c7a469cf4a9f334 | 362 | cpp | C++ | array/Kth Row of Pascal's Triangle.cpp | 1aman1/practice-InterviewBit | cafb841bd57f74f8fc3690a7f7830e6ca9fda916 | [
"MIT"
] | 1 | 2019-08-14T05:46:57.000Z | 2019-08-14T05:46:57.000Z | array/Kth Row of Pascal's Triangle.cpp | 1aman1/practice | cafb841bd57f74f8fc3690a7f7830e6ca9fda916 | [
"MIT"
] | null | null | null | array/Kth Row of Pascal's Triangle.cpp | 1aman1/practice | cafb841bd57f74f8fc3690a7f7830e6ca9fda916 | [
"MIT"
] | null | null | null | /*
A0-> 1
A1-> 1 1
A2-> 1 2 1
A3-> 1 3 3 1
for A, pascal triangle will have A+1 elements
*/
vector<int> Solution::getRow(int A) {
vector<int> result;
int value = 1, index;
for( index = 0; index <= A ; index++){
result.push_back(value);
value = value * (A - index)/(index + 1);
}
return result;
}
| 21.294118 | 52 | 0.508287 | 1aman1 |
eabef1dd8733d3b75f83cffbbeb0509d369503f5 | 103 | cpp | C++ | addresslab.cpp | CaQtiml/CaQ-s-NOOB-LAB | a6cd2a730f2b2e6a834b1b39521052c5125150b5 | [
"MIT"
] | null | null | null | addresslab.cpp | CaQtiml/CaQ-s-NOOB-LAB | a6cd2a730f2b2e6a834b1b39521052c5125150b5 | [
"MIT"
] | null | null | null | addresslab.cpp | CaQtiml/CaQ-s-NOOB-LAB | a6cd2a730f2b2e6a834b1b39521052c5125150b5 | [
"MIT"
] | null | null | null | #include "stdio.h"
int main()
{
int b=8;
int &a=b;
printf("%d",a);
b+=2;
printf("%d",a);
} | 11.444444 | 19 | 0.466019 | CaQtiml |
eac4248c774fa43b3fac2efa59431b406736dfbb | 8,112 | cpp | C++ | aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/securityhub/model/AwsEc2VpcEndpointServiceDetails.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SecurityHub
{
namespace Model
{
AwsEc2VpcEndpointServiceDetails::AwsEc2VpcEndpointServiceDetails() :
m_acceptanceRequired(false),
m_acceptanceRequiredHasBeenSet(false),
m_availabilityZonesHasBeenSet(false),
m_baseEndpointDnsNamesHasBeenSet(false),
m_managesVpcEndpoints(false),
m_managesVpcEndpointsHasBeenSet(false),
m_gatewayLoadBalancerArnsHasBeenSet(false),
m_networkLoadBalancerArnsHasBeenSet(false),
m_privateDnsNameHasBeenSet(false),
m_serviceIdHasBeenSet(false),
m_serviceNameHasBeenSet(false),
m_serviceStateHasBeenSet(false),
m_serviceTypeHasBeenSet(false)
{
}
AwsEc2VpcEndpointServiceDetails::AwsEc2VpcEndpointServiceDetails(JsonView jsonValue) :
m_acceptanceRequired(false),
m_acceptanceRequiredHasBeenSet(false),
m_availabilityZonesHasBeenSet(false),
m_baseEndpointDnsNamesHasBeenSet(false),
m_managesVpcEndpoints(false),
m_managesVpcEndpointsHasBeenSet(false),
m_gatewayLoadBalancerArnsHasBeenSet(false),
m_networkLoadBalancerArnsHasBeenSet(false),
m_privateDnsNameHasBeenSet(false),
m_serviceIdHasBeenSet(false),
m_serviceNameHasBeenSet(false),
m_serviceStateHasBeenSet(false),
m_serviceTypeHasBeenSet(false)
{
*this = jsonValue;
}
AwsEc2VpcEndpointServiceDetails& AwsEc2VpcEndpointServiceDetails::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("AcceptanceRequired"))
{
m_acceptanceRequired = jsonValue.GetBool("AcceptanceRequired");
m_acceptanceRequiredHasBeenSet = true;
}
if(jsonValue.ValueExists("AvailabilityZones"))
{
Array<JsonView> availabilityZonesJsonList = jsonValue.GetArray("AvailabilityZones");
for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex)
{
m_availabilityZones.push_back(availabilityZonesJsonList[availabilityZonesIndex].AsString());
}
m_availabilityZonesHasBeenSet = true;
}
if(jsonValue.ValueExists("BaseEndpointDnsNames"))
{
Array<JsonView> baseEndpointDnsNamesJsonList = jsonValue.GetArray("BaseEndpointDnsNames");
for(unsigned baseEndpointDnsNamesIndex = 0; baseEndpointDnsNamesIndex < baseEndpointDnsNamesJsonList.GetLength(); ++baseEndpointDnsNamesIndex)
{
m_baseEndpointDnsNames.push_back(baseEndpointDnsNamesJsonList[baseEndpointDnsNamesIndex].AsString());
}
m_baseEndpointDnsNamesHasBeenSet = true;
}
if(jsonValue.ValueExists("ManagesVpcEndpoints"))
{
m_managesVpcEndpoints = jsonValue.GetBool("ManagesVpcEndpoints");
m_managesVpcEndpointsHasBeenSet = true;
}
if(jsonValue.ValueExists("GatewayLoadBalancerArns"))
{
Array<JsonView> gatewayLoadBalancerArnsJsonList = jsonValue.GetArray("GatewayLoadBalancerArns");
for(unsigned gatewayLoadBalancerArnsIndex = 0; gatewayLoadBalancerArnsIndex < gatewayLoadBalancerArnsJsonList.GetLength(); ++gatewayLoadBalancerArnsIndex)
{
m_gatewayLoadBalancerArns.push_back(gatewayLoadBalancerArnsJsonList[gatewayLoadBalancerArnsIndex].AsString());
}
m_gatewayLoadBalancerArnsHasBeenSet = true;
}
if(jsonValue.ValueExists("NetworkLoadBalancerArns"))
{
Array<JsonView> networkLoadBalancerArnsJsonList = jsonValue.GetArray("NetworkLoadBalancerArns");
for(unsigned networkLoadBalancerArnsIndex = 0; networkLoadBalancerArnsIndex < networkLoadBalancerArnsJsonList.GetLength(); ++networkLoadBalancerArnsIndex)
{
m_networkLoadBalancerArns.push_back(networkLoadBalancerArnsJsonList[networkLoadBalancerArnsIndex].AsString());
}
m_networkLoadBalancerArnsHasBeenSet = true;
}
if(jsonValue.ValueExists("PrivateDnsName"))
{
m_privateDnsName = jsonValue.GetString("PrivateDnsName");
m_privateDnsNameHasBeenSet = true;
}
if(jsonValue.ValueExists("ServiceId"))
{
m_serviceId = jsonValue.GetString("ServiceId");
m_serviceIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ServiceName"))
{
m_serviceName = jsonValue.GetString("ServiceName");
m_serviceNameHasBeenSet = true;
}
if(jsonValue.ValueExists("ServiceState"))
{
m_serviceState = jsonValue.GetString("ServiceState");
m_serviceStateHasBeenSet = true;
}
if(jsonValue.ValueExists("ServiceType"))
{
Array<JsonView> serviceTypeJsonList = jsonValue.GetArray("ServiceType");
for(unsigned serviceTypeIndex = 0; serviceTypeIndex < serviceTypeJsonList.GetLength(); ++serviceTypeIndex)
{
m_serviceType.push_back(serviceTypeJsonList[serviceTypeIndex].AsObject());
}
m_serviceTypeHasBeenSet = true;
}
return *this;
}
JsonValue AwsEc2VpcEndpointServiceDetails::Jsonize() const
{
JsonValue payload;
if(m_acceptanceRequiredHasBeenSet)
{
payload.WithBool("AcceptanceRequired", m_acceptanceRequired);
}
if(m_availabilityZonesHasBeenSet)
{
Array<JsonValue> availabilityZonesJsonList(m_availabilityZones.size());
for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex)
{
availabilityZonesJsonList[availabilityZonesIndex].AsString(m_availabilityZones[availabilityZonesIndex]);
}
payload.WithArray("AvailabilityZones", std::move(availabilityZonesJsonList));
}
if(m_baseEndpointDnsNamesHasBeenSet)
{
Array<JsonValue> baseEndpointDnsNamesJsonList(m_baseEndpointDnsNames.size());
for(unsigned baseEndpointDnsNamesIndex = 0; baseEndpointDnsNamesIndex < baseEndpointDnsNamesJsonList.GetLength(); ++baseEndpointDnsNamesIndex)
{
baseEndpointDnsNamesJsonList[baseEndpointDnsNamesIndex].AsString(m_baseEndpointDnsNames[baseEndpointDnsNamesIndex]);
}
payload.WithArray("BaseEndpointDnsNames", std::move(baseEndpointDnsNamesJsonList));
}
if(m_managesVpcEndpointsHasBeenSet)
{
payload.WithBool("ManagesVpcEndpoints", m_managesVpcEndpoints);
}
if(m_gatewayLoadBalancerArnsHasBeenSet)
{
Array<JsonValue> gatewayLoadBalancerArnsJsonList(m_gatewayLoadBalancerArns.size());
for(unsigned gatewayLoadBalancerArnsIndex = 0; gatewayLoadBalancerArnsIndex < gatewayLoadBalancerArnsJsonList.GetLength(); ++gatewayLoadBalancerArnsIndex)
{
gatewayLoadBalancerArnsJsonList[gatewayLoadBalancerArnsIndex].AsString(m_gatewayLoadBalancerArns[gatewayLoadBalancerArnsIndex]);
}
payload.WithArray("GatewayLoadBalancerArns", std::move(gatewayLoadBalancerArnsJsonList));
}
if(m_networkLoadBalancerArnsHasBeenSet)
{
Array<JsonValue> networkLoadBalancerArnsJsonList(m_networkLoadBalancerArns.size());
for(unsigned networkLoadBalancerArnsIndex = 0; networkLoadBalancerArnsIndex < networkLoadBalancerArnsJsonList.GetLength(); ++networkLoadBalancerArnsIndex)
{
networkLoadBalancerArnsJsonList[networkLoadBalancerArnsIndex].AsString(m_networkLoadBalancerArns[networkLoadBalancerArnsIndex]);
}
payload.WithArray("NetworkLoadBalancerArns", std::move(networkLoadBalancerArnsJsonList));
}
if(m_privateDnsNameHasBeenSet)
{
payload.WithString("PrivateDnsName", m_privateDnsName);
}
if(m_serviceIdHasBeenSet)
{
payload.WithString("ServiceId", m_serviceId);
}
if(m_serviceNameHasBeenSet)
{
payload.WithString("ServiceName", m_serviceName);
}
if(m_serviceStateHasBeenSet)
{
payload.WithString("ServiceState", m_serviceState);
}
if(m_serviceTypeHasBeenSet)
{
Array<JsonValue> serviceTypeJsonList(m_serviceType.size());
for(unsigned serviceTypeIndex = 0; serviceTypeIndex < serviceTypeJsonList.GetLength(); ++serviceTypeIndex)
{
serviceTypeJsonList[serviceTypeIndex].AsObject(m_serviceType[serviceTypeIndex].Jsonize());
}
payload.WithArray("ServiceType", std::move(serviceTypeJsonList));
}
return payload;
}
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
| 31.937008 | 158 | 0.784147 | perfectrecall |
eac6d42b898df62950c863b4f09fa22c958e6892 | 1,974 | cpp | C++ | PnC/DracoPnC/DracoStateMachine/Initialize.cpp | BharathMasetty/PnC | 3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f | [
"MIT"
] | null | null | null | PnC/DracoPnC/DracoStateMachine/Initialize.cpp | BharathMasetty/PnC | 3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f | [
"MIT"
] | null | null | null | PnC/DracoPnC/DracoStateMachine/Initialize.cpp | BharathMasetty/PnC | 3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f | [
"MIT"
] | null | null | null | #include <PnC/DracoPnC/DracoCtrlArchitecture/DracoCtrlArchitecture.hpp>
#include <PnC/DracoPnC/DracoStateMachine/Initialize.hpp>
Initialize::Initialize(const StateIdentifier state_identifier_in,
DracoControlArchitecture* _ctrl_arch,
RobotSystem* _robot)
: StateMachine(state_identifier_in, _robot) {
myUtils::pretty_constructor(2, "SM: Initialize");
// Set Pointer to Control Architecture
ctrl_arch_ = ((DracoControlArchitecture*)_ctrl_arch);
taf_container_ = ctrl_arch_->taf_container_;
// Get State Provider
sp_ = DracoStateProvider::getStateProvider(robot_);
}
Initialize::~Initialize() {}
void Initialize::firstVisit() {
std::cout << "[Initialize]" << std::endl;
ctrl_start_time_ = sp_->curr_time;
ctrl_arch_->joint_trajectory_manager_->initializeJointTrajectory(
0., end_time_, target_pos_);
}
void Initialize::_taskUpdate() {
// =========================================================================
// Joint
// =========================================================================
ctrl_arch_->joint_trajectory_manager_->updateJointDesired(
state_machine_time_);
}
void Initialize::oneStep() {
state_machine_time_ = sp_->curr_time - ctrl_start_time_;
_taskUpdate();
}
void Initialize::lastVisit() {}
bool Initialize::endOfState() {
if (state_machine_time_ > end_time_) {
return true;
}
return false;
}
StateIdentifier Initialize::getNextState() { return DRACO_STATES::STAND; }
void Initialize::initialization(const YAML::Node& node) {
try {
myUtils::readParameter(node, "target_pos_duration", end_time_);
myUtils::readParameter(node, "smoothing_duration", smoothing_dur_);
myUtils::readParameter(node, "target_pos", target_pos_);
} catch (std::runtime_error& e) {
std::cout << "Error reading parameter [" << e.what() << "] at file: ["
<< __FILE__ << "]" << std::endl
<< std::endl;
exit(0);
}
}
| 31.333333 | 78 | 0.644883 | BharathMasetty |
ead3d66d94475c5d960d55fe1aeb92b8886dbad6 | 127 | hpp | C++ | KGE/Core/Audio/ComponentAudioClip.hpp | jkeywo/KGE | 5ad2619a4e205dd549cdf638854db356a80694ea | [
"MIT"
] | 1 | 2016-08-10T14:03:29.000Z | 2016-08-10T14:03:29.000Z | KGE/Core/Audio/ComponentAudioClip.hpp | jkeywo/KGE | 5ad2619a4e205dd549cdf638854db356a80694ea | [
"MIT"
] | null | null | null | KGE/Core/Audio/ComponentAudioClip.hpp | jkeywo/KGE | 5ad2619a4e205dd549cdf638854db356a80694ea | [
"MIT"
] | null | null | null | #pragma once
#include "Core/Components/Component.hpp"
namespace KGE
{
class ComponentAudioClip : public Component
{
};
}; | 11.545455 | 44 | 0.732283 | jkeywo |
ead6a6563593a425e9fc1fd361c2c6fc2abc5b05 | 1,404 | cpp | C++ | thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 2 | 2020-05-14T07:48:32.000Z | 2021-02-03T14:58:11.000Z | thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 1 | 2020-05-28T16:39:20.000Z | 2020-05-28T16:39:20.000Z | thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 2 | 2018-07-07T20:15:00.000Z | 2018-10-26T05:18:30.000Z | // ===================================================================
//
// Description
// Contains the implementation of BBEvent
//
// Revision history
// Date Description
// 30-Nov-2012 First version
//
// ===================================================================
#include "BBEvent.h"
namespace Sfs2X {
namespace Bitswarm {
namespace BBox {
boost::shared_ptr<string> BBEvent::CONNECT (new string("bb-connect"));
boost::shared_ptr<string> BBEvent::DISCONNECT (new string("bb-disconnect"));
boost::shared_ptr<string> BBEvent::DATA (new string("bb-data"));
boost::shared_ptr<string> BBEvent::IO_ERROR (new string("bb-ioError"));
boost::shared_ptr<string> BBEvent::SECURITY_ERROR (new string("bb-securityError"));
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
BBEvent::BBEvent(boost::shared_ptr<string> type)
: BaseEvent (type, boost::shared_ptr<map<string, boost::shared_ptr<void> > >())
{
}
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
BBEvent::BBEvent(boost::shared_ptr<string> type, boost::shared_ptr<map<string, boost::shared_ptr<void> > > arguments)
: BaseEvent (type, arguments)
{
}
} // namespace BBox
} // namespace Bitswarm
} // namespace Sfs2X
| 31.909091 | 117 | 0.504274 | godot-addons |
ead740e181fb132ccf2430f21f427346276b1b97 | 1,883 | hpp | C++ | include/IStreamSocket.hpp | lordio/insanity | 7dfbf398fe08968f40a32280bf2b16cca2b476a1 | [
"MIT"
] | 1 | 2015-02-05T10:41:14.000Z | 2015-02-05T10:41:14.000Z | include/IStreamSocket.hpp | lordio/insanity | 7dfbf398fe08968f40a32280bf2b16cca2b476a1 | [
"MIT"
] | 1 | 2015-02-04T20:47:52.000Z | 2015-02-05T07:43:05.000Z | include/IStreamSocket.hpp | lordio/insanity | 7dfbf398fe08968f40a32280bf2b16cca2b476a1 | [
"MIT"
] | null | null | null | #ifndef INSANITY_INTERFACE_STREAM_SOCKET
#define INSANITY_INTERFACE_STREAM_SOCKET
#include "Constants.hpp"
#include "IObject.hpp"
namespace Insanity
{
class IByteArray;
class INSANITY_API IStreamSocket : public virtual IObject
{
public:
//=================================================
//Create a new StreamSocket
// Attempts to connect to host, at port.
// Will return an unconnected IStreamSocket if connection fails.
//=================================================
static IStreamSocket * Create(char const * host, u16 port);
//=================================================
//Communicate with remote peer.
// Silently ignores request if unconnected.
//=================================================
virtual void Send(IByteArray const * arr) = 0;
virtual void Receive(IByteArray * arr) = 0;
//=================================================
//Attempt to connect to host, at port.
// Returns false if the connection fails, true otherwise.
// Will Close() the socket if it is open.
//=================================================
virtual bool Connect(const char * host, u16 port) = 0;
//=================================================
//Stops communications on the socket.
// Returns false if socket was already not open, true otherwise.
//=================================================
virtual bool Close() = 0;
//=================================================
//Returns false if the socket is not open, or if there is no pending data.
// True otherwise.
//=================================================
virtual bool HasPendingData() const = 0;
//=================================================
//Returns true if the socket is connected to a server
// false otherwise.
//=================================================
virtual bool IsConnected() const = 0;
};
}
#endif | 34.236364 | 76 | 0.478492 | lordio |
eaeaee7f2c260beb4af190c606e353fb56f190f5 | 1,356 | cpp | C++ | IndependentSet.cpp | manoelstilpen/clique_problem | bf1c9711128b9173301d9ff4d1ad2f837f7f523e | [
"MIT"
] | null | null | null | IndependentSet.cpp | manoelstilpen/clique_problem | bf1c9711128b9173301d9ff4d1ad2f837f7f523e | [
"MIT"
] | null | null | null | IndependentSet.cpp | manoelstilpen/clique_problem | bf1c9711128b9173301d9ff4d1ad2f837f7f523e | [
"MIT"
] | 1 | 2019-07-02T13:55:23.000Z | 2019-07-02T13:55:23.000Z | #include "IndependentSet.hpp"
IndependentSet::IndependentSet(){
definedGraph = false;
}
IndependentSet::IndependentSet(Graph _graph){
setGraph(_graph);
}
int IndependentSet::searchLargestIndependentSet(){
for(int k=0 ; k<graph.getNVertex() ; k++){
vector<int> vertex_list(graph.getNVertex());
iota(vertex_list.begin(), vertex_list.end(), 0);
// crescent ordering
sort(vertex_list.begin(), vertex_list.end(), [&](const int& a, const int& b){
return graph.getNAdjacencyOf(a) > graph.getNAdjacencyOf(b);
});
for(int i=k ; i<vertex_list.size()+k ; i++){
int index;
if(i >= vertex_list.size())
index = vertex_list[i-vertex_list.size()];
else
index = vertex_list[i];
for(int j=0 ; j<vertex_list.size() ; j++){
}
}
/*
for(int j=0 ; j<tam_list ; j++){
if(graph->complement[index][vertex_list[j]] == 1){
if(j < i) i--;
remove_index(vertex_list,tam_list,j);
graph->nAdjacencies[vertex_list[j]]--;
tam_list--;
j--;
}
}
}
if(tam_list > max){
max = tam_list;
history = copy_array(vertex_list, tam_list);
}
free(vertex_list); */
}
}
void IndependentSet::setGraph(Graph _graph){
graph = _graph;
} | 22.229508 | 85 | 0.558997 | manoelstilpen |
eaf0865ae2f420e0b3dd47bcee0fa3c845fbd082 | 953 | cpp | C++ | Ruminate/src/HelperFiles/a_funcs.cpp | Riku32/Ruminate | 0855384c2abb24f2552688561ff90bd555ef3c07 | [
"MIT"
] | null | null | null | Ruminate/src/HelperFiles/a_funcs.cpp | Riku32/Ruminate | 0855384c2abb24f2552688561ff90bd555ef3c07 | [
"MIT"
] | null | null | null | Ruminate/src/HelperFiles/a_funcs.cpp | Riku32/Ruminate | 0855384c2abb24f2552688561ff90bd555ef3c07 | [
"MIT"
] | null | null | null | #include "HelperFiles/a_funcs.hpp"
//relu
inline float Relu(float x)
{
return (x > 0) * x;
}
inline float ReluPrime(float x)
{
return x > 0;
}
//leaky relu
inline float ReluLeaky(float x)
{
if (x < 0)
{
return x * A;
}
else
{
return x;
}
}
inline float ReluLeakyPrime(float x)
{
if (x < 0)
{
return A;
}
else
{
return 1;
}
}
//tanh
inline float Tanh(float x)
{
return tanh(x);
}
inline float TanhPrime(float x)
{
return sinh(x) / cosh(x);
}
//sigmoid
inline float Sigmoid(float x)
{
return 1 / (1 + exp(-x));
}
inline float SigmoidPrime(float x)
{
return exp(-x) / std::pow(1 + exp(-x), 2);
}
//swish
inline float Swish(float x)
{
return x * Sigmoid(x);
}
inline float SwishPrime(float x)
{
return (exp(x) * (exp(x) + x + 1)) / std::pow(exp(x) + 1, 2);
}
| 12.878378 | 66 | 0.499475 | Riku32 |
eaf608c4845378c97f1a955f5533efa1e5c2b962 | 8,845 | cpp | C++ | src/corder.cpp | Cetus-K/corder | cd635c3bf49f578952d65393270a9a980841299e | [
"MIT"
] | null | null | null | src/corder.cpp | Cetus-K/corder | cd635c3bf49f578952d65393270a9a980841299e | [
"MIT"
] | null | null | null | src/corder.cpp | Cetus-K/corder | cd635c3bf49f578952d65393270a9a980841299e | [
"MIT"
] | null | null | null | #include "corder.h"
// corder destructor
corder::~corder() {
vector < int > ().swap(l);
vector < int > ().swap(item);
vector < int > ().swap(sitem);
vector < vector < int > > ().swap(stypeindex);
vector < vector < int > > ().swap(stypelist);
vector < string > ().swap(mode);
vector < string > ().swap(type);
vector < vector < string > > ().swap(stype);
stypelist.clear();
}
// the type of i-th index ion
int corder::mytype ( int idx ) {
int itype,cnt = 0;
for ( itype=0; itype<ntypes; itype++ ) {
cnt += item[itype];
if ( idx < cnt ) break;
}
return itype;
}
// the address that start itype ion indices
// range: [ mystart(a), mystart(a)+item[a] )
int corder::mystart ( int itype ) {
int cnt = 0;
for ( int a=0; a<itype; a++ ) cnt += item[a];
return cnt;
}
// update
double corder::update ( double prev, double add ) {
return ( (double)(itr-f0)/df*prev+add )/((double)(itr-f0)/df+1.0);
}
// main control
int main(int argc, char* argv[]){
// declare
int rank,nmpi; // mpi rank ans its size
double scale; // lattice scale
double beg,time,prog; // progress
map < string,bool > mode; // calc mode
vec cfg(3); // vector and matrix class
ifstream ifs; // fstream
istringstream iss;
string str;
corder co; // corder basis class
// set corder parameter
co.set_param();
// calculation mode
mode["gofr"] = false; // g(r),gab(r)
mode["sofq"] = false; // s(q),sab(q)
mode["dfc"] = false; // msd,msda,<v>,<va>
mode["lboo"] = false; // ql,wl,qlab,wlab
mode["bacf"] = false; // gl(r),glabab(r)
mode["pofqw"] = false; // p(ql),p(wl),p(qlab),p(wlab)
mode["bofree"] = false; // f,fl,fll,fab,flab,fllab
mode["povoro"] = false; // dump trajectory as pov-ray format
mode["csform"] = false; // counting each sharing formations
// dependence parameter
mode["covoro"] = false; // engine for lboo/bacf/pofqw/bofree/voro
mode["coqhull"] = false; // engine for ...
mode["instant"] = false; // instantsneous calculation for write out
for ( int i=0; i<(int)co.mode.size(); i++ ) mode[co.mode[i]] = true;
// dependency
mode["sofq"] = mode["sofq"] and mode["gofr"];
mode["covoro"] = mode["lboo"] or mode["bacf"] or mode["pofqw"] or mode["bofree"] or mode["csform"] or mode["povoro"] or mode["csform"];
mode["instant"] = !( mode["bacf"] or mode["pofqw"] or mode["bofree"] or mode["csform"] );
// check read
if ( co.f1 < co.f0 ) co.f1 = grep_c("XDATCAR","Direct");
// memory allocation:
co.config.resize(co.nions);
for ( int i=0; i<co.nions; i++ ) co.config[i].resize(3);
// initialize
// each class related to mode
// create copy constructor by refference handling
gofr co_gofr(co); co_gofr.init();
sofq co_sofq(co); co_sofq.init();
dfc co_dfc(co); co_dfc.init();
covoro co_covoro(co); co_covoro.init();
lboo co_lboo(co,co_covoro); co_lboo.init();
bacf co_bacf(co,co_covoro); co_bacf.init();
pofqw co_pofqw(co,co_covoro); co_pofqw.init();
bofree co_bofree(co,co_covoro); co_bofree.init();
povoro co_povoro(co,co_covoro);
coqhull co_coqhull(co); co_coqhull.init();
coqhull co_cv_coqhull(co,co_covoro); co_cv_coqhull.init();
csform co_csform(co,co_covoro,co_cv_coqhull); co_csform.init();
// MPI environment
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&nmpi);
MPI_Barrier(MPI_COMM_WORLD);
beg = prog = MPI_Wtime();
// read XDATCAR and skip initial lines without axis at latdyn = false
ifs.open("XDATCAR",ios::in);
if ( !co.latdyn ) for ( int i=0; i<7; i++ ) getline(ifs,str);
// dump system information
if ( rank == 0 ) {
co.info();
cout << endl;
cout << "------------------" << endl;
cout << " Progress" << endl;
cout << "------------------" << endl;
cout << endl;
cout << "Iteration ( completion [%] ) : 1 dump-step cpu time ( total ) [s]" << endl;
cout << "-----------------------------------------------------------------" << endl;
}
MPI_Barrier(MPI_COMM_WORLD);
// iterator init
co.itr = 0;
while ( co.itr<=co.f1 && !ifs.eof() ) {
co.itr ++;
if ( ( co.f0<=co.itr && co.itr<=co.f1 && (co.itr-co.f0)%co.df==0 ) || co.itr==co.f1 ) {
// if lattice dynamics is true
// read lattice system
if ( co.latdyn ) {
// label
getline(ifs,str);
// scale
getline(ifs,str); iss.str(str);
iss >> scale; iss.clear();
// lattice vector >> transform matrix
getline(ifs,str); iss.str(str);
iss >> co.a1(0) >> co.a1(1) >> co.a1(2);
iss.clear(); co.a1 *= scale;
getline(ifs,str); iss.str(str);
iss >> co.a2(0) >> co.a2(1) >> co.a2(2);
iss.clear(); co.a2 *= scale;
getline(ifs,str); iss.str(str);
iss >> co.a3(0) >> co.a3(1) >> co.a3(2);
iss.clear(); co.a3 *= scale;
for ( int i=0; i<3; i++ ) co.latmat(i,0) = co.a1(i);
for ( int i=0; i<3; i++ ) co.latmat(i,1) = co.a2(i);
for ( int i=0; i<3; i++ ) co.latmat(i,2) = co.a3(i);
// type ands item
for ( int i=0; i<2; i++ ) getline(ifs,str);
}
// axis line
getline(ifs,str);
// configuration
for ( int i=0; i<co.nions; i++ ) {
getline(ifs,str); iss.str(str);
for ( int j=0; j<3; j++ ) iss >> cfg(j);
co.config[i] = co.latmat*cfg;
iss.clear();
}
MPI_Barrier(MPI_COMM_WORLD);
// update mode
if ( mode["gofr"] ) {
co_gofr.set(co);
co_gofr.update(rank,nmpi);
}
MPI_Barrier(MPI_COMM_WORLD);
// not using so far
// if ( mode["sofq"] ) {
// co_sofq.set(co);
// MPI_Barrier(MPI_COMM_WORLD);
// }
if ( mode["dfc"] && rank == 0 ) {
co_dfc.set(co);
co_dfc.update();
}
MPI_Barrier(MPI_COMM_WORLD);
if ( mode["covoro"] && !mode["instant"] ) {
co_covoro.set(co);
co_covoro.get();
for ( int a=0; a<co.ntypes; a++ ) {
for ( int b=0; b<co.ntypes; b++ ) {
co_covoro.pget(a,b);
}
}
for ( int spa=0; spa<co.nstypes; spa++ ) {
for ( int spb=0; spb<co.nstypes; spb++ ) {
co_covoro.spget(spa,spb);
}
}
}
MPI_Barrier(MPI_COMM_WORLD);
// not using so far
// if ( mode["lboo"] && rank == 0 ) {
// co_lboo.set(co,co_covoro);
// MPI_Barrier(MPI_COMM_WORLD);
// }
if ( mode["bacf"] ) {
co_bacf.set(co,co_covoro);
co_bacf.update(rank,nmpi);
}
MPI_Barrier(MPI_COMM_WORLD);
if ( mode["pofqw"] && rank == 0 ) {
co_pofqw.set(co,co_covoro);
co_pofqw.update();
}
MPI_Barrier(MPI_COMM_WORLD);
if ( mode["bofree"] && ( (co.itr-co.f0) % (co.df*co.dump) == 0 || co.itr==co.f1 ) ) {
co_bofree.set(co,co_covoro);
co_bofree.update(rank,nmpi);
}
MPI_Barrier(MPI_COMM_WORLD);
if ( mode["csform"] ) {
co_cv_coqhull.set(co,co_covoro);
co_csform.get();
co_csform.pget();
co_csform.spget();
co_csform.update(rank,nmpi);
}
MPI_Barrier(MPI_COMM_WORLD);
// write out
if ( ( (co.itr-co.f0) % (co.df*co.dump) == 0 || co.itr==co.f1 ) && rank == 0 ) {
// write out
if ( mode["gofr"] ) co_gofr.write("gofr");
if ( mode["sofq"] ) {
co_sofq.set(co);
co_sofq.write("sofq",&co_gofr);
}
if ( mode["dfc"] ) co_dfc.write("dfc");
if ( mode["lboo"] ) {
if ( mode["covoro"] && mode["instant"] ) {
co_covoro.set(co);
co_covoro.get();
for ( int a=0; a<co.ntypes; a++ ) {
for ( int b=0; b<co.ntypes; b++ ) {
co_covoro.pget(a,b);
}
}
for ( int spa=0; spa<co.nstypes; spa++ ) {
for ( int spb=0; spb<co.nstypes; spb++ ) {
co_covoro.spget(spa,spb);
}
}
}
co_lboo.set(co,co_covoro);
co_lboo.write("lboo");
}
if ( mode["bacf"] ) co_bacf.write("bacf");
if ( mode["pofqw"] ) co_pofqw.write("pofqw");
if ( mode["bofree"] ) co_bofree.write("bofree");
if ( mode["povoro"] ) {
if ( mode["covoro"] && mode["instant"] ) {
co_covoro.set(co);
co_covoro.get();
for ( int a=0; a<co.ntypes; a++ ) {
for ( int b=0; b<co.ntypes; b++ ) {
co_covoro.pget(a,b);
}
}
for ( int spa=0; spa<co.nstypes; spa++ ) {
for ( int spb=0; spb<co.nstypes; spb++ ) {
co_covoro.spget(spa,spb);
}
}
}
co_povoro.set(co,co_covoro);
co_povoro.write("povoro");
for ( int a=0; a<co.ntypes; a++ ) {
for ( int b=0; b<co.ntypes; b++ ) {
co_povoro.pwrite("povoro",a,b);
}
}
}
if ( mode["csform"] ) {
co_csform.write("csform");
}
// dump progress
time = MPI_Wtime();
cout << co.itr << " ( " << (double)(co.itr-co.f0+1)/(double)(co.f1-co.f0+1)*100.0 << " )";
cout << " : " << time-prog << " ( " << time-beg << " )" << endl;
prog = time;
}
MPI_Barrier(MPI_COMM_WORLD);
} else {
// skip
if ( co.latdyn ) for ( int i=0; i<7; i++ ) getline(ifs,str);
getline(ifs,str); // axis
for ( int i=0; i<co.nions; i++ ) getline(ifs,str);
}
}
MPI_Barrier(MPI_COMM_WORLD);
ifs.close();
MPI_Finalize();
// free
mode.clear();
return 0;
}
| 28.905229 | 136 | 0.5645 | Cetus-K |
46bf4a0966c2e91a134128a667d39e6c9919746f | 8,978 | cpp | C++ | src/terark/io/MemStream.cpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 44 | 2020-12-21T05:14:38.000Z | 2022-03-15T11:27:32.000Z | src/terark/io/MemStream.cpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 2 | 2020-12-28T10:42:03.000Z | 2021-05-21T07:22:47.000Z | src/terark/io/MemStream.cpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 21 | 2020-12-22T09:40:16.000Z | 2021-12-07T18:16:00.000Z | /* vim: set tabstop=4 : */
#include "MemStream.hpp"
#include <stdlib.h>
#include <algorithm>
#include <stdexcept>
#include <typeinfo>
#include <errno.h>
#if defined(_MSC_VER)
# include <intrin.h>
#pragma intrinsic(_BitScanReverse)
//#pragma intrinsic(_BitScanReverse64)
#endif
#include <boost/predef/other/endian.h>
#include <terark/num_to_str.hpp>
#include <stdarg.h>
#include "var_int.hpp"
namespace terark {
//void MemIO_Base::skip(ptrdiff_t diff)
void throw_EndOfFile(const char* func, size_t want, size_t available)
{
string_appender<> oss;
oss << "in " << func << ", want=" << want
<< ", available=" << available
// << ", tell=" << tell() << ", size=" << size()
;
throw EndOfFileException(oss.str().c_str());
}
void throw_OutOfSpace(const char* func, size_t want, size_t available)
{
string_appender<> oss;
oss << "in " << func << ", want=" << want
<< ", available=" << available
// << ", tell=" << tell() << ", size=" << size()
;
throw OutOfSpaceException(oss.str().c_str());
}
void MemIO::throw_EndOfFile(const char* func, size_t want)
{
terark::throw_EndOfFile(func, want, remain());
}
void MemIO::throw_OutOfSpace(const char* func, size_t want)
{
terark::throw_OutOfSpace(func, want, remain());
}
//////////////////////////////////////////////////////////////////////////
void SeekableMemIO::seek(ptrdiff_t newPos)
{
assert(newPos >= 0);
if (newPos < 0 || newPos > m_end - m_beg) {
string_appender<> oss;
size_t curr_size = m_end - m_beg;
oss << "in " << BOOST_CURRENT_FUNCTION
<< "[newPos=" << newPos << ", size=" << curr_size << "]";
// errno = EINVAL;
throw std::invalid_argument(oss.str());
}
m_pos = m_beg + newPos;
}
void SeekableMemIO::seek(ptrdiff_t offset, int origin)
{
size_t pos;
switch (origin)
{
default:
{
string_appender<> oss;
oss << "in " << BOOST_CURRENT_FUNCTION
<< "[offset=" << offset << ", origin=" << origin << "(invalid)]";
// errno = EINVAL;
throw std::invalid_argument(oss.str().c_str());
}
case 0: pos = (size_t)(0 + offset); break;
case 1: pos = (size_t)(tell() + offset); break;
case 2: pos = (size_t)(size() + offset); break;
}
seek(pos);
}
// rarely used methods....
//
std::pair<byte*, byte*> SeekableMemIO::range(size_t ibeg, size_t iend) const
{
assert(ibeg <= iend);
assert(ibeg <= size());
assert(iend <= size());
if (ibeg <= iend && ibeg <= size() && iend <= size())
{
return std::pair<byte*, byte*>(m_beg + ibeg, m_beg + iend);
}
string_appender<> oss;
oss << BOOST_CURRENT_FUNCTION
<< ": size=" << size()
<< ", tell=" << tell()
<< ", ibeg=" << ibeg
<< ", iend=" << iend
;
throw std::invalid_argument(oss.str());
}
//////////////////////////////////////////////////////////////////////////
AutoGrownMemIO::AutoGrownMemIO(size_t size)
{
if (size) {
m_beg = (byte*)malloc(size);
if (NULL == m_beg) {
#ifdef _MSC_VER_FUCK
char szMsg[128];
sprintf(szMsg
, "AutoGrownMemIO::AutoGrownMemIO(size=%lu)"
, (unsigned long)size
);
throw std::bad_alloc(szMsg);
#else
throw std::bad_alloc();
#endif
}
m_end = m_beg + size;
m_pos = m_beg;
}
else
m_pos = m_end = m_beg = NULL;
}
AutoGrownMemIO::~AutoGrownMemIO()
{
if (m_beg)
free(m_beg);
}
void AutoGrownMemIO::clone(const AutoGrownMemIO& src)
{
AutoGrownMemIO t(src.size());
memcpy(t.begin(), src.begin(), src.size());
this->swap(t);
}
/**
@brief 改变 buffer 尺寸
不改变 buffer 中的已存内容,不改变 pos
@note must m_pos <= newsize
*/
void AutoGrownMemIO::resize(size_t newsize)
{
assert(tell() <= newsize);
if (newsize < tell()) {
THROW_STD(length_error,
"newsize=%zd is less than tell()=%zd", newsize, tell());
}
#ifdef _MSC_VER
size_t oldsize = size();
#endif
byte* newbeg = (byte*)realloc(m_beg, newsize);
if (newbeg) {
m_pos = newbeg + (m_pos - m_beg);
m_end = newbeg + newsize;
m_beg = newbeg;
}
else {
#ifdef _MSC_VER_FUCK
string_appender<> oss;
oss << "realloc failed in \"void AutoGrownMemIO::resize(size[new=" << newsize << ", old=" << oldsize
<< "])\", the AutoGrownMemIO object is not mutated!";
throw std::bad_alloc(oss.str().c_str());
#else
throw std::bad_alloc();
#endif
}
}
void AutoGrownMemIO::grow(size_t nGrow) {
size_t oldsize = m_end - m_beg;
size_t newsize = oldsize + nGrow;
size_t newcap = std::max<size_t>(32, oldsize);
while (newcap < newsize) newcap *= 2;
resize(newcap);
}
/**
@brief 释放原先的空间并重新分配
相当于按新尺寸重新构造一个新 AutoGrownMemIO
不需要把旧内容拷贝到新地址
*/
void AutoGrownMemIO::init(size_t newsize)
{
#ifdef _MSC_VER
size_t oldsize = (size_t)(m_beg - m_beg);
#endif
if (m_beg)
::free(m_beg);
if (newsize) {
m_beg = (byte*)::malloc(newsize);
if (NULL == m_beg) {
m_pos = m_end = NULL;
#ifdef _MSC_VER_FUCK
char szMsg[128];
sprintf(szMsg
, "malloc failed in AutoGrownMemIO::init(newsize=%lu), oldsize=%lu"
, (unsigned long)newsize
, (unsigned long)oldsize
);
throw std::bad_alloc(szMsg);
#else
throw std::bad_alloc();
#endif
}
m_pos = m_beg;
m_end = m_beg + newsize;
}
else
m_pos = m_end = m_beg = NULL;
}
void AutoGrownMemIO::growAndWrite(const void* data, size_t length)
{
using namespace std;
size_t nSize = size();
size_t nGrow = max(length, nSize);
resize(max(nSize + nGrow, (size_t)64u));
memcpy(m_pos, data, length);
m_pos += length;
}
void AutoGrownMemIO::growAndWriteByte(byte b)
{
using namespace std;
resize(max(2u * size(), (size_t)64u));
*m_pos++ = b;
}
void AutoGrownMemIO::clear() {
if (this->m_beg) {
::free(this->m_beg);
this->m_beg = NULL;
this->m_end = NULL;
this->m_pos = NULL;
}
else {
assert(NULL == this->m_end);
assert(NULL == this->m_pos);
}
}
/**
* shrink allocated memory to fit this->tell()
*/
void AutoGrownMemIO::shrink_to_fit() {
if (NULL == m_beg) {
assert(NULL == m_pos);
assert(NULL == m_end);
}
else {
assert(m_beg <= m_pos);
assert(m_pos <= m_end);
size_t realsize = m_pos - m_beg;
if (0 == realsize) {
::free(m_beg);
m_beg = m_end = m_pos = NULL;
}
else {
byte* newbeg = (byte*)realloc(m_beg, realsize);
assert(NULL != newbeg);
if (NULL == newbeg) {
// realloc should always success on shrink
abort();
}
m_end = m_pos = newbeg + realsize;
m_beg = newbeg;
}
}
}
size_t AutoGrownMemIO::printf(const char* format, ...)
{
va_list ap;
size_t n;
va_start(ap, format);
n = this->vprintf(format, ap);
va_end(ap);
return n;
}
size_t AutoGrownMemIO::vprintf(const char* format, va_list ap)
{
if (m_end - m_pos < 64) {
this->resize(std::max<size_t>(64, (m_end-m_beg)*2));
}
while (1) {
ptrdiff_t n, size = m_end - m_pos;
#if defined(va_copy)
va_list ap_copy;
va_copy(ap_copy, ap);
n = ::vsnprintf((char*)m_pos, size, format, ap_copy);
va_end(ap_copy);
#else
n = ::vsnprintf((char*)m_pos, size, format, ap);
#endif
/* If that worked, return the written bytes. */
if (n > -1 && n < size) {
m_pos += n;
return n;
}
/* Else try again with more space. */
if (n > -1) /* glibc 2.1 */
size = n+1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
this->resize((m_pos - m_beg + size) * 2);
}
}
///////////////////////////////////////////////////////
//
#if defined(__GLIBC__) || defined(__CYGWIN__)
ssize_t
MemIO_FILE_read(void *cookie, char *buf, size_t size)
{
MemIO* input = (MemIO*)cookie;
return input->read(buf, size);
}
ssize_t
AutoGrownMemIO_FILE_write(void *cookie, const char *buf, size_t size)
{
AutoGrownMemIO* output = (AutoGrownMemIO*)cookie;
return output->write(buf, size);
}
#if defined(__CYGWIN__)
int AutoGrownMemIO_FILE_seek(void* cookie, _off64_t* offset, int whence)
#else
int AutoGrownMemIO_FILE_seek(void* cookie, off64_t* offset, int whence)
#endif
{
AutoGrownMemIO* output = (AutoGrownMemIO*)cookie;
try {
output->seek(*offset, whence);
*offset = output->tell();
return 0;
}
catch (const std::exception& e) {
errno = EINVAL;
return -1;
}
}
/**
* @note must call fclose after use of returned FILE
*/
FILE* MemIO::forInputFILE()
{
cookie_io_functions_t func = {
MemIO_FILE_read,
NULL,
NULL,
NULL
};
void* cookie = this;
assert(cookie);
FILE* fp = fopencookie(cookie,"r", func);
if (fp == NULL) {
perror("fopencookie@MemIO::getInputFILE");
return NULL;
}
return fp;
}
/**
* @note must call fclose after use of returned FILE
*/
FILE* AutoGrownMemIO::forFILE(const char* mode)
{
cookie_io_functions_t func = {
MemIO_FILE_read,
AutoGrownMemIO_FILE_write,
AutoGrownMemIO_FILE_seek,
NULL
};
void* cookie = this;
assert(cookie);
FILE* fp = fopencookie(cookie, mode, func);
if (fp == NULL) {
perror("fopencookie@AutoGrownMemIO::forOutputFILE");
return NULL;
}
return fp;
}
#endif
#define STREAM_READER MinMemIO
#define STREAM_WRITER MinMemIO
#include "var_int_io.hpp"
#define STREAM_READER MemIO
#define STREAM_WRITER MemIO
#include "var_int_io.hpp"
#define STREAM_WRITER AutoGrownMemIO
#include "var_int_io.hpp"
} // namespace terark
| 21.124706 | 102 | 0.631989 | rockeet |
46c7a76985f5d3f9668922bd594d87318ead7fe1 | 1,040 | cpp | C++ | AtCoder/abc161/E.cpp | noobie7/Codes | 4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4 | [
"MIT"
] | 2 | 2021-09-14T15:57:24.000Z | 2022-03-18T14:11:04.000Z | AtCoder/abc161/E.cpp | noobie7/Codes | 4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4 | [
"MIT"
] | null | null | null | AtCoder/abc161/E.cpp | noobie7/Codes | 4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4 | [
"MIT"
] | null | null | null | /*
"Do I really belong in this game I ponder, I just wanna play my part."
- Guts over fear, Eminem
*/
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define ff first
#define Shazam ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ss second
#define all(c) c.begin(),c.end()
#define endl "\n"
#define test() int t; cin>>t; while(t--)
#define fl(i,a,b) for(int i = a ; i <b ;i++)
#define get(a) fl(i,0,a.size()) cin>>a[i];
#define pra(a) fl(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
#define pr(a,n) fl(i,0,n) cout<<a[i]<<" "; cout<<endl;
const ll INF = 2e18;
const int inf = 2e9;
const int mod1 = 1e9 + 7;
int main(){
Shazam;
int n,c,k; cin>>n>>k>>c;
string s; cin>>s;
vector<int> a,b;
for(int i = 0 ; i < n ; i++) if(s[i]=='o'){a.push_back(i); i+=c;}
for(int i = n-1; i >=0; i--) if(s[i]=='o'){b.push_back(i); i-=c;}
for(int i = 0 ; i < k ; i++) {if(a[i]==b[k-1-i]) cout<<a[i]+1<<endl;}
return 0;
} | 29.714286 | 81 | 0.575962 | noobie7 |
46cdd8004bd7e3f2911eb9073495f88913ee36c7 | 2,051 | cpp | C++ | LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp | a4org/Angorithm4 | d2227d36608491bed270375bcea67fbde134209a | [
"MIT"
] | 3 | 2021-07-26T15:58:45.000Z | 2021-09-08T14:55:11.000Z | LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp | a4org/Angorithm4 | d2227d36608491bed270375bcea67fbde134209a | [
"MIT"
] | null | null | null | LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp | a4org/Angorithm4 | d2227d36608491bed270375bcea67fbde134209a | [
"MIT"
] | 2 | 2021-05-31T11:27:59.000Z | 2021-10-03T13:26:00.000Z | /*
* LeetCode 3 Longest Substring Without Repeating Characters
* Medium
* Shuo Feng
* 2021.9.15
*/
/*
* Solution 1:
* Begin with a starting point and check characters after, update a set and record the maximum size.
* When meet a repeating character, remove the previous point in set till there have not repeat, change starting point in " s ".
*
* a b c a b c b b Longest Substring:
* Begin ↑(Find repeat) (abc)
* a b c a b c b b
* Begin ↑ (bca)
* a b c a b c b b
* Begin ↑ (cab)
* a b c a b c b b
* Begin ↑ (abc)
* a b c a b c b b
* Begin ↑ (bc)
* a b c a b c b b
* Begin ↑ (cb)
* a b c a b c b b
* Begin ↑ (b)
* a b c a b c b b
* Begin (b)
*/
#include<iostream>
#include<string>
#include<utility>
#include<unordered_set>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int size = s.size();
if (size < 2) return size;
int max_size = 0;
int Begin = 0; // Begining place.
unordered_set <char> search;
for (int i = 0; i < size; ++i) {
// Search in set.
// Repetitive.
while (search.find(s[i]) != search.end()) {
search.erase(s[Begin]);
Begin += 1; // Begin with next point.
}
// non_Repetitive.
search.insert(s[i]);
max_size = max(max_size, i - Begin + 1);
}
return max_size;
}
};
| 32.046875 | 130 | 0.387128 | a4org |
46cf676f19bb9b2850daf5c31dd6fa692a4b68ff | 2,789 | cpp | C++ | sources/Page.cpp | khsabrina/notebook-b | 5ab09040f7b3658314239148a54a45747a918b22 | [
"MIT"
] | null | null | null | sources/Page.cpp | khsabrina/notebook-b | 5ab09040f7b3658314239148a54a45747a918b22 | [
"MIT"
] | null | null | null | sources/Page.cpp | khsabrina/notebook-b | 5ab09040f7b3658314239148a54a45747a918b22 | [
"MIT"
] | null | null | null | #include "Row.hpp"
#include "Page.hpp"
using namespace std;
#include <iostream>
#include <iterator>
#include <map>
const int LENGHT_ROW=100;
Page::Page(){
}
void Page::add(int col,int row,Direction dir, string str){
if(dir == Direction::Horizontal){
int size = str.size();
if (col + size > LENGHT_ROW){
throw invalid_argument{"You can't write here1"};
}
if (!rows.contains(row)){
Row New;
rows.insert({row, New});
rows[row].add(col,str);
}
else{
rows[row].check_horizontal(col, str.size());
//if(!check){return;}
rows[row].add(col,str);
}
}
if(dir == Direction::Vertical){
for(int i= 0; i<str.size();i++){
if(!rows.contains(row+i)){
Row New;
rows.insert({row+i, New});
}
else{
rows[row+i].check_vertical(col);
//if(!check){return;}
}
}
for(int i=0; i<str.size();i++){
string c(1, (char)str[(unsigned long)i]);
rows[row+i].add(col,c);
}
}
}
string Page::read(int col,int row,Direction dir, int size){
string ans;
if(dir == Direction::Horizontal){
if (col + size > LENGHT_ROW){
throw invalid_argument{"You can't write here"};
}
if(!rows.contains(row)){
Row New;
rows.insert({row, New});
}
ans = rows[row].read(col,size);
}
else{
if (col > LENGHT_ROW){
throw invalid_argument{"You can't write here"};
}
for(int i=0; i<size; i++){
if(!rows.contains(row+i)){
Row New;
rows.insert({row+i, New});
}
ans += rows[row+i].read(col,1);
}
}
return ans;
}
void Page::erase(int col,int row, Direction dir , int size){
if(dir == Direction::Horizontal){
if (col + size > LENGHT_ROW){
cout << "here5";
throw invalid_argument{"You can't write here4"};
return;
}
if(!rows.contains(row)){
Row New;
rows.insert({row, New});
}
rows[row].erase(col,size);
}
else{
for(int i=0; i<size; i++){
if(!rows.contains(row+i)){
Row New;
rows.insert({row+i, New});
}
rows[row+i].erase(col,1);
}
}
}
void Page::show(){
map<int, Row>::iterator itr;
for (itr = rows.begin(); itr != rows.end(); ++itr) {
cout << itr->first << ".";
itr->second.show();
cout << '\n';
}
}
// Page::~Page(){
// return;
// }
| 24.901786 | 64 | 0.453926 | khsabrina |
46d9f66e3002849d353f2a3c08eb1ff530d8bd2a | 334 | hpp | C++ | include/Btk/impl/mixer.hpp | BusyStudent/Btk | 27b23aa77e4fbcc48bdfe566ce7cae46183c289c | [
"MIT"
] | 2 | 2021-06-19T08:21:38.000Z | 2021-08-15T21:37:30.000Z | include/Btk/impl/mixer.hpp | BusyStudent/Btk | 27b23aa77e4fbcc48bdfe566ce7cae46183c289c | [
"MIT"
] | null | null | null | include/Btk/impl/mixer.hpp | BusyStudent/Btk | 27b23aa77e4fbcc48bdfe566ce7cae46183c289c | [
"MIT"
] | 1 | 2021-04-03T14:27:39.000Z | 2021-04-03T14:27:39.000Z | #if !defined(_BTK_IMPL_MIXER)
#define _BTK_IMPL_MIXER
//Implment for mixer
#include <SDL2/SDL_audio.h>
#include <SDL2/SDL_error.h>
#include <SDL2/SDL_rwops.h>
#include "../mixer.hpp"
#include "../rwops.hpp"
#include "../function.hpp"
#include "atomic.hpp"
#include <vector>
#include <mutex>
#include <list>
#endif // _BTK_IMPL_MIXER
| 20.875 | 29 | 0.730539 | BusyStudent |
46ef9733080898aed1ced4a6f987e79f1a761388 | 3,766 | cpp | C++ | src/network/socket.cpp | leezhenghui/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 351 | 2016-10-12T14:06:09.000Z | 2022-03-24T14:53:54.000Z | src/network/socket.cpp | leezhenghui/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 7 | 2017-03-07T01:49:16.000Z | 2018-07-27T08:51:54.000Z | src/network/socket.cpp | UncP/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 62 | 2016-10-31T12:46:45.000Z | 2021-12-28T11:25:26.000Z | /**
* > Author: UncP
* > Github: www.github.com/UncP/Mushroom
* > License: BSD-3
* > Time: 2017-04-23 10:23:53
**/
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cassert>
#include <cerrno>
#include "socket.hpp"
namespace Mushroom {
Socket::Socket():fd_(-1) { }
Socket::Socket(int fd):fd_(fd) { }
Socket::~Socket() { }
int Socket::fd() const
{
return fd_;
}
bool Socket::Valid() const
{
return fd_ != -1;
}
bool Socket::Create()
{
fd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
return fd_ != -1;
}
bool Socket::Close()
{
bool flag = true;
if (fd_ != -1) {
flag = !close(fd_);
fd_ = -1;
}
return flag;
}
bool Socket::Connect(const EndPoint &end_point)
{
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(end_point.Port());
server.sin_addr.s_addr = end_point.Address();
return !connect(fd_, (const struct sockaddr *)&server, sizeof(server));
}
bool Socket::Bind(uint16_t port)
{
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
return !bind(fd_, (const struct sockaddr *)&server, sizeof(server));
}
bool Socket::Listen()
{
return !listen(fd_, 32);
}
int Socket::Accept()
{
struct sockaddr_in client;
memset(&client, 0, sizeof(client));
socklen_t len = sizeof(client);
int fd = accept(fd_, (struct sockaddr *)&client, &len);
return fd;
}
bool Socket::SetOption(int value, bool flag)
{
return !setsockopt(fd_, SOL_SOCKET, value, &flag, sizeof(flag));
}
bool Socket::GetOption(int value, int *ret)
{
socklen_t len = sizeof(*ret);
return !getsockopt(fd_, SOL_SOCKET, value, ret, &len);
}
bool Socket::SetResuseAddress()
{
int flag = 1;
return !setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
}
bool Socket::GetPeerName(EndPoint *endpoint)
{
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
socklen_t len = sizeof(addr);
if (!getsockname(fd_, (struct sockaddr *)&addr, &len)) {
*endpoint = EndPoint(ntohs(addr.sin_port), addr.sin_addr.s_addr);
return true;
}
return false;
}
bool Socket::GetSockName(EndPoint *endpoint)
{
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
socklen_t len = sizeof(addr);
if (!getpeername(fd_, (struct sockaddr *)&addr, &len)) {
*endpoint = EndPoint(ntohs(addr.sin_port), addr.sin_addr.s_addr);
return true;
}
return false;
}
bool Socket::AddFlag(int flag)
{
int value = fcntl(fd_, F_GETFL, 0);
assert(value != -1);
return !fcntl(fd_, F_SETFL, value | flag);
}
bool Socket::SetNonBlock()
{
int value = fcntl(fd_, F_GETFL, 0);
assert(value != -1);
return !fcntl(fd_, F_SETFL, value | O_NONBLOCK);
}
uint32_t Socket::Write(const char *data, uint32_t len, bool *blocked)
{
uint32_t written = 0;
for (; written < len;) {
ssize_t r = write(fd_, data + written, len - written);
if (r > 0) {
written += r;
continue;
} else if (r == -1) {
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
*blocked = true;
break;
}
}
printf("write error, %s :(\n", strerror(errno));
break;
}
return written;
}
uint32_t Socket::Read(char *data, uint32_t len, bool *blocked)
{
uint32_t has_read = 0;
ssize_t r;
for (; has_read < len && (r = read(fd_, data + has_read, len - has_read));) {
if (r == -1) {
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK)
*blocked = true;
else
printf("read error, %s :(\n", strerror(errno));
break;
}
has_read += r;
}
return has_read;
}
} // namespace Mushroom
| 20.467391 | 78 | 0.648168 | leezhenghui |
46f35ad0d1bfa320692ae6d13de0007a229878f3 | 130 | cpp | C++ | nano/src/nano/nano.cpp | lyLoveSharon/nano | aa768a241a4ea282f83ccd088561a5eefd59d342 | [
"Apache-2.0"
] | null | null | null | nano/src/nano/nano.cpp | lyLoveSharon/nano | aa768a241a4ea282f83ccd088561a5eefd59d342 | [
"Apache-2.0"
] | null | null | null | nano/src/nano/nano.cpp | lyLoveSharon/nano | aa768a241a4ea282f83ccd088561a5eefd59d342 | [
"Apache-2.0"
] | null | null | null | #include "nano/nano.h"
const char *nano_version()
{
return "0.0.1";
}
const char *nano_module_name()
{
return "nano";
}
| 10.833333 | 30 | 0.623077 | lyLoveSharon |
46f7ea9131f1e0f8f0ac7885da9e48173eabfb30 | 1,208 | cpp | C++ | ModeChoice/Household_List.cpp | kravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | 2 | 2018-04-27T11:07:02.000Z | 2020-04-24T06:53:21.000Z | ModeChoice/Household_List.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | ModeChoice/Household_List.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | //*********************************************************
// Household_List.cpp - read the household list file
//*********************************************************
#include "ModeChoice.hpp"
#include "Utility.hpp"
//---------------------------------------------------------
// Household_List
//---------------------------------------------------------
void ModeChoice::Household_List (void)
{
int hhold, nfile;
for (nfile=0; ; nfile++) {
if (hhlist_file.Extend ()) {
if (nfile > 0) {
if (!hhlist_file.Open (nfile)) return;
}
Show_Message ("Reading %s %s -- Record", hhlist_file.File_Type (), hhlist_file.Extension ());
} else {
if (nfile > 0) return;
Show_Message ("Reading %s -- Record", hhlist_file.File_Type ());
}
Set_Progress ();
//---- store the household list ----
while (hhlist_file.Read ()) {
Show_Progress ();
Get_Integer (hhlist_file.Record (), &hhold);
if (hhold <= 0) continue;
if (!hhold_list.Add (hhold)) {
Error ("Adding Household %d to the List", hhold);
}
}
End_Progress ();
}
hhlist_file.Close ();
Print (2, "Total Number of Household List Records = %d", hhold_list.Num_Records ());
hhold_list.Optimize ();
}
| 24.16 | 96 | 0.508278 | kravitz |
46fc87995f5fde8b171405aa8a3901dc788264c8 | 1,186 | cpp | C++ | SRC/2018ICPC/Web_XuZhou/H.cpp | YouDad/ACM | ac26e0b360267943af32692629d6c34e739ee70d | [
"MIT"
] | 2 | 2018-07-27T08:09:48.000Z | 2018-09-26T16:36:37.000Z | SRC/2018ICPC/Web_XuZhou/H.cpp | YouDad/ACM | ac26e0b360267943af32692629d6c34e739ee70d | [
"MIT"
] | null | null | null | SRC/2018ICPC/Web_XuZhou/H.cpp | YouDad/ACM | ac26e0b360267943af32692629d6c34e739ee70d | [
"MIT"
] | null | null | null | // https://nanti.jisuanke.com/t/31460
#include<stdio.h>
#include<string.h>
typedef long long ll;
const int maxn=100005;
ll arr[(1<<18)+2],iarr[(1<<18)+2],M;
void update(ll*a,int x,ll val){
for(a[x+=M]=val,x/=2;x;x/=2)
a[x]=a[2*x]+a[2*x+1];
}
ll query(ll*a,int l,int r){
ll ans=0;
for(l+=M-1,r+=M+1;l^r^1;l/=2,r/=2){
if(~l&1)ans+=a[l^1];
if( r&1)ans+=a[r^1];
}
return ans;
}
int main(){
#ifdef LOCAL_DEBUG
freopen("E:/ACM/SRC/1.txt","r",stdin);
#endif
for(int n,q;~scanf("%d%d",&n,&q);){
M=1;while(M-2<n)M*=2;
for(int i=M+1;i<=M+n;i++)
scanf("%lld",arr+i);
for(int i=M+1;i<=M+n;i++)
iarr[i]=arr[i]*(M+n+1-i);
for(int i=M;i;i--)
arr[i]=arr[i*2]+arr[i*2+1],
iarr[i]=iarr[i*2]+iarr[i*2+1];
for(int op,l;q--;){
ll r;
scanf("%d%d%lld",&op,&l,&r);
if(op==1){
ll ret1=query(arr,l,r);
ll ret2=query(iarr,l,r);
printf("%lld\n",ret2-ret1*(n-r));
}else{
update(arr,l,r);
update(iarr,l,(n+1-l)*r);
}
}
}
return 0;
} | 25.782609 | 49 | 0.436762 | YouDad |
46fd94f34eb507d75cdb0864c86d48bb91ffe0fc | 1,936 | cc | C++ | app/oxs/base/lock.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | app/oxs/base/lock.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | app/oxs/base/lock.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | /* FILE: lock.cc -*-Mode: c++-*-
*
* Data structure locking class
*
*/
#include "oc.h"
#include "lock.h"
#include "oxsexcept.h"
OC_USE_STD_NAMESPACE; // Specify std namespace, if supported
/* End includes */
OC_UINT4m Oxs_Lock::id_count=0;
Oxs_Lock::~Oxs_Lock()
{
if(write_lock>0)
OXS_THROW(Oxs_BadLock,"Delete with open write lock");
if(read_lock>0)
OXS_THROW(Oxs_BadLock,"Delete with open read lock(s)");
if(dep_lock>0)
OXS_THROW(Oxs_BadLock,"Delete with open dep lock(s)");
obj_id=0;
}
// Assignment operator does not copy lock counts, but
// does check access restrictions. obj_id is copied
// if there are no outstanding locks and obj_id>0.
Oxs_Lock& Oxs_Lock::operator=(const Oxs_Lock& other)
{
if(read_lock>0)
OXS_THROW(Oxs_BadLock,"Assignment attempt over open read lock(s)");
if(write_lock==0) {
// This is the no-lock situation
if(other.obj_id!=0) {
obj_id = other.obj_id;
} else {
// Take the next valid id
if((obj_id = ++id_count)==0) {
obj_id = ++id_count; // Safety
// Wrap around. For now make this fatal.
OXS_THROW(Oxs_BadLock,"Lock count id overflow.");
}
}
}
// if write_lock>0, then presumably obj_id is already 0.
return *this;
}
OC_BOOL Oxs_Lock::SetDepLock()
{
++dep_lock;
return 1;
}
OC_BOOL Oxs_Lock::ReleaseDepLock()
{
if(dep_lock<1) return 0;
--dep_lock;
return 1;
}
OC_BOOL Oxs_Lock::SetReadLock()
{
if(write_lock) return 0;
++read_lock;
return 1;
}
OC_BOOL Oxs_Lock::ReleaseReadLock()
{
if(read_lock<1) return 0;
--read_lock;
return 1;
}
OC_BOOL Oxs_Lock::SetWriteLock()
{
if(read_lock>0 || write_lock>0) return 0;
write_lock=1;
obj_id=0;
return 1;
}
OC_BOOL Oxs_Lock::ReleaseWriteLock()
{
if(write_lock!=1) return 0;
if((obj_id = ++id_count)==0) {
// Wrap around. Might want to issue a warning.
obj_id = ++id_count;
}
write_lock=0;
return 1;
}
| 19.555556 | 71 | 0.658058 | ViennaNovoFlop |
46fe7414e6a5c9bc077c601133632078f87b21aa | 6,197 | cc | C++ | libsrc/pylith/faults/FaultCohesiveTract.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | 1 | 2021-01-20T17:18:28.000Z | 2021-01-20T17:18:28.000Z | libsrc/pylith/faults/FaultCohesiveTract.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | null | null | null | libsrc/pylith/faults/FaultCohesiveTract.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | null | null | null | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "FaultCohesiveTract.hh" // implementation of object methods
#include "CohesiveTopology.hh" // USES CohesiveTopology
#include "pylith/topology/Fields.hh" // USES Fields
#include "pylith/topology/Field.hh" // USES Field
#include "pylith/topology/Stratum.hh" // USES StratumIS
#include "pylith/feassemble/Quadrature.hh" // USES Quadrature
#include <cassert> // USES assert()
#include <sstream> // USES std::ostringstream
#include <stdexcept> // USES std::runtime_error
// ----------------------------------------------------------------------
// Default constructor.
pylith::faults::FaultCohesiveTract::FaultCohesiveTract(void)
{ // constructor
_useLagrangeConstraints = false;
} // constructor
// ----------------------------------------------------------------------
// Destructor.
pylith::faults::FaultCohesiveTract::~FaultCohesiveTract(void)
{ // destructor
deallocate();
} // destructor
// ----------------------------------------------------------------------
// Deallocate PETSc and local data structures.
void
pylith::faults::FaultCohesiveTract::deallocate(void)
{ // deallocate
PYLITH_METHOD_BEGIN;
FaultCohesive::deallocate();
PYLITH_METHOD_END;
} // deallocate
// ----------------------------------------------------------------------
// Initialize fault. Determine orientation and setup boundary
void
pylith::faults::FaultCohesiveTract::initialize(const topology::Mesh& mesh,
const PylithScalar upDir[3])
{ // initialize
PYLITH_METHOD_BEGIN;
assert(upDir);
assert(_quadrature);
delete _faultMesh; _faultMesh = new topology::Mesh();
CohesiveTopology::createFaultParallel(_faultMesh, mesh, id(), label(), useLagrangeConstraints());
// Reset fields.
delete _fields; _fields = new topology::Fields(*_faultMesh);assert(_fields);
// Initialize quadrature geometry.
_quadrature->initializeGeometry();
PYLITH_METHOD_END;
} // initialize
// ----------------------------------------------------------------------
// Integrate contribution of cohesive cells to residual term.
void
pylith::faults::FaultCohesiveTract::integrateResidual(const topology::Field& residual,
const PylithScalar t,
topology::SolutionFields* const fields)
{ // integrateResidual
throw std::logic_error("FaultCohesiveTract::integrateResidual() not implemented.");
} // integrateResidual
// ----------------------------------------------------------------------
// Compute Jacobian matrix (A) associated with operator.
void
pylith::faults::FaultCohesiveTract::integrateJacobian(topology::Jacobian* jacobian,
const PylithScalar t,
topology::SolutionFields* const fields)
{ // integrateJacobian
throw std::logic_error("FaultCohesiveTract::integrateJacobian() not implemented.");
_needNewJacobian = false;
} // integrateJacobian
// ----------------------------------------------------------------------
// Verify configuration is acceptable.
void
pylith::faults::FaultCohesiveTract::verifyConfiguration(const topology::Mesh& mesh) const
{ // verifyConfiguration
PYLITH_METHOD_BEGIN;
assert(_quadrature);
const PetscDM dmMesh = mesh.dmMesh();assert(dmMesh);
PetscBool hasLabel = PETSC_FALSE;
PetscErrorCode err = DMHasLabel(dmMesh, label(), &hasLabel);PYLITH_CHECK_ERROR(err);
if (!hasLabel) {
std::ostringstream msg;
msg << "Mesh missing group of vertices '" << label()
<< " for boundary condition.";
throw std::runtime_error(msg.str());
} // if
// check compatibility of mesh and quadrature scheme
const int dimension = mesh.dimension()-1;
if (_quadrature->cellDim() != dimension) {
std::ostringstream msg;
msg << "Dimension of reference cell in quadrature scheme ("
<< _quadrature->cellDim()
<< ") does not match dimension of cells in mesh ("
<< dimension << ") for fault '" << label()
<< "'.";
throw std::runtime_error(msg.str());
} // if
const int numCorners = _quadrature->refGeometry().numCorners();
const bool includeOnlyCells = true;
topology::StratumIS cohesiveIS(dmMesh, "material-id", id(), includeOnlyCells);
const PetscInt* cells = cohesiveIS.points();
const PetscInt ncells = cohesiveIS.size();
PetscInt coneSize = 0;
for (PetscInt i=0; i < ncells; ++i) {
err = DMPlexGetConeSize(dmMesh, cells[i], &coneSize);PYLITH_CHECK_ERROR(err);
// TODO: Should be changed to Closure()
if (2*numCorners != coneSize) {
// No Lagrange vertices, just negative and positive sides of the
// fault, so coneSize is 2*numCorners.
std::ostringstream msg;
msg << "Number of vertices in reference cell (" << numCorners
<< ") is not compatible with number of vertices (" << coneSize
<< ") in cohesive cell " << cells[i] << " for fault '"
<< label() << "'.";
throw std::runtime_error(msg.str());
} // if
} // for
PYLITH_METHOD_END;
} // verifyConfiguration
// ----------------------------------------------------------------------
// Get vertex field associated with integrator.
const pylith::topology::Field&
pylith::faults::FaultCohesiveTract::vertexField(const char* name,
const topology::SolutionFields* fields)
{ // vertexField
throw std::logic_error("FaultCohesiveTract::vertexField() not implemented.");
} // vertexField
// ----------------------------------------------------------------------
// Get cell field associated with integrator.
const pylith::topology::Field&
pylith::faults::FaultCohesiveTract::cellField(const char* name,
const topology::SolutionFields* fields)
{ // cellField
throw std::logic_error("FaultCohesiveTract::cellField() not implemented.");
} // cellField
// End of file
| 34.237569 | 99 | 0.619977 | joegeisz |
46ffcc9c9c990a00d3ce0571090b9f9ef3d5f5e1 | 507 | cpp | C++ | p205/p205.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | 1 | 2019-10-07T05:00:21.000Z | 2019-10-07T05:00:21.000Z | p205/p205.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | p205/p205.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | class Solution {
public:
bool isIsomorphic(string s, string t) {
if (s.length() != t.length())
return false;
int n = s.length();
vector<char> from(260,'#'),to(260,'#');
for (int i = 0; i < n; ++i)
{
if (from[t[i]] == '#' && to[s[i]] == '#')
{
from[t[i]] = s[i];
to[s[i]] = t[i];
}
else
if (from[t[i]] != s[i] || to[s[i]] != t[i])
return false;
}
return true;
}
};
| 22.043478 | 52 | 0.368836 | suzyz |
2002db0faa04c7cbb83a2d9acf6bcb78b4a028bd | 2,966 | cpp | C++ | 06-class-design/readerEx.06.06/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | 81 | 2018-11-15T21:23:19.000Z | 2022-03-06T09:46:36.000Z | 06-class-design/readerEx.06.06/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | null | null | null | 06-class-design/readerEx.06.06/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | 41 | 2018-11-15T21:23:24.000Z | 2022-02-24T03:02:26.000Z | // TODO: FIX ME! Does not handle delta between dates correctly.
//
// main.cpp
//
// This program exercises the Calendar interface exported in calendar.h.
//
// --------------------------------------------------------------------------
// Attribution: "Programming Abstractions in C++" by Eric Roberts
// Chapter 6, Exercise 6
// Stanford University, Autumn Quarter 2012
// http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf
// --------------------------------------------------------------------------
//
// Created by Glenn Streiff on 12/17/15.
// Copyright © 2015 Glenn Streiff. All rights reserved.
//
#include <iostream>
#include "calendar.h"
const std::string HEADER = "CS106B Programming Abstractions in C++: Ex 6.6\n";
const std::string DETAIL = "Extend the calendar.h interface even more.";
const std::string BANNER = HEADER + DETAIL;
int main(int argc, char * argv[]) {
std::cout << BANNER << std::endl << std::endl;
Date moonLanding1(JULY, 20, 1969);
Date moonLanding2(20, JULY, 1969);
Date earlier(JULY, 20, 1969);
Date sameAsEarlier(JULY, 20, 1969);
Date later(JULY, 21, 1969);
Date later2(AUGUST, 19, 1969);
if (earlier < later) {
std::cout << "[PASS] " << earlier << " is earlier than "
<< later << std::endl;
} else {
std::cout << "[FAIL] " << earlier << " is later than "
<< later << std::endl;
}
if (earlier < later2) {
std::cout << "[PASS] " << earlier << " is earlier than "
<< later2 << std::endl;
} else {
std::cout << "[FAIL] " << earlier << " is later than "
<< later2 << std::endl;
}
if (earlier == sameAsEarlier) {
std::cout << "[PASS] " << earlier << " is same as "
<< sameAsEarlier << std::endl;
} else {
std::cout << "[FAIL] " << earlier << " is later than "
<< sameAsEarlier << std::endl;
}
if (later > earlier) {
std::cout << "[PASS] " << later << " is later than "
<< earlier << std::endl;
} else {
std::cout << "[FAIL] " << later << " is earlier than "
<< earlier << std::endl;
}
if (earlier != later) {
std::cout << "[PASS] " << earlier << " is not equal to "
<< later << std::endl;
} else {
std::cout << "[FAIL] " << earlier << " is equal to "
<< later << std::endl;
}
// Add overloaded '<<' operator.
std::cout << std::endl << moonLanding1 << std::endl;
std::cout << moonLanding2 << std::endl;
Date date(DECEMBER, 31, 1898);
//Date date(FEBRUARY, 28, 1900);
std::cout << toEpochDay(date) << std::endl;
std::cout << toDate(1) << std::endl;
std::cout << toDate(2) << std::endl;
std::cout << toDate(0) << std::endl;
std::cout << toDate(-1) << std::endl;
return 0;
}
| 31.892473 | 91 | 0.50472 | heavy3 |
200ae272cc1adb37009bf64dc648c03075bdad2c | 8,195 | cpp | C++ | src/rotoSolver/fileUtils.cpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 47 | 2016-07-27T07:22:06.000Z | 2021-08-17T13:08:19.000Z | src/rotoSolver/fileUtils.cpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 1 | 2016-09-24T06:04:39.000Z | 2016-09-25T10:34:19.000Z | src/rotoSolver/fileUtils.cpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 13 | 2016-07-27T10:44:35.000Z | 2020-07-01T21:08:33.000Z | /**************************************************************************
** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):
**
** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds
** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell
**
** w.li AT cs.ucl.ac.uk
** http://visual.cs.ucl.ac.uk/pubs/rotopp
**
** Copyright (c) 2016, Wenbin Li
** 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 and data 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.
**
** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA 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 "include/rotoSolver/fileUtils.hpp"
#include "include/rotoSolver/eigenUtils.hpp"
#include <gflags/gflags.h>
#include <fstream>
DECLARE_bool(use_planar_tracker_weights);
// The missing string trim function - v. useful..
// Taken from http://www.codeproject.com/KB/stl/stdstringtrim.aspx
void trim( string& str )
{
string::size_type pos = str.find_last_not_of(' ');
if (pos != string::npos)
{
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if (pos != string::npos)
str.erase(0, pos);
}
else
{
str.erase(str.begin(), str.end());
}
}
void removeWhiteSpace(string& str)
{
trim(str);
std::vector<char> charsToRemove({'\t', '\r', '\n'});
//for (const char c : charsToRemove)
for (int i = 0; i < charsToRemove.size(); i++)
{
const char c = charsToRemove[i];
str.erase(std::remove(str.begin(), str.end(), c), str.end());
}
trim(str);
}
string readLineFromFile(FilePtr& fp)
{
const int maxLen = 2048;
char buffer[maxLen];
if(std::fgets(buffer, maxLen, fp)==NULL)
cout << "";
buffer[maxLen-1] = '\0';
string line(buffer);
removeWhiteSpace(line);
return line;
}
void SaveSolverOutputFile(string textFilename,
const Matrix& Data,
const int startIdx,
const int stopIdx)
{
const int NUM_VALUES_PER_ROTO_POINT = 6;
int D = Data.cols();
nassert (remainder(D, NUM_VALUES_PER_ROTO_POINT) == 0);
D /= NUM_VALUES_PER_ROTO_POINT;
std::ofstream ofs(textFilename.c_str());
ofs << D << "\n";
ofs << startIdx << " " << stopIdx << "\n";
ofs << Data.transpose();
ofs.close();
std::cout << "Saved output to \"" << textFilename << "\"." << std::endl;
}
TrackingDataType TrackingDataTypeMapper(string str)
{
removeWhiteSpace(str);
if (str.compare("forward") == 0)
return ForwardPlanar;
else if (str.compare("backward") == 0)
return BackwardPlanar;
else if (str.compare("point") == 0)
return Point;
return Unknown;
}
string TrackingDataTypeToString(const TrackingDataType& t)
{
switch (t)
{
case (ForwardPlanar):
return "ForwardPlanar";
break;
case (BackwardPlanar):
return "BackwardPlanar";
break;
case (Point):
return "Point";
break;
case (Unknown):
default:
return "Unknown";
break;
}
}
PlanarTrackingData::PlanarTrackingData(string txtFilename)
{
DataType = Unknown;
FilePtr fp(txtFilename.c_str(), "r");
OrigFileName = txtFilename;
ShapeName = readLineFromFile(fp);
KeyFrames.clear();
std::stringstream keyFramesStr(readLineFromFile(fp));
while (!keyFramesStr.eof())
{
try
{
int i = -1;
keyFramesStr >> i;
if (i > 0)
KeyFrames.push_back(i);
}
catch (...)
{}
}
std::sort(KeyFrames.begin(), KeyFrames.end());
StartIndex = *(std::min_element(KeyFrames.begin(), KeyFrames.end()));
EndIndex = *(std::max_element(KeyFrames.begin(), KeyFrames.end()));
NumFrames = EndIndex - StartIndex + 1;
//std::vector<int> ptID;
std::vector<Eigen::VectorXd> data;
std::stringstream sstream;
int numFramesOfData = -1;
while (!feof(fp))
{
Eigen::VectorXd v(NumFrames);
int pt = -1;
int numRead = 0;
std::stringstream s(readLineFromFile(fp));
s.exceptions(std::stringstream::failbit | std::stringstream::badbit);
try
{
if (feof(fp))
{
break;
}
s >> pt;
if (pt < 0)
{
break;
}
for (int i = 0; i < NumFrames; ++i)
{
s >> v[i];
++numRead;
}
if (s.bad())
{
break;
}
}
catch (...)
{
}
if (numFramesOfData < 0)
numFramesOfData = numRead;
if (numRead == numFramesOfData)
{
PointIDs.push_back(pt);
data.push_back(v.head(numFramesOfData));
}
else
{
break;
}
}
DataType = TrackingDataTypeMapper(sstream.str());
vdbg(DataType);
vdbg(numFramesOfData);
vdbg(data.size());
TrackingData.resize(numFramesOfData, data.size());
for(int i = 0; i < data.size(); i++){
Eigen::VectorXd v = data[i];
TrackingData.col(i) = v;
}
FrameWeights = Eigen::VectorXd::Ones(NumFrames);
vdbg(FLAGS_use_planar_tracker_weights);
if (FLAGS_use_planar_tracker_weights)
{
SetFrameWeights();
}
}
void PlanarTrackingData::SaveToOutputFile(const string textFilename) const
{
SaveSolverOutputFile(textFilename, TrackingData, StartIndex, EndIndex);
}
void PlanarTrackingData::SetFrameWeights()
{
typedef Eigen::Matrix<double, 1, 1> Vector1d;
double startWeight = 0.0;
double stopWeight = 0.0;
switch (DataType)
{
case Unknown:
case Point:
return;
break;
case ForwardPlanar:
startWeight = 1.0;
stopWeight = 0.0;
break;
case BackwardPlanar:
startWeight = 0.0;
stopWeight = 1.0;
break;
}
// REMEMBER TO TAKE THE SQUARING OF THE COST INTO ACCOUNT..
for (int i = 0, I = KeyFrames.size() - 1; i < I; ++i)
{
const int a = KeyFrames[i] - StartIndex;
const int b = KeyFrames[i+1] - StartIndex;
Interpolator<int> interp(a, b, Vector1d::Constant(startWeight), Vector1d::Constant(stopWeight));
for (int k = a+1; k < b; ++k)
{
nassert (k < NumFrames);
FrameWeights.row(k) = interp.get(k);
}
}
vdbg(FrameWeights.transpose());
}
void PlanarTrackingData::Print() const
{
vdbg(ShapeName);
vdbg(NumFrames);
vdbg(StartIndex);
vdbg(EndIndex);
vdbg(TrackingData.rows());
vdbg(TrackingData.cols());
vdbg(TrackingData(0,0));
vdbg(TrackingData(0,1));
vdbg(TrackingData(1,0));
vdbg(TrackingData(TrackingData.rows()-1, TrackingData.cols()-1));
}
| 25.29321 | 104 | 0.587065 | vinben |
200aeed19c847f9e7f6959f2f19a9af7eee99f9e | 2,251 | cpp | C++ | questions/68721681/app/main.cpp | xGreat/stackoverflow | b9a404a5c93eb764dc58a57484d7b86dc5016579 | [
"MIT"
] | 302 | 2017-03-04T00:05:23.000Z | 2022-03-28T22:51:29.000Z | questions/68721681/app/main.cpp | xGreat/stackoverflow | b9a404a5c93eb764dc58a57484d7b86dc5016579 | [
"MIT"
] | 30 | 2017-12-02T19:26:43.000Z | 2022-03-28T07:40:36.000Z | questions/68721681/app/main.cpp | xGreat/stackoverflow | b9a404a5c93eb764dc58a57484d7b86dc5016579 | [
"MIT"
] | 388 | 2017-07-04T16:53:12.000Z | 2022-03-18T22:20:19.000Z | #include "foointerface.h"
#include <QDir>
#include <QGuiApplication>
#include <QPluginLoader>
#include <QQmlApplicationEngine>
#include <QTimer>
#include <QTranslator>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QTranslator appTranslator;
qDebug() << "appTranslator Loaded?:" << appTranslator.load(":/languages/app.qm");
QTranslator pluginTranslator;
qDebug() << "pluginTranslator Loaded?:" << pluginTranslator.load(":/languages/plugin.qm");
FooInterface *fooInterface = nullptr;
QDir pluginsDir(QCoreApplication::applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS") {
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
const QStringList entries = pluginsDir.entryList(QDir::Files);
for (const QString &fileName : entries) {
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader.instance();
if (plugin) {
fooInterface = qobject_cast<FooInterface *>(plugin);
if (fooInterface)
break;
pluginLoader.unload();
}
}
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [fooInterface](){
qDebug() << fooInterface->print();
});
timer.start(1000);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
QTimer::singleShot(1000, &engine, [&](){
QCoreApplication::instance()->installTranslator(&appTranslator);
QCoreApplication::instance()->installTranslator(&pluginTranslator);
engine.retranslate();
});
return app.exec();
}
| 30.013333 | 97 | 0.646379 | xGreat |
200d9fcf6cacbb73137ca211017c7b3b49bc9990 | 54,260 | inl | C++ | Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/Engine/Foundation/Basics/Platform/Android/AndroidJni.inl | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | struct ezJniModifiers
{
enum Enum
{
PUBLIC = 1,
PRIVATE = 2,
PROTECTED = 4,
STATIC = 8,
FINAL = 16,
SYNCHRONIZED = 32,
VOLATILE = 64,
TRANSIENT = 128,
NATIVE = 256,
INTERFACE = 512,
ABSTRACT = 1024,
STRICT = 2048,
};
};
ezJniObject::ezJniObject(jobject object, ezJniOwnerShip ownerShip)
: m_class(nullptr)
{
switch (ownerShip)
{
case ezJniOwnerShip::OWN:
m_object = object;
m_own = true;
break;
case ezJniOwnerShip::COPY:
m_object = ezJniAttachment::GetEnv()->NewLocalRef(object);
m_own = true;
break;
case ezJniOwnerShip::BORROW:
m_object = object;
m_own = false;
break;
}
}
ezJniObject::ezJniObject(const ezJniObject& other)
: m_class(nullptr)
{
m_object = ezJniAttachment::GetEnv()->NewLocalRef(other.m_object);
m_own = true;
}
ezJniObject::ezJniObject(ezJniObject&& other)
{
m_object = other.m_object;
m_class = other.m_class;
m_own = other.m_own;
other.m_object = nullptr;
other.m_class = nullptr;
other.m_own = false;
}
ezJniObject& ezJniObject::operator=(const ezJniObject& other)
{
if (this == &other)
return *this;
Reset();
m_object = ezJniAttachment::GetEnv()->NewLocalRef(other.m_object);
m_own = true;
return *this;
}
ezJniObject& ezJniObject::operator=(ezJniObject&& other)
{
if (this == &other)
return *this;
Reset();
m_object = other.m_object;
m_class = other.m_class;
m_own = other.m_own;
other.m_object = nullptr;
other.m_class = nullptr;
other.m_own = false;
return *this;
}
ezJniObject::~ezJniObject()
{
Reset();
}
void ezJniObject::Reset()
{
if (m_object && m_own)
{
ezJniAttachment::GetEnv()->DeleteLocalRef(m_object);
m_object = nullptr;
m_own = false;
}
if (m_class)
{
ezJniAttachment::GetEnv()->DeleteLocalRef(m_class);
m_class = nullptr;
}
}
jobject ezJniObject::GetJObject() const
{
return m_object;
}
bool ezJniObject::operator==(const ezJniObject& other) const
{
return ezJniAttachment::GetEnv()->IsSameObject(m_object, other.m_object) == JNI_TRUE;
}
bool ezJniObject::operator!=(const ezJniObject& other) const
{
return !operator==(other);
}
// Template specializations to dispatch to the correct JNI method for each C++ type.
template <typename T, bool unused = false>
struct ezJniTraits
{
static_assert(unused, "The passed C++ type is not supported by the JNI wrapper. Arguments and returns types must be one of bool, signed char/jbyte, unsigned short/jchar, short/jshort, int/jint, long long/jlong, float/jfloat, double/jdouble, ezJniObject, ezJniString or ezJniClass.");
// Places the argument inside a jvalue union.
static jvalue ToValue(T);
// Retrieves the Java class static type of the argument. For primitives, this is not the boxed type, but the primitive type.
static ezJniClass GetStaticType();
// Retrieves the Java class dynamic type of the argument. For primitives, this is not the boxed type, but the primitive type.
static ezJniClass GetRuntimeType(T);
// Creates an invalid/null object to return in case of errors.
static T GetEmptyObject();
// Call an instance method with the return type.
template <typename... Args>
static T CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
// Call a static method with the return type.
template <typename... Args>
static T CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
// Sets/gets a field of the type.
static void SetField(jobject self, jfieldID field, T);
static T GetField(jobject self, jfieldID field);
// Sets/gets a static field of the type.
static void SetStaticField(jclass clazz, jfieldID field, T);
static T GetStaticField(jclass clazz, jfieldID field);
// Appends the JNI type signature of this type to the string buf
static bool AppendSignature(const T& obj, ezStringBuilder& str);
static const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<bool>
{
static inline jvalue ToValue(bool value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(bool);
static inline bool GetEmptyObject();
template <typename... Args>
static bool CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static bool CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, bool arg);
static inline bool GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, bool arg);
static inline bool GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(bool, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jbyte>
{
static inline jvalue ToValue(jbyte value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jbyte);
static inline jbyte GetEmptyObject();
template <typename... Args>
static jbyte CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jbyte CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jbyte arg);
static inline jbyte GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jbyte arg);
static inline jbyte GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jbyte, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jchar>
{
static inline jvalue ToValue(jchar value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jchar);
static inline jchar GetEmptyObject();
template <typename... Args>
static jchar CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jchar CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jchar arg);
static inline jchar GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jchar arg);
static inline jchar GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jchar, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jshort>
{
static inline jvalue ToValue(jshort value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jshort);
static inline jshort GetEmptyObject();
template <typename... Args>
static jshort CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jshort CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jshort arg);
static inline jshort GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jshort arg);
static inline jshort GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jshort, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jint>
{
static inline jvalue ToValue(jint value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jint);
static inline jint GetEmptyObject();
template <typename... Args>
static jint CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jint CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jint arg);
static inline jint GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jint arg);
static inline jint GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jint, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jlong>
{
static inline jvalue ToValue(jlong value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jlong);
static inline jlong GetEmptyObject();
template <typename... Args>
static jlong CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jlong CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jlong arg);
static inline jlong GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jlong arg);
static inline jlong GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jlong, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jfloat>
{
static inline jvalue ToValue(jfloat value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jfloat);
static inline jfloat GetEmptyObject();
template <typename... Args>
static jfloat CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jfloat CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jfloat arg);
static inline jfloat GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jfloat arg);
static inline jfloat GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jfloat, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<jdouble>
{
static inline jvalue ToValue(jdouble value);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(jdouble);
static inline jdouble GetEmptyObject();
template <typename... Args>
static jdouble CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static jdouble CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, jdouble arg);
static inline jdouble GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, jdouble arg);
static inline jdouble GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(jdouble, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<ezJniObject>
{
static inline jvalue ToValue(const ezJniObject& object);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(const ezJniObject& object);
static inline ezJniObject GetEmptyObject();
template <typename... Args>
static ezJniObject CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static ezJniObject CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, const ezJniObject& arg);
static inline ezJniObject GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniObject& arg);
static inline ezJniObject GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(const ezJniObject& obj, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<ezJniClass>
{
static inline jvalue ToValue(const ezJniClass& object);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(const ezJniClass& object);
static inline ezJniClass GetEmptyObject();
template <typename... Args>
static ezJniClass CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static ezJniClass CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, const ezJniClass& arg);
static inline ezJniClass GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniClass& arg);
static inline ezJniClass GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(const ezJniClass& obj, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<ezJniString>
{
static inline jvalue ToValue(const ezJniString& object);
static inline ezJniClass GetStaticType();
static inline ezJniClass GetRuntimeType(const ezJniString& object);
static inline ezJniString GetEmptyObject();
template <typename... Args>
static ezJniString CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static ezJniString CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline void SetField(jobject self, jfieldID field, const ezJniString& arg);
static inline ezJniString GetField(jobject self, jfieldID field);
static inline void SetStaticField(jclass clazz, jfieldID field, const ezJniString& arg);
static inline ezJniString GetStaticField(jclass clazz, jfieldID field);
static inline bool AppendSignature(const ezJniString& obj, ezStringBuilder& str);
static inline const char* GetSignatureStatic();
};
template <>
struct ezJniTraits<void>
{
static inline ezJniClass GetStaticType();
static inline void GetEmptyObject();
template <typename... Args>
static void CallInstanceMethod(jobject self, jmethodID method, const Args&... args);
template <typename... Args>
static void CallStaticMethod(jclass clazz, jmethodID method, const Args&... args);
static inline const char* GetSignatureStatic();
};
// Helpers to unpack variadic templates.
struct ezJniImpl
{
static void CollectArgumentTypes(ezJniClass* target)
{
}
template <typename T, typename... Tail>
static void CollectArgumentTypes(ezJniClass* target, const T& arg, const Tail&... tail)
{
*target = ezJniTraits<T>::GetRuntimeType(arg);
return ezJniImpl::CollectArgumentTypes(target + 1, tail...);
}
static void UnpackArgs(jvalue* target)
{
}
template <typename T, typename... Tail>
static void UnpackArgs(jvalue* target, const T& arg, const Tail&... tail)
{
*target = ezJniTraits<T>::ToValue(arg);
return UnpackArgs(target + 1, tail...);
}
template <typename Ret, typename... Args>
static bool BuildMethodSignature(ezStringBuilder& signature, const Args&... args)
{
signature.Append("(");
if (!ezJniImpl::AppendSignature(signature, args...))
{
return false;
}
signature.Append(")");
signature.Append(ezJniTraits<Ret>::GetSignatureStatic());
return true;
}
static bool AppendSignature(ezStringBuilder& signature)
{
return true;
}
template <typename T, typename... Tail>
static bool AppendSignature(ezStringBuilder& str, const T& arg, const Tail&... tail)
{
return ezJniTraits<T>::AppendSignature(arg, str) && AppendSignature(str, tail...);
}
};
jvalue ezJniTraits<bool>::ToValue(bool value)
{
jvalue result;
result.z = value ? JNI_TRUE : JNI_FALSE;
return result;
}
ezJniClass ezJniTraits<bool>::GetStaticType()
{
return ezJniClass("java/lang/Boolean").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<bool>::GetRuntimeType(bool)
{
return GetStaticType();
}
bool ezJniTraits<bool>::GetEmptyObject()
{
return false;
}
template <typename... Args>
bool ezJniTraits<bool>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallBooleanMethodA(self, method, array) == JNI_TRUE;
}
template <typename... Args>
bool ezJniTraits<bool>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticBooleanMethodA(clazz, method, array) == JNI_TRUE;
}
void ezJniTraits<bool>::SetField(jobject self, jfieldID field, bool arg)
{
return ezJniAttachment::GetEnv()->SetBooleanField(self, field, arg ? JNI_TRUE : JNI_FALSE);
}
bool ezJniTraits<bool>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetBooleanField(self, field) == JNI_TRUE;
}
void ezJniTraits<bool>::SetStaticField(jclass clazz, jfieldID field, bool arg)
{
return ezJniAttachment::GetEnv()->SetStaticBooleanField(clazz, field, arg ? JNI_TRUE : JNI_FALSE);
}
bool ezJniTraits<bool>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticBooleanField(clazz, field) == JNI_TRUE;
}
bool ezJniTraits<bool>::AppendSignature(bool, ezStringBuilder& str)
{
str.Append("Z");
return true;
}
const char* ezJniTraits<bool>::GetSignatureStatic()
{
return "Z";
}
jvalue ezJniTraits<jbyte>::ToValue(jbyte value)
{
jvalue result;
result.b = value;
return result;
}
ezJniClass ezJniTraits<jbyte>::GetStaticType()
{
return ezJniClass("java/lang/Byte").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jbyte>::GetRuntimeType(jbyte)
{
return GetStaticType();
}
jbyte ezJniTraits<jbyte>::GetEmptyObject()
{
return 0;
}
template <typename... Args>
jbyte ezJniTraits<jbyte>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallByteMethodA(self, method, array);
}
template <typename... Args>
jbyte ezJniTraits<jbyte>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticByteMethodA(clazz, method, array);
}
void ezJniTraits<jbyte>::SetField(jobject self, jfieldID field, jbyte arg)
{
return ezJniAttachment::GetEnv()->SetByteField(self, field, arg);
}
jbyte ezJniTraits<jbyte>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetByteField(self, field);
}
void ezJniTraits<jbyte>::SetStaticField(jclass clazz, jfieldID field, jbyte arg)
{
return ezJniAttachment::GetEnv()->SetStaticByteField(clazz, field, arg);
}
jbyte ezJniTraits<jbyte>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticByteField(clazz, field);
}
bool ezJniTraits<jbyte>::AppendSignature(jbyte, ezStringBuilder& str)
{
str.Append("B");
return true;
}
const char* ezJniTraits<jbyte>::GetSignatureStatic()
{
return "B";
}
jvalue ezJniTraits<jchar>::ToValue(jchar value)
{
jvalue result;
result.c = value;
return result;
}
ezJniClass ezJniTraits<jchar>::GetStaticType()
{
return ezJniClass("java/lang/Character").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jchar>::GetRuntimeType(jchar)
{
return GetStaticType();
}
jchar ezJniTraits<jchar>::GetEmptyObject()
{
return 0;
}
template <typename... Args>
jchar ezJniTraits<jchar>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallCharMethodA(self, method, array);
}
template <typename... Args>
jchar ezJniTraits<jchar>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticCharMethodA(clazz, method, array);
}
void ezJniTraits<jchar>::SetField(jobject self, jfieldID field, jchar arg)
{
return ezJniAttachment::GetEnv()->SetCharField(self, field, arg);
}
jchar ezJniTraits<jchar>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetCharField(self, field);
}
void ezJniTraits<jchar>::SetStaticField(jclass clazz, jfieldID field, jchar arg)
{
return ezJniAttachment::GetEnv()->SetStaticCharField(clazz, field, arg);
}
jchar ezJniTraits<jchar>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticCharField(clazz, field);
}
bool ezJniTraits<jchar>::AppendSignature(jchar, ezStringBuilder& str)
{
str.Append("C");
return true;
}
const char* ezJniTraits<jchar>::GetSignatureStatic()
{
return "C";
}
jvalue ezJniTraits<jshort>::ToValue(jshort value)
{
jvalue result;
result.s = value;
return result;
}
ezJniClass ezJniTraits<jshort>::GetStaticType()
{
return ezJniClass("java/lang/Short").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jshort>::GetRuntimeType(jshort)
{
return GetStaticType();
}
jshort ezJniTraits<jshort>::GetEmptyObject()
{
return 0;
}
template <typename... Args>
jshort ezJniTraits<jshort>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallShortMethodA(self, method, array);
}
template <typename... Args>
jshort ezJniTraits<jshort>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticShortMethodA(clazz, method, array);
}
void ezJniTraits<jshort>::SetField(jobject self, jfieldID field, jshort arg)
{
return ezJniAttachment::GetEnv()->SetShortField(self, field, arg);
}
jshort ezJniTraits<jshort>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetShortField(self, field);
}
void ezJniTraits<jshort>::SetStaticField(jclass clazz, jfieldID field, jshort arg)
{
return ezJniAttachment::GetEnv()->SetStaticShortField(clazz, field, arg);
}
jshort ezJniTraits<jshort>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticShortField(clazz, field);
}
bool ezJniTraits<jshort>::AppendSignature(jshort, ezStringBuilder& str)
{
str.Append("S");
return true;
}
const char* ezJniTraits<jshort>::GetSignatureStatic()
{
return "S";
}
jvalue ezJniTraits<jint>::ToValue(jint value)
{
jvalue result;
result.i = value;
return result;
}
ezJniClass ezJniTraits<jint>::GetStaticType()
{
return ezJniClass("java/lang/Integer").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jint>::GetRuntimeType(jint)
{
return GetStaticType();
}
jint ezJniTraits<jint>::GetEmptyObject()
{
return 0;
}
template <typename... Args>
jint ezJniTraits<jint>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallIntMethodA(self, method, array);
}
template <typename... Args>
jint ezJniTraits<jint>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticIntMethodA(clazz, method, array);
}
void ezJniTraits<jint>::SetField(jobject self, jfieldID field, jint arg)
{
return ezJniAttachment::GetEnv()->SetIntField(self, field, arg);
}
jint ezJniTraits<jint>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetIntField(self, field);
}
void ezJniTraits<jint>::SetStaticField(jclass clazz, jfieldID field, jint arg)
{
return ezJniAttachment::GetEnv()->SetStaticIntField(clazz, field, arg);
}
jint ezJniTraits<jint>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticIntField(clazz, field);
}
bool ezJniTraits<jint>::AppendSignature(jint, ezStringBuilder& str)
{
str.Append("I");
return true;
}
const char* ezJniTraits<jint>::GetSignatureStatic()
{
return "I";
}
jvalue ezJniTraits<jlong>::ToValue(jlong value)
{
jvalue result;
result.j = value;
return result;
}
ezJniClass ezJniTraits<jlong>::GetStaticType()
{
return ezJniClass("java/lang/Long").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jlong>::GetRuntimeType(jlong)
{
return GetStaticType();
}
jlong ezJniTraits<jlong>::GetEmptyObject()
{
return 0;
}
template <typename... Args>
jlong ezJniTraits<jlong>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallLongMethodA(self, method, array);
}
template <typename... Args>
jlong ezJniTraits<jlong>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticLongMethodA(clazz, method, array);
}
void ezJniTraits<jlong>::SetField(jobject self, jfieldID field, jlong arg)
{
return ezJniAttachment::GetEnv()->SetLongField(self, field, arg);
}
jlong ezJniTraits<jlong>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetLongField(self, field);
}
void ezJniTraits<jlong>::SetStaticField(jclass clazz, jfieldID field, jlong arg)
{
return ezJniAttachment::GetEnv()->SetStaticLongField(clazz, field, arg);
}
jlong ezJniTraits<jlong>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticLongField(clazz, field);
}
bool ezJniTraits<jlong>::AppendSignature(jlong, ezStringBuilder& str)
{
str.Append("J");
return true;
}
const char* ezJniTraits<jlong>::GetSignatureStatic()
{
return "J";
}
jvalue ezJniTraits<jfloat>::ToValue(jfloat value)
{
jvalue result;
result.f = value;
return result;
}
ezJniClass ezJniTraits<jfloat>::GetStaticType()
{
return ezJniClass("java/lang/Float").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jfloat>::GetRuntimeType(jfloat)
{
return GetStaticType();
}
jfloat ezJniTraits<jfloat>::GetEmptyObject()
{
return nanf("");
}
template <typename... Args>
jfloat ezJniTraits<jfloat>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallFloatMethodA(self, method, array);
}
template <typename... Args>
jfloat ezJniTraits<jfloat>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticFloatMethodA(clazz, method, array);
}
void ezJniTraits<jfloat>::SetField(jobject self, jfieldID field, jfloat arg)
{
return ezJniAttachment::GetEnv()->SetFloatField(self, field, arg);
}
jfloat ezJniTraits<jfloat>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetFloatField(self, field);
}
void ezJniTraits<jfloat>::SetStaticField(jclass clazz, jfieldID field, jfloat arg)
{
return ezJniAttachment::GetEnv()->SetStaticFloatField(clazz, field, arg);
}
jfloat ezJniTraits<jfloat>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticFloatField(clazz, field);
}
bool ezJniTraits<jfloat>::AppendSignature(jfloat, ezStringBuilder& str)
{
str.Append("F");
return true;
}
const char* ezJniTraits<jfloat>::GetSignatureStatic()
{
return "F";
}
jvalue ezJniTraits<jdouble>::ToValue(jdouble value)
{
jvalue result;
result.d = value;
return result;
}
ezJniClass ezJniTraits<jdouble>::GetStaticType()
{
return ezJniClass("java/lang/Double").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
ezJniClass ezJniTraits<jdouble>::GetRuntimeType(jdouble)
{
return GetStaticType();
}
jdouble ezJniTraits<jdouble>::GetEmptyObject()
{
return nan("");
}
template <typename... Args>
jdouble ezJniTraits<jdouble>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallDoubleMethodA(self, method, array);
}
template <typename... Args>
jdouble ezJniTraits<jdouble>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticDoubleMethodA(clazz, method, array);
}
void ezJniTraits<jdouble>::SetField(jobject self, jfieldID field, jdouble arg)
{
return ezJniAttachment::GetEnv()->SetDoubleField(self, field, arg);
}
jdouble ezJniTraits<jdouble>::GetField(jobject self, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetDoubleField(self, field);
}
void ezJniTraits<jdouble>::SetStaticField(jclass clazz, jfieldID field, jdouble arg)
{
return ezJniAttachment::GetEnv()->SetStaticDoubleField(clazz, field, arg);
}
jdouble ezJniTraits<jdouble>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniAttachment::GetEnv()->GetStaticDoubleField(clazz, field);
}
bool ezJniTraits<jdouble>::AppendSignature(jdouble, ezStringBuilder& str)
{
str.Append("D");
return true;
}
const char* ezJniTraits<jdouble>::GetSignatureStatic()
{
return "D";
}
jvalue ezJniTraits<ezJniObject>::ToValue(const ezJniObject& value)
{
jvalue result;
result.l = value.GetHandle();
return result;
}
ezJniClass ezJniTraits<ezJniObject>::GetStaticType()
{
return ezJniClass("java/lang/Object");
}
ezJniClass ezJniTraits<ezJniObject>::GetRuntimeType(const ezJniObject& arg)
{
return arg.GetClass();
}
ezJniObject ezJniTraits<ezJniObject>::GetEmptyObject()
{
return ezJniObject();
}
template <typename... Args>
ezJniObject ezJniTraits<ezJniObject>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniObject(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array), ezJniOwnerShip::OWN);
}
template <typename... Args>
ezJniObject ezJniTraits<ezJniObject>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniObject(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array), ezJniOwnerShip::OWN);
}
void ezJniTraits<ezJniObject>::SetField(jobject self, jfieldID field, const ezJniObject& arg)
{
return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle());
}
ezJniObject ezJniTraits<ezJniObject>::GetField(jobject self, jfieldID field)
{
return ezJniObject(ezJniAttachment::GetEnv()->GetObjectField(self, field), ezJniOwnerShip::OWN);
}
void ezJniTraits<ezJniObject>::SetStaticField(jclass clazz, jfieldID field, const ezJniObject& arg)
{
return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle());
}
ezJniObject ezJniTraits<ezJniObject>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniObject(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field), ezJniOwnerShip::OWN);
}
bool ezJniTraits<ezJniObject>::AppendSignature(const ezJniObject& obj, ezStringBuilder& str)
{
if (obj.IsNull())
{
// Ensure null objects never generate valid signatures in order to force using the reflection path
return false;
}
else
{
str.Append("L");
str.Append(obj.GetClass().UnsafeCall<ezJniString>("getName", "()Ljava/lang/String;").GetData());
str.ReplaceAll(".", "/");
str.Append(";");
return true;
}
}
const char* ezJniTraits<ezJniObject>::GetSignatureStatic()
{
return "Ljava/lang/Object;";
}
jvalue ezJniTraits<ezJniClass>::ToValue(const ezJniClass& value)
{
jvalue result;
result.l = value.GetHandle();
return result;
}
ezJniClass ezJniTraits<ezJniClass>::GetStaticType()
{
return ezJniClass("java/lang/Class");
}
ezJniClass ezJniTraits<ezJniClass>::GetRuntimeType(const ezJniClass& arg)
{
// Assume there are no types derived from Class
return GetStaticType();
}
ezJniClass ezJniTraits<ezJniClass>::GetEmptyObject()
{
return ezJniClass();
}
template <typename... Args>
ezJniClass ezJniTraits<ezJniClass>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniClass(jclass(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array)), ezJniOwnerShip::OWN);
}
template <typename... Args>
ezJniClass ezJniTraits<ezJniClass>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniClass(jclass(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array)), ezJniOwnerShip::OWN);
}
void ezJniTraits<ezJniClass>::SetField(jobject self, jfieldID field, const ezJniClass& arg)
{
return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle());
}
ezJniClass ezJniTraits<ezJniClass>::GetField(jobject self, jfieldID field)
{
return ezJniClass(jclass(ezJniAttachment::GetEnv()->GetObjectField(self, field)), ezJniOwnerShip::OWN);
}
void ezJniTraits<ezJniClass>::SetStaticField(jclass clazz, jfieldID field, const ezJniClass& arg)
{
return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle());
}
ezJniClass ezJniTraits<ezJniClass>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniClass(jclass(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field)), ezJniOwnerShip::OWN);
}
bool ezJniTraits<ezJniClass>::AppendSignature(const ezJniClass& obj, ezStringBuilder& str)
{
str.Append("Ljava/lang/Class;");
return true;
}
const char* ezJniTraits<ezJniClass>::GetSignatureStatic()
{
return "Ljava/lang/Class;";
}
jvalue ezJniTraits<ezJniString>::ToValue(const ezJniString& value)
{
jvalue result;
result.l = value.GetHandle();
return result;
}
ezJniClass ezJniTraits<ezJniString>::GetStaticType()
{
return ezJniClass("java/lang/String");
}
ezJniClass ezJniTraits<ezJniString>::GetRuntimeType(const ezJniString& arg)
{
// Assume there are no types derived from String
return GetStaticType();
}
ezJniString ezJniTraits<ezJniString>::GetEmptyObject()
{
return ezJniString();
}
template <typename... Args>
ezJniString ezJniTraits<ezJniString>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniString(jstring(ezJniAttachment::GetEnv()->CallObjectMethodA(self, method, array)), ezJniOwnerShip::OWN);
}
template <typename... Args>
ezJniString ezJniTraits<ezJniString>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniString(jstring(ezJniAttachment::GetEnv()->CallStaticObjectMethodA(clazz, method, array)), ezJniOwnerShip::OWN);
}
void ezJniTraits<ezJniString>::SetField(jobject self, jfieldID field, const ezJniString& arg)
{
return ezJniAttachment::GetEnv()->SetObjectField(self, field, arg.GetHandle());
}
ezJniString ezJniTraits<ezJniString>::GetField(jobject self, jfieldID field)
{
return ezJniString(jstring(ezJniAttachment::GetEnv()->GetObjectField(self, field)), ezJniOwnerShip::OWN);
}
void ezJniTraits<ezJniString>::SetStaticField(jclass clazz, jfieldID field, const ezJniString& arg)
{
return ezJniAttachment::GetEnv()->SetStaticObjectField(clazz, field, arg.GetHandle());
}
ezJniString ezJniTraits<ezJniString>::GetStaticField(jclass clazz, jfieldID field)
{
return ezJniString(jstring(ezJniAttachment::GetEnv()->GetStaticObjectField(clazz, field)), ezJniOwnerShip::OWN);
}
bool ezJniTraits<ezJniString>::AppendSignature(const ezJniString& obj, ezStringBuilder& str)
{
str.Append("Ljava/lang/String;");
return true;
}
const char* ezJniTraits<ezJniString>::GetSignatureStatic()
{
return "Ljava/lang/String;";
}
ezJniClass ezJniTraits<void>::GetStaticType()
{
return ezJniClass("java/lang/Void").UnsafeGetStaticField<ezJniClass>("TYPE", "Ljava/lang/Class;");
}
void ezJniTraits<void>::GetEmptyObject()
{
return;
}
template <typename... Args>
void ezJniTraits<void>::CallInstanceMethod(jobject self, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallVoidMethodA(self, method, array);
}
template <typename... Args>
void ezJniTraits<void>::CallStaticMethod(jclass clazz, jmethodID method, const Args&... args)
{
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniAttachment::GetEnv()->CallStaticVoidMethodA(clazz, method, array);
}
const char* ezJniTraits<void>::GetSignatureStatic()
{
return "V";
}
template <typename... Args>
ezJniObject ezJniClass::CreateInstance(const Args&... args) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return ezJniObject();
}
const size_t N = sizeof...(args);
ezJniClass inputTypes[N];
ezJniImpl::CollectArgumentTypes(inputTypes, args...);
ezJniObject foundMethod = FindConstructor(*this, inputTypes, N);
if (foundMethod.IsNull())
{
return ezJniObject();
}
jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.GetHandle());
jvalue array[sizeof...(args)];
ezJniImpl::UnpackArgs(array, args...);
return ezJniObject(ezJniAttachment::GetEnv()->NewObjectA(GetHandle(), method, array), ezJniOwnerShip::OWN);
}
template <typename Ret, typename... Args>
Ret ezJniClass::CallStatic(const char* name, const Args&... args) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return ezJniTraits<Ret>::GetEmptyObject();
}
if (!GetJObject())
{
ezLog::Error("Attempting to call static method '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
ezStringBuilder signature;
if (ezJniImpl::BuildMethodSignature<Ret>(signature, args...))
{
jmethodID method = ezJniAttachment::GetEnv()->GetStaticMethodID(GetHandle(), name, signature.GetData());
if (method)
{
return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...);
}
else
{
ezJniAttachment::GetEnv()->ExceptionClear();
}
}
const size_t N = sizeof...(args);
ezJniClass returnType = ezJniTraits<Ret>::GetStaticType();
ezJniClass inputTypes[N];
ezJniImpl::CollectArgumentTypes(inputTypes, args...);
ezJniObject foundMethod = FindMethod(true, name, *this, returnType, inputTypes, N);
if (foundMethod.IsNull())
{
return ezJniTraits<Ret>::GetEmptyObject();
}
jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.GetHandle());
return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...);
}
template <typename Ret, typename... Args>
Ret ezJniClass::UnsafeCallStatic(const char* name, const char* signature, const Args&... args) const
{
if (!GetJObject())
{
ezLog::Error("Attempting to call static method '{}' on null class.", name);
ezLog::Error("Attempting to call static method '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
jmethodID method = ezJniAttachment::GetEnv()->GetStaticMethodID(GetHandle(), name, signature);
if (!method)
{
ezLog::Error("No such static method: '{}' with signature '{}' in class '{}'.", name, signature, ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_METHOD);
return ezJniTraits<Ret>::GetEmptyObject();
}
else
{
return ezJniTraits<Ret>::CallStaticMethod(GetHandle(), method, args...);
}
}
template <typename Ret>
Ret ezJniClass::GetStaticField(const char* name) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return ezJniTraits<Ret>::GetEmptyObject();
}
if (!GetJObject())
{
ezLog::Error("Attempting to get static field '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
jfieldID fieldID = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, ezJniTraits<Ret>::GetSignatureStatic());
if (fieldID)
{
return ezJniTraits<Ret>::GetStaticField(GetHandle(), fieldID);
}
else
{
ezJniAttachment::GetEnv()->ExceptionClear();
}
ezJniObject field = UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name));
if (ezJniAttachment::GetEnv()->ExceptionOccurred())
{
ezJniAttachment::GetEnv()->ExceptionClear();
ezLog::Error("No field named '{}' found in class '{}'.", name, ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
if ((field.UnsafeCall<jint>("getModifiers", "()I") & ezJniModifiers::STATIC) == 0)
{
ezLog::Error("Field named '{}' in class '{}' isn't static.", name, ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;");
ezJniClass returnType = ezJniTraits<Ret>::GetStaticType();
if (!returnType.IsAssignableFrom(fieldType))
{
ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned to return type '{}'.", name, fieldType.ToString().GetData(), ToString().GetData(), returnType.ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
return ezJniTraits<Ret>::GetStaticField(GetHandle(), ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()));
}
template <typename Ret>
Ret ezJniClass::UnsafeGetStaticField(const char* name, const char* signature) const
{
if (!GetJObject())
{
ezLog::Error("Attempting to get static field '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
jfieldID field = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, signature);
if (!field)
{
ezLog::Error("No such field: '{}' with signature '{}'.", name, signature);
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
else
{
return ezJniTraits<Ret>::GetStaticField(GetHandle(), field);
}
}
template <typename T>
void ezJniClass::SetStaticField(const char* name, const T& arg) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return;
}
if (!GetJObject())
{
ezLog::Error("Attempting to set static field '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return;
}
ezJniObject field = UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name));
if (ezJniAttachment::GetEnv()->ExceptionOccurred())
{
ezJniAttachment::GetEnv()->ExceptionClear();
ezLog::Error("No field named '{}' found in class '{}'.", name, ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
ezJniClass modifierClass("java/lang/reflect/Modifier");
jint modifiers = field.UnsafeCall<jint>("getModifiers", "()I");
if ((modifiers & ezJniModifiers::STATIC) == 0)
{
ezLog::Error("Field named '{}' in class '{}' isn't static.", name, ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
if ((modifiers & ezJniModifiers::FINAL) != 0)
{
ezLog::Error("Field named '{}' in class '{}' is final.", name, ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;");
ezJniClass argType = ezJniTraits<T>::GetRuntimeType(arg);
if (argType.IsNull())
{
if (fieldType.IsPrimitive())
{
ezLog::Error("Field '{}' of type '{}' can't be assigned null because it is a primitive type.", name, fieldType.ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
}
else
{
if (!fieldType.IsAssignableFrom(argType))
{
ezLog::Error("Field '{}' of type '{}' can't be assigned from type '{}'.", name, fieldType.ToString().GetData(), argType.ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
}
return ezJniTraits<T>::SetStaticField(GetHandle(), ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()), arg);
}
template <typename T>
void ezJniClass::UnsafeSetStaticField(const char* name, const char* signature, const T& arg) const
{
if (!GetJObject())
{
ezLog::Error("Attempting to set static field '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return;
}
jfieldID field = ezJniAttachment::GetEnv()->GetStaticFieldID(GetHandle(), name, signature);
if (!field)
{
ezLog::Error("No such field: '{}' with signature '{}'.", name, signature);
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
else
{
return ezJniTraits<T>::SetStaticField(GetHandle(), field, arg);
}
}
template <typename Ret, typename... Args>
Ret ezJniObject::Call(const char* name, const Args&... args) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return ezJniTraits<Ret>::GetEmptyObject();
}
if (!m_object)
{
ezLog::Error("Attempting to call method '{}' on null object.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
// Fast path: Lookup method via signature built from parameters.
// This only works for exact matches, but is roughly 50 times faster.
ezStringBuilder signature;
if (ezJniImpl::BuildMethodSignature<Ret>(signature, args...))
{
jmethodID method = ezJniAttachment::GetEnv()->GetMethodID(reinterpret_cast<jclass>(GetClass().GetHandle()), name, signature.GetData());
if (method)
{
return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...);
}
else
{
ezJniAttachment::GetEnv()->ExceptionClear();
}
}
// Fallback to slow path using reflection
const size_t N = sizeof...(args);
ezJniClass returnType = ezJniTraits<Ret>::GetStaticType();
ezJniClass inputTypes[N];
ezJniImpl::CollectArgumentTypes(inputTypes, args...);
ezJniObject foundMethod = FindMethod(false, name, GetClass(), returnType, inputTypes, N);
if (foundMethod.IsNull())
{
return ezJniTraits<Ret>::GetEmptyObject();
}
jmethodID method = ezJniAttachment::GetEnv()->FromReflectedMethod(foundMethod.m_object);
return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...);
}
template <typename Ret, typename... Args>
Ret ezJniObject::UnsafeCall(const char* name, const char* signature, const Args&... args) const
{
if (!m_object)
{
ezLog::Error("Attempting to call method '{}' on null object.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
jmethodID method = ezJniAttachment::GetEnv()->GetMethodID(jclass(GetClass().m_object), name, signature);
if (!method)
{
ezLog::Error("No such method: '{}' with signature '{}' in class '{}'.", name, signature, GetClass().ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_METHOD);
return ezJniTraits<Ret>::GetEmptyObject();
}
else
{
return ezJniTraits<Ret>::CallInstanceMethod(m_object, method, args...);
}
}
template <typename T>
void ezJniObject::SetField(const char* name, const T& arg) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return;
}
if (!m_object)
{
ezLog::Error("Attempting to set field '{}' on null object.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return;
}
// No fast path here since we need to be able to report failures when attempting
// to set final fields, which we can only do using reflection.
ezJniObject field = GetClass().UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name));
if (ezJniAttachment::GetEnv()->ExceptionOccurred())
{
ezJniAttachment::GetEnv()->ExceptionClear();
ezLog::Error("No field named '{}' found.", name);
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
ezJniClass modifierClass("java/lang/reflect/Modifier");
jint modifiers = field.UnsafeCall<jint>("getModifiers", "()I");
if ((modifiers & ezJniModifiers::STATIC) != 0)
{
ezLog::Error("Field named '{}' in class '{}' is static.", name, GetClass().ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
if ((modifiers & ezJniModifiers::FINAL) != 0)
{
ezLog::Error("Field named '{}' in class '{}' is final.", name, GetClass().ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;");
ezJniClass argType = ezJniTraits<T>::GetRuntimeType(arg);
if (argType.IsNull())
{
if (fieldType.IsPrimitive())
{
ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned null because it is a primitive type.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
}
else
{
if (!fieldType.IsAssignableFrom(argType))
{
ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned from type '{}'.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData(), argType.ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
}
return ezJniTraits<T>::SetField(m_object, ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()), arg);
}
template <typename T>
void ezJniObject::UnsafeSetField(const char* name, const char* signature, const T& arg) const
{
if (!m_object)
{
ezLog::Error("Attempting to set field '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return;
}
jfieldID field = ezJniAttachment::GetEnv()->GetFieldID(jclass(GetClass().GetHandle()), name, signature);
if (!field)
{
ezLog::Error("No such field: '{}' with signature '{}'.", name, signature);
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
else
{
return ezJniTraits<T>::SetField(m_object, field, arg);
}
}
template <typename Ret>
Ret ezJniObject::GetField(const char* name) const
{
if (ezJniAttachment::FailOnPendingErrorOrException())
{
return ezJniTraits<Ret>::GetEmptyObject();
}
if (!m_object)
{
ezLog::Error("Attempting to get field '{}' on null object.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return ezJniTraits<Ret>::GetEmptyObject();
}
jfieldID fieldID = ezJniAttachment::GetEnv()->GetFieldID(GetClass().GetHandle(), name, ezJniTraits<Ret>::GetSignatureStatic());
if (fieldID)
{
return ezJniTraits<Ret>::GetField(m_object, fieldID);
}
else
{
ezJniAttachment::GetEnv()->ExceptionClear();
}
ezJniObject field = GetClass().UnsafeCall<ezJniObject>("getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ezJniString(name));
if (ezJniAttachment::GetEnv()->ExceptionOccurred())
{
ezJniAttachment::GetEnv()->ExceptionClear();
ezLog::Error("No field named '{}' found in class '{}'.", name, GetClass().ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
if ((field.UnsafeCall<jint>("getModifiers", "()I") & ezJniModifiers::STATIC) != 0)
{
ezLog::Error("Field named '{}' in class '{}' is static.", name, GetClass().ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
ezJniClass fieldType = field.UnsafeCall<ezJniClass>("getType", "()Ljava/lang/Class;");
ezJniClass returnType = ezJniTraits<Ret>::GetStaticType();
if (!returnType.IsAssignableFrom(fieldType))
{
ezLog::Error("Field '{}' of type '{}' in class '{}' can't be assigned to return type '{}'.", name, fieldType.ToString().GetData(), GetClass().ToString().GetData(), returnType.ToString().GetData());
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return ezJniTraits<Ret>::GetEmptyObject();
}
return ezJniTraits<Ret>::GetField(m_object, ezJniAttachment::GetEnv()->FromReflectedField(field.GetHandle()));
}
template <typename Ret>
Ret ezJniObject::UnsafeGetField(const char* name, const char* signature) const
{
if (!m_object)
{
ezLog::Error("Attempting to get field '{}' on null class.", name);
ezJniAttachment::SetLastError(ezJniErrorState::CALL_ON_NULL_OBJECT);
return;
}
jfieldID field = ezJniAttachment::GetEnv()->GetFieldID(GetClass().GetHandle(), name, signature);
if (!field)
{
ezLog::Error("No such field: '{}' with signature '{}'.", name, signature);
ezJniAttachment::SetLastError(ezJniErrorState::NO_MATCHING_FIELD);
return;
}
else
{
return ezJniTraits<Ret>::GetField(m_object, field);
}
}
| 29.298056 | 285 | 0.729414 | Tekh-ops |
201039418cb79f69a96c443540e3dd27e909876a | 3,458 | cpp | C++ | source/LibFgBase/src/FgSerial.cpp | SingularInversions/FaceGenBaseLibrary | e928b482fa78597cfcf3923f7252f7902ec0dfa9 | [
"MIT"
] | 41 | 2016-04-09T07:48:10.000Z | 2022-03-01T15:46:08.000Z | source/LibFgBase/src/FgSerial.cpp | SingularInversions/FaceGenBaseLibrary | e928b482fa78597cfcf3923f7252f7902ec0dfa9 | [
"MIT"
] | 9 | 2015-09-23T10:54:50.000Z | 2020-01-04T21:16:57.000Z | source/LibFgBase/src/FgSerial.cpp | SingularInversions/FaceGenBaseLibrary | e928b482fa78597cfcf3923f7252f7902ec0dfa9 | [
"MIT"
] | 29 | 2015-10-01T14:44:42.000Z | 2022-01-05T01:28:43.000Z | //
// Coypright (c) 2021 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
#include "stdafx.h"
#include "FgSerial.hpp"
#include "FgCommand.hpp"
using namespace std;
namespace Fg {
void
srlz_(bool v,String & s)
{
uchar b = v ? 1 : 0;
srlz_(b,s);
}
void
dsrlz_(String const & s,size_t & p,bool & v)
{
uchar b;
dsrlz_(s,p,b);
v = (b == 1);
}
void
dsrlz_(String const & s,size_t & p,long & v)
{
int64 t;
dsrlzRaw_(s,p,t);
FGASSERT(t >= std::numeric_limits<long>::lowest());
FGASSERT(t <= std::numeric_limits<long>::max());
v = static_cast<long>(t);
}
void
dsrlz_(String const & s,size_t & p,unsigned long & v)
{
uint64 t;
dsrlzRaw_(s,p,t);
FGASSERT(t <= std::numeric_limits<unsigned long>::max());
v = static_cast<unsigned long>(t);
}
void
srlz_(String const & v,String & s)
{
srlz_(uint64(v.size()),s);
s.append(v);
}
void
dsrlz_(String const & s,size_t & p,String & v)
{
uint64 sz;
dsrlz_(s,p,sz);
FGASSERT(p+sz <= s.size());
v.assign(s,p,size_t(sz));
p += sz;
}
namespace {
void
test0()
{
int i = 42;
FGASSERT(i == dsrlz<int>(srlz(i)));
uint u = 42U;
FGASSERT(u == dsrlz<uint>(srlz(u)));
long l = 42L;
FGASSERT(l == dsrlz<long>(srlz(l)));
long long ll = 42LL;
FGASSERT(ll == dsrlz<long long>(srlz(ll)));
unsigned long long ull = 42ULL;
FGASSERT(ull == dsrlz<unsigned long long>(srlz(ull)));
String s = "Test String";
FGASSERT(s == dsrlz<String>(srlz(s)));
}
void
test1()
{
Strings tns;
int a = 5;
double b = 3.14;
typeNames_(tns,a,b);
fgout << fgnl << tns;
}
}
struct A
{
int i;
float f;
};
FG_SERIAL_2(A,i,f)
struct B
{
A a;
double d;
};
FG_SERIAL_2(B,a,d)
struct Op
{
double acc {0};
template<typename T>
void operator()(T r) {acc += double(r); }
};
void traverseMembers_(Op & op,int s) {op(s); }
void traverseMembers_(Op & op,float s) {op(s); }
void traverseMembers_(Op & op,double s) {op(s); }
void
test2()
{
Strings names;
reflectNames_<B>(names);
fgout << fgnl << names;
A a {3,0.1f};
B b {a,2.7};
Op op;
traverseMembers_(op,b);
fgout << fgnl << "Acc: " << op.acc;
}
void
testSerial(CLArgs const &)
{
test0();
test1();
test2();
{
Svec<string> in {"first","second"},
out = dsrlz<Strings>(srlz(in));
FGASSERT(in == out);
}
{
String8 dd = dataDir() + "base/test/";
String msg = "This is a test",
ser = srlz(msg);
//saveRaw(ser,dd+"serial32");
//saveRaw(ser,dd+"serial64");
String msg32 = dsrlz<String>(loadRaw(dd+"serial32")),
msg64 = dsrlz<String>(loadRaw(dd+"serial64"));
FGASSERT(msg32 == msg);
FGASSERT(msg64 == msg);
}
}
}
| 21.214724 | 79 | 0.484095 | SingularInversions |
2010aeff4c31c302980dd1eb4e0e5ecc25b2f041 | 3,544 | hpp | C++ | include/strict_variant/variant_storage.hpp | reuk/strict-variant | 7d0f1433d5126951b1af350213a0c7e75575fab0 | [
"BSL-1.0"
] | 62 | 2016-08-02T05:15:16.000Z | 2020-02-14T18:02:34.000Z | include/strict_variant/variant_storage.hpp | reuk/strict-variant | 7d0f1433d5126951b1af350213a0c7e75575fab0 | [
"BSL-1.0"
] | 6 | 2016-12-07T03:00:46.000Z | 2018-12-03T22:03:27.000Z | include/strict_variant/variant_storage.hpp | reuk/strict-variant | 7d0f1433d5126951b1af350213a0c7e75575fab0 | [
"BSL-1.0"
] | 6 | 2016-12-10T18:59:18.000Z | 2019-11-05T08:11:11.000Z | // (C) Copyright 2016 - 2018 Christopher Beck
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <new>
#include <strict_variant/mpl/max.hpp>
#include <strict_variant/mpl/typelist.hpp>
#include <strict_variant/wrapper.hpp>
#include <utility>
namespace strict_variant {
namespace detail {
// Implementation note:
// Internal visitors need to be able to access the "true" type, the
// reference_wrapper<T> when it is within the variant, to implement ctors
// and special memeber functions.
// External visitors are supposed to have this elided.
// The `get_value` function uses tag dispatch to do the right thing.
struct true_ {};
struct false_ {};
// Storage for the types in a list of types.
// Provides typed access using the index within the list as a template parameter.
// And some facilities for piercing recursive_wrapper
template <typename First, typename... Types>
struct storage {
/***
* Determine size and alignment of our storage
*/
template <typename T>
struct Sizeof {
static constexpr size_t value = sizeof(T);
};
template <typename T>
struct Alignof {
static constexpr size_t value = alignof(T);
};
// size = max of size of each thing
static constexpr size_t m_size = mpl::max<Sizeof, First, Types...>::value;
// align = max align of each thing
static constexpr size_t m_align = mpl::max<Alignof, First, Types...>::value;
/***
* Storage
*/
// alignas(m_align) char m_storage[m_size];
using aligned_storage_t = typename std::aligned_storage<m_size, m_align>::type;
aligned_storage_t m_storage;
void * address() { return reinterpret_cast<void *>(&m_storage); }
const void * address() const { return reinterpret_cast<const void *>(&m_storage); }
/***
* Index -> Type
*/
using my_types = mpl::TypeList<First, Types...>;
template <size_t index>
using value_t = mpl::Index_At<my_types, index>;
/***
* Initialize to the type at a particular value
*/
template <size_t index, typename... Args>
void initialize(Args &&... args) noexcept(
noexcept(value_t<index>(std::forward<Args>(std::declval<Args>())...))) {
new (this->address()) value_t<index>(std::forward<Args>(args)...);
}
/***
* Typed access which pierces recursive_wrapper if detail::false_ is passed
* "Internal" (non-piercing) access is achieved if detail::true_ is passed
*/
template <size_t index>
value_t<index> & get_value(detail::true_) & {
return *reinterpret_cast<value_t<index> *>(this->address());
}
template <size_t index>
const value_t<index> & get_value(detail::true_) const & {
return *reinterpret_cast<const value_t<index> *>(this->address());
}
template <size_t index>
value_t<index> && get_value(detail::true_) && {
return std::move(*reinterpret_cast<value_t<index> *>(this->address()));
}
template <size_t index>
unwrap_type_t<value_t<index>> & get_value(detail::false_) & {
return detail::pierce_wrapper(this->get_value<index>(detail::true_{}));
}
template <size_t index>
const unwrap_type_t<value_t<index>> & get_value(detail::false_) const & {
return detail::pierce_wrapper(this->get_value<index>(detail::true_{}));
}
template <size_t index>
unwrap_type_t<value_t<index>> && get_value(detail::false_) && {
return std::move(detail::pierce_wrapper(this->get_value<index>(detail::true_{})));
}
};
} // end namespace detail
} // end namespace strict_variant
| 30.033898 | 86 | 0.696106 | reuk |
2016fc451b4a8820fea9720af0f7d82da85c557c | 6,850 | cpp | C++ | src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp | opengamejam/OpenJam | 565dd19fa7f1a727966b4274b810424e5395600b | [
"MIT"
] | 4 | 2015-08-13T08:25:36.000Z | 2017-04-07T21:33:10.000Z | src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp | opengamejam/OpenJam | 565dd19fa7f1a727966b4274b810424e5395600b | [
"MIT"
] | null | null | null | src/render/OGLES1_0/CShaderProgramOGLES1_0.cpp | opengamejam/OpenJam | 565dd19fa7f1a727966b4274b810424e5395600b | [
"MIT"
] | null | null | null | //
// CShaderProgramOGLES1_0.h
// OpenJam
//
// Created by Yevgeniy Logachev
// Copyright (c) 2014 yev. All rights reserved.
//
#if defined(RENDER_OGLES1_0)
#include "CShaderProgramOGLES1_0.h"
using namespace jam;
// *****************************************************************************
// Constants
// *****************************************************************************
// *****************************************************************************
// Public Methods
// *****************************************************************************
CShaderProgramOGLES1_0::CShaderProgramOGLES1_0()
: m_ProectionMatrixHadle(-1u)
, m_ModelMatrixHadle(-1u)
, m_VertexCoordHandle(-1u)
, m_VertexNormalHandle(-1u)
, m_TextureCoordHandle(-1u)
, m_VertexColorHandle(-1u)
, m_ColorHandle(-1u)
, m_IsLinked(false)
{
}
CShaderProgramOGLES1_0::~CShaderProgramOGLES1_0()
{
}
void CShaderProgramOGLES1_0::Bind()
{
}
void CShaderProgramOGLES1_0::Unbind()
{
}
void CShaderProgramOGLES1_0::AttachShader(IShaderPtr shader)
{
std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shader->Type());
if (it != m_AttachedShaders.end()) {
m_AttachedShaders.erase(it);
}
m_AttachedShaders[shader->Type()] = shader;
}
void CShaderProgramOGLES1_0::DetachShader(IShader::ShaderType shaderType)
{
std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shaderType);
if (it != m_AttachedShaders.end()) {
m_AttachedShaders.erase(it);
}
}
bool CShaderProgramOGLES1_0::IsShaderAttached(IShader::ShaderType shaderType)
{
std::map<IShader::ShaderType, IShaderPtr>::const_iterator it = m_AttachedShaders.find(shaderType);
return (it != m_AttachedShaders.end());
}
bool CShaderProgramOGLES1_0::IsValid()
{
return (IsShaderAttached(IShader::Vertex) && IsShaderAttached(IShader::Fragment));
}
bool CShaderProgramOGLES1_0::Link()
{
m_VertexCoordHandle = Attribute("MainVertexPosition");
m_TextureCoordHandle = Attribute("MainVertexUV");
m_VertexColorHandle = Attribute("MainVertexColor");
m_TextureDataHadle.resize(6);
for (size_t i = 0; i < m_TextureDataHadle.size(); ++i) {
m_TextureDataHadle[i] = -1u;
}
m_TextureDataHadle[0] = Uniform("MainTexture0");
m_TextureDataHadle[1] = Uniform("MainTexture1");
m_TextureDataHadle[2] = Uniform("MainTexture2");
m_TextureDataHadle[3] = Uniform("MainTexture3");
m_TextureDataHadle[4] = Uniform("MainTexture4");
m_TextureDataHadle[5] = Uniform("MainTexture5");
m_ColorHandle = Uniform("MainColor");
m_ProectionMatrixHadle = Uniform("MainProjectionMatrix");
m_ModelMatrixHadle = Uniform("MainModelMatrix");
m_IsLinked = true;
return m_IsLinked;
}
bool CShaderProgramOGLES1_0::IsLinked() const
{
return m_IsLinked;
}
uint32_t CShaderProgramOGLES1_0::Attribute(const std::string& name)
{
static std::unordered_map<std::string, int> attributes = {
{ "MainVertexPosition", 0 },
{ "MainVertexUV", 1 },
{ "MainVertexColor", 2 }
};
if (attributes.find(name) != attributes.end()) {
return attributes[name];
}
return -1u;
}
uint32_t CShaderProgramOGLES1_0::Uniform(const std::string& name)
{
static std::unordered_map<std::string, int> uniforms = {
{ "MainTexture0", 0 },
{ "MainTexture1", 1 },
{ "MainTexture2", 2 },
{ "MainTexture3", 3 },
{ "MainTexture4", 4 },
{ "MainTexture5", 5 },
{ "MainColor", 6 },
{ "MainProjectionMatrix", 7 },
{ "MainModelMatrix", 8 },
};
if (uniforms.find(name) != uniforms.end()) {
return uniforms[name];
}
return -1u;
}
uint32_t CShaderProgramOGLES1_0::VertexPosition()
{
return m_VertexCoordHandle;
}
uint32_t CShaderProgramOGLES1_0::VertexNormal()
{
return m_VertexNormalHandle;
}
uint32_t CShaderProgramOGLES1_0::VertexUV()
{
return m_TextureCoordHandle;
}
uint32_t CShaderProgramOGLES1_0::VertexColor()
{
return m_VertexColorHandle;
}
uint32_t CShaderProgramOGLES1_0::MainTexture()
{
return m_TextureDataHadle[0];
}
uint32_t CShaderProgramOGLES1_0::MainColor()
{
return m_ColorHandle;
}
uint32_t CShaderProgramOGLES1_0::ProjectionMatrix()
{
return m_ProectionMatrixHadle;
}
uint32_t CShaderProgramOGLES1_0::ModelMatrix()
{
return m_ModelMatrixHadle;
}
uint32_t CShaderProgramOGLES1_0::Texture(uint32_t index)
{
if (index < 5) {
return m_TextureDataHadle[index];
}
return -1u;
}
uint32_t CShaderProgramOGLES1_0::DiffuseTexture()
{
return m_TextureDataHadle[0];
}
uint32_t CShaderProgramOGLES1_0::NormalTexture()
{
return m_TextureDataHadle[1];
}
uint32_t CShaderProgramOGLES1_0::SpecularTexture()
{
return m_TextureDataHadle[2];
}
uint32_t CShaderProgramOGLES1_0::EnvironmentTexture()
{
return m_TextureDataHadle[3];
}
bool CShaderProgramOGLES1_0::BindUniform1i(const std::string& uniform, int value)
{
m_UniInt[Uniform(uniform)] = { value };
return true;
}
bool CShaderProgramOGLES1_0::BindUniform1f(const std::string& uniform, float value)
{
m_UniFloat[Uniform(uniform)] = { value };
return true;
}
bool CShaderProgramOGLES1_0::BindUniform2i(const std::string& uniform, int value1, int value2)
{
m_UniInt[Uniform(uniform)] = { value1, value2 };
return true;
}
bool CShaderProgramOGLES1_0::BindUniform2f(const std::string& uniform, float value1, float value2)
{
m_UniFloat[Uniform(uniform)] = { value1, value2 };
return true;
}
bool CShaderProgramOGLES1_0::BindUniformfv(const std::string& uniform, const std::vector<float>& value)
{
m_UniFloatVec[Uniform(uniform)] = value;
return true;
}
bool CShaderProgramOGLES1_0::BindUniformMatrix4x4f(const std::string& uniform, const glm::mat4x4& value)
{
m_UniMatrixFloat[Uniform(uniform)] = value;
return true;
}
const IShaderProgram::TUniInt& CShaderProgramOGLES1_0::Uniformsi() const
{
return m_UniInt;
}
const IShaderProgram::TUniFloat& CShaderProgramOGLES1_0::Uniformsf() const
{
return m_UniFloat;
}
const IShaderProgram::TUniFloat& CShaderProgramOGLES1_0::Uniformsfv() const
{
return m_UniFloatVec;
}
const IShaderProgram::TUniMatrix4Float& CShaderProgramOGLES1_0::UniformsMatrix4x4f() const
{
return m_UniMatrixFloat;
}
void CShaderProgramOGLES1_0::UpdateUniforms() const
{
}
// *****************************************************************************
// Protected Methods
// *****************************************************************************
// *****************************************************************************
// Private Methods
// *****************************************************************************
#endif /* defined(RENDER_OGLES1_0) */
| 24.035088 | 106 | 0.643212 | opengamejam |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.