hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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
|
9eb8c75d4134e31fb7cd5a15e831fff7c1bc2abb
| 1,173
|
cpp
|
C++
|
icpc/2019-9-24/I.cpp
|
Riteme/test
|
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
|
[
"BSD-Source-Code"
] | 3
|
2018-08-30T09:43:20.000Z
|
2019-12-03T04:53:43.000Z
|
icpc/2019-9-24/I.cpp
|
Riteme/test
|
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
|
[
"BSD-Source-Code"
] | null | null | null |
icpc/2019-9-24/I.cpp
|
Riteme/test
|
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
|
[
"BSD-Source-Code"
] | null | null | null |
#include <cstdio>
#include <algorithm>
using namespace std;
#define NMAX 50
typedef unsigned char u8;
static int n, m, _, cnt;
static int u[NMAX], v[NMAX];
static u8 s[NMAX];
void dfs(int i) {
if (i == m) cnt++;
else if (s[u[i]] < s[v[i]]) {
dfs(i + 1);
swap(s[u[i]], s[v[i]]);
dfs(i + 1);
swap(s[u[i]], s[v[i]]);
}
}
inline void reset(int len) {
for (int i = 0; i < len; i++)
s[i] = i + 1;
}
int solve() {
cnt = 0;
reset(n);
dfs(0);
for (int i = 0; i < n; i++) {
reset(n);
for (int j = i - 1; j >= 0; j--) {
swap(s[j], s[j + 1]);
if (j + 1 != i) dfs(0);
}
reset(n);
for (int j = i + 1; j < n; j++) {
swap(s[j], s[j - 1]);
dfs(0);
}
}
return cnt;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d%d%d", &n, &m, &_);
for (int i = 0; i < m; i++) {
scanf("%d%d", u + i, v + i);
u[i]--;
v[i]--;
}
reverse(u, u + m);
reverse(v, v + m);
printf("%d\n", solve());
}
return 0;
}
| 17.772727
| 42
| 0.369991
|
Riteme
|
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
|
19b36115b0c392143e7461c8ca9b6eb61a4b9f70
| 338
|
hpp
|
C++
|
src/core/menu.hpp
|
dynilath/cqcppsdk
|
8f14c2ed85b6d2917ad7aef149acdfb89512937f
|
[
"MIT"
] | 154
|
2020-01-03T02:51:51.000Z
|
2020-08-03T19:44:53.000Z
|
src/core/menu.hpp
|
dynilath/cqcppsdk
|
8f14c2ed85b6d2917ad7aef149acdfb89512937f
|
[
"MIT"
] | 22
|
2020-01-26T04:18:28.000Z
|
2020-07-04T06:38:28.000Z
|
src/core/menu.hpp
|
dynilath/cqcppsdk
|
8f14c2ed85b6d2917ad7aef149acdfb89512937f
|
[
"MIT"
] | 40
|
2020-01-06T11:17:25.000Z
|
2020-08-07T08:26:32.000Z
|
#pragma once
#include "event_export_def.hpp"
#define CQ_MENU(FuncName) \
static void __cq_menu_##FuncName(); \
_CQ_EVENT(int32_t, FuncName, 0)() { \
__cq_menu_##FuncName(); \
return 0; \
} \
static void __cq_menu_##FuncName()
| 28.166667
| 41
| 0.482249
|
dynilath
|
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
|
19b6d2ecf6c5083c17df38b8f6498e6d484e2696
| 139
|
cpp
|
C++
|
base/win32/fusion/tools/idlxml/cpp.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
base/win32/fusion/tools/idlxml/cpp.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
base/win32/fusion/tools/idlxml/cpp.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
// Copyright (c) Microsoft Corporation
#define SORTPP_PASS
#define GUID_DEFINED
#define IN __in
#define OUT __out
#include "h.h"
| 15.444444
| 39
| 0.719424
|
npocmaka
|
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
|
19c14f19b5a65412d1f04fe10f48be8ce004e7e8
| 669
|
cpp
|
C++
|
SPOJ/MATGAME.cpp
|
TISparta/competitive-programming-solutions
|
31987d4e67bb874bf15653565c6418b5605a20a8
|
[
"MIT"
] | 1
|
2018-01-30T13:21:30.000Z
|
2018-01-30T13:21:30.000Z
|
SPOJ/MATGAME.cpp
|
TISparta/competitive-programming-solutions
|
31987d4e67bb874bf15653565c6418b5605a20a8
|
[
"MIT"
] | null | null | null |
SPOJ/MATGAME.cpp
|
TISparta/competitive-programming-solutions
|
31987d4e67bb874bf15653565c6418b5605a20a8
|
[
"MIT"
] | 1
|
2018-08-29T13:26:50.000Z
|
2018-08-29T13:26:50.000Z
|
/**
* > Author : TISparta
* > Date : 11-08-18
* > Tags : Game Theory
* > Difficulty : 4 / 10
*/
#include <bits/stdc++.h>
using namespace std;
const int MAX_M = 50;
int T, N, M, pile[MAX_M + 1], nim_sum, SGV;
int main() {
scanf("%d", &T);
while (T--) {
nim_sum = 0;
scanf("%d %d", &N, &M);
for (int row = 0; row < N; row++) {
for (int col = 0; col < M; col++) scanf("%d", &pile[col]);
SGV = pile[M - 1];
for (int col = M - 2; col >= 0; col--) SGV = pile[col] - (pile[col] <= SGV);
nim_sum ^= SGV;
}
puts(nim_sum == 0 ? "SECOND" : "FIRST");
}
return (0);
}
| 21.580645
| 88
| 0.442451
|
TISparta
|
19c4476cfd25ef06185acc5fc28c0a2a364af5a6
| 13,112
|
cpp
|
C++
|
src/mame/drivers/btoads.cpp
|
Robbbert/messui
|
49b756e2140d8831bc81335298ee8c5471045e79
|
[
"BSD-3-Clause"
] | 26
|
2015-03-31T06:25:51.000Z
|
2021-12-14T09:29:04.000Z
|
src/mame/drivers/btoads.cpp
|
Robbbert/messui
|
49b756e2140d8831bc81335298ee8c5471045e79
|
[
"BSD-3-Clause"
] | null | null | null |
src/mame/drivers/btoads.cpp
|
Robbbert/messui
|
49b756e2140d8831bc81335298ee8c5471045e79
|
[
"BSD-3-Clause"
] | 10
|
2015-03-27T05:45:51.000Z
|
2022-02-04T06:57:36.000Z
|
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/*************************************************************************
BattleToads
driver by Aaron Giles
**************************************************************************/
#include "emu.h"
#include "includes/btoads.h"
#include "speaker.h"
#define CPU_CLOCK XTAL(64'000'000)
#define VIDEO_CLOCK XTAL(20'000'000)
#define SOUND_CLOCK XTAL(24'000'000)
/*************************************
*
* Machine init
*
*************************************/
void btoads_state::machine_start()
{
m_nvram_data = std::make_unique<uint8_t[]>(0x2000);
subdevice<nvram_device>("nvram")->set_base(m_nvram_data.get(), 0x2000);
save_item(NAME(m_main_to_sound_data));
save_item(NAME(m_main_to_sound_ready));
save_item(NAME(m_sound_to_main_data));
save_item(NAME(m_sound_to_main_ready));
save_item(NAME(m_sound_int_state));
save_pointer(NAME(m_nvram_data), 0x2000);
}
/*************************************
*
* NVRAM
*
*************************************/
void btoads_state::nvram_w(offs_t offset, uint8_t data)
{
m_nvram_data[offset] = data;
}
uint8_t btoads_state::nvram_r(offs_t offset)
{
return m_nvram_data[offset];
}
/*************************************
*
* Main -> sound CPU communication
*
*************************************/
void btoads_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
switch (id)
{
case TIMER_ID_DELAYED_SOUND:
m_main_to_sound_data = param;
m_main_to_sound_ready = 1;
m_audiocpu->signal_interrupt_trigger();
// use a timer to make long transfers faster
timer_set(attotime::from_usec(50), TIMER_ID_NOP);
break;
}
}
void btoads_state::main_sound_w(offs_t offset, uint16_t data, uint16_t mem_mask)
{
if (ACCESSING_BITS_0_7)
synchronize(TIMER_ID_DELAYED_SOUND, data & 0xff);
}
uint16_t btoads_state::main_sound_r()
{
m_sound_to_main_ready = 0;
return m_sound_to_main_data;
}
READ_LINE_MEMBER( btoads_state::main_to_sound_r )
{
return m_main_to_sound_ready;
}
READ_LINE_MEMBER( btoads_state::sound_to_main_r )
{
return m_sound_to_main_ready;
}
/*************************************
*
* Sound -> main CPU communication
*
*************************************/
void btoads_state::sound_data_w(uint8_t data)
{
m_sound_to_main_data = data;
m_sound_to_main_ready = 1;
}
uint8_t btoads_state::sound_data_r()
{
m_main_to_sound_ready = 0;
return m_main_to_sound_data;
}
uint8_t btoads_state::sound_ready_to_send_r()
{
return m_sound_to_main_ready ? 0x00 : 0x80;
}
uint8_t btoads_state::sound_data_ready_r()
{
if (m_audiocpu->pc() == 0xd50 && !m_main_to_sound_ready)
m_audiocpu->spin_until_interrupt();
return m_main_to_sound_ready ? 0x00 : 0x80;
}
/*************************************
*
* Sound CPU interrupt generation
*
*************************************/
void btoads_state::sound_int_state_w(uint8_t data)
{
/* top bit controls BSMT2000 reset */
if (!(m_sound_int_state & 0x80) && (data & 0x80))
m_bsmt->reset();
/* also clears interrupts */
m_audiocpu->set_input_line(0, CLEAR_LINE);
m_sound_int_state = data;
}
/*************************************
*
* Sound CPU BSMT2000 communication
*
*************************************/
uint8_t btoads_state::bsmt_ready_r()
{
return m_bsmt->read_status() << 7;
}
void btoads_state::bsmt2000_port_w(offs_t offset, uint8_t data)
{
m_bsmt->write_reg(offset >> 8);
m_bsmt->write_data(((offset & 0xff) << 8) | data);
}
/*************************************
*
* Main CPU memory map
*
*************************************/
void btoads_state::main_map(address_map &map)
{
map(0x00000000, 0x003fffff).ram();
map(0x20000000, 0x2000007f).portr("P1");
map(0x20000080, 0x200000ff).portr("P2");
map(0x20000100, 0x2000017f).portr("P3");
map(0x20000180, 0x200001ff).portr("UNK");
map(0x20000200, 0x2000027f).portr("SPECIAL");
map(0x20000280, 0x200002ff).portr("SW1");
map(0x20000000, 0x200000ff).writeonly().share("sprite_scale");
map(0x20000100, 0x2000017f).writeonly().share("sprite_control");
map(0x20000180, 0x200001ff).w(FUNC(btoads_state::display_control_w));
map(0x20000200, 0x2000027f).w(FUNC(btoads_state::scroll0_w));
map(0x20000280, 0x200002ff).w(FUNC(btoads_state::scroll1_w));
map(0x20000300, 0x2000037f).rw(m_tlc34076, FUNC(tlc34076_device::read), FUNC(tlc34076_device::write)).umask32(0x000000ff);
map(0x20000380, 0x200003ff).rw(FUNC(btoads_state::main_sound_r), FUNC(btoads_state::main_sound_w));
map(0x20000400, 0x2000047f).w(FUNC(btoads_state::misc_control_w));
map(0x40000000, 0x4000001f).nopw(); /* watchdog? */
map(0x60000000, 0x6003ffff).rw(FUNC(btoads_state::nvram_r), FUNC(btoads_state::nvram_w)).umask32(0x000000ff);
map(0xa0000000, 0xa03fffff).rw(FUNC(btoads_state::vram_fg_display_r), FUNC(btoads_state::vram_fg_display_w));
map(0xa4000000, 0xa43fffff).rw(FUNC(btoads_state::vram_fg_draw_r), FUNC(btoads_state::vram_fg_draw_w));
map(0xa8000000, 0xa87fffff).ram().share("vram_fg_data");
map(0xa8800000, 0xa8ffffff).nopw();
map(0xb0000000, 0xb03fffff).rw(FUNC(btoads_state::vram_bg0_r), FUNC(btoads_state::vram_bg0_w));
map(0xb4000000, 0xb43fffff).rw(FUNC(btoads_state::vram_bg1_r), FUNC(btoads_state::vram_bg1_w));
map(0xfc000000, 0xffffffff).rom().region("user1", 0);
}
/*************************************
*
* Sound CPU memory map
*
*************************************/
void btoads_state::sound_map(address_map &map)
{
map(0x0000, 0x7fff).rom();
map(0x8000, 0xffff).ram();
}
void btoads_state::sound_io_map(address_map &map)
{
map(0x0000, 0x7fff).w(FUNC(btoads_state::bsmt2000_port_w));
map(0x8000, 0x8000).rw(FUNC(btoads_state::sound_data_r), FUNC(btoads_state::sound_data_w));
map(0x8002, 0x8002).w(FUNC(btoads_state::sound_int_state_w));
map(0x8004, 0x8004).r(FUNC(btoads_state::sound_data_ready_r));
map(0x8005, 0x8005).r(FUNC(btoads_state::sound_ready_to_send_r));
map(0x8006, 0x8006).r(FUNC(btoads_state::bsmt_ready_r));
}
/*************************************
*
* Input ports
*
*************************************/
static INPUT_PORTS_START( btoads )
PORT_START("P1")
PORT_BIT( 0x00000001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1)
PORT_BIT( 0x00000002, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1)
PORT_BIT( 0x00000004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1)
PORT_BIT( 0x00000008, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1)
PORT_BIT( 0x00000010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x00000020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1)
PORT_BIT( 0x00000040, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_IMPULSE(2)
PORT_BIT( 0x00000080, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("P2")
PORT_BIT( 0x00000001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2)
PORT_BIT( 0x00000002, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2)
PORT_BIT( 0x00000004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2)
PORT_BIT( 0x00000008, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2)
PORT_BIT( 0x00000010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x00000020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
PORT_BIT( 0x00000040, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_IMPULSE(2)
PORT_BIT( 0x00000080, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("P3")
PORT_BIT( 0x00000001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(3)
PORT_BIT( 0x00000002, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(3)
PORT_BIT( 0x00000004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(3)
PORT_BIT( 0x00000008, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(3)
PORT_BIT( 0x00000010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
PORT_BIT( 0x00000020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
PORT_BIT( 0x00000040, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_IMPULSE(2)
PORT_BIT( 0x00000080, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("UNK")
PORT_BIT( 0xffffffff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("SPECIAL")
PORT_BIT( 0x00000001, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(btoads_state, sound_to_main_r)
PORT_SERVICE_NO_TOGGLE( 0x0002, IP_ACTIVE_LOW )
PORT_BIT( 0x00000080, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_READ_LINE_MEMBER(btoads_state, main_to_sound_r)
PORT_BIT( 0xffffff7c, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("SW1")
PORT_DIPNAME( 0x0001, 0x0000, DEF_STR( Demo_Sounds )) PORT_DIPLOCATION("SW1:1")
PORT_DIPSETTING( 0x0001, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPNAME( 0x0002, 0x0000, DEF_STR( Stereo )) PORT_DIPLOCATION("SW1:2")
PORT_DIPSETTING( 0x0002, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPNAME( 0x0004, 0x0000, "Common Coin Mech") PORT_DIPLOCATION("SW1:3")
PORT_DIPSETTING( 0x0004, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPNAME( 0x0008, 0x0008, "Three Players") PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x0008, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Free_Play )) PORT_DIPLOCATION("SW1:5")
PORT_DIPSETTING( 0x0010, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPNAME( 0x0020, 0x0020, "Blood Free Mode") PORT_DIPLOCATION("SW1:6")
PORT_DIPSETTING( 0x0020, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPNAME( 0x0040, 0x0040, "Credit Retention") PORT_DIPLOCATION("SW1:7")
PORT_DIPSETTING( 0x0040, DEF_STR( Off ))
PORT_DIPSETTING( 0x0000, DEF_STR( On ))
PORT_DIPUNKNOWN_DIPLOC(0x0080, 0x0080, "SW1:8")
PORT_BIT( 0xffffff00, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
/*************************************
*
* Machine drivers
*
*************************************/
void btoads_state::btoads(machine_config &config)
{
TMS34020(config, m_maincpu, CPU_CLOCK/2);
m_maincpu->set_addrmap(AS_PROGRAM, &btoads_state::main_map);
m_maincpu->set_halt_on_reset(false);
m_maincpu->set_pixel_clock(VIDEO_CLOCK/2);
m_maincpu->set_pixels_per_clock(1);
m_maincpu->set_scanline_rgb32_callback(FUNC(btoads_state::scanline_update));
m_maincpu->set_shiftreg_in_callback(FUNC(btoads_state::to_shiftreg));
m_maincpu->set_shiftreg_out_callback(FUNC(btoads_state::from_shiftreg));
Z80(config, m_audiocpu, SOUND_CLOCK/4);
m_audiocpu->set_addrmap(AS_PROGRAM, &btoads_state::sound_map);
m_audiocpu->set_addrmap(AS_IO, &btoads_state::sound_io_map);
m_audiocpu->set_periodic_int(FUNC(btoads_state::irq0_line_assert), attotime::from_hz(SOUND_CLOCK/4/32768));
NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_1);
/* video hardware */
TLC34076(config, m_tlc34076, tlc34076_device::TLC34076_6_BIT);
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_raw(VIDEO_CLOCK/2, 640, 0, 512, 257, 0, 224);
m_screen->set_screen_update("maincpu", FUNC(tms34020_device::tms340x0_rgb32));
/* sound hardware */
SPEAKER(config, "lspeaker").front_left();
SPEAKER(config, "rspeaker").front_right();
BSMT2000(config, m_bsmt, SOUND_CLOCK);
m_bsmt->add_route(0, "lspeaker", 1.0);
m_bsmt->add_route(1, "rspeaker", 1.0);
}
/*************************************
*
* ROM definitions
*
*************************************/
ROM_START( btoads )
ROM_REGION( 0x10000, "audiocpu", 0 ) /* sound program, M27C256B rom */
ROM_LOAD( "bt.u102", 0x0000, 0x8000, CRC(a90b911a) SHA1(6ec25161e68df1c9870d48cc2b1f85cd1a49aba9) )
ROM_REGION32_LE( 0x800000, "user1", 0 ) /* 34020 code, M27C322 roms */
ROM_LOAD32_WORD( "btc0-p0.u120", 0x000000, 0x400000, CRC(0dfd1e35) SHA1(733a0a4235bebd598c600f187ed2628f28cf9bd0) )
ROM_LOAD32_WORD( "btc0-p1.u121", 0x000002, 0x400000, CRC(df7487e1) SHA1(67151b900767bb2653b5261a98c81ff8827222c3) )
ROM_REGION( 0x1000000, "bsmt", 0 ) /* BSMT data, M27C160 rom */
ROM_LOAD( "btc0-s.u109", 0x00000, 0x200000, CRC(d9612ddb) SHA1(f186dfb013e81abf81ba8ac5dc7eb731c1ad82b6) )
ROM_REGION( 0x080a, "plds", 0 )
ROM_LOAD( "u10.bin", 0x0000, 0x0157, CRC(b1144178) SHA1(15fb047adee4125e9fcf04171e0a502655e0a3d8) ) /* GAL20V8A-15LP Located at U10. */
ROM_LOAD( "u11.bin", 0x0000, 0x0157, CRC(7c6beb96) SHA1(2f19d21889dd765b344ad7d257ea7c244baebec2) ) /* GAL20V8A-15LP Located at U11. */
ROM_LOAD( "u57.bin", 0x0000, 0x0157, CRC(be355a56) SHA1(975238bb1ea8fef14458d6f264a82aa77ecf865d) ) /* GAL20V8A-15LP Located at U57. */
ROM_LOAD( "u58.bin", 0x0000, 0x0157, CRC(41ed339c) SHA1(5853c805a902e6d12c979958d878d1cefd6908cc) ) /* GAL20V8A-15LP Located at U58. */
ROM_LOAD( "u90.bin", 0x0000, 0x0157, CRC(a0d0c3f1) SHA1(47464c2ef9fadbba933df27767f377e0c29158aa) ) /* GAL20V8A-15LP Located at U90. */
ROM_LOAD( "u144.bin", 0x0000, 0x0157, CRC(8597017f) SHA1(003d7b5de57e48f831ab211e2783fff338ce2f32) ) /* GAL20V8A-15LP Located at U144. */
ROM_END
/*************************************
*
* Game drivers
*
*************************************/
GAME( 1994, btoads, 0, btoads, btoads, btoads_state, empty_init, ROT0, "Rare / Electronic Arts", "Battletoads", MACHINE_SUPPORTS_SAVE )
| 32.862155
| 138
| 0.690589
|
Robbbert
|
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
|
19cabdd0e228af0ec12b2a070e143a05b4998947
| 1,994
|
cpp
|
C++
|
testtool/common.cpp
|
obono/TinyJoypadWorks
|
e9f5403fc435b7fece1b6d488dcef3a6699e6194
|
[
"MIT"
] | 3
|
2020-12-28T20:22:44.000Z
|
2022-02-22T08:33:14.000Z
|
testtool/common.cpp
|
obono/TinyJoypadWorks
|
e9f5403fc435b7fece1b6d488dcef3a6699e6194
|
[
"MIT"
] | null | null | null |
testtool/common.cpp
|
obono/TinyJoypadWorks
|
e9f5403fc435b7fece1b6d488dcef3a6699e6194
|
[
"MIT"
] | null | null | null |
#include "common.h"
/* Defines */
#define NUMBER_DIGITS 3
#define DPAD_BUTTONS (LEFT_BUTTON | RIGHT_BUTTON | DOWN_BUTTON | UP_BUTTON)
/* Global Variables */
RECORD_T record;
char stringBuffer[STRING_BUFFERS][STRING_BUFFER_SIZE];
int8_t dpadX, dpadY;
/* Local Variables */
static PROGMEM const uint8_t imgButtons[] = { // 6x6 x5
0x04, 0x04, 0x0E, 0x0E, 0x1F, 0x00, // left
0x1F, 0x0E, 0x0E, 0x04, 0x04, 0x00, // right
0x01, 0x07, 0x1F, 0x07, 0x01, 0x00, // down
0x10, 0x1C, 0x1F, 0x1C, 0x10, 0x00, // up
0x0E, 0x1F, 0x1F, 0x1F, 0x0E, 0x00, // A
};
static uint8_t dpadCounter;
/*---------------------------------------------------------------------------*/
void setDpadSprite(uint8_t idx, DPAD_SPRITE_T type, int8_t x, int8_t y)
{
const uint8_t *p = imgButtons;
uint8_t w = 12;
switch (type) {
case DPAD_SPRITE_ALL: w = 30; break;
case DPAD_SPRITE_X_AXIS: break;
case DPAD_SPRITE_Y_AXIS: p += 12; break;
case DPAD_SPRITE_BUTTON: p += 24; w = 6; break;
}
setSprite(idx, x, y, p, w, 8, WHITE);
}
char *(setStringBuffer)(uint8_t idx, const __FlashStringHelper *pFlashString)
{
uint8_t len = strlen_P((const char *)pFlashString);
char *p = stringBuffer[idx];
memcpy_P(p, pFlashString, len + 1);
return p;
}
void printNumber(uint8_t idx, uint8_t offset, uint16_t number, uint8_t radix)
{
char *p = &stringBuffer[idx][offset];
for (int8_t i = 0; i < NUMBER_DIGITS; i++) {
uint8_t c = number % radix;
*p-- = (number || i == 0) ? c + ((c < 10) ? '0' : 'A' - 10) : ' ';
number /= radix;
}
}
void handleDpad(void)
{
dpadX = isButtonPressed(RIGHT_BUTTON) - isButtonPressed(LEFT_BUTTON);
dpadY = isButtonPressed(DOWN_BUTTON) - isButtonPressed(UP_BUTTON);
if (isButtonPressed(DPAD_BUTTONS)) {
if (dpadCounter < DPAD_REPEAT_DELAY && dpadCounter++ > 0) dpadX = dpadY = 0;
} else {
dpadCounter = 0;
}
}
| 28.898551
| 84
| 0.599799
|
obono
|
19cb35df39f98f047e984076450eebeaa84167f1
| 5,535
|
cpp
|
C++
|
test/test_session.cpp
|
dvetutnev/tomsksoft
|
39741046e1355ac36775189b4e8970af3a7861cd
|
[
"MIT"
] | null | null | null |
test/test_session.cpp
|
dvetutnev/tomsksoft
|
39741046e1355ac36775189b4e8970af3a7861cd
|
[
"MIT"
] | null | null | null |
test/test_session.cpp
|
dvetutnev/tomsksoft
|
39741046e1355ac36775189b4e8970af3a7861cd
|
[
"MIT"
] | null | null | null |
#include "session.h"
#include "mocks.h"
#include "create_packet.h"
#include <algorithm>
using ::testing::SaveArg;
using ::testing::InSequence;
using ::testing::StrictMock;
using ::testing::NiceMock;
using ::testing::AtLeast;
TEST(Session, timeout) {
MockServer server;
StrictMock<MockWriter> writer;
auto client = std::make_shared<NiceMock<MockSocket>>();
MockHandle::THandler<uvw::DataEvent> handlerDataEvent;
EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent));
{
InSequence _;
EXPECT_CALL(*client, read).Times(1);
EXPECT_CALL(*client, stop).Times(1);
EXPECT_CALL(*client, close).Times(1);
}
auto timer = std::make_shared<StrictMock<MockTimer>>();
MockHandle::THandler<uvw::TimerEvent> handlerTimerEvent;
EXPECT_CALL(*timer, saveHandler).WillOnce(SaveArg<0>(&handlerTimerEvent));
{
InSequence _;
EXPECT_CALL(*timer, start).Times(1);
EXPECT_CALL(*timer, stop).Times(1);
EXPECT_CALL(*timer, close).Times(1);
}
Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer};
EXPECT_CALL(server, remove(&session)).Times(1);
uvw::DataEvent dataEvent{std::make_unique<char[]>(3), 3};;
handlerDataEvent(dataEvent, *client);
handlerTimerEvent(uvw::TimerEvent{}, *timer);
}
TEST(Session, networkError) {
MockServer server;
StrictMock<MockWriter> writer;
auto client = std::make_shared<NiceMock<MockSocket>>();
MockHandle::THandler<uvw::DataEvent> handlerDataEvent;
EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent));
MockHandle::THandler<uvw::ErrorEvent> handlerErrorEvent;
EXPECT_CALL(*client, saveErrorHandler).WillOnce(SaveArg<0>(&handlerErrorEvent));
{
InSequence _;
EXPECT_CALL(*client, read).Times(1);
EXPECT_CALL(*client, stop).Times(1);
EXPECT_CALL(*client, close).Times(1);
}
auto timer = std::make_shared<NiceMock<MockTimer>>();
{
InSequence _;
EXPECT_CALL(*timer, start).Times(1);
EXPECT_CALL(*timer, stop).Times(1);
EXPECT_CALL(*timer, close).Times(1);
}
Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer};
EXPECT_CALL(server, remove(&session)).Times(1);
uvw::DataEvent dataEvent{std::make_unique<char[]>(3), 3};;
handlerDataEvent(dataEvent, *client);
handlerErrorEvent(uvw::ErrorEvent{static_cast<std::underlying_type_t<uv_errno_t>>(UV_EFAULT)}, *client);
}
TEST(Session, normal) {
StrictMock<MockServer> server;
MockWriter writer;
auto client = std::make_shared<NiceMock<MockSocket>>();
MockHandle::THandler<uvw::DataEvent> handlerDataEvent;
EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent));
EXPECT_CALL(*client, read).Times(1);
auto timer = std::make_shared<NiceMock<MockTimer>>();
EXPECT_CALL(*timer, start).Times(1);
Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer};
EXPECT_CALL(writer, push("abcdef")).Times(1);
auto dataEvent = createPacket("abcdef");
handlerDataEvent(dataEvent, *client);
}
TEST(Session, repeat) {
StrictMock<MockServer> server;
MockWriter writer;
auto client = std::make_shared<NiceMock<MockSocket>>();
MockHandle::THandler<uvw::DataEvent> handlerDataEvent;
EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent));
EXPECT_CALL(*client, read).Times(1);
auto timer = std::make_shared<NiceMock<MockTimer>>();
EXPECT_CALL(*timer, start).Times(1);
EXPECT_CALL(*timer, again).Times(AtLeast(1));
Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer};
const std::string data1 = "abcdefqwert";
auto packet1 = createPacket(data1);
const std::string data2 = "42abcdefqwert";
auto packet2 = createPacket(data2);
{
InSequence _;
EXPECT_CALL(writer, push(data1)).Times(1);
EXPECT_CALL(writer, push(data2)).Times(1);
}
handlerDataEvent(packet1, *client);
handlerDataEvent(packet2, *client);
}
TEST(Session, disconnect) {
StrictMock<MockServer> server;
NiceMock<MockWriter> writer;
auto client = std::make_shared<NiceMock<MockSocket>>();
MockHandle::THandler<uvw::DataEvent> handlerDataEvent;
EXPECT_CALL(*client, saveDataHandler).WillOnce(SaveArg<0>(&handlerDataEvent));
MockHandle::THandler<uvw::EndEvent> handlerEndEvent;
EXPECT_CALL(*client, saveEndHandler).WillOnce(SaveArg<0>(&handlerEndEvent));
EXPECT_CALL(*client, read).Times(1);
auto timer = std::make_shared<NiceMock<MockTimer>>();
Session<MockServer, MockWriter, MockSocket, MockTimer> session{server, writer, client, timer};
auto createPacket = [](const std::string& data) -> uvw::DataEvent {
std::uint32_t header = ::htonl(data.size());
std::size_t packetLength = sizeof(header) + data.size();
uvw::DataEvent packet{std::make_unique<char[]>(packetLength), packetLength};;
std::copy_n(reinterpret_cast<const char*>(&header), sizeof(header), packet.data.get());
std::copy_n(data.data(), data.size(), packet.data.get() + sizeof(header));
return packet;
};
EXPECT_CALL(server, remove(&session)).Times(1);
auto packet = createPacket("abcdefqwert");
handlerDataEvent(packet, *client);
handlerEndEvent(uvw::EndEvent{}, *client);
}
| 31.810345
| 108
| 0.687263
|
dvetutnev
|
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
|
19d280bfd3df9525e25a7dcb89e6102afb006dac
| 970
|
cpp
|
C++
|
vdslib/src/tests/distribution/randombucket.cpp
|
kennyeric/vespa
|
f69f960d5ae48d246f56a60e6e46c90a58f836ba
|
[
"Apache-2.0"
] | 1
|
2018-12-30T05:42:18.000Z
|
2018-12-30T05:42:18.000Z
|
vdslib/src/tests/distribution/randombucket.cpp
|
kennyeric/vespa
|
f69f960d5ae48d246f56a60e6e46c90a58f836ba
|
[
"Apache-2.0"
] | 1
|
2021-03-31T22:27:25.000Z
|
2021-03-31T22:27:25.000Z
|
vdslib/src/tests/distribution/randombucket.cpp
|
kennyeric/vespa
|
f69f960d5ae48d246f56a60e6e46c90a58f836ba
|
[
"Apache-2.0"
] | 1
|
2020-02-01T07:21:28.000Z
|
2020-02-01T07:21:28.000Z
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "randombucket.h"
#include <vespa/vdslib/state/random.h>
namespace RandomBucket{
uint64_t _num_users;
uint64_t _locationbits;
bool _scheme = false;
storage::lib::RandomGen rg;
void setUserDocScheme(uint64_t num_users, uint64_t locationbits)
{
_scheme = true;
_num_users = num_users;
_locationbits = locationbits;
}
void setDocScheme()
{
_scheme = false;
}
uint64_t get()
{
uint64_t u = rg.nextUint64();
if(_scheme){ // userdoc
uint64_t shift = 8 * sizeof(uint64_t) - _locationbits;
uint64_t lsb = u << shift;
lsb >>= shift;
lsb %= _num_users;
u >>= _locationbits;
u <<= _locationbits;
u |= lsb;
}
return u;
}
void setSeed(int seed)
{
if(seed == -1){
rg = storage::lib::RandomGen();
}
else{
rg.setSeed(seed);
}
}
}
| 19.019608
| 118
| 0.627835
|
kennyeric
|
19d59469611a8e400bce05b775c6c90b3652d6d0
| 4,617
|
cpp
|
C++
|
lammps-master/lib/poems/virtualmatrix.cpp
|
rajkubp020/helloword
|
4bd22691de24b30a0f5b73821c35a7ac0666b034
|
[
"MIT"
] | null | null | null |
lammps-master/lib/poems/virtualmatrix.cpp
|
rajkubp020/helloword
|
4bd22691de24b30a0f5b73821c35a7ac0666b034
|
[
"MIT"
] | null | null | null |
lammps-master/lib/poems/virtualmatrix.cpp
|
rajkubp020/helloword
|
4bd22691de24b30a0f5b73821c35a7ac0666b034
|
[
"MIT"
] | null | null | null |
/*
*_________________________________________________________________________*
* POEMS: PARALLELIZABLE OPEN SOURCE EFFICIENT MULTIBODY SOFTWARE *
* DESCRIPTION: SEE READ-ME *
* FILE NAME: virtualmatrix.cpp *
* AUTHORS: See Author List *
* GRANTS: See Grants List *
* COPYRIGHT: (C) 2005 by Authors as listed in Author's List *
* LICENSE: Please see License Agreement *
* DOWNLOAD: Free at www.rpi.edu/~anderk5 *
* ADMINISTRATOR: Prof. Kurt Anderson *
* Computational Dynamics Lab *
* Rensselaer Polytechnic Institute *
* 110 8th St. Troy NY 12180 *
* CONTACT: anderk5@rpi.edu *
*_________________________________________________________________________*/
#include "virtualmatrix.h"
#include "matrixfun.h"
#include <cstdlib>
using namespace std;
VirtualMatrix::VirtualMatrix(){
numrows = numcols = 0;
}
VirtualMatrix::~VirtualMatrix(){
}
int VirtualMatrix::GetNumRows() const {
return numrows;
}
int VirtualMatrix::GetNumCols() const {
return numcols;
}
double& VirtualMatrix::operator() (int i, int j){ // array access
return operator_2int(i,j);
}
double VirtualMatrix::Get(int i, int j) const{
return Get_2int(i,j);
}
void VirtualMatrix::Set(int i, int j, double value){
Set_2int(i,j,value);
}
double VirtualMatrix::BasicGet(int i, int j) const{
return BasicGet_2int(i,j);
}
void VirtualMatrix::BasicSet(int i, int j, double value){
BasicSet_2int(i,j,value);
}
void VirtualMatrix::BasicIncrement(int i, int j, double value){
BasicIncrement_2int(i,j,value);
}
double& VirtualMatrix::operator() (int i){
return operator_1int(i);
}
double VirtualMatrix::Get(int i) const{
return Get_1int(i);
}
void VirtualMatrix::Set(int i, double value){
Set_1int(i, value);
}
double VirtualMatrix::BasicGet(int i) const{
return BasicGet_1int(i);
}
void VirtualMatrix::BasicSet(int i, double value){
BasicSet_1int(i, value);
}
void VirtualMatrix::BasicIncrement(int i, double value){
BasicIncrement_1int(i, value);
}
double& VirtualMatrix::operator_1int (int i) {
cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl;
exit(0);
return *(new double);
}
double VirtualMatrix::Get_1int(int i) const {
cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl;
exit(0);
return 0.0;
}
void VirtualMatrix::Set_1int(int i, double value){
cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl;
exit(0);
}
double VirtualMatrix::BasicGet_1int(int i) const {
cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl;
exit(0);
return 0.0;
}
void VirtualMatrix::BasicSet_1int(int i, double value) {
cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl;
exit(0);
}
void VirtualMatrix::BasicIncrement_1int(int i, double value){
cerr << "Error: single dimensional access is not defined for matrices of type " << GetType() << endl;
exit(0);
}
void VirtualMatrix::Zeros(){
Const(0.0);
}
void VirtualMatrix::Ones(){
Const(1.0);
}
ostream& VirtualMatrix::WriteData(ostream& c) const {
cerr << "Error: no output definition for matrices of type " << GetType() << endl;
exit(0);
}
istream& VirtualMatrix::ReadData(istream& c){
cerr << "Error: no input definition for matrices of type " << GetType() << endl;
exit(0);
}
//
// operators and functions
//
ostream& operator<< (ostream& c, const VirtualMatrix& A){ //output
c << A.GetType() << ' ';
A.WriteData(c);
c << endl;
return c;
}
istream& operator>> (istream& c, VirtualMatrix& A){ //input
VirtualMatrix* vm;
int matrixtype;
c >> matrixtype;
if( MatrixType(matrixtype) == A.GetType() ) A.ReadData(c);
else{
// issue a warning?
cerr << "Warning: During matrix read expected type " << A.GetType() << " and got type " << matrixtype << endl;
vm = NewMatrix(matrixtype);
if(!vm){
cerr << "Error: unable to instantiate matrix of type " << matrixtype << endl;
exit(0);
}
vm->ReadData(c);
A.AssignVM(*vm);
delete vm;
}
return c;
}
| 26.843023
| 114
| 0.621183
|
rajkubp020
|
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 <amoinier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* 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
|
19de5723db8d917abd9a56bffc906ebfb0b90aec
| 542
|
cpp
|
C++
|
3rdParty/B-Human/Tools/Streams/InOut.cpp
|
h3ndrk/CompiledNN
|
8ed33a8d976367bfe7a62f506ba6215256a5b26c
|
[
"MIT"
] | null | null | null |
3rdParty/B-Human/Tools/Streams/InOut.cpp
|
h3ndrk/CompiledNN
|
8ed33a8d976367bfe7a62f506ba6215256a5b26c
|
[
"MIT"
] | null | null | null |
3rdParty/B-Human/Tools/Streams/InOut.cpp
|
h3ndrk/CompiledNN
|
8ed33a8d976367bfe7a62f506ba6215256a5b26c
|
[
"MIT"
] | null | null | null |
/**
* @file Tools/Streams/InOut.cpp
*
* Implementation of the streamable function endl.
*
* @author <a href="mailto:oberlies@sim.tu-darmstadt.de">Tobias Oberlies</a>
*/
#include "InOut.h"
#include <cstring>
Out& endl(Out& out)
{
out.outEndL();
return out;
}
In& endl(In& in)
{
in.inEndL();
return in;
}
namespace Streaming
{
void trimName(const char*& name)
{
if(name)
{
const char* p = name + strlen(name) - 1;
while(p >= name && *p != ')' && *p != ' ')
--p;
name = p + 1;
}
}
}
| 14.648649
| 76
| 0.551661
|
h3ndrk
|
19e483c8ad2f6650868557d6c731d793e94a8c5b
| 437
|
hpp
|
C++
|
server/api/include/irods/rsFileRead.hpp
|
aghsmith/irods
|
31d48a47a4942df688da94b30aa8a5b5210261bb
|
[
"BSD-3-Clause"
] | 1
|
2022-03-08T13:00:56.000Z
|
2022-03-08T13:00:56.000Z
|
server/api/include/irods/rsFileRead.hpp
|
selroc/irods
|
d232c7f3e0154cacc3a115aa50e366a98617b126
|
[
"BSD-3-Clause"
] | null | null | null |
server/api/include/irods/rsFileRead.hpp
|
selroc/irods
|
d232c7f3e0154cacc3a115aa50e366a98617b126
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef RS_FILE_READ_HPP
#define RS_FILE_READ_HPP
#include "irods/rodsConnect.h"
#include "irods/fileRead.h"
int rsFileRead( rsComm_t *rsComm, fileReadInp_t *fileReadInp, bytesBuf_t *fileReadOutBBuf );
int _rsFileRead( rsComm_t *rsComm, fileReadInp_t *fileReadInp, bytesBuf_t *fileReadOutBBuf );
int remoteFileRead( rsComm_t *rsComm, fileReadInp_t *fileReadInp, bytesBuf_t *fileReadOutBBuf, rodsServerHost_t *rodsServerHost );
#endif
| 36.416667
| 130
| 0.816934
|
aghsmith
|
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
|
19e89de6247e69bf0bb45872c22c40fc10280620
| 1,551
|
cpp
|
C++
|
test/spMatspMat_test.cpp
|
pnnl/NWGraph
|
bd9e091d2eed4e655c109347c3ec734bf399ff70
|
[
"BSD-4-Clause-UC"
] | null | null | null |
test/spMatspMat_test.cpp
|
pnnl/NWGraph
|
bd9e091d2eed4e655c109347c3ec734bf399ff70
|
[
"BSD-4-Clause-UC"
] | null | null | null |
test/spMatspMat_test.cpp
|
pnnl/NWGraph
|
bd9e091d2eed4e655c109347c3ec734bf399ff70
|
[
"BSD-4-Clause-UC"
] | null | null | null |
/**
* @file spMatspMat_test.cpp
*
* @copyright SPDX-FileCopyrightText: 2022 Battelle Memorial Institute
* @copyright SPDX-FileCopyrightText: 2022 University of Washington
*
* SPDX-License-Identifier: BSD-3-Clause
*
* @authors
* Andrew Lumsdaine
*
*/
#include <tuple>
#include <vector>
#include "nwgraph/graph_concepts.hpp"
#include "nwgraph/adaptors/edge_range.hpp"
#include "common/test_header.hpp"
#include "nwgraph/algorithms/spMatspMat.hpp"
TEST_CASE("Row times Row", "[row-row") {
// Create A, B and known correct answer
// By hand
// Generate random A, B compute C with known, slow, approach
// (e.g., convert A, B to dense
// Compute C = A * B with spMatspMat
// Compare C with known correct answer
/*
[ 3, 1, 4 ] [ 8, 6, 7 ] [ 65, 21, 57 ]
[ 1, 5, 9 ] [ 5, 3, 0 ] = [ 114, 21, 88 ]
[ 2, 6, 7 ] [ 9, 0, 9 ] [ 109, 30, 77 ]
*/
using SparseMatrix = std::vector<std::vector<std::tuple<int, double>>>;
SparseMatrix A {
{ { 0, 3 }, { 1, 1 }, { 2, 4 } },
{ { 0, 1 }, { 1, 5 }, { 2, 9 } },
{ { 0, 2 }, { 1, 6 }, { 2, 7 } },
};
SparseMatrix B {
{ { 0, 8 }, { 1, 6 }, { 2, 7 } },
{ { 0, 5 }, { 1, 3 }, { 2, 0 } },
{ { 0, 9 }, { 1, 0 }, { 2, 9 } },
};
SparseMatrix C {
{ { 0, 65 }, { 1, 21 }, { 2, 57 } },
{ { 0, 114 }, { 1, 21 }, { 2, 88 } },
{ { 0, 109 }, { 1, 30 }, { 2, 77 } },
};
auto d = nw::graph::spMatspMat<double>(A, B);
REQUIRE(std::equal(begin(d), end(d), begin(nw::graph::make_edge_range<0>(C))));
}
| 25.42623
| 81
| 0.516441
|
pnnl
|
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
|
19ea691d62f5de4780a604b7cda878648f87c921
| 35,453
|
cpp
|
C++
|
src/Layers/xrRender/xrRender_console.cpp
|
clayne/xray-16
|
32ebf81a252c7179e2824b2874f911a91e822ad1
|
[
"OML",
"Linux-OpenIB"
] | 2
|
2015-02-23T10:43:02.000Z
|
2015-06-11T14:45:08.000Z
|
src/Layers/xrRender/xrRender_console.cpp
|
clayne/xray-16
|
32ebf81a252c7179e2824b2874f911a91e822ad1
|
[
"OML",
"Linux-OpenIB"
] | 17
|
2022-01-25T08:58:23.000Z
|
2022-03-28T17:18:28.000Z
|
src/Layers/xrRender/xrRender_console.cpp
|
clayne/xray-16
|
32ebf81a252c7179e2824b2874f911a91e822ad1
|
[
"OML",
"Linux-OpenIB"
] | 1
|
2015-06-05T20:04:00.000Z
|
2015-06-05T20:04:00.000Z
|
#include "stdafx.h"
#pragma hdrstop
#include "xrRender_console.h"
#include "xrCore/xr_token.h"
#include "xrCore/Animation/SkeletonMotions.hpp"
u32 ps_Preset = 2;
const xr_token qpreset_token[] = {{"Minimum", 0}, {"Low", 1}, {"Default", 2}, {"High", 3}, {"Extreme", 4}, {nullptr, 0}};
u32 ps_r2_smapsize = 2048;
const xr_token qsmapsize_token[] =
{
#if !defined(MASTER_GOLD) || RENDER == R_R1
{ "256", 256 }, // Too bad for R2+
{ "512", 512 }, // But works
#endif
{ "1024", 1024 },
{ "1032", 1032 },
{ "1536", 1536 },
{ "2048", 2048 },
{ "2560", 2560 },
{ "3072", 3072 },
{ "3584", 3584 },
{ "4096", 4096 },
#if defined(USE_DX11) || defined(USE_OGL) // XXX: check if values more than 8192 are supported on OpenGL
{ "5120", 5120 },
{ "6144", 6144 },
{ "7168", 7168 },
{ "8192", 8192 },
{ "9216", 9216 },
{ "10240", 10240 },
{ "11264", 11264 },
{ "12288", 12288 },
{ "13312", 13312 },
{ "14336", 14336 },
{ "15360", 15360 },
{ "16384", 16384 },
#endif // !USE_DX9
{ nullptr, 0 }
};
u32 ps_r_ssao_mode = 2;
const xr_token qssao_mode_token[] = {{"disabled", 0}, {"default", 1}, {"hdao", 2}, {"hbao", 3}, {nullptr, 0}};
u32 ps_r_sun_shafts = 2;
const xr_token qsun_shafts_token[] = {{"st_opt_off", 0}, {"st_opt_low", 1}, {"st_opt_medium", 2}, {"st_opt_high", 3}, {nullptr, 0}};
u32 ps_r_ssao = 3;
const xr_token qssao_token[] = {{"st_opt_off", 0}, {"st_opt_low", 1}, {"st_opt_medium", 2}, {"st_opt_high", 3},
#if defined(USE_DX11) || defined(USE_OGL)
{"st_opt_ultra", 4},
#endif
{nullptr, 0}};
u32 ps_r_sun_quality = 1; // = 0;
const xr_token qsun_quality_token[] = {{"st_opt_low", 0}, {"st_opt_medium", 1}, {"st_opt_high", 2},
#if defined(USE_DX11) // TODO: OGL: fix ultra and extreme settings
{"st_opt_ultra", 3}, {"st_opt_extreme", 4},
#endif // !USE_DX9
{nullptr, 0}};
u32 ps_r_water_reflection = 3;
const xr_token qwater_reflection_quality_token[] =
{
{ "st_opt_off", 0 },
{ "st_opt_low", 1 },
{ "st_opt_medium", 2 },
{ "st_opt_high", 3 },
{ "st_opt_ultra", 4 },
{ nullptr, -1 }
};
u32 ps_r3_msaa = 0; // = 0;
const xr_token qmsaa_token[] = {{"st_opt_off", 0}, {"2x", 1}, {"4x", 2}, {"8x", 3},
{nullptr, 0}};
u32 ps_r3_msaa_atest = 0; // = 0;
const xr_token qmsaa__atest_token[] = {
{"st_opt_off", 0}, {"st_opt_atest_msaa_dx10_0", 1}, {"st_opt_atest_msaa_dx10_1", 2}, {nullptr, 0}};
u32 ps_r3_minmax_sm = 3; // = 0;
const xr_token qminmax_sm_token[] = {{"off", 0}, {"on", 1}, {"auto", 2}, {"autodetect", 3}, {nullptr, 0}};
// “Off”
// “DX10.0 style [Standard]”
// “DX10.1 style [Higher quality]”
// Common
extern int psSkeletonUpdate;
extern float r__dtex_range;
Flags32 ps_r__common_flags = { RFLAG_ACTOR_SHADOW | RFLAG_NO_RAM_TEXTURES }; // All renders
//int ps_r__Supersample = 1;
int ps_r__LightSleepFrames = 10;
float ps_r__Detail_l_ambient = 0.9f;
float ps_r__Detail_l_aniso = 0.25f;
float ps_r__Detail_density = 0.3f;
float ps_r__Detail_height = 1.f;
float ps_r__Detail_rainbow_hemi = 0.75f;
float ps_r__Tree_w_rot = 10.0f;
float ps_r__Tree_w_speed = 1.00f;
float ps_r__Tree_w_amp = 0.005f;
Fvector ps_r__Tree_Wave = {.1f, .01f, .11f};
float ps_r__Tree_SBC = 1.5f; // scale bias correct
float ps_r__WallmarkTTL = 50.f;
float ps_r__WallmarkSHIFT = 0.0001f;
float ps_r__WallmarkSHIFT_V = 0.0001f;
float ps_r__GLOD_ssa_start = 256.f;
float ps_r__GLOD_ssa_end = 64.f;
float ps_r__LOD = 0.75f;
//float ps_r__LOD_Power = 1.5f;
float ps_r__ssaDISCARD = 3.5f; // RO
float ps_r__ssaDONTSORT = 32.f; // RO
float ps_r__ssaHZBvsTEX = 96.f; // RO
int ps_r__tf_Anisotropic = 8;
float ps_r__tf_Mipbias = 0.0f;
// R1
float ps_r1_ssaLOD_A = 64.f;
float ps_r1_ssaLOD_B = 48.f;
Flags32 ps_r1_flags = {R1FLAG_DLIGHTS}; // r1-only
float ps_r1_lmodel_lerp = 0.1f;
float ps_r1_dlights_clip = 40.f;
float ps_r1_pps_u = 0.f;
float ps_r1_pps_v = 0.f;
int ps_r1_force_geomx = 0;
// R1-specific
int ps_r1_GlowsPerFrame = 16; // r1-only
float ps_r1_fog_luminance = 1.1f; // r1-only
int ps_r1_SoftwareSkinning = 0; // r1-only
// R2
bool ps_r2_sun_static = false;
bool ps_r2_advanced_pp = true; // advanced post process and effects
float ps_r2_ssaLOD_A = 64.f;
float ps_r2_ssaLOD_B = 48.f;
// R2-specific
Flags32 ps_r2_ls_flags = {R2FLAG_SUN
//| R2FLAG_SUN_IGNORE_PORTALS
| R2FLAG_EXP_DONT_TEST_UNSHADOWED | R2FLAG_USE_NVSTENCIL | R2FLAG_EXP_SPLIT_SCENE | R2FLAG_EXP_MT_CALC |
R3FLAG_DYN_WET_SURF | R3FLAG_VOLUMETRIC_SMOKE
//| R3FLAG_MSAA
//| R3FLAG_MSAA_OPT
| R3FLAG_GBUFFER_OPT | R2FLAG_DETAIL_BUMP | R2FLAG_DOF | R2FLAG_SOFT_PARTICLES | R2FLAG_SOFT_WATER |
R2FLAG_STEEP_PARALLAX | R2FLAG_SUN_FOCUS | R2FLAG_SUN_TSM | R2FLAG_TONEMAP | R2FLAG_VOLUMETRIC_LIGHTS}; // r2-only
Flags32 ps_r2_ls_flags_ext = {
/*R2FLAGEXT_SSAO_OPT_DATA |*/ R2FLAGEXT_SSAO_HALF_DATA | R2FLAGEXT_ENABLE_TESSELLATION | R3FLAGEXT_SSR_HALF_DEPTH |
R3FLAGEXT_SSR_JITTER};
float ps_r2_df_parallax_h = 0.02f;
float ps_r2_df_parallax_range = 75.f;
float ps_r2_tonemap_middlegray = 1.f; // r2-only
float ps_r2_tonemap_adaptation = 1.f; // r2-only
float ps_r2_tonemap_low_lum = 0.0001f; // r2-only
float ps_r2_tonemap_amount = 0.7f; // r2-only
float ps_r2_ls_bloom_kernel_g = 3.f; // r2-only
float ps_r2_ls_bloom_kernel_b = .7f; // r2-only
float ps_r2_ls_bloom_speed = 100.f; // r2-only
float ps_r2_ls_bloom_kernel_scale = .7f; // r2-only // gauss
float ps_r2_ls_dsm_kernel = .7f; // r2-only
float ps_r2_ls_psm_kernel = .7f; // r2-only
float ps_r2_ls_ssm_kernel = .7f; // r2-only
float ps_r2_ls_bloom_threshold = .00001f; // r2-only
Fvector ps_r2_aa_barier = {.8f, .1f, 0}; // r2-only
Fvector ps_r2_aa_weight = {.25f, .25f, 0}; // r2-only
float ps_r2_aa_kernel = .5f; // r2-only
float ps_r2_mblur = .0f; // .5f
int ps_r2_GI_depth = 1; // 1..5
int ps_r2_GI_photons = 16; // 8..64
float ps_r2_GI_clip = EPS_L; // EPS
float ps_r2_GI_refl = .9f; // .9f
float ps_r2_ls_depth_scale = 1.00001f; // 1.00001f
float ps_r2_ls_depth_bias = -0.0003f; // -0.0001f
float ps_r2_ls_squality = 1.0f; // 1.00f
float ps_r2_sun_tsm_projection = 0.3f; // 0.18f
float ps_r2_sun_tsm_bias = -0.01f; //
float ps_r2_sun_near = 20.f; // 12.0f
extern float OLES_SUN_LIMIT_27_01_07; // actually sun_far
float ps_r2_sun_near_border = 0.75f; // 1.0f
float ps_r2_sun_depth_far_scale = 1.00000f; // 1.00001f
float ps_r2_sun_depth_far_bias = -0.00002f; // -0.0000f
float ps_r2_sun_depth_near_scale = 1.0000f; // 1.00001f
float ps_r2_sun_depth_near_bias = 0.00001f; // -0.00005f
float ps_r2_sun_lumscale = 1.0f; // 1.0f
float ps_r2_sun_lumscale_hemi = 1.0f; // 1.0f
float ps_r2_sun_lumscale_amb = 1.0f;
float ps_r2_gmaterial = 2.2f; //
float ps_r2_zfill = 0.25f; // .1f
float ps_r2_dhemi_sky_scale = 0.08f; // 1.5f
float ps_r2_dhemi_light_scale = 0.2f;
float ps_r2_dhemi_light_flow = 0.1f;
int ps_r2_dhemi_count = 5; // 5
int ps_r2_wait_sleep = 0;
int ps_r2_wait_timeout = 500;
float ps_r2_lt_smooth = 1.f; // 1.f
float ps_r2_slight_fade = 0.5f; // 1.f
// x - min (0), y - focus (1.4), z - max (100)
Fvector3 ps_r2_dof = Fvector3().set(-1.25f, 1.4f, 600.f);
float ps_r2_dof_sky = 30; // distance to sky
float ps_r2_dof_kernel_size = 5.0f; // 7.0f
float ps_r3_dyn_wet_surf_near = 5.f; // 10.0f
float ps_r3_dyn_wet_surf_far = 20.f; // 30.0f
int ps_r3_dyn_wet_surf_sm_res = 256; // 256
u32 ps_steep_parallax = 0;
int ps_r__detail_radius = 49;
u32 dm_size = 24;
u32 dm_cache1_line = 12; //dm_size*2/dm_cache1_count
u32 dm_cache_line = 49; //dm_size+1+dm_size
u32 dm_cache_size = 2401; //dm_cache_line*dm_cache_line
float dm_fade = 47.5; //float(2*dm_size)-.5f;
u32 dm_current_size = 24;
u32 dm_current_cache1_line = 12; //dm_current_size*2/dm_cache1_count
u32 dm_current_cache_line = 49; //dm_current_size+1+dm_current_size
u32 dm_current_cache_size = 2401; //dm_current_cache_line*dm_current_cache_line
float dm_current_fade = 47.5; //float(2*dm_current_size)-.5f;
float ps_current_detail_density = 0.6f;
float ps_current_detail_height = 1.f;
xr_token ext_quality_token[] = {{"qt_off", 0}, {"qt_low", 1}, {"qt_medium", 2},
{"qt_high", 3}, {"qt_extreme", 4}, {nullptr, 0}};
//-AVO
//- Mad Max
float ps_r2_gloss_factor = 4.0f;
//- Mad Max
#ifndef _EDITOR
#include "xrEngine/XR_IOConsole.h"
#include "xrEngine/xr_ioc_cmd.h"
#if defined(USE_DX11)
#include "Layers/xrRenderDX10/StateManager/dx10SamplerStateCache.h"
#endif
//-----------------------------------------------------------------------
//AVO: detail draw radius
class CCC_detail_radius : public CCC_Integer
{
public:
void apply()
{
dm_current_size = iFloor((float)ps_r__detail_radius / 4) * 2;
dm_current_cache1_line = dm_current_size * 2 / 4; // assuming cache1_count = 4
dm_current_cache_line = dm_current_size + 1 + dm_current_size;
dm_current_cache_size = dm_current_cache_line * dm_current_cache_line;
dm_current_fade = float(2 * dm_current_size) - .5f;
}
CCC_detail_radius(LPCSTR N, int* V, int _min = 0, int _max = 999) : CCC_Integer(N, V, _min, _max) {};
void Execute(LPCSTR args) override
{
CCC_Integer::Execute(args);
apply();
}
void GetStatus(TStatus& S) override
{
CCC_Integer::GetStatus(S);
}
};
//-AVO
class CCC_tf_Aniso : public CCC_Integer
{
public:
void apply()
{
#if defined(USE_DX9) || defined(USE_DX11)
if (nullptr == HW.pDevice)
return;
#endif
int val = *value;
clamp(val, 1, 16);
#if defined(USE_DX9)
for (u32 i = 0; i < HW.Caps.raster.dwStages; i++)
CHK_DX(HW.pDevice->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, val));
#elif defined(USE_DX11)
SSManager.SetMaxAnisotropy(val);
#elif defined(USE_OGL)
// OGL: don't set aniso here because it will be updated after vid restart
#else
# error No graphics API selected or enabled!
#endif
}
CCC_tf_Aniso(LPCSTR N, int* v) : CCC_Integer(N, v, 1, 16){};
virtual void Execute(LPCSTR args)
{
CCC_Integer::Execute(args);
apply();
}
virtual void GetStatus(TStatus& S)
{
CCC_Integer::GetStatus(S);
apply();
}
};
class CCC_tf_MipBias : public CCC_Float
{
public:
void apply()
{
#if defined(USE_DX9) || defined(USE_DX11)
if (nullptr == HW.pDevice)
return;
#endif
#if defined(USE_DX9)
for (u32 i = 0; i < HW.Caps.raster.dwStages; i++)
CHK_DX(HW.pDevice->SetSamplerState(i, D3DSAMP_MIPMAPLODBIAS, *((u32*)value)));
#elif defined(USE_DX11)
SSManager.SetMipLODBias(*value);
#endif
}
CCC_tf_MipBias(LPCSTR N, float* v) : CCC_Float(N, v, -3.f, +3.f) {}
virtual void Execute(LPCSTR args)
{
CCC_Float::Execute(args);
apply();
}
virtual void GetStatus(TStatus& S)
{
CCC_Float::GetStatus(S);
apply();
}
};
class CCC_R2GM : public CCC_Float
{
public:
CCC_R2GM(LPCSTR N, float* v) : CCC_Float(N, v, 0.f, 4.f) { *v = 0; };
virtual void Execute(LPCSTR args)
{
if (0 == xr_strcmp(args, "on"))
{
ps_r2_ls_flags.set(R2FLAG_GLOBALMATERIAL, TRUE);
}
else if (0 == xr_strcmp(args, "off"))
{
ps_r2_ls_flags.set(R2FLAG_GLOBALMATERIAL, FALSE);
}
else
{
CCC_Float::Execute(args);
if (ps_r2_ls_flags.test(R2FLAG_GLOBALMATERIAL))
{
static LPCSTR name[4] = {"oren", "blin", "phong", "metal"};
float mid = *value;
int m0 = iFloor(mid) % 4;
int m1 = (m0 + 1) % 4;
float frc = mid - float(iFloor(mid));
Msg("* material set to [%s]-[%s], with lerp of [%f]", name[m0], name[m1], frc);
}
}
}
};
class CCC_Screenshot : public IConsole_Command
{
public:
CCC_Screenshot(LPCSTR N) : IConsole_Command(N){};
virtual void Execute(LPCSTR args)
{
if (GEnv.isDedicatedServer)
return;
string_path name;
name[0] = 0;
sscanf(args, "%s", name);
LPCSTR image = xr_strlen(name) ? name : 0;
GEnv.Render->Screenshot(IRender::SM_NORMAL, image);
}
};
class CCC_ModelPoolStat : public IConsole_Command
{
public:
CCC_ModelPoolStat(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = TRUE; };
virtual void Execute(LPCSTR /*args*/) { RImplementation.Models->dump(); }
};
class CCC_SSAO_Mode : public CCC_Token
{
public:
CCC_SSAO_Mode(LPCSTR N, u32* V, const xr_token* T) : CCC_Token(N, V, T){};
virtual void Execute(LPCSTR args)
{
CCC_Token::Execute(args);
switch (*value)
{
case 0:
{
ps_r_ssao = 0;
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 0);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 0);
break;
}
case 1:
{
if (ps_r_ssao == 0)
{
ps_r_ssao = 1;
}
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 0);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 0);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HALF_DATA, 0);
break;
}
case 2:
{
if (ps_r_ssao == 0)
{
ps_r_ssao = 1;
}
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 0);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 1);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_OPT_DATA, 0);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HALF_DATA, 0);
break;
}
case 3:
{
if (ps_r_ssao == 0)
{
ps_r_ssao = 1;
}
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HBAO, 1);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_HDAO, 0);
ps_r2_ls_flags_ext.set(R2FLAGEXT_SSAO_OPT_DATA, 1);
break;
}
}
}
};
//-----------------------------------------------------------------------
class CCC_Preset : public CCC_Token
{
public:
CCC_Preset(LPCSTR N, u32* V, const xr_token* T) : CCC_Token(N, V, T){};
virtual void Execute(LPCSTR args)
{
CCC_Token::Execute(args);
string_path _cfg;
string_path cmd;
switch (*value)
{
case 0: xr_strcpy(_cfg, "rspec_minimum.ltx"); break;
case 1: xr_strcpy(_cfg, "rspec_low.ltx"); break;
case 2: xr_strcpy(_cfg, "rspec_default.ltx"); break;
case 3: xr_strcpy(_cfg, "rspec_high.ltx"); break;
case 4: xr_strcpy(_cfg, "rspec_extreme.ltx"); break;
}
FS.update_path(_cfg, "$game_config$", _cfg);
strconcat(sizeof(cmd), cmd, "cfg_load", " ", _cfg);
Console->Execute(cmd);
}
};
class CCC_memory_stats : public IConsole_Command
{
public:
CCC_memory_stats(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = true; };
virtual void Execute(LPCSTR /*args*/)
{
// TODO: OGL: Implement memory usage statistics.
#if defined(USE_DX9) || defined(USE_DX11)
u32 m_base = 0;
u32 c_base = 0;
u32 m_lmaps = 0;
u32 c_lmaps = 0;
RImplementation.ResourcesGetMemoryUsage(m_base, c_base, m_lmaps, c_lmaps);
Msg("memory usage mb \t \t video \t managed \t system \n");
const float MiB = 1024*1024; // XXX: use it as common enum value (like in X-Ray 2.0)
const u32* mem_usage = HW.stats_manager.memory_usage_summary[enum_stats_buffer_type_vertex];
float vb_video = mem_usage[D3DPOOL_DEFAULT] / MiB;
float vb_managed = mem_usage[D3DPOOL_MANAGED] / MiB;
float vb_system = mem_usage[D3DPOOL_SYSTEMMEM] / MiB;
Msg("vertex buffer \t \t %f \t %f \t %f ", vb_video, vb_managed, vb_system);
float ib_video = mem_usage[D3DPOOL_DEFAULT] / MiB;
float ib_managed = mem_usage[D3DPOOL_MANAGED] / MiB;
float ib_system = mem_usage[D3DPOOL_SYSTEMMEM] / MiB;
Msg("index buffer \t \t %f \t %f \t %f ", ib_video, ib_managed, ib_system);
float textures_managed = (m_base+m_lmaps)/MiB;
Msg("textures \t \t %f \t %f \t %f ", 0.f, textures_managed, 0.f);
mem_usage = HW.stats_manager.memory_usage_summary[enum_stats_buffer_type_rtarget];
float rt_video = mem_usage[D3DPOOL_DEFAULT] / MiB;
float rt_managed = mem_usage[D3DPOOL_MANAGED] / MiB;
float rt_system = mem_usage[D3DPOOL_SYSTEMMEM] / MiB;
Msg("R-Targets \t \t %f \t %f \t %f ", rt_video, rt_managed, rt_system);
Msg("\nTotal \t \t %f \t %f \t %f ", vb_video + ib_video + rt_video,
textures_managed + vb_managed + ib_managed + rt_managed, vb_system + ib_system + rt_system);
#endif // !USE_OGL
}
};
class CCC_DumpResources final : public IConsole_Command
{
public:
CCC_DumpResources(pcstr name) : IConsole_Command(name) { bEmptyArgsHandled = true; }
void Execute(pcstr /*args*/) override
{
RImplementation.Models->dump();
RImplementation.Resources->Dump(false);
}
};
class CCC_MotionsStat final : public IConsole_Command
{
public:
CCC_MotionsStat(pcstr name) : IConsole_Command(name) { bEmptyArgsHandled = true; }
void Execute(pcstr /*args*/) override
{
g_pMotionsContainer->dump();
}
};
class CCC_TexturesStat final : public IConsole_Command
{
public:
CCC_TexturesStat(pcstr name) : IConsole_Command(name) { bEmptyArgsHandled = true; }
void Execute(pcstr /*args*/) override
{
RImplementation.Resources->_DumpMemoryUsage();
}
};
#if RENDER != R_R1
#include "r__pixel_calculator.h"
class CCC_BuildSSA : public IConsole_Command
{
public:
CCC_BuildSSA(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = TRUE; };
virtual void Execute(LPCSTR /*args*/)
{
r_pixel_calculator c;
c.run();
}
};
#endif
class CCC_DofFar : public CCC_Float
{
public:
CCC_DofFar(LPCSTR N, float* V, float _min = 0.0f, float _max = 10000.0f) : CCC_Float(N, V, _min, _max) {}
virtual void Execute(LPCSTR args)
{
float v = float(atof(args));
if (v < ps_r2_dof.y + 0.1f)
{
char pBuf[256];
_snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value greater or equal to r2_dof_focus+0.1");
Msg("~ Invalid syntax in call to '%s'", cName);
Msg("~ Valid arguments: %s", pBuf);
Console->Execute("r2_dof_focus");
}
else
{
CCC_Float::Execute(args);
if (g_pGamePersistent)
g_pGamePersistent->SetBaseDof(ps_r2_dof);
}
}
// CCC_Dof should save all data as well as load from config
virtual void Save(IWriter* /*F*/) { ; }
};
class CCC_DofNear : public CCC_Float
{
public:
CCC_DofNear(LPCSTR N, float* V, float _min = 0.0f, float _max = 10000.0f) : CCC_Float(N, V, _min, _max) {}
virtual void Execute(LPCSTR args)
{
float v = float(atof(args));
if (v > ps_r2_dof.y - 0.1f)
{
char pBuf[256];
_snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value less or equal to r2_dof_focus-0.1");
Msg("~ Invalid syntax in call to '%s'", cName);
Msg("~ Valid arguments: %s", pBuf);
Console->Execute("r2_dof_focus");
}
else
{
CCC_Float::Execute(args);
if (g_pGamePersistent)
g_pGamePersistent->SetBaseDof(ps_r2_dof);
}
}
// CCC_Dof should save all data as well as load from config
virtual void Save(IWriter* /*F*/) { ; }
};
class CCC_DofFocus : public CCC_Float
{
public:
CCC_DofFocus(LPCSTR N, float* V, float _min = 0.0f, float _max = 10000.0f) : CCC_Float(N, V, _min, _max) {}
virtual void Execute(LPCSTR args)
{
float v = float(atof(args));
if (v > ps_r2_dof.z - 0.1f)
{
char pBuf[256];
_snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value less or equal to r2_dof_far-0.1");
Msg("~ Invalid syntax in call to '%s'", cName);
Msg("~ Valid arguments: %s", pBuf);
Console->Execute("r2_dof_far");
}
else if (v < ps_r2_dof.x + 0.1f)
{
char pBuf[256];
_snprintf(pBuf, sizeof(pBuf) / sizeof(pBuf[0]), "float value greater or equal to r2_dof_far-0.1");
Msg("~ Invalid syntax in call to '%s'", cName);
Msg("~ Valid arguments: %s", pBuf);
Console->Execute("r2_dof_near");
}
else
{
CCC_Float::Execute(args);
if (g_pGamePersistent)
g_pGamePersistent->SetBaseDof(ps_r2_dof);
}
}
// CCC_Dof should save all data as well as load from config
virtual void Save(IWriter* /*F*/) { ; }
};
class CCC_Dof : public CCC_Vector3
{
public:
CCC_Dof(LPCSTR N, Fvector* V, const Fvector _min, const Fvector _max) : CCC_Vector3(N, V, _min, _max) { ; }
virtual void Execute(LPCSTR args)
{
Fvector v;
if (3 != sscanf(args, "%f,%f,%f", &v.x, &v.y, &v.z))
InvalidSyntax();
else if ((v.x > v.y - 0.1f) || (v.z < v.y + 0.1f))
{
InvalidSyntax();
Msg("x <= y - 0.1");
Msg("y <= z - 0.1");
}
else
{
CCC_Vector3::Execute(args);
if (g_pGamePersistent)
g_pGamePersistent->SetBaseDof(ps_r2_dof);
}
}
virtual void GetStatus(TStatus& S) { xr_sprintf(S, "%f,%f,%f", value->x, value->y, value->z); }
virtual void Info(TInfo& I)
{
xr_sprintf(I, "vector3 in range [%f,%f,%f]-[%f,%f,%f]", min.x, min.y, min.z, max.x, max.y, max.z);
}
};
#ifdef DEBUG
class CCC_SunshaftsIntensity : public CCC_Float
{
public:
CCC_SunshaftsIntensity(LPCSTR N, float* V, float _min, float _max) : CCC_Float(N, V, _min, _max) {}
virtual void Save(IWriter*) { ; }
};
#endif
// Allow real-time fog config reload
#if (RENDER == R_R3) || (RENDER == R_R4)
# ifndef MASTER_GOLD
# include "Layers/xrRenderDX10/3DFluid/dx103DFluidManager.h"
class CCC_Fog_Reload : public IConsole_Command
{
public:
CCC_Fog_Reload(LPCSTR N) : IConsole_Command(N) { bEmptyArgsHandled = TRUE; };
virtual void Execute(LPCSTR /*args*/) { FluidManager.UpdateProfiles(); }
};
# endif // MASTER_GOLD
#endif // (RENDER == R_R3) || (RENDER == R_R4)
//-----------------------------------------------------------------------
void xrRender_initconsole()
{
CMD3(CCC_Preset, "_preset", &ps_Preset, qpreset_token);
CMD4(CCC_Integer, "rs_skeleton_update", &psSkeletonUpdate, 2, 128);
#ifndef MASTER_GOLD
CMD1(CCC_DumpResources, "dump_resources");
CMD1(CCC_MotionsStat, "stat_motions");
CMD1(CCC_TexturesStat, "stat_textures");
#endif
CMD4(CCC_Float, "r__dtex_range", &r__dtex_range, 5, 175);
// Common
CMD1(CCC_Screenshot, "screenshot");
#ifdef DEBUG
#if RENDER != R_R1
CMD1(CCC_BuildSSA, "build_ssa");
#endif
CMD4(CCC_Integer, "r__lsleep_frames", &ps_r__LightSleepFrames, 4, 30);
CMD4(CCC_Float, "r__ssa_glod_start", &ps_r__GLOD_ssa_start, 128, 512);
CMD4(CCC_Float, "r__ssa_glod_end", &ps_r__GLOD_ssa_end, 16, 96);
CMD4(CCC_Float, "r__wallmark_shift_pp", &ps_r__WallmarkSHIFT, 0.0f, 1.f);
CMD4(CCC_Float, "r__wallmark_shift_v", &ps_r__WallmarkSHIFT_V, 0.0f, 1.f);
CMD1(CCC_ModelPoolStat, "stat_models");
#endif // DEBUG
CMD4(CCC_Float, "r__wallmark_ttl", &ps_r__WallmarkTTL, 1.0f, 10.f * 60.f);
CMD4(CCC_Integer, "r__supersample", &ps_r__Supersample, 1, 8);
Fvector tw_min, tw_max;
CMD4(CCC_Float, "r__geometry_lod", &ps_r__LOD, 0.1f, 2.f);
//CMD4(CCC_Float, "r__geometry_lod_pow", &ps_r__LOD_Power, 0, 2);
CMD4(CCC_Float, "r__detail_density", &ps_current_detail_density/*&ps_r__Detail_density*/, 0.1f, 0.99f);
CMD4(CCC_detail_radius, "r__detail_radius", &ps_r__detail_radius, 49, 300);
CMD4(CCC_Float, "r__detail_height", &ps_r__Detail_height, 1, 2);
#ifdef DEBUG
CMD4(CCC_Float, "r__detail_l_ambient", &ps_r__Detail_l_ambient, .5f, .95f);
CMD4(CCC_Float, "r__detail_l_aniso", &ps_r__Detail_l_aniso, .1f, .5f);
CMD4(CCC_Float, "r__d_tree_w_amp", &ps_r__Tree_w_amp, .001f, 1.f);
CMD4(CCC_Float, "r__d_tree_w_rot", &ps_r__Tree_w_rot, .01f, 100.f);
CMD4(CCC_Float, "r__d_tree_w_speed", &ps_r__Tree_w_speed, 1.0f, 10.f);
tw_min.set(EPS, EPS, EPS);
tw_max.set(2, 2, 2);
CMD4(CCC_Vector3, "r__d_tree_wave", &ps_r__Tree_Wave, tw_min, tw_max);
#endif // DEBUG
CMD3(CCC_Mask, "r__no_ram_textures", &ps_r__common_flags, RFLAG_NO_RAM_TEXTURES);
CMD3(CCC_Mask, "r__actor_shadow", &ps_r__common_flags, RFLAG_ACTOR_SHADOW);
CMD2(CCC_tf_Aniso, "r__tf_aniso", &ps_r__tf_Anisotropic); // {1..16}
CMD2(CCC_tf_MipBias, "r1_tf_mipbias", &ps_r__tf_Mipbias); // {-3 +3}
CMD2(CCC_tf_MipBias, "r2_tf_mipbias", &ps_r__tf_Mipbias); // {-3 +3}
// R1
CMD4(CCC_Float, "r1_ssa_lod_a", &ps_r1_ssaLOD_A, 16, 96);
CMD4(CCC_Float, "r1_ssa_lod_b", &ps_r1_ssaLOD_B, 16, 64);
CMD4(CCC_Float, "r1_lmodel_lerp", &ps_r1_lmodel_lerp, 0, 0.333f);
CMD3(CCC_Mask, "r1_dlights", &ps_r1_flags, R1FLAG_DLIGHTS);
CMD4(CCC_Float, "r1_dlights_clip", &ps_r1_dlights_clip, 10.f, 150.f);
CMD4(CCC_Float, "r1_pps_u", &ps_r1_pps_u, -1.f, +1.f);
CMD4(CCC_Float, "r1_pps_v", &ps_r1_pps_v, -1.f, +1.f);
CMD4(CCC_Integer, "r1_force_geomx", &ps_r1_force_geomx, 0, 1);
// R1-specific
CMD4(CCC_Integer, "r1_glows_per_frame", &ps_r1_GlowsPerFrame, 2, 32);
CMD3(CCC_Mask, "r1_detail_textures", &ps_r2_ls_flags, R1FLAG_DETAIL_TEXTURES);
CMD4(CCC_Float, "r1_fog_luminance", &ps_r1_fog_luminance, 0.2f, 5.f);
// Software Skinning
// 0 - disabled (renderer can override)
// 1 - enabled
// 2 - forced hardware skinning (renderer can not override)
CMD4(CCC_Integer, "r1_software_skinning", &ps_r1_SoftwareSkinning, 0, 2);
// R2
CMD4(CCC_Float, "r2_ssa_lod_a", &ps_r2_ssaLOD_A, 16, 96);
CMD4(CCC_Float, "r2_ssa_lod_b", &ps_r2_ssaLOD_B, 32, 64);
// R2-specific
CMD2(CCC_R2GM, "r2em", &ps_r2_gmaterial);
CMD3(CCC_Mask, "r2_tonemap", &ps_r2_ls_flags, R2FLAG_TONEMAP);
CMD4(CCC_Float, "r2_tonemap_middlegray", &ps_r2_tonemap_middlegray, 0.0f, 2.0f);
CMD4(CCC_Float, "r2_tonemap_adaptation", &ps_r2_tonemap_adaptation, 0.01f, 10.0f);
CMD4(CCC_Float, "r2_tonemap_lowlum", &ps_r2_tonemap_low_lum, 0.0001f, 1.0f);
CMD4(CCC_Float, "r2_tonemap_amount", &ps_r2_tonemap_amount, 0.0000f, 1.0f);
CMD4(CCC_Float, "r2_ls_bloom_kernel_scale", &ps_r2_ls_bloom_kernel_scale, 0.5f, 2.f);
CMD4(CCC_Float, "r2_ls_bloom_kernel_g", &ps_r2_ls_bloom_kernel_g, 1.f, 7.f);
CMD4(CCC_Float, "r2_ls_bloom_kernel_b", &ps_r2_ls_bloom_kernel_b, 0.01f, 1.f);
CMD4(CCC_Float, "r2_ls_bloom_threshold", &ps_r2_ls_bloom_threshold, 0.f, 1.f);
CMD4(CCC_Float, "r2_ls_bloom_speed", &ps_r2_ls_bloom_speed, 0.f, 100.f);
CMD3(CCC_Mask, "r2_ls_bloom_fast", &ps_r2_ls_flags, R2FLAG_FASTBLOOM);
CMD4(CCC_Float, "r2_ls_dsm_kernel", &ps_r2_ls_dsm_kernel, .1f, 3.f);
CMD4(CCC_Float, "r2_ls_psm_kernel", &ps_r2_ls_psm_kernel, .1f, 3.f);
CMD4(CCC_Float, "r2_ls_ssm_kernel", &ps_r2_ls_ssm_kernel, .1f, 3.f);
CMD4(CCC_Float, "r2_ls_squality", &ps_r2_ls_squality, .5f, 1.f);
CMD3(CCC_Mask, "r2_zfill", &ps_r2_ls_flags, R2FLAG_ZFILL);
CMD4(CCC_Float, "r2_zfill_depth", &ps_r2_zfill, .001f, .5f);
CMD3(CCC_Mask, "r2_allow_r1_lights", &ps_r2_ls_flags, R2FLAG_R1LIGHTS);
//- Mad Max
CMD4(CCC_Float, "r2_gloss_factor", &ps_r2_gloss_factor, .0f, 10.f);
//- Mad Max
#ifdef DEBUG
CMD3(CCC_Mask, "r2_use_nvdbt", &ps_r2_ls_flags, R2FLAG_USE_NVDBT);
CMD3(CCC_Mask, "r2_mt", &ps_r2_ls_flags, R2FLAG_EXP_MT_CALC);
#endif // DEBUG
CMD3(CCC_Mask, "r2_sun", &ps_r2_ls_flags, R2FLAG_SUN);
CMD3(CCC_Mask, "r2_sun_details", &ps_r2_ls_flags, R2FLAG_SUN_DETAILS);
CMD3(CCC_Mask, "r2_sun_focus", &ps_r2_ls_flags, R2FLAG_SUN_FOCUS);
//CMD3(CCC_Mask, "r2_sun_static", &ps_r2_ls_flags, R2FLAG_SUN_STATIC);
//CMD3(CCC_Mask, "r2_exp_splitscene", &ps_r2_ls_flags, R2FLAG_EXP_SPLIT_SCENE);
//CMD3(CCC_Mask, "r2_exp_donttest_uns", &ps_r2_ls_flags, R2FLAG_EXP_DONT_TEST_UNSHADOWED);
CMD3(CCC_Mask, "r2_exp_donttest_shad", &ps_r2_ls_flags, R2FLAG_EXP_DONT_TEST_SHADOWED);
CMD3(CCC_Mask, "r2_sun_tsm", &ps_r2_ls_flags, R2FLAG_SUN_TSM);
CMD4(CCC_Float, "r2_sun_tsm_proj", &ps_r2_sun_tsm_projection, .001f, 0.8f);
CMD4(CCC_Float, "r2_sun_tsm_bias", &ps_r2_sun_tsm_bias, -0.5, +0.5);
CMD4(CCC_Float, "r2_sun_near", &ps_r2_sun_near, 1.f, 150.f); //AVO: extended from 50.f to 150.f
#if RENDER != R_R1
CMD4(CCC_Float, "r2_sun_far", &OLES_SUN_LIMIT_27_01_07, 51.f, 180.f);
#endif
CMD4(CCC_Float, "r2_sun_near_border", &ps_r2_sun_near_border, .5f, 1.0f);
CMD4(CCC_Float, "r2_sun_depth_far_scale", &ps_r2_sun_depth_far_scale, 0.5, 1.5);
CMD4(CCC_Float, "r2_sun_depth_far_bias", &ps_r2_sun_depth_far_bias, -0.5, +0.5);
CMD4(CCC_Float, "r2_sun_depth_near_scale", &ps_r2_sun_depth_near_scale, 0.5, 1.5);
CMD4(CCC_Float, "r2_sun_depth_near_bias", &ps_r2_sun_depth_near_bias, -0.5, +0.5);
CMD4(CCC_Float, "r2_sun_lumscale", &ps_r2_sun_lumscale, -1.0, +3.0);
CMD4(CCC_Float, "r2_sun_lumscale_hemi", &ps_r2_sun_lumscale_hemi, 0.0, +3.0);
CMD4(CCC_Float, "r2_sun_lumscale_amb", &ps_r2_sun_lumscale_amb, 0.0, +3.0);
CMD3(CCC_Mask, "r2_aa", &ps_r2_ls_flags, R2FLAG_AA);
CMD4(CCC_Float, "r2_aa_kernel", &ps_r2_aa_kernel, 0.3f, 0.7f);
CMD4(CCC_Float, "r2_mblur", &ps_r2_mblur, 0.0f, 1.0f);
CMD3(CCC_Mask, "r2_gi", &ps_r2_ls_flags, R2FLAG_GI);
CMD4(CCC_Float, "r2_gi_clip", &ps_r2_GI_clip, EPS, 0.1f);
CMD4(CCC_Integer, "r2_gi_depth", &ps_r2_GI_depth, 1, 5);
CMD4(CCC_Integer, "r2_gi_photons", &ps_r2_GI_photons, 8, 256);
CMD4(CCC_Float, "r2_gi_refl", &ps_r2_GI_refl, EPS_L, 0.99f);
CMD4(CCC_Integer, "r2_wait_sleep", &ps_r2_wait_sleep, 0, 1);
CMD4(CCC_Integer, "r2_wait_timeout", &ps_r2_wait_timeout, 100, 1000);
#ifndef MASTER_GOLD
CMD4(CCC_Integer, "r2_dhemi_count", &ps_r2_dhemi_count, 4, 25);
CMD4(CCC_Float, "r2_dhemi_sky_scale", &ps_r2_dhemi_sky_scale, 0.0f, 100.f);
CMD4(CCC_Float, "r2_dhemi_light_scale", &ps_r2_dhemi_light_scale, 0, 100.f);
CMD4(CCC_Float, "r2_dhemi_light_flow", &ps_r2_dhemi_light_flow, 0, 1.f);
CMD4(CCC_Float, "r2_dhemi_smooth", &ps_r2_lt_smooth, 0.f, 10.f);
CMD3(CCC_Mask, "rs_hom_depth_draw", &ps_r2_ls_flags_ext, R_FLAGEXT_HOM_DEPTH_DRAW);
CMD3(CCC_Mask, "r2_shadow_cascede_zcul", &ps_r2_ls_flags_ext, R2FLAGEXT_SUN_ZCULLING);
CMD3(CCC_Mask, "r2_shadow_cascede_old", &ps_r2_ls_flags_ext, R2FLAGEXT_SUN_OLD);
#endif // DEBUG
CMD4(CCC_Float, "r2_ls_depth_scale", &ps_r2_ls_depth_scale, 0.5, 1.5);
CMD4(CCC_Float, "r2_ls_depth_bias", &ps_r2_ls_depth_bias, -0.5, +0.5);
CMD4(CCC_Float, "r2_parallax_h", &ps_r2_df_parallax_h, .0f, .5f);
// CMD4(CCC_Float, "r2_parallax_range", &ps_r2_df_parallax_range, 5.0f, 175.0f );
CMD4(CCC_Float, "r2_slight_fade", &ps_r2_slight_fade, .2f, 1.f);
CMD3(CCC_Token, "r2_smap_size", &ps_r2_smapsize, qsmapsize_token);
tw_min.set(0, 0, 0);
tw_max.set(1, 1, 1);
CMD4(CCC_Vector3, "r2_aa_break", &ps_r2_aa_barier, tw_min, tw_max);
tw_min.set(0, 0, 0);
tw_max.set(1, 1, 1);
CMD4(CCC_Vector3, "r2_aa_weight", &ps_r2_aa_weight, tw_min, tw_max);
// Igor: Depth of field
tw_min.set(-10000, -10000, 0);
tw_max.set(10000, 10000, 10000);
CMD4(CCC_Dof, "r2_dof", &ps_r2_dof, tw_min, tw_max);
CMD4(CCC_DofNear, "r2_dof_near", &ps_r2_dof.x, tw_min.x, tw_max.x);
CMD4(CCC_DofFocus, "r2_dof_focus", &ps_r2_dof.y, tw_min.y, tw_max.y);
CMD4(CCC_DofFar, "r2_dof_far", &ps_r2_dof.z, tw_min.z, tw_max.z);
CMD4(CCC_Float, "r2_dof_kernel", &ps_r2_dof_kernel_size, .0f, 10.f);
CMD4(CCC_Float, "r2_dof_sky", &ps_r2_dof_sky, -10000.f, 10000.f);
CMD3(CCC_Mask, "r2_dof_enable", &ps_r2_ls_flags, R2FLAG_DOF);
//float ps_r2_dof_near = 0.f; // 0.f
//float ps_r2_dof_focus = 1.4f; // 1.4f
#ifdef DEBUG
CMD4(CCC_SunshaftsIntensity, "r__sunshafts_intensity", &SunshaftsIntensity, 0.f, 1.f);
#endif
CMD3(CCC_Mask, "r2_volumetric_lights", &ps_r2_ls_flags, R2FLAG_VOLUMETRIC_LIGHTS);
//CMD3(CCC_Mask, "r2_sun_shafts", &ps_r2_ls_flags, R2FLAG_SUN_SHAFTS);
CMD3(CCC_Token, "r2_sun_shafts", &ps_r_sun_shafts, qsun_shafts_token);
CMD3(CCC_SSAO_Mode, "r2_ssao_mode", &ps_r_ssao_mode, qssao_mode_token);
CMD3(CCC_Token, "r2_ssao", &ps_r_ssao, qssao_token);
CMD3(CCC_Mask, "r2_ssao_blur", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_BLUR); // Need restart
CMD3(CCC_Mask, "r2_ssao_opt_data", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_OPT_DATA); // Need restart
CMD3(CCC_Mask, "r2_ssao_half_data", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_HALF_DATA); // Need restart
CMD3(CCC_Mask, "r2_ssao_hbao", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_HBAO); // Need restart
CMD3(CCC_Mask, "r2_ssao_hdao", &ps_r2_ls_flags_ext, R2FLAGEXT_SSAO_HDAO); // Need restart
CMD3(CCC_Mask, "r4_enable_tessellation", &ps_r2_ls_flags_ext, R2FLAGEXT_ENABLE_TESSELLATION); // Need restart
CMD3(CCC_Mask, "r4_wireframe", &ps_r2_ls_flags_ext, R2FLAGEXT_WIREFRAME); // Need restart
CMD3(CCC_Mask, "r2_steep_parallax", &ps_r2_ls_flags, R2FLAG_STEEP_PARALLAX);
CMD3(CCC_Mask, "r2_detail_bump", &ps_r2_ls_flags, R2FLAG_DETAIL_BUMP);
CMD3(CCC_Token, "r2_sun_quality", &ps_r_sun_quality, qsun_quality_token);
//Igor: need restart
CMD3(CCC_Mask, "r2_soft_water", &ps_r2_ls_flags, R2FLAG_SOFT_WATER);
CMD3(CCC_Mask, "r2_soft_particles", &ps_r2_ls_flags, R2FLAG_SOFT_PARTICLES);
CMD3(CCC_Token, "r3_water_refl", &ps_r_water_reflection, qwater_reflection_quality_token);
CMD3(CCC_Mask, "r3_water_refl_half_depth", &ps_r2_ls_flags_ext, R3FLAGEXT_SSR_HALF_DEPTH);
CMD3(CCC_Mask, "r3_water_refl_jitter", &ps_r2_ls_flags_ext, R3FLAGEXT_SSR_JITTER);
//CMD3(CCC_Mask, "r3_msaa", &ps_r2_ls_flags, R3FLAG_MSAA);
CMD3(CCC_Token, "r3_msaa", &ps_r3_msaa, qmsaa_token);
//CMD3(CCC_Mask, "r3_msaa_hybrid", &ps_r2_ls_flags, R3FLAG_MSAA_HYBRID);
//CMD3(CCC_Mask, "r3_msaa_opt", &ps_r2_ls_flags, R3FLAG_MSAA_OPT);
CMD3(CCC_Mask, "r3_gbuffer_opt", &ps_r2_ls_flags, R3FLAG_GBUFFER_OPT);
CMD3(CCC_Mask, "r3_use_dx10_1", &ps_r2_ls_flags, (u32)R3FLAG_USE_DX10_1);
//CMD3(CCC_Mask, "r3_msaa_alphatest", &ps_r2_ls_flags, (u32)R3FLAG_MSAA_ALPHATEST);
CMD3(CCC_Token, "r3_msaa_alphatest", &ps_r3_msaa_atest, qmsaa__atest_token);
CMD3(CCC_Token, "r3_minmax_sm", &ps_r3_minmax_sm, qminmax_sm_token);
// Allow real-time fog config reload
#if (RENDER == R_R3) || (RENDER == R_R4)
# ifndef MASTER_GOLD
CMD1(CCC_Fog_Reload, "r3_fog_reload");
# endif
#endif // (RENDER == R_R3) || (RENDER == R_R4)
CMD3(CCC_Mask, "r3_dynamic_wet_surfaces", &ps_r2_ls_flags, R3FLAG_DYN_WET_SURF);
CMD4(CCC_Float, "r3_dynamic_wet_surfaces_near", &ps_r3_dyn_wet_surf_near, 5, 70);
CMD4(CCC_Float, "r3_dynamic_wet_surfaces_far", &ps_r3_dyn_wet_surf_far, 20, 100);
CMD4(CCC_Integer, "r3_dynamic_wet_surfaces_sm_res", &ps_r3_dyn_wet_surf_sm_res, 64, 2048);
CMD3(CCC_Mask, "r3_volumetric_smoke", &ps_r2_ls_flags, R3FLAG_VOLUMETRIC_SMOKE);
CMD1(CCC_memory_stats, "render_memory_stats");
//CMD3(CCC_Mask, "r2_sun_ignore_portals", &ps_r2_ls_flags, R2FLAG_SUN_IGNORE_PORTALS);
}
#endif
| 36.250511
| 132
| 0.657829
|
clayne
|
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
|
19efac7200deaecbf0f347811fe5588f81e17813
| 811
|
cpp
|
C++
|
Advanced-Programming/Lab-Assignment-1/1-a.cpp
|
hstr2785/CS
|
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
|
[
"MIT"
] | null | null | null |
Advanced-Programming/Lab-Assignment-1/1-a.cpp
|
hstr2785/CS
|
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
|
[
"MIT"
] | 1
|
2020-09-25T17:04:57.000Z
|
2020-09-25T17:04:57.000Z
|
Advanced-Programming/Lab-Assignment-1/1-a.cpp
|
hstr2785/CS
|
d1eaec5413887c8e271f598d41ef6ccd565c5ac8
|
[
"MIT"
] | 2
|
2020-10-01T05:01:38.000Z
|
2020-10-01T08:11:50.000Z
|
#include <iostream>
using namespace std;
// create a class
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
void set_length() {
length = 42.5;
}
void set_breadth() {
breadth = 30.8;
}
void set_height() {
height = 19.2;
}
};
int main() {
// create object of Room class
Room room1;
// assign values to data members
room1.set_length();
room1.set_breadth();
room1.set_height();
// calculate and display the area and volume of the room
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
| 18.860465
| 66
| 0.610358
|
hstr2785
|
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
|
19f16206b89ed62e69a4342207b50b798aeee477
| 10,511
|
cpp
|
C++
|
src/core/features/esp.cpp
|
luk1337/gamesneeze
|
9b85e177d5af9a1bd30a296172c4d80f91966966
|
[
"MIT"
] | 1
|
2021-02-10T00:33:31.000Z
|
2021-02-10T00:33:31.000Z
|
src/core/features/esp.cpp
|
luk1337/gamesneeze
|
9b85e177d5af9a1bd30a296172c4d80f91966966
|
[
"MIT"
] | null | null | null |
src/core/features/esp.cpp
|
luk1337/gamesneeze
|
9b85e177d5af9a1bd30a296172c4d80f91966966
|
[
"MIT"
] | null | null | null |
#include "features.hpp"
#include "../../includes.hpp"
#include <sstream>
bool worldToScreen( const Vector& origin, Vector& screen ) {
float w = Globals::worldToScreenMatrix[3][0] * origin.x
+ Globals::worldToScreenMatrix[3][1] * origin.y
+ Globals::worldToScreenMatrix[3][2] * origin.z
+ Globals::worldToScreenMatrix[3][3];
if ( w < 0.01f )
return false;
float inverseW = 1 / w;
screen.x = (Globals::screenSizeX/2) + (0.5f * ((Globals::worldToScreenMatrix[0][0] * origin.x + Globals::worldToScreenMatrix[0][1] * origin.y +
Globals::worldToScreenMatrix[0][2] * origin.z + Globals::worldToScreenMatrix[0][3]) * inverseW) * Globals::screenSizeX + 0.5f);
screen.y = (Globals::screenSizeY/2) - (0.5f * ((Globals::worldToScreenMatrix[1][0] * origin.x + Globals::worldToScreenMatrix[1][1] * origin.y +
Globals::worldToScreenMatrix[1][2] * origin.z + Globals::worldToScreenMatrix[1][3]) * inverseW) * Globals::screenSizeY + 0.5f);
return true;
}
static bool getBox(Entity* entity, int& x, int& y, int& x2, int& y2) {
Vector vOrigin, min, max;
Vector flb, brt, blb, frt, frb, brb, blt, flt; // think of these as Front-Left-Bottom/Front-Left-Top... Etc.
vOrigin = entity->origin();
min = entity->collideable().OBBMins() + vOrigin;
max = entity->collideable().OBBMaxs() + vOrigin;
Vector points[] = { Vector( min.x, min.y, min.z ),
Vector( min.x, max.y, min.z ),
Vector( max.x, max.y, min.z ),
Vector( max.x, min.y, min.z ),
Vector( max.x, max.y, max.z ),
Vector( min.x, max.y, max.z ),
Vector( min.x, min.y, max.z ),
Vector( max.x, min.y, max.z ) };
// Get screen positions
if ( !worldToScreen( points[3], flb ) || !worldToScreen( points[5], brt )
|| !worldToScreen( points[0], blb ) || !worldToScreen( points[4], frt )
|| !worldToScreen( points[2], frb ) || !worldToScreen( points[1], brb )
|| !worldToScreen( points[6], blt ) || !worldToScreen( points[7], flt ) )
return false;
Vector arr[] = { flb, brt, blb, frt, frb, brb, blt, flt };
float left = flb.x;
float top = flb.y;
float right = flb.x;
float bottom = flb.y;
for ( int i = 1; i < 8; i++ ) {
if (left > arr[i].x)
left = arr[i].x;
if (bottom < arr[i].y)
bottom = arr[i].y;
if (right < arr[i].x)
right = arr[i].x;
if (top > arr[i].y)
top = arr[i].y;
}
x = (int)left;
y = (int)top;
x2 = (int)right;
y2 = (int)bottom;
return true;
}
void outlinedText(ImVec2 pos, ImColor color, char* text) {
Globals::drawList->AddText(ImVec2(pos.x-1, pos.y), ImColor(0, 0, 0, 255), text);
Globals::drawList->AddText(ImVec2(pos.x+1, pos.y), ImColor(0, 0, 0, 255), text);
Globals::drawList->AddText(ImVec2(pos.x, pos.y-1), ImColor(0, 0, 0, 255), text);
Globals::drawList->AddText(ImVec2(pos.x, pos.y+1), ImColor(0, 0, 0, 255), text);
Globals::drawList->AddText(ImVec2(pos.x, pos.y), color, text);
}
void drawBox(int x, int y, int x2, int y2, bool drawBox, ImColor color, char* topText, char* rightText, int health = -1, bool dynamicHealthColor = false, ImColor defaultHealthBarColor = ImColor(0, 240, 0, 255)) {
if (drawBox) {
Globals::drawList->AddRect(ImVec2(x, y), ImVec2(x2, y2), color);
Globals::drawList->AddRect(ImVec2(x-1, y-1), ImVec2(x2+1, y2+1), ImColor(0, 0, 0, 255));
Globals::drawList->AddRect(ImVec2(x+1, y+1), ImVec2(x2-1, y2-1), ImColor(0, 0, 0, 255));
}
if (health != -1) {
//border color
Globals::drawList->AddRectFilled(ImVec2(x - 6, y2 - (((float) health / 100.f) * (y2 - y)) - 1),
ImVec2(x - 2, y2 + 1), ImColor(0, 0, 0, 255));
//bar color
ImColor healthBarColor = defaultHealthBarColor;
if (dynamicHealthColor) {
ImGui::ColorConvertHSVtoRGB(((float)health-20.f)/255.f, 1.f, 1.f, healthBarColor.Value.x, healthBarColor.Value.y, healthBarColor.Value.z);
}
Globals::drawList->AddRectFilled(ImVec2(x - 5, y2 - (((float) health / 100.f) * (y2 - y))),ImVec2(x - 3, y2), healthBarColor);
}
outlinedText(ImVec2(x2+1, y), ImColor(255, 255, 255, 255), rightText);
outlinedText(ImVec2(x+((x2-x)/2)-(ImGui::CalcTextSize(topText).x/2), y-(ImGui::CalcTextSize(topText).y)), ImColor(255, 255, 255, 255), topText);
}
void drawPlayer(Player* p) {
if (!p->dormant()) {
if (p->health() > 0) {
int x, y, x2, y2;
if (getBox(p, x, y, x2, y2)) {
player_info_t info;
Interfaces::engine->GetPlayerInfo(p->index(), &info);
if (p->team() != Globals::localPlayer->team()) {
if ((Globals::localPlayer->health() == 0 && CONFIGBOOL("Visuals>Enemies>ESP>Only When Dead")) || !CONFIGBOOL("Visuals>Enemies>ESP>Only When Dead")) {
std::stringstream rightText;
if (CONFIGBOOL("Visuals>Enemies>ESP>Health"))
rightText << p->health() << "hp\n";
if (CONFIGBOOL("Visuals>Enemies>ESP>Money"))
rightText << "$" << p->money() << "\n";
drawBox(x, y, x2, y2, CONFIGBOOL("Visuals>Enemies>ESP>Box"),
CONFIGCOL("Visuals>Enemies>ESP>Box Color"), CONFIGBOOL("Visuals>Enemies>ESP>Name") ? info.name : (char*)"",
(char*)rightText.str().c_str(), CONFIGBOOL("Visuals>Enemies>ESP>Health Bar") ? p->health() : -1, CONFIGBOOL("Visuals>Enemies>ESP>Dynamic Color"),
CONFIGCOL("Visuals>Enemies>ESP>Health Bar Color"));
}
}
if (p->team() == Globals::localPlayer->team()) {
if ((Globals::localPlayer->health() == 0 && CONFIGBOOL("Visuals>Teammates>ESP>Only When Dead")) || !CONFIGBOOL("Visuals>Teammates>ESP>Only When Dead")) {
std::stringstream rightText;
if (CONFIGBOOL("Visuals>Teammates>ESP>Health"))
rightText << p->health() << "hp\n";
if (CONFIGBOOL("Visuals>Teammates>ESP>Money"))
rightText << "$" << p->money() << "\n";
drawBox(x, y, x2, y2, CONFIGBOOL("Visuals>Teammates>ESP>Box"),
CONFIGCOL("Visuals>Teammates>ESP>Box Color"), CONFIGBOOL("Visuals>Teammates>ESP>Name") ? info.name : (char*)"",
(char*)rightText.str().c_str(), CONFIGBOOL("Visuals>Teammates>ESP>Health Bar") ? p->health() : -1, CONFIGBOOL("Visuals>Teammates>ESP>Dynamic Color"),
CONFIGCOL("Visuals>Teammates>ESP>Health Bar Color"));
}
}
}
}
}
}
void drawGenericEnt(Entity* ent, bool box, ImColor color, const char* label) {
int x, y, x2, y2;
if (getBox(ent, x, y, x2, y2)) {
drawBox(x, y, x2, y2, box, color, (char*)label, (char*)"", -1);
}
}
void Features::ESP::draw() {
if (Interfaces::engine->IsInGame()) {
int highest = Interfaces::entityList->GetHighestEntityIndex();
for (int i; i < highest; i++) {
if (Globals::localPlayer) {
if (i != Interfaces::engine->GetLocalPlayer()) {
Entity* ent = (Entity*)Interfaces::entityList->GetClientEntity(i);
if (ent) {
ClientClass* clientClass = ent->clientClass();
/* Player ESP */
if (clientClass->m_ClassID == EClassIds::CCSPlayer) {
drawPlayer((Player*)ent);
}
/* Weapon ESP */
if ((clientClass->m_ClassID != EClassIds::CBaseWeaponWorldModel && strstr(clientClass->m_pNetworkName, "Weapon")) || clientClass->m_ClassID == EClassIds::CDEagle || clientClass->m_ClassID == EClassIds::CC4 || clientClass->m_ClassID == EClassIds::CAK47) {
if (((Weapon*)ent)->owner() == -1) {
try {
drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Weapon Box"), CONFIGCOL("Visuals>World>Items>Weapon Box Color"), CONFIGBOOL("Visuals>World>Items>Weapon Label") ? itemIndexMap.at(((Weapon*)ent)->itemIndex()) : "");
}
catch(const std::exception & e) {
//Log::log(WARN, "itemDefinitionIndex %d not found!", ((Weapon*)ent)->itemIndex());
}
}
}
/* Planted C4 ESP */
if (clientClass->m_ClassID == EClassIds::CPlantedC4) {
char label[32] = "";
snprintf(label, 32, "Planted C4\n%.3f", ((PlantedC4*)ent)->time() - Interfaces::globals->curtime);
drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Planted C4 Box"), CONFIGCOL("Visuals>World>Items>Planted C4 Box Color"), CONFIGBOOL("Visuals>World>Items>Planted C4 Label") ? label : "");
}
/* Chicken ESP */
if (clientClass->m_ClassID == EClassIds::CChicken) {
drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Chicken Box"), CONFIGCOL("Visuals>World>Items>Chicken Box Color"), CONFIGBOOL("Visuals>World>Items>Chicken Label") ? "Chicken" : "");
}
/* Fish ESP */
if (clientClass->m_ClassID == EClassIds::CFish) {
drawGenericEnt(ent, CONFIGBOOL("Visuals>World>Items>Fish Box"), CONFIGCOL("Visuals>World>Items>Fish Box Color"), CONFIGBOOL("Visuals>World>Items>Fish Label") ? "Fish" : "");
}
/* Debug ESP Everything*/
if (CONFIGBOOL("Visuals>World>Items>ESP Quite literally everything")) {
char label[128] = "";
snprintf(label, 128, "%d\n%s", clientClass->m_ClassID, clientClass->m_pNetworkName);
drawGenericEnt(ent, true, ImColor(255, 255, 255, 255), label);
}
}
}
}
}
}
}
| 50.533654
| 278
| 0.528779
|
luk1337
|
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
|
19f601a94df656254a9839f6c61047cf33f698e1
| 2,001
|
cpp
|
C++
|
opencv_1/hue.cpp
|
liangjisheng/computer-vision
|
b2f05f87334078f4a51775383aac04f2bdedae7c
|
[
"MIT"
] | null | null | null |
opencv_1/hue.cpp
|
liangjisheng/computer-vision
|
b2f05f87334078f4a51775383aac04f2bdedae7c
|
[
"MIT"
] | null | null | null |
opencv_1/hue.cpp
|
liangjisheng/computer-vision
|
b2f05f87334078f4a51775383aac04f2bdedae7c
|
[
"MIT"
] | null | null | null |
#include <cv.h>
#include <highgui.h>
int main( int argc, char** argv )
{
IplImage* src;
if( argc == 2 && (src=cvLoadImage(argv[1], 1))!= 0)
{
IplImage* h_plane = cvCreateImage( cvGetSize(src), 8, 1 );
IplImage* s_plane = cvCreateImage( cvGetSize(src), 8, 1 );
IplImage* v_plane = cvCreateImage( cvGetSize(src), 8, 1 );
IplImage* planes[] = { h_plane, s_plane };
IplImage* hsv = cvCreateImage( cvGetSize(src), 8, 3 );
int h_bins = 30, s_bins = 32;
int hist_size[] = {h_bins, s_bins};
float h_ranges[] = { 0, 180 }; /* hue varies from 0 (~0°red) to 180 (~360°red again) */
float s_ranges[] = { 0, 255 }; /* saturation varies from 0 (black-gray-white) to 255 (pure spectrum color) */
float* ranges[] = { h_ranges, s_ranges };
int scale = 10;
IplImage* hist_img = cvCreateImage( cvSize(h_bins*scale,s_bins*scale), 8, 3 );
CvHistogram* hist;
float max_value = 0;
int h, s;
cvCvtColor( src, hsv, CV_BGR2HSV );
cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 );
hist = cvCreateHist( 2, hist_size, CV_HIST_ARRAY, ranges, 1 );
cvCalcHist( planes, hist, 0, 0 );
cvGetMinMaxHistValue( hist, 0, &max_value, 0, 0 );
cvZero( hist_img );
for( h = 0; h < h_bins; h++ )
{
for( s = 0; s < s_bins; s++ )
{
float bin_val = cvQueryHistValue_2D( hist, h, s );
int intensity = cvRound(bin_val*255/max_value);
cvRectangle( hist_img, cvPoint( h*scale, s*scale ),
cvPoint( (h+1)*scale - 1, (s+1)*scale - 1),
CV_RGB(intensity,intensity,intensity),
CV_FILLED );
}
}
cvNamedWindow( "Source", 1 );
cvShowImage( "Source", src );
cvNamedWindow( "H-S Histogram", 1 );
cvShowImage( "H-S Histogram", hist_img );
cvWaitKey(0);
}
}
| 39.235294
| 117
| 0.534733
|
liangjisheng
|
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
|
19faf5d2f964194152886e599066c6da7721c1e3
| 7,764
|
cc
|
C++
|
third_party/blink/renderer/core/fileapi/public_url_manager.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
third_party/blink/renderer/core/fileapi/public_url_manager.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
third_party/blink/renderer/core/fileapi/public_url_manager.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
/*
* Copyright (C) 2012 Motorola Mobility Inc.
* Copyright (C) 2013 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/fileapi/public_url_manager.h"
#include "third_party/blink/public/mojom/blob/blob_registry.mojom-blink.h"
#include "third_party/blink/renderer/core/fileapi/url_registry.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/blob/blob_url.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/weborigin/url_security_origin_map.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
namespace {
// When a blob URL is created in a unique origin the origin is serialized into
// the URL as "null". Since that makes it impossible to parse the origin back
// out and compare it against a context's origin (to check if a context is
// allowed to dereference the URL) we store a map of blob URL to SecurityOrigin
// instance for blob URLs with unique origins.
class BlobOriginMap : public URLSecurityOriginMap {
public:
BlobOriginMap();
SecurityOrigin* GetOrigin(const KURL&) override;
};
typedef HashMap<String, scoped_refptr<SecurityOrigin>> BlobURLOriginMap;
static ThreadSpecific<BlobURLOriginMap>& OriginMap() {
// We want to create the BlobOriginMap exactly once because it is shared by
// all the threads.
DEFINE_THREAD_SAFE_STATIC_LOCAL(BlobOriginMap, cache, ());
(void)cache; // BlobOriginMap's constructor does the interesting work.
DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<BlobURLOriginMap>, map, ());
return map;
}
static void SaveToOriginMap(SecurityOrigin* origin, const KURL& url) {
// If the blob URL contains null origin, as in the context with unique
// security origin or file URL, save the mapping between url and origin so
// that the origin can be retrieved when doing security origin check.
//
// See the definition of the origin of a Blob URL in the File API spec.
DCHECK(!url.HasFragmentIdentifier());
if (origin && BlobURL::GetOrigin(url) == "null")
OriginMap()->insert(url.GetString(), origin);
}
static void RemoveFromOriginMap(const KURL& url) {
if (BlobURL::GetOrigin(url) == "null")
OriginMap()->erase(url.GetString());
}
BlobOriginMap::BlobOriginMap() {
SecurityOrigin::SetMap(this);
}
SecurityOrigin* BlobOriginMap::GetOrigin(const KURL& url) {
if (url.ProtocolIs("blob")) {
KURL url_without_fragment = url;
url_without_fragment.RemoveFragmentIdentifier();
return OriginMap()->at(url_without_fragment.GetString());
}
return nullptr;
}
} // namespace
PublicURLManager* PublicURLManager::Create(ExecutionContext* context) {
return new PublicURLManager(context);
}
PublicURLManager::PublicURLManager(ExecutionContext* context)
: ContextLifecycleObserver(context), is_stopped_(false) {}
String PublicURLManager::RegisterURL(URLRegistrable* registrable) {
if (is_stopped_)
return String();
SecurityOrigin* origin = GetExecutionContext()->GetMutableSecurityOrigin();
const KURL& url = BlobURL::CreatePublicURL(origin);
DCHECK(!url.IsEmpty());
const String& url_string = url.GetString();
mojom::blink::BlobPtr blob;
if (RuntimeEnabledFeatures::MojoBlobURLsEnabled())
blob = registrable->AsMojoBlob();
if (blob) {
if (!url_store_) {
BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin(
origin, MakeRequest(&url_store_));
}
url_store_->Register(std::move(blob), url);
mojo_urls_.insert(url_string);
} else {
URLRegistry* registry = ®istrable->Registry();
registry->RegisterURL(origin, url, registrable);
url_to_registry_.insert(url_string, registry);
}
SaveToOriginMap(origin, url);
return url_string;
}
void PublicURLManager::Revoke(const KURL& url) {
if (is_stopped_)
return;
// Don't bother trying to revoke URLs that can't have been registered anyway.
if (!url.ProtocolIs("blob") || url.HasFragmentIdentifier())
return;
// Don't support revoking cross-origin blob URLs.
if (!SecurityOrigin::Create(url)->IsSameSchemeHostPort(
GetExecutionContext()->GetSecurityOrigin()))
return;
if (RuntimeEnabledFeatures::MojoBlobURLsEnabled()) {
if (!url_store_) {
BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin(
GetExecutionContext()->GetSecurityOrigin(), MakeRequest(&url_store_));
}
url_store_->Revoke(url);
mojo_urls_.erase(url.GetString());
}
RemoveFromOriginMap(url);
auto it = url_to_registry_.find(url.GetString());
if (it == url_to_registry_.end())
return;
it->value->UnregisterURL(url);
url_to_registry_.erase(it);
}
void PublicURLManager::Resolve(
const KURL& url,
network::mojom::blink::URLLoaderFactoryRequest factory_request) {
DCHECK(RuntimeEnabledFeatures::MojoBlobURLsEnabled());
DCHECK(url.ProtocolIs("blob"));
if (!url_store_) {
BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin(
GetExecutionContext()->GetSecurityOrigin(), MakeRequest(&url_store_));
}
url_store_->ResolveAsURLLoaderFactory(url, std::move(factory_request));
}
void PublicURLManager::Resolve(
const KURL& url,
mojom::blink::BlobURLTokenRequest token_request) {
DCHECK(RuntimeEnabledFeatures::MojoBlobURLsEnabled());
DCHECK(url.ProtocolIs("blob"));
if (!url_store_) {
BlobDataHandle::GetBlobRegistry()->URLStoreForOrigin(
GetExecutionContext()->GetSecurityOrigin(), MakeRequest(&url_store_));
}
url_store_->ResolveForNavigation(url, std::move(token_request));
}
void PublicURLManager::ContextDestroyed(ExecutionContext*) {
if (is_stopped_)
return;
is_stopped_ = true;
for (auto& url_registry : url_to_registry_) {
url_registry.value->UnregisterURL(KURL(url_registry.key));
RemoveFromOriginMap(KURL(url_registry.key));
}
for (const auto& url : mojo_urls_)
RemoveFromOriginMap(KURL(url));
url_to_registry_.clear();
mojo_urls_.clear();
url_store_.reset();
}
void PublicURLManager::Trace(blink::Visitor* visitor) {
ContextLifecycleObserver::Trace(visitor);
}
} // namespace blink
| 36.971429
| 82
| 0.748841
|
zipated
|
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
|
19fe8fe5fae8bf2351fae313f8ece406d47d9340
| 7,638
|
cpp
|
C++
|
indra/newview/llvowater.cpp
|
humbletim/archived-casviewer
|
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
|
[
"Unlicense"
] | null | null | null |
indra/newview/llvowater.cpp
|
humbletim/archived-casviewer
|
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
|
[
"Unlicense"
] | null | null | null |
indra/newview/llvowater.cpp
|
humbletim/archived-casviewer
|
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
|
[
"Unlicense"
] | null | null | null |
/**
* @file llvowater.cpp
* @brief LLVOWater class implementation
*
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llvowater.h"
#include "llviewercontrol.h"
#include "lldrawable.h"
#include "lldrawpoolwater.h"
#include "llface.h"
#include "llsky.h"
#include "llsurface.h"
#include "llvosky.h"
#include "llviewercamera.h"
#include "llviewertexturelist.h"
#include "llviewerregion.h"
#include "llworld.h"
#include "pipeline.h"
#include "llspatialpartition.h"
const BOOL gUseRoam = FALSE;
///////////////////////////////////
template<class T> inline T LERP(T a, T b, F32 factor)
{
return a + (b - a) * factor;
}
const U32 N_RES_HALF = (N_RES >> 1);
const U32 WIDTH = (N_RES * WAVE_STEP); //128.f //64 // width of wave tile, in meters
const F32 WAVE_STEP_INV = (1. / WAVE_STEP);
LLVOWater::LLVOWater(const LLUUID &id,
const LLPCode pcode,
LLViewerRegion *regionp) :
LLStaticViewerObject(id, pcode, regionp),
mRenderType(LLPipeline::RENDER_TYPE_WATER)
{
// Terrain must draw during selection passes so it can block objects behind it.
mbCanSelect = FALSE;
// <FS:CR> Aurora Sim
//setScale(LLVector3(256.f, 256.f, 0.f)); // Hack for setting scale for bounding boxes/visibility.
setScale(LLVector3(mRegionp->getWidth(), mRegionp->getWidth(), 0.f));
// </FS:CR> Aurora Sim
mUseTexture = TRUE;
mIsEdgePatch = FALSE;
}
void LLVOWater::markDead()
{
LLViewerObject::markDead();
}
BOOL LLVOWater::isActive() const
{
return FALSE;
}
void LLVOWater::setPixelAreaAndAngle(LLAgent &agent)
{
mAppAngle = 50;
mPixelArea = 500*500;
}
// virtual
void LLVOWater::updateTextures()
{
}
// Never gets called
void LLVOWater::idleUpdate(LLAgent &agent, const F64 &time)
{
}
LLDrawable *LLVOWater::createDrawable(LLPipeline *pipeline)
{
pipeline->allocDrawable(this);
mDrawable->setLit(FALSE);
mDrawable->setRenderType(mRenderType);
LLDrawPoolWater *pool = (LLDrawPoolWater*) gPipeline.getPool(LLDrawPool::POOL_WATER);
if (mUseTexture)
{
mDrawable->setNumFaces(1, pool, mRegionp->getLand().getWaterTexture());
}
else
{
mDrawable->setNumFaces(1, pool, LLWorld::getInstance()->getDefaultWaterTexture());
}
return mDrawable;
}
static LLTrace::BlockTimerStatHandle FTM_UPDATE_WATER("Update Water");
BOOL LLVOWater::updateGeometry(LLDrawable *drawable)
{
LL_RECORD_BLOCK_TIME(FTM_UPDATE_WATER);
LLFace *face;
if (drawable->getNumFaces() < 1)
{
LLDrawPoolWater *poolp = (LLDrawPoolWater*) gPipeline.getPool(LLDrawPool::POOL_WATER);
drawable->addFace(poolp, NULL);
}
face = drawable->getFace(0);
if (!face)
{
return TRUE;
}
// LLVector2 uvs[4];
// LLVector3 vtx[4];
LLStrider<LLVector3> verticesp, normalsp;
LLStrider<LLVector2> texCoordsp;
LLStrider<U16> indicesp;
U16 index_offset;
// A quad is 4 vertices and 6 indices (making 2 triangles)
static const unsigned int vertices_per_quad = 4;
static const unsigned int indices_per_quad = 6;
const S32 size = gSavedSettings.getBOOL("RenderTransparentWater") && LLGLSLShader::sNoFixedFunction ? 16 : 1;
const S32 num_quads = size * size;
face->setSize(vertices_per_quad * num_quads,
indices_per_quad * num_quads);
LLVertexBuffer* buff = face->getVertexBuffer();
if (!buff || !buff->isWriteable())
{
buff = new LLVertexBuffer(LLDrawPoolWater::VERTEX_DATA_MASK, GL_DYNAMIC_DRAW_ARB);
buff->allocateBuffer(face->getGeomCount(), face->getIndicesCount(), TRUE);
face->setIndicesIndex(0);
face->setGeomIndex(0);
face->setVertexBuffer(buff);
}
else
{
buff->resizeBuffer(face->getGeomCount(), face->getIndicesCount());
}
index_offset = face->getGeometry(verticesp,normalsp,texCoordsp, indicesp);
LLVector3 position_agent;
position_agent = getPositionAgent();
face->mCenterAgent = position_agent;
face->mCenterLocal = position_agent;
S32 x, y;
F32 step_x = getScale().mV[0] / size;
F32 step_y = getScale().mV[1] / size;
const LLVector3 up(0.f, step_y * 0.5f, 0.f);
const LLVector3 right(step_x * 0.5f, 0.f, 0.f);
const LLVector3 normal(0.f, 0.f, 1.f);
F32 size_inv = 1.f / size;
F32 z_fudge = 0.f;
if (getIsEdgePatch())
{ //bump edge patches down 10 cm to prevent aliasing along edges
z_fudge = -0.1f;
}
for (y = 0; y < size; y++)
{
for (x = 0; x < size; x++)
{
S32 toffset = index_offset + 4*(y*size + x);
position_agent = getPositionAgent() - getScale() * 0.5f;
position_agent.mV[VX] += (x + 0.5f) * step_x;
position_agent.mV[VY] += (y + 0.5f) * step_y;
position_agent.mV[VZ] += z_fudge;
*verticesp++ = position_agent - right + up;
*verticesp++ = position_agent - right - up;
*verticesp++ = position_agent + right + up;
*verticesp++ = position_agent + right - up;
*texCoordsp++ = LLVector2(x*size_inv, (y+1)*size_inv);
*texCoordsp++ = LLVector2(x*size_inv, y*size_inv);
*texCoordsp++ = LLVector2((x+1)*size_inv, (y+1)*size_inv);
*texCoordsp++ = LLVector2((x+1)*size_inv, y*size_inv);
*normalsp++ = normal;
*normalsp++ = normal;
*normalsp++ = normal;
*normalsp++ = normal;
*indicesp++ = toffset + 0;
*indicesp++ = toffset + 1;
*indicesp++ = toffset + 2;
*indicesp++ = toffset + 1;
*indicesp++ = toffset + 3;
*indicesp++ = toffset + 2;
}
}
buff->flush();
mDrawable->movePartition();
LLPipeline::sCompiles++;
return TRUE;
}
void LLVOWater::initClass()
{
}
void LLVOWater::cleanupClass()
{
}
void setVecZ(LLVector3& v)
{
v.mV[VX] = 0;
v.mV[VY] = 0;
v.mV[VZ] = 1;
}
void LLVOWater::setUseTexture(const BOOL use_texture)
{
mUseTexture = use_texture;
}
void LLVOWater::setIsEdgePatch(const BOOL edge_patch)
{
mIsEdgePatch = edge_patch;
}
void LLVOWater::updateSpatialExtents(LLVector4a &newMin, LLVector4a& newMax)
{
LLVector4a pos;
pos.load3(getPositionAgent().mV);
LLVector4a scale;
scale.load3(getScale().mV);
scale.mul(0.5f);
newMin.setSub(pos, scale);
newMax.setAdd(pos, scale);
pos.setAdd(newMin,newMax);
pos.mul(0.5f);
mDrawable->setPositionGroup(pos);
}
U32 LLVOWater::getPartitionType() const
{
if (mIsEdgePatch)
{
return LLViewerRegion::PARTITION_VOIDWATER;
}
return LLViewerRegion::PARTITION_WATER;
}
U32 LLVOVoidWater::getPartitionType() const
{
return LLViewerRegion::PARTITION_VOIDWATER;
}
LLWaterPartition::LLWaterPartition(LLViewerRegion* regionp)
: LLSpatialPartition(0, FALSE, GL_DYNAMIC_DRAW_ARB, regionp)
{
mInfiniteFarClip = TRUE;
mDrawableType = LLPipeline::RENDER_TYPE_WATER;
mPartitionType = LLViewerRegion::PARTITION_WATER;
}
LLVoidWaterPartition::LLVoidWaterPartition(LLViewerRegion* regionp) : LLWaterPartition(regionp)
{
mOcclusionEnabled = FALSE;
mDrawableType = LLPipeline::RENDER_TYPE_VOIDWATER;
mPartitionType = LLViewerRegion::PARTITION_VOIDWATER;
}
| 24.094637
| 110
| 0.707384
|
humbletim
|
c20073cf03e1fac2b7f5c24b5c4e22352b84dc79
| 4,986
|
cpp
|
C++
|
code_reading/oceanbase-master/src/storage/blocksstable/ob_storage_cache_suite.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | null | null | null |
code_reading/oceanbase-master/src/storage/blocksstable/ob_storage_cache_suite.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | null | null | null |
code_reading/oceanbase-master/src/storage/blocksstable/ob_storage_cache_suite.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | 1
|
2020-10-18T12:59:31.000Z
|
2020-10-18T12:59:31.000Z
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "ob_storage_cache_suite.h"
using namespace oceanbase::common;
namespace oceanbase {
namespace blocksstable {
ObStorageCacheSuite::ObStorageCacheSuite()
: block_index_cache_(), user_block_cache_(), user_row_cache_(), bf_cache_(), fuse_row_cache_(), is_inited_(false)
{}
ObStorageCacheSuite::~ObStorageCacheSuite()
{
destroy();
}
ObStorageCacheSuite& ObStorageCacheSuite::get_instance()
{
static ObStorageCacheSuite instance_;
return instance_;
}
int ObStorageCacheSuite::init(const int64_t index_cache_priority, const int64_t user_block_cache_priority,
const int64_t user_row_cache_priority, const int64_t fuse_row_cache_priority, const int64_t bf_cache_priority,
const int64_t bf_cache_miss_count_threshold)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(is_inited_)) {
ret = OB_INIT_TWICE;
STORAGE_LOG(WARN, "The cache suite has been inited, ", K(ret));
} else if (OB_FAIL(block_index_cache_.init("block_index_cache", index_cache_priority))) {
STORAGE_LOG(ERROR, "init block index cache failed, ", K(ret));
} else if (OB_FAIL(user_block_cache_.init("user_block_cache", user_block_cache_priority))) {
STORAGE_LOG(ERROR, "init user block cache failed, ", K(ret));
} else if (OB_FAIL(user_row_cache_.init("user_row_cache", user_row_cache_priority))) {
STORAGE_LOG(ERROR, "init user sstable row cache failed, ", K(ret));
} else if (OB_FAIL(bf_cache_.init("bf_cache", bf_cache_priority))) {
STORAGE_LOG(ERROR, "init bloom filter cache failed, ", K(ret));
} else if (OB_FAIL(bf_cache_.set_bf_cache_miss_count_threshold(bf_cache_miss_count_threshold))) {
STORAGE_LOG(ERROR, "failed to set bf_cache_miss_count_threshold", K(ret));
} else if (OB_FAIL(fuse_row_cache_.init("fuse_row_cache", fuse_row_cache_priority))) {
STORAGE_LOG(ERROR, "fail to init fuse row cache", K(ret));
} else {
is_inited_ = true;
}
if (OB_UNLIKELY(OB_SUCCESS != ret && !is_inited_)) {
destroy();
}
return ret;
}
int ObStorageCacheSuite::reset_priority(const int64_t index_cache_priority, const int64_t user_block_cache_priority,
const int64_t user_row_cache_priority, const int64_t fuse_row_cache_priority, const int64_t bf_cache_priority)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!is_inited_)) {
ret = OB_NOT_INIT;
STORAGE_LOG(WARN, "The cache suite has not been inited, ", K(ret));
} else if (OB_FAIL(block_index_cache_.set_priority(index_cache_priority))) {
STORAGE_LOG(ERROR, "set priority for block index cache failed, ", K(ret));
} else if (OB_FAIL(user_block_cache_.set_priority(user_block_cache_priority))) {
STORAGE_LOG(ERROR, "set priority for user block cache failed, ", K(ret));
} else if (OB_FAIL(user_row_cache_.set_priority(user_row_cache_priority))) {
STORAGE_LOG(ERROR, "set priority for user sstable row cache failed, ", K(ret));
} else if (OB_FAIL(bf_cache_.set_priority(bf_cache_priority))) {
STORAGE_LOG(ERROR, "set priority for bloom filter cache failed, ", K(ret));
} else if (OB_FAIL(fuse_row_cache_.set_priority(fuse_row_cache_priority))) {
STORAGE_LOG(ERROR, "fail to set priority for fuse row cache", K(ret));
}
return ret;
}
int ObStorageCacheSuite::set_bf_cache_miss_count_threshold(const int64_t bf_cache_miss_count_threshold)
{
int ret = OB_SUCCESS;
if (OB_FAIL(bf_cache_.set_bf_cache_miss_count_threshold(bf_cache_miss_count_threshold))) {
STORAGE_LOG(WARN, "failed to set bf_cache_miss_count_threshold", K(ret), K(bf_cache_miss_count_threshold));
}
return ret;
}
void ObStorageCacheSuite::destroy()
{
block_index_cache_.destroy();
user_block_cache_.destroy();
user_row_cache_.destroy();
bf_cache_.destroy();
fuse_row_cache_.destroy();
is_inited_ = false;
}
void ObStorageCacheContext::set(ObBlockCacheWorkingSet& block_cache_ws)
{
block_index_cache_ = &(OB_STORE_CACHE.block_index_cache_);
block_cache_ = &(OB_STORE_CACHE.user_block_cache_);
block_cache_ws_ = &block_cache_ws;
bf_cache_ = &(OB_STORE_CACHE.bf_cache_);
row_cache_ = &(OB_STORE_CACHE.user_row_cache_);
}
bool ObStorageCacheContext::is_valid() const
{
return NULL != block_index_cache_ && NULL != block_cache_ && NULL != block_cache_ws_ && NULL != row_cache_ &&
NULL != bf_cache_;
}
void ObStorageCacheContext::reset()
{
block_index_cache_ = NULL;
block_cache_ = NULL;
block_cache_ws_ = NULL;
row_cache_ = NULL;
bf_cache_ = NULL;
}
} // namespace blocksstable
} // namespace oceanbase
| 38.651163
| 117
| 0.751304
|
wangcy6
|
c201ef5788f72bf70434e8fa03e8b42033133303
| 1,104
|
cpp
|
C++
|
WickedEngine/wiLoadingScreen.cpp
|
rohankumardubey/WickedEngine
|
2e94230c520f0921718ea531c1de9c76611c8944
|
[
"MIT"
] | 11
|
2021-12-27T11:31:24.000Z
|
2021-12-30T08:02:57.000Z
|
WickedEngine/wiLoadingScreen.cpp
|
rohankumardubey/WickedEngine
|
2e94230c520f0921718ea531c1de9c76611c8944
|
[
"MIT"
] | null | null | null |
WickedEngine/wiLoadingScreen.cpp
|
rohankumardubey/WickedEngine
|
2e94230c520f0921718ea531c1de9c76611c8944
|
[
"MIT"
] | 3
|
2021-12-28T02:31:08.000Z
|
2021-12-31T07:32:00.000Z
|
#include "wiLoadingScreen.h"
#include "wiApplication.h"
#include <thread>
namespace wi
{
bool LoadingScreen::isActive()
{
return wi::jobsystem::IsBusy(ctx);
}
void LoadingScreen::addLoadingFunction(std::function<void(wi::jobsystem::JobArgs)> loadingFunction)
{
if (loadingFunction != nullptr)
{
tasks.push_back(loadingFunction);
}
}
void LoadingScreen::addLoadingComponent(RenderPath* component, Application* main, float fadeSeconds, wi::Color fadeColor)
{
addLoadingFunction([=](wi::jobsystem::JobArgs args) {
component->Load();
});
onFinished([=] {
main->ActivatePath(component, fadeSeconds, fadeColor);
});
}
void LoadingScreen::onFinished(std::function<void()> finishFunction)
{
if (finishFunction != nullptr)
finish = finishFunction;
}
void LoadingScreen::Start()
{
for (auto& x : tasks)
{
wi::jobsystem::Execute(ctx, x);
}
std::thread([this]() {
wi::jobsystem::Wait(ctx);
finish();
}).detach();
RenderPath2D::Start();
}
void LoadingScreen::Stop()
{
tasks.clear();
finish = nullptr;
RenderPath2D::Stop();
}
}
| 18.098361
| 122
| 0.671196
|
rohankumardubey
|
c202af40ed7454f6c723d5124d070870fc6b40e0
| 264
|
cpp
|
C++
|
src/main/algorithms/cpp/graph/clone_graph_133/graph_node.cpp
|
algorithmlover2016/leet_code
|
2eecc7971194c8a755e67719d8f66c636694e7e9
|
[
"Apache-2.0"
] | null | null | null |
src/main/algorithms/cpp/graph/clone_graph_133/graph_node.cpp
|
algorithmlover2016/leet_code
|
2eecc7971194c8a755e67719d8f66c636694e7e9
|
[
"Apache-2.0"
] | null | null | null |
src/main/algorithms/cpp/graph/clone_graph_133/graph_node.cpp
|
algorithmlover2016/leet_code
|
2eecc7971194c8a755e67719d8f66c636694e7e9
|
[
"Apache-2.0"
] | null | null | null |
#include "./graph_node.h"
Node::Node() : val(0),
neighbors(std::vector<Node*>()) {
}
Node::Node(int _val) : val(_val),
neighbors(std::vector<Node*>()) {
}
Node::Node(int _val, std::vector<Node*> const & _neighbors): val(_val),
neighbors(_neighbors) {
}
| 17.6
| 71
| 0.625
|
algorithmlover2016
|
c204cf8e0458653fecc337527805f7fe2de01019
| 17,967
|
cpp
|
C++
|
src/globals/graph_types.cpp
|
zakimjz/GPU_graph_mining
|
22ba73bea97533ed6b2af613bd263ef4d869e71a
|
[
"Apache-2.0"
] | 2
|
2020-05-13T09:09:50.000Z
|
2021-07-16T12:51:53.000Z
|
src/globals/graph_types.cpp
|
zakimjz/GPU_graph_mining
|
22ba73bea97533ed6b2af613bd263ef4d869e71a
|
[
"Apache-2.0"
] | null | null | null |
src/globals/graph_types.cpp
|
zakimjz/GPU_graph_mining
|
22ba73bea97533ed6b2af613bd263ef4d869e71a
|
[
"Apache-2.0"
] | 1
|
2022-03-22T01:15:33.000Z
|
2022-03-22T01:15:33.000Z
|
#include <graph_types.hpp>
#include <algorithm>
#include <cassert>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <logger.hpp>
#include <utils.hpp>
#include <cstring>
namespace types {
template <class T, class Iterator>
void tokenize(const char *str, Iterator iterator)
{
std::istringstream is(std::string(str));
std::copy(std::istream_iterator <T> (is), std::istream_iterator <T> (), iterator);
}
Graph::Graph() : edge_size_(0), directed(false)
{
}
Graph::Graph(bool _directed)
{
directed = _directed;
}
void Graph::buildEdge()
{
char buf[512];
std::map <std::string, unsigned int> tmp;
unsigned int id = 0;
for(int from = 0; from < (int)size(); ++from) {
for(Vertex::edge_iterator it = (*this)[from].edge.begin();
it != (*this)[from].edge.end(); ++it) {
if(directed || from <= it->to)
std::sprintf(buf, "%d %d %d", from, it->to, it->elabel);
else
std::sprintf(buf, "%d %d %d", it->to, from, it->elabel);
// Assign unique id's for the edges.
if(tmp.find(buf) == tmp.end()) {
it->id = id;
tmp[buf] = id;
++id;
} else {
it->id = tmp[buf];
}
}
}
edge_size_ = id;
}
std::istream &Graph::read(std::istream &is)
{
char line[1024];
std::vector<std::string> result;
clear();
while(true) {
unsigned int pos = is.tellg();
if(!is.getline(line, 1024)) {
break;
}
result.clear();
utils::split(line, result);
if(result.empty()) {
// do nothing
} else if(result[0] == "t") {
if(!empty()) { // use as delimiter
is.seekg(pos, std::ios_base::beg);
break;
} else {
// y = atoi (result[3].c_str());
}
} else if(result[0] == "v" && result.size() >= 3) {
unsigned int id = atoi(result[1].c_str());
this->resize(id + 1);
(*this)[id].label = atoi(result[2].c_str());
} else if(result[0] == "e" && result.size() >= 4) {
int from = atoi(result[1].c_str());
int to = atoi(result[2].c_str());
int elabel = atoi(result[3].c_str());
if((int)size() <= from || (int)size() <= to) {
std::cerr << "Format Error: define vertex lists before edges, from: " << from << "; to: " << to << "; vertex count: " << size() << std::endl;
throw std::runtime_error("Format Error: define vertex lists before edges");
}
(*this)[from].push(from, to, elabel);
if(directed == false)
(*this)[to].push(to, from, elabel);
}
}
buildEdge();
return is;
}
std::istream &Graph::read_fsg(std::istream &is)
{
char line[1024];
std::vector<std::string> result;
clear();
std::map<std::string,int > vertex_labels;
std::map<std::string,int > edge_labels;
int num_vertex_labels = 0, num_edge_labels = 0;
while(true) {
unsigned int pos = is.tellg();
if(!is.getline(line, 1024)) {
break;
}
result.clear();
utils::split(line, result);
if(result.empty()) {
// do nothing
} else if(result[0] == "t") {
if(!empty()) { // use as delimiter
is.seekg(pos, std::ios_base::beg);
break;
} else {
// y = atoi (result[3].c_str());
}
} else if(result[0] == "v" && result.size() >= 3) {
unsigned int id = atoi(result[1].c_str());
this->resize(id + 1);
if(vertex_labels.count(result[2]) == 0 )
vertex_labels[result[2]] = num_vertex_labels++;
(*this)[id].label = vertex_labels[result[2]];
//(*this)[id].label = atoi(result[2].c_str());
} else if(result[0] == "u" && result.size() >= 4) {
int from = atoi(result[1].c_str());
int to = atoi(result[2].c_str());
//int elabel = atoi(result[3].c_str());
if(edge_labels.count(result[3]) == 0 )
edge_labels[result[3]] = num_edge_labels++;
int elabel = edge_labels[result[3]];
if((int)size() <= from || (int)size() <= to) {
std::cerr << "Format Error: define vertex lists before edges, from: " << from << "; to: " << to << "; vertex count: " << size() << std::endl;
throw std::runtime_error("Format Error: define vertex lists before edges");
}
(*this)[from].push(from, to, elabel);
if(directed == false)
(*this)[to].push(to, from, elabel);
}
}
buildEdge();
return is;
}
std::ostream &Graph::write(std::ostream &os)
{
char buf[512];
std::set <std::string> tmp;
for(int from = 0; from < (int)size(); ++from) {
os << "v " << from << " " << (*this)[from].label << std::endl;
for(Vertex::edge_iterator it = (*this)[from].edge.begin();
it != (*this)[from].edge.end(); ++it) {
if(directed || from <= it->to) {
std::sprintf(buf, "%d %d %d", from, it->to, it->elabel);
} else {
std::sprintf(buf, "%d %d %d", it->to, from, it->elabel);
}
tmp.insert(buf);
} // for it
} // for from
for(std::set<std::string>::iterator it = tmp.begin(); it != tmp.end(); ++it) {
os << "e " << *it << std::endl;
} // for it
return os;
}
void Graph::check(void)
{
// Check all indices
for(int from = 0; from < (int)size(); ++from) {
//mexPrintf ("check vertex %d, label %d\n", from, (*this)[from].label);
for(Vertex::edge_iterator it = (*this)[from].edge.begin();
it != (*this)[from].edge.end(); ++it) {
//mexPrintf (" check edge from %d to %d, label %d\n", it->from, it->to, it->elabel);
assert(it->from >= 0 && it->from < size());
assert(it->to >= 0 && it->to < size());
}
}
}
std::string Edge::to_string() const {
std::stringstream ss;
ss << "e(" << from << "," << to << "," << elabel << ")";
return ss.str();
}
std::string PDFS::to_string() const {
std::stringstream ss;
ss << "[" << id << "," << edge->to_string() << "]";
return ss.str();
}
std::string PDFS::to_string_projection(types::graph_database_t &gdb, types::graph_database_cuda &cgdb) const
{
const PDFS *curr = this;
std::string result;
while(curr != 0) {
std::stringstream ss;
types::Graph &grph = gdb[curr->id];
int cuda_grph_from = cgdb.translate_to_device(curr->id, curr->edge->from);
int cuda_grph_to = cgdb.translate_to_device(curr->id, curr->edge->to);
ss << "(" << grph.get_vertex_label(curr->edge->from) << ") " << curr->edge->from << "/" << cuda_grph_from << " = " << curr->edge->elabel << " = " << curr->edge->to << "/" << cuda_grph_to << " (" << grph.get_vertex_label(curr->edge->to) << "); ";
result = ss.str() + result; //curr->to_string();
curr = curr->prev;
}
return result;
}
std::string Projected::to_string() const
{
std::stringstream ss;
for(int i = 0; i < size(); i++) {
ss << (*this)[i].to_string() << "; ";
} // for i
return ss.str();
} // Projected::to_string
void History::build(const Graph &graph, PDFS *e)
{
// first build history
clear();
edge.clear();
edge.resize(graph.edge_size());
vertex.clear();
vertex.resize(graph.size());
if(e) {
push_back(e->edge);
edge[e->edge->id] = vertex[e->edge->from] = vertex[e->edge->to] = 1;
for(PDFS *p = e->prev; p; p = p->prev) {
push_back(p->edge); // this line eats 8% of overall instructions(!)
edge[p->edge->id] = vertex[p->edge->from] = vertex[p->edge->to] = 1;
}
std::reverse(begin(), end());
}
}
std::string History::to_string() const
{
std::stringstream ss;
//ostream_iterator<
for(int i = 0; i < size(); i++) {
ss << at(i)->to_string() << "; ";
}
return ss.str();
}
/* Original comment:
* get_forward_pure ()
* e1 (from1, elabel1, to1)
* from から繋がる edge e2(from2, elabel2, to2) を返す.
*
* minlabel <= elabel2,
* (elabel1 < elabel2 ||
* (elabel == elabel2 && tolabel1 < tolabel2) の条件をみたす.
* (elabel1, to1) のほうが先に探索されるべき
* また, いままで見た vertex には逝かない (backward のやくめ)
*
* RK comment:
* ???? gets the edge that starts and extends the right-most path.
*
*/
bool get_forward_rmpath(const Graph &graph, Edge *e, int minlabel, History& history, types::EdgeList &result)
{
result.clear();
assert(e->to >= 0 && e->to < graph.size());
assert(e->from >= 0 && e->from < graph.size());
int tolabel = graph[e->to].label;
for(Vertex::const_edge_iterator it = graph[e->from].edge.begin();
it != graph[e->from].edge.end(); ++it) {
int tolabel2 = graph[it->to].label;
if(e->to == it->to || minlabel > tolabel2 || history.hasVertex(it->to))
continue;
if(e->elabel < it->elabel || (e->elabel == it->elabel && tolabel <= tolabel2))
result.push_back(const_cast<Edge*>(&(*it)));
}
return (!result.empty());
}
/* Original comment:
* get_forward_pure ()
* e (from, elabel, to)
* to から繋がる edge を返す
* ただし, minlabel より大きいものにしかいかない (DFSの制約)
* また, いままで見た vertex には逝かない (backward のやくめ)
*
* RK comment: this function takes a "pure" forward edge, that is: an
* edge that extends the last node of the right-most path, i.e., the
* right-most node.
*
*/
bool get_forward_pure(const Graph &graph, Edge *e, int minlabel, History& history, types::EdgeList &result)
{
result.clear();
assert(e->to >= 0 && e->to < graph.size());
// Walk all edges leaving from vertex e->to.
for(Vertex::const_edge_iterator it = graph[e->to].edge.begin();
it != graph[e->to].edge.end(); ++it) {
// -e-> [e->to] -it-> [it->to]
assert(it->to >= 0 && it->to < graph.size());
if(minlabel > graph[it->to].label || history.hasVertex(it->to))
continue;
result.push_back(const_cast<Edge*>(&(*it)));
}
return (!result.empty());
}
/*
* Original comment:
* graph の vertex からはえる edge を探す
* ただし, fromlabel <= tolabel の性質を満たす.
*
* RK comment:
*
*/
bool get_forward_root(const Graph &g, const Vertex &v, types::EdgeList &result)
{
result.clear();
for(Vertex::const_edge_iterator it = v.edge.begin(); it != v.edge.end(); ++it) {
assert(it->to >= 0 && it->to < g.size());
if(v.label <= g[it->to].label)
result.push_back(const_cast<Edge*>(&(*it)));
}
return (!result.empty());
}
/* Original comment:
* get_backward (graph, e1, e2, history);
* e1 (from1, elabel1, to1)
* e2 (from2, elabel2, to2)
* to2 -> from1 に繋がるかどうかしらべる.
*
* (elabel1 < elabel2 ||
* (elabel == elabel2 && tolabel1 < tolabel2) の条件をみたす. (elabel1, to1) のほうが先に探索されるべき
*
* RK comment: gets backward edge that starts and ends at the right most path
* e1 is the forward edge and the backward edge goes to e1->from
*/
Edge *get_backward(const Graph &graph, Edge* e1, Edge* e2, History& history)
{
if(e1 == e2)
return 0;
assert(e1->from >= 0 && e1->from < graph.size());
assert(e1->to >= 0 && e1->to < graph.size());
assert(e2->to >= 0 && e2->to < graph.size());
for(Vertex::const_edge_iterator it = graph[e2->to].edge.begin();
it != graph[e2->to].edge.end(); ++it) {
if(history.hasEdge(it->id))
continue;
if((it->to == e1->from) &&
((e1->elabel < it->elabel) ||
(e1->elabel == it->elabel) &&
(graph[e1->to].label <= graph[e2->to].label)
)) {
return const_cast<Edge*>(&(*it));
} // if(...)
} // for(it)
return 0;
}
std::string Graph::to_string() const
{
std::stringstream ss;
for(int i = 0; i < vertex_size(); i++) {
const Vertex &v = at(i);
for(int k = 0; k < v.edge.size(); k++) {
ss << "from: " << v.edge[k].from << "; to: " << v.edge[k].to
<< "; (" << v.label << ", " << v.edge[k].elabel << ", " << get_vertex_label(v.edge[k].to) << ")" << std::endl;
//<< get_vertex_label(v.edge[k].from) << ", " << get_vertex_label(v.edge[k].to)<< std::endl;
} // for k
} // for i
return ss.str();
//DFSCode dfs = get_min_dfs_code();
//return dfs.to_string();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Serialization
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
size_t Vertex::get_serialized_size(const Vertex &vrtx)
{
// vertex label + 4 * #of edges * sizeof(int) + number of edges + label;
return sizeof(int) + 4 * vrtx.edge.size() * sizeof(int) + sizeof(int) + sizeof(int);
}
size_t Vertex::get_serialized_size(char *buffer, size_t buffer_size)
{
int s = *((int*)buffer);
return s;
}
size_t Vertex::serialize(const Vertex &vrtx, char *buffer, size_t buffer_size)
{
if(buffer_size < get_serialized_size(vrtx)) throw std::runtime_error("Buffer too small.");
int pos = 0;
// size of this serialized vertex in bytes.
*((int*)(buffer + pos)) = get_serialized_size(vrtx);
pos += sizeof(int);
// store the vertex label
*((int*)(buffer + pos)) = vrtx.label;
pos += sizeof(int);
// store number of edges
*((int*)(buffer + pos)) = vrtx.edge.size();
pos += sizeof(int);
for(int i = 0; i < vrtx.edge.size(); i++) {
*((int*)(buffer + pos)) = vrtx.edge[i].from;
pos += sizeof(int);
*((int*)(buffer + pos)) = vrtx.edge[i].to;
pos += sizeof(int);
*((int*)(buffer + pos)) = vrtx.edge[i].elabel;
pos += sizeof(int);
*((int*)(buffer + pos)) = vrtx.edge[i].id;
pos += sizeof(int);
} // for i
return pos;
} // Vertex::serialize
size_t Vertex::deserialize(Vertex &vrtx, char *buffer, size_t buffer_size)
{
// TODO: check minimum buffer size
if(buffer_size < get_serialized_size(buffer, buffer_size)) throw std::runtime_error("Buffer too small.");
int pos = 0;
vrtx.edge.clear();
// read buffer s
pos += sizeof(int);
// read the vertex label
vrtx.label = *((int*)(buffer + pos));
pos += sizeof(int);
// read the number of edges
int edge_count = *((int*)(buffer + pos));
pos += sizeof(int);
for(int i = 0; i < edge_count; i++) {
Edge tmp_edge;
tmp_edge.from = *((int*)(buffer + pos));
pos += sizeof(int);
tmp_edge.to = *((int*)(buffer + pos));
pos += sizeof(int);
tmp_edge.elabel = *((int*)(buffer + pos));
pos += sizeof(int);
tmp_edge.id = *((int*)(buffer + pos));
pos += sizeof(int);
vrtx.edge.push_back(tmp_edge);
} // for i
return pos;
} // Vertex::deserialize
size_t Graph::get_serialized_size(const Graph &grph)
{
size_t s = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(bool); // edge_size_ + total buffer size + number of vertices + variable directed(bool)
for(int i = 0; i < grph.size(); i++) {
s += Vertex::get_serialized_size(grph[i]);
} // for i
return s;
} // Graph::get_serialized_size
size_t Graph::get_serialized_size(char *buffer, size_t buffer_size)
{
return *((int*) buffer);
}
size_t Graph::serialize(const Graph &grph, char *buffer, size_t buffer_size)
{
if(get_serialized_size(grph) > buffer_size) throw std::runtime_error("Buffer too small.");
int pos = 0;
// store buffer size
*((int*)(buffer + pos)) = get_serialized_size(grph);
pos += sizeof(int);
// store edge_size_
*((int*)(buffer + pos)) = grph.edge_size_;
pos += sizeof(int);
// store number of vertices
*((bool*)(buffer + pos)) = grph.directed;
pos += sizeof(grph.directed);
// store number of vertices
*((int*)(buffer + pos)) = grph.size();
pos += sizeof(int);
for(int i = 0; i < grph.size(); i++) {
int tmp_pos = Vertex::serialize(grph.at(i), buffer + pos, buffer_size - pos);
pos += tmp_pos;
} // for i
return pos;
} // Graph::serialize
size_t Graph::deserialize(Graph &grph, char *buffer, size_t buffer_size)
{
if(Graph::get_serialized_size(buffer, buffer_size) > buffer_size) throw std::runtime_error("Buffer too small.");
grph.clear();
int pos = 0;
// store buffer size
pos += sizeof(int);
// store edge_size_
grph.edge_size_ = *((int*)(buffer + pos));
pos += sizeof(int);
// store number of vertices
grph.directed = *((bool*)(buffer + pos));
pos += sizeof(grph.directed);
// store number of vertices
int vert_count = *((int*)(buffer + pos));
pos += sizeof(int);
for(int i = 0; i < vert_count; i++) {
Vertex tmp_vert;
int tmp_pos = Vertex::deserialize(tmp_vert, buffer + pos, buffer_size - pos);
grph.push_back(tmp_vert);
pos += tmp_pos;
} // for i
return pos;
} // Graph::deserialize
size_t Graph::get_serialized_size(const graph_database_t &grph_db)
{
size_t min_buff_size = 0;
min_buff_size += sizeof(int) + sizeof(int); // size of the database + size of the buffer
for(size_t i = 0; i < grph_db.size(); i++) {
min_buff_size += get_serialized_size(grph_db[i]);
} // for i
return min_buff_size;
} // Graph::get_serialized_size
size_t Graph::get_serialized_size_db(char *buffer, size_t buffer_size)
{
//abort();
return *((int*) buffer);
} // Graph::get_serialized_size
size_t Graph::serialize(const graph_database_t &grph_db, char *buffer, size_t buffer_size)
{
size_t pos = 0;
int min_buff_size = get_serialized_size(grph_db);
if(min_buff_size > buffer_size) throw std::runtime_error("Buffer too small.");
*((int*)(buffer + pos)) = min_buff_size;
pos += sizeof(int);
*((int*)(buffer + pos)) = grph_db.size();
pos += sizeof(int);
for(int i = 0; i < grph_db.size(); i++) {
size_t tmp_pos = serialize(grph_db[i], buffer + pos, buffer_size - pos);
pos += tmp_pos;
}
return pos;
} // Graph::serialize
size_t Graph::deserialize(graph_database_t &grph_db, char *buffer, size_t buffer_size)
{
int min_buf_size = get_serialized_size_db(buffer, buffer_size);
if(buffer_size < min_buf_size) throw std::runtime_error("Buffer too small.");
grph_db.clear();
size_t pos = 0;
// skip buffer size
pos += sizeof(int);
int grph_db_size = *((int*)(buffer + pos));
pos += sizeof(int);
for(int i = 0; i < grph_db_size; i++) {
Graph grph;
size_t tmp_pos = deserialize(grph, buffer + pos, buffer_size - pos);
pos += tmp_pos;
grph_db.push_back(grph);
} // for i
return pos;
} // Graph::deserialize
} // namespace types
| 25.926407
| 251
| 0.577336
|
zakimjz
|
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
|
c2053ff6133d4df21d6d024cadbd635fabd32763
| 85,297
|
cpp
|
C++
|
vm/compiler/Loop.cpp
|
HazouPH/android_dalvik
|
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
|
[
"Apache-2.0"
] | null | null | null |
vm/compiler/Loop.cpp
|
HazouPH/android_dalvik
|
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
|
[
"Apache-2.0"
] | null | null | null |
vm/compiler/Loop.cpp
|
HazouPH/android_dalvik
|
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Dalvik.h"
#include "CompilerInternals.h"
#include "Dataflow.h"
#include "Loop.h"
#include "Utility.h"
#ifdef ARCH_IA32
#include "PassDriver.h"
#endif
#ifdef DEBUG_LOOP_ON
#define DEBUG_LOOP(X) X
#else
#define DEBUG_LOOP(X)
#endif
#ifndef ARCH_IA32
/**
* Find the predecessor block of a given BasicBlock: the single predecessor whichever if only one predecessor,
* the entry block if there are two predecessors and the entry block is a predecessor, 0 otherwise
*/
static BasicBlock *findPredecessorBlock(const CompilationUnit *cUnit,
const BasicBlock *bb)
{
int numPred = dvmCountSetBits(bb->predecessors);
BitVectorIterator bvIterator;
dvmBitVectorIteratorInit(bb->predecessors, &bvIterator);
if (numPred == 1) {
int predIdx = dvmBitVectorIteratorNext(&bvIterator);
return (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList,
predIdx);
/* First loop block */
} else if ((numPred == 2) &&
dvmIsBitSet(bb->predecessors, cUnit->entryBlock->id)) {
while (true) {
int predIdx = dvmBitVectorIteratorNext(&bvIterator);
if (predIdx == cUnit->entryBlock->id) continue;
return (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList,
predIdx);
}
/* Doesn't support other shape of control flow yet */
} else {
return NULL;
}
}
/* Used for normalized loop exit condition checks */
static Opcode negateOpcode(Opcode opcode)
{
switch (opcode) {
/* reg/reg cmp */
case OP_IF_EQ:
return OP_IF_NE;
case OP_IF_NE:
return OP_IF_EQ;
case OP_IF_LT:
return OP_IF_GE;
case OP_IF_GE:
return OP_IF_LT;
case OP_IF_GT:
return OP_IF_LE;
case OP_IF_LE:
return OP_IF_GT;
/* reg/zero cmp */
case OP_IF_EQZ:
return OP_IF_NEZ;
case OP_IF_NEZ:
return OP_IF_EQZ;
case OP_IF_LTZ:
return OP_IF_GEZ;
case OP_IF_GEZ:
return OP_IF_LTZ;
case OP_IF_GTZ:
return OP_IF_LEZ;
case OP_IF_LEZ:
return OP_IF_GTZ;
default:
ALOGE("opcode %d cannot be negated", opcode);
dvmAbort();
break;
}
return (Opcode)-1; // unreached
}
/*
* A loop is considered optimizable if:
* 1) It has one basic induction variable.
* 2) The loop back branch compares the BIV with a constant.
* 3) We need to normalize the loop exit condition so that the loop is exited
* via the taken path.
* 4) If it is a count-up loop, the condition is GE/GT. Otherwise it is
* LE/LT/LEZ/LTZ for a count-down loop.
*
* Return false for loops that fail the above tests.
*/
static bool isSimpleCountedLoop(CompilationUnit *cUnit)
{
unsigned int i;
BasicBlock *loopBackBlock = cUnit->entryBlock->fallThrough;
LoopAnalysis *loopAnalysis = cUnit->loopAnalysis;
if (loopAnalysis->numBasicIV != 1) return false;
for (i = 0; i < loopAnalysis->ivList->numUsed; i++) {
InductionVariableInfo *ivInfo;
ivInfo = GET_ELEM_N(loopAnalysis->ivList, InductionVariableInfo*, i);
/* Count up or down loop? */
if (ivInfo->ssaReg == ivInfo->basicSSAReg) {
/* Infinite loop */
if (ivInfo->loopIncrement == 0) {
return false;
}
loopAnalysis->isCountUpLoop = ivInfo->loopIncrement > 0;
break;
}
}
/* Find the block that ends with a branch to exit the loop */
while (true) {
loopBackBlock = findPredecessorBlock(cUnit, loopBackBlock);
/* Loop structure not recognized as counted blocks */
if (loopBackBlock == NULL) {
return false;
}
/* Unconditional goto - continue to trace up the predecessor chain */
if (loopBackBlock->taken == NULL) {
continue;
}
break;
}
MIR *branch = loopBackBlock->lastMIRInsn;
Opcode opcode = branch->dalvikInsn.opcode;
// Remember the offset of the branch MIR in order to use it
// when generating the extended MIRs
loopAnalysis->loopBranchMIROffset = branch->offset;
/* Last instruction is not a conditional branch - bail */
if (dexGetFlagsFromOpcode(opcode) != (kInstrCanContinue|kInstrCanBranch)) {
return false;
}
int endSSAReg;
int endDalvikReg;
/* reg/reg comparison */
if (branch->ssaRep->numUses == 2) {
if (branch->ssaRep->uses[0] == loopAnalysis->ssaBIV) {
endSSAReg = branch->ssaRep->uses[1];
} else if (branch->ssaRep->uses[1] == loopAnalysis->ssaBIV) {
endSSAReg = branch->ssaRep->uses[0];
opcode = negateOpcode(opcode);
} else {
return false;
}
endDalvikReg = dvmConvertSSARegToDalvik(cUnit, endSSAReg);
/*
* If the comparison is not between the BIV and a loop invariant,
* return false. endDalvikReg is loop invariant if one of the
* following is true:
* - It is not defined in the loop (ie DECODE_SUB returns 0)
* - It is reloaded with a constant
*/
if ((DECODE_SUB(endDalvikReg) != 0) &&
!dvmIsBitSet(cUnit->isConstantV, endSSAReg)) {
return false;
}
/* Compare against zero */
} else if (branch->ssaRep->numUses == 1) {
if (branch->ssaRep->uses[0] == loopAnalysis->ssaBIV) {
/* Keep the compiler happy */
endDalvikReg = -1;
} else {
return false;
}
} else {
return false;
}
/* Normalize the loop exit check as "if (iv op end) exit;" */
if (loopBackBlock->taken->blockType == kDalvikByteCode) {
opcode = negateOpcode(opcode);
}
if (loopAnalysis->isCountUpLoop) {
/*
* If the normalized condition op is not > or >=, this is not an
* optimization candidate.
*/
switch (opcode) {
case OP_IF_GT:
case OP_IF_GE:
break;
default:
return false;
}
loopAnalysis->endConditionReg = DECODE_REG(endDalvikReg);
} else {
/*
* If the normalized condition op is not < or <=, this is not an
* optimization candidate.
*/
switch (opcode) {
case OP_IF_LT:
case OP_IF_LE:
loopAnalysis->endConditionReg = DECODE_REG(endDalvikReg);
break;
case OP_IF_LTZ:
case OP_IF_LEZ:
break;
default:
return false;
}
}
/*
* Remember the normalized opcode, which will be used to determine the end
* value used for the yanked range checks.
*/
loopAnalysis->loopBranchOpcode = opcode;
return true;
}
/*
* Record the upper and lower bound information for range checks for each
* induction variable. If array A is accessed by index "i+5", the upper and
* lower bound will be len(A)-5 and -5, respectively.
*/
static void updateRangeCheckInfo(CompilationUnit *cUnit, int arrayReg,
int idxReg)
{
InductionVariableInfo *ivInfo;
LoopAnalysis *loopAnalysis = cUnit->loopAnalysis;
unsigned int i, j;
for (i = 0; i < loopAnalysis->ivList->numUsed; i++) {
ivInfo = GET_ELEM_N(loopAnalysis->ivList, InductionVariableInfo*, i);
if (ivInfo->ssaReg == idxReg) {
ArrayAccessInfo *arrayAccessInfo = NULL;
for (j = 0; j < loopAnalysis->arrayAccessInfo->numUsed; j++) {
ArrayAccessInfo *existingArrayAccessInfo =
GET_ELEM_N(loopAnalysis->arrayAccessInfo,
ArrayAccessInfo*,
j);
if (existingArrayAccessInfo->arrayReg == arrayReg) {
if (ivInfo->constant > existingArrayAccessInfo->maxC) {
existingArrayAccessInfo->maxC = ivInfo->constant;
}
if (ivInfo->constant < existingArrayAccessInfo->minC) {
existingArrayAccessInfo->minC = ivInfo->constant;
}
arrayAccessInfo = existingArrayAccessInfo;
break;
}
}
if (arrayAccessInfo == NULL) {
arrayAccessInfo =
(ArrayAccessInfo *)dvmCompilerNew(sizeof(ArrayAccessInfo),
false);
arrayAccessInfo->ivReg = ivInfo->basicSSAReg;
arrayAccessInfo->arrayReg = arrayReg;
arrayAccessInfo->maxC = (ivInfo->constant > 0) ? ivInfo->constant : 0;
arrayAccessInfo->minC = (ivInfo->constant < 0) ? ivInfo->constant : 0;
arrayAccessInfo->loopIncrement = ivInfo->loopIncrement;
dvmInsertGrowableList(loopAnalysis->arrayAccessInfo,
(intptr_t) arrayAccessInfo);
}
break;
}
}
}
/* Returns true if the loop body cannot throw any exceptions */
static bool doLoopBodyCodeMotion(CompilationUnit *cUnit)
{
BasicBlock *loopBody = cUnit->entryBlock->fallThrough;
MIR *mir;
bool loopBodyCanThrow = false;
for (mir = loopBody->firstMIRInsn; mir; mir = mir->next) {
DecodedInstruction *dInsn = &mir->dalvikInsn;
int dfAttributes =
dvmCompilerDataFlowAttributes[mir->dalvikInsn.opcode];
/* Skip extended MIR instructions */
if ((u2) dInsn->opcode >= kNumPackedOpcodes) continue;
int instrFlags = dexGetFlagsFromOpcode(dInsn->opcode);
/* Instruction is clean */
if ((instrFlags & kInstrCanThrow) == 0) continue;
/*
* Currently we can only optimize away null and range checks. Punt on
* instructions that can throw due to other exceptions.
*/
if (!(dfAttributes & DF_HAS_NR_CHECKS)) {
loopBodyCanThrow = true;
continue;
}
/*
* This comparison is redundant now, but we will have more than one
* group of flags to check soon.
*/
if (dfAttributes & DF_HAS_NR_CHECKS) {
/*
* Check if the null check is applied on a loop invariant register?
* If the register's SSA id is less than the number of Dalvik
* registers, then it is loop invariant.
*/
int refIdx;
switch (dfAttributes & DF_HAS_NR_CHECKS) {
case DF_NULL_N_RANGE_CHECK_0:
refIdx = 0;
break;
case DF_NULL_N_RANGE_CHECK_1:
refIdx = 1;
break;
case DF_NULL_N_RANGE_CHECK_2:
refIdx = 2;
break;
default:
refIdx = 0;
ALOGE("Jit: bad case in doLoopBodyCodeMotion");
dvmCompilerAbort(cUnit);
}
int useIdx = refIdx + 1;
int subNRegArray =
dvmConvertSSARegToDalvik(cUnit, mir->ssaRep->uses[refIdx]);
int arraySub = DECODE_SUB(subNRegArray);
/*
* If the register is never updated in the loop (ie subscript == 0),
* it is an optimization candidate.
*/
if (arraySub != 0) {
loopBodyCanThrow = true;
continue;
}
/*
* Then check if the range check can be hoisted out of the loop if
* it is basic or dependent induction variable.
*/
if (dvmIsBitSet(cUnit->loopAnalysis->isIndVarV,
mir->ssaRep->uses[useIdx])) {
mir->OptimizationFlags |=
MIR_IGNORE_RANGE_CHECK | MIR_IGNORE_NULL_CHECK;
updateRangeCheckInfo(cUnit, mir->ssaRep->uses[refIdx],
mir->ssaRep->uses[useIdx]);
}
}
}
return !loopBodyCanThrow;
}
static void genHoistedChecks(CompilationUnit *cUnit)
{
unsigned int i;
BasicBlock *entry = cUnit->entryBlock;
LoopAnalysis *loopAnalysis = cUnit->loopAnalysis;
int globalMaxC = 0;
int globalMinC = 0;
/* Should be loop invariant */
int idxReg = 0;
for (i = 0; i < loopAnalysis->arrayAccessInfo->numUsed; i++) {
ArrayAccessInfo *arrayAccessInfo =
GET_ELEM_N(loopAnalysis->arrayAccessInfo,
ArrayAccessInfo*, i);
int arrayReg = DECODE_REG(
dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->arrayReg));
idxReg = DECODE_REG(
dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->ivReg));
MIR *rangeCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true);
rangeCheckMIR->dalvikInsn.opcode = (loopAnalysis->isCountUpLoop) ?
(Opcode)kMirOpNullNRangeUpCheck : (Opcode)kMirOpNullNRangeDownCheck;
rangeCheckMIR->dalvikInsn.vA = arrayReg;
rangeCheckMIR->dalvikInsn.vB = idxReg;
rangeCheckMIR->dalvikInsn.vC = loopAnalysis->endConditionReg;
rangeCheckMIR->dalvikInsn.arg[0] = arrayAccessInfo->maxC;
rangeCheckMIR->dalvikInsn.arg[1] = arrayAccessInfo->minC;
rangeCheckMIR->dalvikInsn.arg[2] = loopAnalysis->loopBranchOpcode;
rangeCheckMIR->dalvikInsn.arg[3] = arrayAccessInfo->loopIncrement;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
rangeCheckMIR->offset = entry->startOffset;
dvmCompilerAppendMIR(entry, rangeCheckMIR);
if (arrayAccessInfo->maxC > globalMaxC) {
globalMaxC = arrayAccessInfo->maxC;
}
if (arrayAccessInfo->minC < globalMinC) {
globalMinC = arrayAccessInfo->minC;
}
}
if (loopAnalysis->arrayAccessInfo->numUsed != 0) {
if (loopAnalysis->isCountUpLoop) {
MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true);
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound;
boundCheckMIR->dalvikInsn.vA = idxReg;
boundCheckMIR->dalvikInsn.vB = globalMinC;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = entry->startOffset;
dvmCompilerAppendMIR(entry, boundCheckMIR);
} else {
if (loopAnalysis->loopBranchOpcode == OP_IF_LT ||
loopAnalysis->loopBranchOpcode == OP_IF_LE) {
MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR), true);
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound;
boundCheckMIR->dalvikInsn.vA = loopAnalysis->endConditionReg;
boundCheckMIR->dalvikInsn.vB = globalMinC;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = entry->startOffset;
/*
* If the end condition is ">" in the source, the check in the
* Dalvik bytecode is OP_IF_LE. In this case add 1 back to the
* constant field to reflect the fact that the smallest index
* value is "endValue + constant + 1".
*/
if (loopAnalysis->loopBranchOpcode == OP_IF_LE) {
boundCheckMIR->dalvikInsn.vB++;
}
dvmCompilerAppendMIR(entry, boundCheckMIR);
} else if (loopAnalysis->loopBranchOpcode == OP_IF_LTZ) {
/* Array index will fall below 0 */
if (globalMinC < 0) {
MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR),
true);
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = entry->startOffset;
dvmCompilerAppendMIR(entry, boundCheckMIR);
}
} else if (loopAnalysis->loopBranchOpcode == OP_IF_LEZ) {
/* Array index will fall below 0 */
if (globalMinC < -1) {
MIR *boundCheckMIR = (MIR *)dvmCompilerNew(sizeof(MIR),
true);
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = entry->startOffset;
dvmCompilerAppendMIR(entry, boundCheckMIR);
}
} else {
ALOGE("Jit: bad case in genHoistedChecks");
dvmCompilerAbort(cUnit);
}
}
}
}
#else //IA32
/**
* @brief Used to flip the condition of an "if" bytecode
* @param opcode Dalvik opcode to negate
* @param negatedOpcode Updated by function to contain negated
* opcode. Only valid if function returns true.
* @return Returns true if successfully negated.
*/
static bool negateOpcode(Opcode opcode, Opcode & negatedOpcode)
{
//Eagerly assume we will succeed
bool success = true;
switch (opcode) {
/* reg/reg cmp */
case OP_IF_EQ:
negatedOpcode = OP_IF_NE;
break;
case OP_IF_NE:
negatedOpcode = OP_IF_EQ;
break;
case OP_IF_LT:
negatedOpcode = OP_IF_GE;
break;
case OP_IF_GE:
negatedOpcode = OP_IF_LT;
break;
case OP_IF_GT:
negatedOpcode = OP_IF_LE;
break;
case OP_IF_LE:
negatedOpcode = OP_IF_GT;
break;
/* reg/zero cmp */
case OP_IF_EQZ:
negatedOpcode = OP_IF_NEZ;
break;
case OP_IF_NEZ:
negatedOpcode = OP_IF_EQZ;
break;
case OP_IF_LTZ:
negatedOpcode = OP_IF_GEZ;
break;
case OP_IF_GEZ:
negatedOpcode = OP_IF_LTZ;
break;
case OP_IF_GTZ:
negatedOpcode = OP_IF_LEZ;
break;
case OP_IF_LEZ:
negatedOpcode = OP_IF_GTZ;
break;
default:
success = false;
break;
}
return success;
}
/*
* A loop is considered optimizable if:
* 1) It has one basic induction variable.
* 2) The loop back branch compares the BIV with a constant.
* 3) We need to normalize the loop exit condition so that the loop is exited
* via the taken path.
* 4) If it is a count-up loop, the condition is GE/GT. Otherwise it is
* LE/LT/LEZ/LTZ for a count-down loop.
*/
/**
* @brief Checks if the loops is suitable for hoisting range/null checks
* @param cUnit the CompilationUnit
* @param pass the Pass
* @return false for loops that fail the above tests.
*/
//TODO: this should take a LoopInformation to be tested for inner loops
static bool isSimpleCountedLoop(CompilationUnit *cUnit)
{
unsigned int i;
BasicBlock *loopBackBlock = NULL;
LoopInformation *loopInfo = cUnit->loopInformation;
GrowableList* ivList = &cUnit->loopInformation->getInductionVariableList ();
/* This either counted up or down loop, 2 BIVs could bring complication
to detect that. Potentially we can enhance the algorithm to utilize > 1
BIV in case inc for all BIVs > 0 ( or < 0)
*/
if (loopInfo->getNumBasicIV(cUnit) != 1) {
return false;
}
for (i = 0; i < ivList->numUsed; i++) {
InductionVariableInfo *ivInfo;
ivInfo = GET_ELEM_N(ivList, InductionVariableInfo*, i);
/* Count up or down loop? */
if (ivInfo->isBasicIV () == true) {
/* Infinite loop */
if (ivInfo->loopIncrement == 0) {
return false;
}
loopInfo->setCountUpLoop(ivInfo->loopIncrement > 0);
break;
}
}
// Get Back branch bb, need to find loop exit condition
// the main hypotethis is that Back branch bb is a
// predecessor of a loop exit bb.
BasicBlock *bb = NULL;
BitVectorIterator bvIterator;
BitVector *exitbbs = const_cast<BitVector *> (loopInfo->getExitLoops());
int nexitbbs = dvmCountSetBits(exitbbs);
// We limit the optimization to cases where just 1 exit bb
// due to unpredictable behaviour in other cases
if (nexitbbs != 1) {
return false;
}
/* Get loopBack branch bb */
// 1. Get exit bb
dvmBitVectorIteratorInit (exitbbs, &bvIterator);
int bIdx = dvmBitVectorIteratorNext (&bvIterator);
assert (bIdx != -1);
bb = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, bIdx);
if (bb == NULL) {
return false;
}
// 2. Get loop exit bb predecessor
dvmBitVectorIteratorInit(bb->predecessors, &bvIterator);
bIdx = dvmBitVectorIteratorNext(&bvIterator);
assert (bIdx != -1);
// 3. Finally get loopBack branch bb
loopBackBlock = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, bIdx));
// paranoid, didn't find loopBack bb
if (loopBackBlock == NULL) {
return false;
}
// Find exit block which contains loop exit condition
MIR *branch = loopBackBlock->lastMIRInsn;
if (branch == NULL) {
return false;
}
Opcode op = branch->dalvikInsn.opcode;
Opcode opcode = op;
// Paranoid: Check this is not extendent MIR because
// dexGetFlagsFromOpcode call is not safe then
if (opcode >= kNumPackedOpcodes) {
return false;
}
/* Last instruction is not a conditional branch - bail */
if (dexGetFlagsFromOpcode(opcode) != (kInstrCanContinue|kInstrCanBranch)) {
return false;
}
int endSSAReg;
int endDalvikReg;
/* Detect end condition register
As soon as we found loop back branch we can
get the condition and a loop limit from it
*/
if (branch->ssaRep->numUses == 2)
{
if (branch->ssaRep->uses[0] == loopInfo->getSSABIV()) {
endSSAReg = branch->ssaRep->uses[1];
} else if (branch->ssaRep->uses[1] == loopInfo->getSSABIV()) {
endSSAReg = branch->ssaRep->uses[0];
negateOpcode(op, opcode);
} else {
return false;
}
endDalvikReg = dvmConvertSSARegToDalvik(cUnit, endSSAReg);
/*
* If the comparison is not between the BIV and a loop invariant,
* return false. endDalvikReg is loop invariant if one of the
* following is true:
* - It is not defined in the loop (ie DECODE_SUB returns 0)
* - It is reloaded with a constant
*/
if ((DECODE_SUB(endDalvikReg) != 0) &&
dvmCompilerIsRegConstant (cUnit, endSSAReg) == false) {
return false;
}
} else {
return false;
}
if (loopInfo->isCountUpLoop() == true) {
/*
* If the normalized condition op is not > or >=, this is not an
* optimization candidate.
*/
switch (opcode) {
case OP_IF_GT:
case OP_IF_GE:
break;
default:
return false;
}
loopInfo->setEndConditionReg(DECODE_REG(endDalvikReg));
} else {
/*
* If the normalized condition op is not < or <=, this is not an
* optimization candidate.
*/
switch (opcode) {
case OP_IF_LT:
case OP_IF_LE:
loopInfo->setEndConditionReg(DECODE_REG(endDalvikReg));
break;
case OP_IF_LTZ:
case OP_IF_LEZ:
break;
default:
return false;
}
}
/*
* Remember the normalized opcode, which will be used to determine the end
* value used for the yanked range checks.
*/
loopInfo->setLoopBranchOpcode(opcode);
return true;
}
/**
* @brief Record the upper and lower bound information for range checks for each IV
* @param cUnit the CompilationUnit
* @param arrayReg the array register
* @param idxReg the array index register
*/
// If array A is accessed by index "i+5", the upper and
// lower bound will be len(A)-5 and -5, respectively.
static void updateRangeCheckInfo(CompilationUnit *cUnit, int arrayReg,
int idxReg)
{
InductionVariableInfo *ivInfo;
//Get the IV list
GrowableList* ivList = &cUnit->loopInformation->getInductionVariableList ();
LoopInformation *loopInfo = cUnit->loopInformation;
assert (loopInfo != NULL);
unsigned int i, j;
// when the tested idxReg is found to be an IV this is an array access point.
// As soon as such point is found we create array access info or update existing one.
// The update means identification of maxC and minC which are the min/max of the same index.
// E.g. A[i], A[i+1], ..., A[i+N] will result in maxC = N. It will be used to aggregate
// several range checks into a single hoisted one.
for (i = 0; i < ivList->numUsed; i++) {
ivInfo = GET_ELEM_N(ivList, InductionVariableInfo*, i);
if (ivInfo->ssaReg == idxReg) {
ArrayAccessInfo *arrayAccessInfo = NULL;
for (j = 0; j < loopInfo->getArrayAccessInfo()->numUsed; j++) {
ArrayAccessInfo *existingArrayAccessInfo =
GET_ELEM_N(loopInfo->getArrayAccessInfo(),
ArrayAccessInfo*,
j);
if (existingArrayAccessInfo->arrayReg == arrayReg) {
if (ivInfo->constant > existingArrayAccessInfo->maxC) {
existingArrayAccessInfo->maxC = ivInfo->constant;
}
if (ivInfo->constant < existingArrayAccessInfo->minC) {
existingArrayAccessInfo->minC = ivInfo->constant;
}
arrayAccessInfo = existingArrayAccessInfo;
break;
}
}
if (arrayAccessInfo == NULL) {
arrayAccessInfo =
(ArrayAccessInfo *)dvmCompilerNew(sizeof(ArrayAccessInfo),
false);
arrayAccessInfo->ivReg = ivInfo->basicSSAReg;
arrayAccessInfo->arrayReg = arrayReg;
arrayAccessInfo->maxC = (ivInfo->constant > 0) ? ivInfo->constant : 0;
arrayAccessInfo->minC = (ivInfo->constant < 0) ? ivInfo->constant : 0;
arrayAccessInfo->inc = ivInfo->loopIncrement;
dvmInsertGrowableList(cUnit->loopInformation->getArrayAccessInfo(),
(intptr_t) arrayAccessInfo);
}
break;
}
}
}
void dvmCompilerBodyCodeMotion (CompilationUnit *cUnit, Pass *currentPass)
{
//Get the BasicBlock vector for this loop
BitVector *blocks = const_cast<BitVector *> (cUnit->loopInformation->getBasicBlocks ());
MIR *mir;
//Iterate through basic blocks
BitVectorIterator bvIterator;
dvmBitVectorIteratorInit (blocks, &bvIterator);
while (true)
{
//Get block index
int blockIdx = dvmBitVectorIteratorNext (&bvIterator);
//If done, bail
if (blockIdx == -1)
{
break;
}
BasicBlock *loopBody = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx));
//Paranoid
if (loopBody == 0)
{
break;
}
for (mir = loopBody->firstMIRInsn; mir; mir = mir->next) {
DecodedInstruction *dInsn = &mir->dalvikInsn;
long long dfAttributes =
dvmCompilerDataFlowAttributes[mir->dalvikInsn.opcode];
/* Skip extended MIR instructions */
if (dInsn->opcode >= kNumPackedOpcodes) {
continue;
}
int instrFlags = dexGetFlagsFromOpcode(dInsn->opcode);
/* Instruction is clean */
if ((instrFlags & kInstrCanThrow) == 0) {
continue;
}
/*
* Currently we can only optimize away null and range checks.
*/
if ((dfAttributes & DF_HAS_NR_CHECKS) == 0) {
continue;
}
/*
* This comparison is redundant now, but we will have more than one
* group of flags to check soon.
*/
if (dfAttributes & DF_HAS_NR_CHECKS) {
/*
* Check if the null check is applied on a loop invariant register?
* If the register's SSA id is less than the number of Dalvik
* registers, then it is loop invariant.
*/
int refIdx;
switch (dfAttributes & DF_HAS_NR_CHECKS) {
case DF_NULL_N_RANGE_CHECK_0:
refIdx = 0;
break;
case DF_NULL_N_RANGE_CHECK_1:
refIdx = 1;
break;
case DF_NULL_N_RANGE_CHECK_2:
refIdx = 2;
break;
default:
refIdx = 0;
ALOGE("Jit: bad case in dvmCompilerBodyCodeMotion");
// bail - should not reach here
dvmCompilerAbort(cUnit);
return;
}
int useIdx = refIdx + 1;
int subNRegArray =
dvmConvertSSARegToDalvik(cUnit, mir->ssaRep->uses[refIdx]);
int arraySub = DECODE_SUB(subNRegArray);
/*
* If the register is never updated in the loop (ie subscript == 0),
* it is an optimization candidate.
*/
if (arraySub != 0) {
continue;
}
/*
* Then check if the range check can be hoisted out of the loop if
* it is basic or dependent induction variable.
*/
if (cUnit->loopInformation->isAnInductionVariable(cUnit, mir->ssaRep->uses[useIdx], true)) {
mir->OptimizationFlags |=
MIR_IGNORE_RANGE_CHECK | MIR_IGNORE_NULL_CHECK;
updateRangeCheckInfo(cUnit, mir->ssaRep->uses[refIdx],
mir->ssaRep->uses[useIdx]);
}
}
}
}
//Unused argument
(void) currentPass;
}
bool dvmCompilerHoistedChecksGate(const CompilationUnit* cUnit, Pass* pass)
{
if (cUnit->loopInformation != NULL && isSimpleCountedLoop((CompilationUnit*)cUnit)) {
return true;
}
//Unused argument
(void) pass;
return false;
}
/**
* @brief Dump hoisted checks debugging info
* @param cUnit is the CompilationUnit
*/
static void dvmDumpHoistedRangeCheckInfo(CompilationUnit* cUnit)
{
LoopInformation* loopInfo = cUnit->loopInformation;
InductionVariableInfo *ivInfo;
//Get the IV list
GrowableList* ivList = &loopInfo->getInductionVariableList ();
unsigned int i;
/* dump IV info */
ALOGD("BASIC_IV_NUMBER_INFO: number of basic IV: %d", loopInfo->getNumBasicIV(cUnit));
for (i = 0; i < ivList->numUsed; i++)
{
ivInfo = GET_ELEM_N(ivList, InductionVariableInfo*, i);
if (ivInfo->isBasicIV () == true)
{
/* Basic IV */
ALOGD("BASIC_IV_INFO: ssaReg: %d, basicSSAReg: %d, inc: %d, VR: %d_%dn", ivInfo->ssaReg, ivInfo->basicSSAReg, ivInfo->loopIncrement,
dvmExtractSSARegister (cUnit, ivInfo->ssaReg), dvmExtractSSASubscript (cUnit, ivInfo->ssaReg));
}
else
{
/* Dependent IV */
ALOGD("DEPENDENT_IV_INFO: ssaReg: %d, depSSAReg: %d, inc: %d, VR: %d_%d c=%d\n", ivInfo->ssaReg, ivInfo->basicSSAReg, ivInfo->loopIncrement,
dvmExtractSSARegister (cUnit, ivInfo->ssaReg), dvmExtractSSASubscript (cUnit, ivInfo->ssaReg), ivInfo->constant);
}
}
/* dump array access info */
for (i = 0; i < loopInfo->getArrayAccessInfo()->numUsed; i++) {
ArrayAccessInfo *arrayAccessInfo =
GET_ELEM_N(loopInfo->getArrayAccessInfo(),
ArrayAccessInfo*, i);
ALOGE("JIT_INFO: arrayReg: %d, idxReg: %d, endConditionReg: %d, maxC: %d, minC: %d, inc: %d",
arrayAccessInfo->arrayReg, arrayAccessInfo->ivReg, loopInfo->getEndConditionReg(),
arrayAccessInfo->maxC, arrayAccessInfo->minC, arrayAccessInfo->inc);
}
}
#endif
#ifdef ARCH_IA32
// The main purpose of the function is to transform internal array access info into
// hoisted checks extended MIRs at start of a loop which will be transformed to
// assembly using special algorithm and data from hoisted checks MIR's
// Terms: e.g. for (int i=0; i<=100; i+=2) {A[i]...}
// A - array, i - index, end condition reg - 100 (reg), inc - 2(i+=2)
// For loop body like {A[i-1] ... a[i+N]} maxC = N, minC = -1
// loopbranch opcode - >/>=/</<=, counted up/down cycle - ?inc >0 or <0
void dvmCompilerGenHoistedChecks(CompilationUnit *cUnit, Pass* pass)
{
unsigned int i;
if (cUnit->loopInformation == NULL) {
return;
}
BasicBlock *entry = cUnit->entryBlock;
LoopInformation* loopInfo = cUnit->loopInformation;
int globalMaxC = 0;
int globalMinC = 0;
/* Should be loop invariant */
int idxReg = 0;
//TODO The offset in entry->offset may not be correct to use. The offset for exception
//must use the offset of the first instruction in block before heavy optimizations are
//applied like invariant hoisting. The same applies for the parent method for these
//extended MIRs. They technically have no source method but the one matching the first
//instruction in loop should be assigned. This ensures that correct exit PC is set
//in case these checks lead to exception.
const unsigned int offsetForException = entry->startOffset;
NestedMethod nesting (cUnit->method);
// Go through array access elements and generate range checks
// Range check in the current implemntation is the upper border of the loop
// E.g. for count down loops it is lowest index
// Lower border check of a loop is done using Bound checks below
for (i = 0; i < loopInfo->getArrayAccessInfo()->numUsed; i++) {
ArrayAccessInfo *arrayAccessInfo =
GET_ELEM_N(loopInfo->getArrayAccessInfo(),
ArrayAccessInfo*, i);
// get reg containing array ref
int arrayReg = DECODE_REG(
dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->arrayReg));
// get reg containing index
idxReg = DECODE_REG(
dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->ivReg));
// create new mir using the array access info
// see genHoistedChecks* to check with the hoisted check algorithm
MIR *rangeCheckMIR = dvmCompilerNewMIR ();
rangeCheckMIR->dalvikInsn.opcode = (loopInfo->isCountUpLoop()) ?
(Opcode)kMirOpNullNRangeUpCheck : (Opcode)kMirOpNullNRangeDownCheck;
rangeCheckMIR->dalvikInsn.vA = arrayReg;
rangeCheckMIR->dalvikInsn.vB = idxReg;
rangeCheckMIR->dalvikInsn.vC = loopInfo->getEndConditionReg();
rangeCheckMIR->dalvikInsn.arg[0] = arrayAccessInfo->maxC;
rangeCheckMIR->dalvikInsn.arg[1] = arrayAccessInfo->minC;
rangeCheckMIR->dalvikInsn.arg[2] = loopInfo->getLoopBranchOpcode();
rangeCheckMIR->dalvikInsn.arg[3] = arrayAccessInfo->inc;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
rangeCheckMIR->offset = offsetForException;
rangeCheckMIR->nesting = nesting;
dvmCompilerAppendMIR(entry, rangeCheckMIR);
// To do bound check we need to know globalMaxC/globalMinC value
// as soon as we're limited with just one BIV globalMaxC will contain
// the max/min index change inside a loop body
if (arrayAccessInfo->maxC > globalMaxC) {
globalMaxC = arrayAccessInfo->maxC;
}
if (arrayAccessInfo->minC < globalMinC) {
globalMinC = arrayAccessInfo->minC;
}
}
// Insert Bound check (lower loop border check)
// See the bound check algorithm in GenHoistedBoundCheck function
// Bound check values should be adjusted to meet loop branch condition
if (loopInfo->getArrayAccessInfo()->numUsed != 0) {
if (loopInfo->isCountUpLoop()) {
MIR *boundCheckMIR = dvmCompilerNewMIR ();
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound;
boundCheckMIR->dalvikInsn.vA = idxReg;
boundCheckMIR->dalvikInsn.vB = globalMinC;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = offsetForException;
boundCheckMIR->nesting = nesting;
dvmCompilerAppendMIR(entry, boundCheckMIR);
} else {
if (loopInfo->getLoopBranchOpcode() == OP_IF_LT ||
loopInfo->getLoopBranchOpcode() == OP_IF_LE) {
MIR *boundCheckMIR = dvmCompilerNewMIR ();
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpLowerBound;
boundCheckMIR->dalvikInsn.vA = loopInfo->getEndConditionReg();
boundCheckMIR->dalvikInsn.vB = globalMinC;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = offsetForException;
boundCheckMIR->nesting = nesting;
/*
* If the end condition is ">" in the source, the check in the
* Dalvik bytecode is OP_IF_LE. In this case add 1 back to the
* constant field to reflect the fact that the smallest index
* value is "endValue + constant + 1".
*/
if (loopInfo->getLoopBranchOpcode() == OP_IF_LE) {
boundCheckMIR->dalvikInsn.vB++;
}
dvmCompilerAppendMIR(entry, boundCheckMIR);
} else if (loopInfo->getLoopBranchOpcode() == OP_IF_LTZ) {
/* Array index will fall below 0 */
if (globalMinC < 0) {
MIR *boundCheckMIR = dvmCompilerNewMIR ();
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = offsetForException;
boundCheckMIR->nesting = nesting;
dvmCompilerAppendMIR(entry, boundCheckMIR);
}
} else if (loopInfo->getLoopBranchOpcode() == OP_IF_LEZ) {
/* Array index will fall below 0 */
if (globalMinC < -1) {
MIR *boundCheckMIR = dvmCompilerNewMIR ();
boundCheckMIR->dalvikInsn.opcode = (Opcode)kMirOpPunt;
// set offset to the start offset of entry block
// this will set rPC in case of bail to interpreter
boundCheckMIR->offset = offsetForException;
boundCheckMIR->nesting = nesting;
dvmCompilerAppendMIR(entry, boundCheckMIR);
}
} else {
ALOGE("Jit: bad case in genHoistedChecks");
dvmCompilerAbort(cUnit);
}
}
}
if (cUnit->printPass == true)
{
dvmDumpHoistedRangeCheckInfo(cUnit);
}
(void) pass;
}
#endif
void resetBlockEdges(BasicBlock *bb)
{
bb->taken = NULL;
bb->fallThrough = NULL;
bb->successorBlockList.blockListType = kNotUsed;
}
static bool clearPredecessorVector(struct CompilationUnit *cUnit,
struct BasicBlock *bb)
{
dvmClearAllBits(bb->predecessors);
return false;
}
/**
* @brief Check if a BasicBlock has a restricted instruction for a loop
* Certain opcodes cannot be included in a loop formation (in the nonFixableOpcodes array)
* Certain opcodes can be "fixed" if the function handleFixableOpcode returns true and thus won't be cause to reject the loop
* @param cUnit the CompilationUnit
* @param bb the BasicBlock
* @return whether or not we accept the BasicBlock in regards to the instructions
*/
static bool checkBBInstructionsForCFGLoop (CompilationUnit *cUnit, BasicBlock *bb)
{
//Non fixable opcodes: tested against the bb's MIR instructions
//If present, there is nothing we can do about it
static unsigned int nonFixableOpcodes[] = {
OP_RETURN_VOID,
OP_RETURN,
OP_RETURN_WIDE,
OP_RETURN_OBJECT,
OP_MONITOR_ENTER,
OP_MONITOR_EXIT,
OP_NEW_INSTANCE,
OP_NEW_ARRAY,
OP_THROW,
OP_RETURN_VOID_BARRIER,
OP_BREAKPOINT,
OP_THROW_VERIFICATION_ERROR,
//We reject virtual/interface invokes because we have no mechanism yet for method prediction.
//Thus we prefer that we get the trace which has the runtime prediction.
OP_INVOKE_VIRTUAL,
OP_INVOKE_VIRTUAL_RANGE,
OP_INVOKE_VIRTUAL_QUICK,
OP_INVOKE_VIRTUAL_QUICK_RANGE,
OP_INVOKE_INTERFACE,
OP_INVOKE_INTERFACE_RANGE,
};
//Go through each instruction
unsigned int nbr = sizeof (nonFixableOpcodes) / sizeof (nonFixableOpcodes[0]);
for (MIR *mir = bb->firstMIRInsn; mir != 0; mir = mir->next)
{
//Go through each non supported instructions
for (unsigned int i = 0; i < nbr; i++)
{
//If we don't support it, just quit
if (mir->dalvikInsn.opcode == nonFixableOpcodes[i])
{
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: unsupported opcode in loop : %s",
cUnit->entryBlock->startOffset, dexGetOpcodeName(mir->dalvikInsn.opcode));
}
return false;
}
}
}
//If we got here we are good to go
return true;
}
/**
* @brief Accept a CFG as a loop (Helper function)
* @param cUnit the CompilationUnit
* @param bb the BasicBlock
* @return whether or not the trace is a loop but acceptCFGLoops must still check min and max
*/
static bool acceptCFGLoopsHelper (CompilationUnit *cUnit, BasicBlock *bb)
{
//Paranoid check
if (bb == 0)
{
return true;
}
//Visited check
if (bb->visited == true)
{
return true;
}
//Color it now
bb->visited = true;
//If hidden, we stop
if (bb->hidden == true)
{
return true;
}
//Check instructions: add the restrictive, we will try to inline later
bool res = checkBBInstructionsForCFGLoop (cUnit, bb);
//If it says no, we say no
if (res == false)
{
return false;
}
//Now mark it as a BasicBlock of the loop
dvmCompilerSetBit(cUnit->tempBlockV, bb->id);
//Now recurse
res = acceptCFGLoopsHelper (cUnit, bb->taken) && acceptCFGLoopsHelper (cUnit, bb->fallThrough);
//Return it, whatever it is
return res;
}
/**
* @brief Go from the BasicBlock cur to its predecessors, up until first
* @param cUnit the CompilationUnit
* @param cur the current BasicBlock
* @param first the start of the loop
*/
static void climbTheLoopHelper (CompilationUnit *cUnit, BasicBlock *cur, const BasicBlock *first)
{
BitVectorIterator bvIterator;
//Paranoid
assert (cur != 0 && cur->predecessors != 0);
//Have we visited it yet: normally redundant but paranoid
if (cur->visited == true)
{
return;
}
cur->visited = true;
//Unhide the current block
cur->hidden = false;
//Are we done?
if (cur == first)
{
return;
}
//Get predecessors
dvmBitVectorIteratorInit(cur->predecessors, &bvIterator);
while (true) {
//Get the next iterator
int blockIdx = dvmBitVectorIteratorNext(&bvIterator);
//If it is finished, exit
if (blockIdx == -1)
{
break;
}
BasicBlock *predBB = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx));
//Paranoid
if (predBB == 0)
{
break;
}
//We found a trail, enable it from first
if (predBB->taken == cur)
{
predBB->taken->hidden = false;
}
else
{
//Then it must be fallThrough
assert (predBB->fallThrough == cur);
predBB->fallThrough->hidden = false;
}
//Continue up
climbTheLoopHelper (cUnit, predBB, first);
}
}
/*
* @brief Go from the BasicBlock cur downwards to bottom but bail at notLoop
* @param cUnit the CompilationUnit
* @param cur the current BasicBlock
* @param bottom the end of the loop
* @param notLoop the exit of the loop
*/
static void descendTheLoopHelper (CompilationUnit *cUnit, BasicBlock *cur, BasicBlock *bottom, BasicBlock *notLoop)
{
//If nil, or notLoop
if (cur == 0 || cur == notLoop)
{
return;
}
//Have we visited it yet: normally redundant but paranoid
if (cur->visited == true)
{
return;
}
cur->visited = true;
//Unhide the current block
cur->hidden = false;
//Are we done?
if (cur == bottom)
{
return;
}
//Now call children
descendTheLoopHelper (cUnit, cur->taken, bottom, notLoop);
descendTheLoopHelper (cUnit, cur->fallThrough, bottom, notLoop);
}
/**
* @brief Walk the loop from its predecessors that form the loop
* @param cUnit the CompilationUnit
* @param bb the BasicBlock that is the start of the loop
*/
static bool walkTheLoop (CompilationUnit *cUnit, BasicBlock *bb)
{
//Get first BasicBlock of the loop
BasicBlock *first = cUnit->entryBlock->fallThrough;
//Is it a backward branch
if (bb->loopTraversalType.walkBackward == true)
{
climbTheLoopHelper (cUnit, bb, first);
//Now what can happen is that we have inter-twined loops,
//So actually now hide again any child of bb that is not the first
if (bb->taken != 0 && bb->taken != first)
{
bb->taken->hidden = true;
}
if (bb->fallThrough != 0 && bb->fallThrough != first)
{
bb->fallThrough->hidden = true;
}
}
else
{
//Or is it a forward loop
if (bb->loopTraversalType.walkForward == true)
{
//A BB could be both, but we reject the double case if we are walking backwards
//To the first BB
if (bb->loopTraversalType.walkBackward == true &&
(bb->taken == first || bb->fallThrough == first))
{
return false;
}
//Find the notLoop
BasicBlock *notLoop = bb->taken;
if (notLoop == first)
{
notLoop = bb->fallThrough;
}
descendTheLoopHelper (cUnit, first, bb, notLoop);
}
}
return false;
}
/**
* @brief Clear visited and hide dispatched function
* @param cUnit the CompilationUnit
* @param bb the current BasicBlock
* @return returns true to signal we changed the BasicBlock
*/
static bool clearVisitedAndHide (CompilationUnit *cUnit, BasicBlock *bb)
{
bb->visited = false;
bb->hidden = true;
return true;
}
/**
* @brief Is the loop bottom formed?
* @param cUnit the CompilationUnit
* @param first the first BasicBlock of the trace
* @return whether or not the loop is bottom formed
*/
static bool isBottomFormed (CompilationUnit *cUnit, BasicBlock *first)
{
//We still have work to do if it isn't topFormed
BitVectorIterator bvIterator;
//Paranoid
assert (first->predecessors != 0);
//Get predecessors
dvmBitVectorIteratorInit(first->predecessors, &bvIterator);
while (true) {
//Get the next iterator
int blockIdx = dvmBitVectorIteratorNext(&bvIterator);
//If it is finished, exit
if (blockIdx == -1)
{
break;
}
BasicBlock *predBB = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx));
if (predBB == 0)
{
continue;
}
//If predBB is first, we can skip it
if (first == predBB)
{
continue;
}
//Is the predBB kDalvikByteCode, one child must be towards first
if (predBB->blockType == kDalvikByteCode)
{
if (predBB->taken == first)
{
if (predBB->fallThrough == 0 || predBB->fallThrough->hidden == false)
{
return false;
}
}
else
{
if (predBB->fallThrough == first)
{
if (predBB->taken == 0 || predBB->taken->hidden == false)
{
return false;
}
}
}
}
}
return true;
}
bool acceptOldLoops (CompilationUnit *cUnit)
{
BasicBlock *firstBB = cUnit->entryBlock->fallThrough;
/* Record blocks included in the loop */
dvmClearAllBits(cUnit->tempBlockV);
dvmCompilerSetBit(cUnit->tempBlockV, cUnit->entryBlock->id);
dvmCompilerSetBit(cUnit->tempBlockV, firstBB->id);
BasicBlock *bodyBB = firstBB;
/*
* First try to include the fall-through block in the loop, then the taken
* block. Stop loop formation on the first backward branch that enters the
* first block (ie only include the inner-most loop).
*/
while (true) {
/* Loop formed */
if (bodyBB->taken == firstBB) {
/* Check if the fallThrough edge will cause a nested loop */
if (bodyBB->fallThrough && dvmIsBitSet(cUnit->tempBlockV, bodyBB->fallThrough->id)) {
return false;
}
/* Single loop formed */
break;
} else if (bodyBB->fallThrough == firstBB) {
/* Check if the taken edge will cause a nested loop */
if (bodyBB->taken && dvmIsBitSet(cUnit->tempBlockV, bodyBB->taken->id)) {
return false;
}
/* Single loop formed */
break;
}
/* Inner loops formed first - quit */
if (bodyBB->fallThrough && dvmIsBitSet(cUnit->tempBlockV, bodyBB->fallThrough->id)) {
return false;
}
if (bodyBB->taken && dvmIsBitSet(cUnit->tempBlockV, bodyBB->taken->id)) {
return false;
}
if (bodyBB->fallThrough) {
if (bodyBB->fallThrough->iDom == bodyBB) {
bodyBB = bodyBB->fallThrough;
dvmCompilerSetBit(cUnit->tempBlockV, bodyBB->id);
/*
* Loop formation to be detected at the beginning of next
* iteration.
*/
continue;
}
}
if (bodyBB->taken) {
if (bodyBB->taken->iDom == bodyBB) {
bodyBB = bodyBB->taken;
dvmCompilerSetBit(cUnit->tempBlockV, bodyBB->id);
/*
* Loop formation to be detected at the beginning of next
* iteration.
*/
continue;
}
}
/*
* Current block is not the immediate dominator of either fallthrough
* nor taken block - bail out of loop formation.
*/
return false;
}
//Loop accepted
return true;
}
/**
* @brief Accept a CFG as a loop
* @param cUnit the CompilationUnit
* @return whether or not the trace is a loop
*/
static bool acceptCFGLoops (CompilationUnit *cUnit)
{
BasicBlock *first = cUnit->entryBlock->fallThrough;
//Clear visiting flags
dvmCompilerDataFlowAnalysisDispatcher(cUnit, clearVisitedAndHide, kAllNodes, false /* isIterative */);
//We must go through the list by hand because the dispatcher looks at hidden and we set it to true
GrowableListIterator iterator;
dvmGrowableListIteratorInit(&cUnit->blockList, &iterator);
while (true) {
BasicBlock *bb = (BasicBlock *) dvmGrowableListIteratorNext(&iterator);
//Paranoid
if (bb == NULL)
{
break;
}
//Ok, either it is the first, or it goes towards the first
if (bb != first && bb->taken != first && bb->fallThrough != first)
{
continue;
}
//Call back to walk the loop: we only care about the outer loop
walkTheLoop (cUnit, bb);
}
//Unhide the entry
cUnit->entryBlock->hidden = false;
//We have a loop if first->taken or first->fallThrough are not hidden and we aren't either
bool res = first->hidden;
if (res == true)
{
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: first BB hidden",
cUnit->entryBlock->startOffset);
}
return false;
}
//Otherwise, look at the children
res = (first->taken != 0 && first->taken->hidden == false) ||
(first->fallThrough != 0 && first->fallThrough->hidden == false);
if (res == false)
{
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: children of first BB hidden",
cUnit->entryBlock->startOffset);
}
return false;
}
//Clear bits
dvmClearAllBits (cUnit->tempBlockV);
//Reset flags
dvmCompilerDataFlowAnalysisDispatcher(cUnit, dvmCompilerClearVisitedFlag, kAllNodes, false);
//Call the helper
bool found = acceptCFGLoopsHelper (cUnit, cUnit->entryBlock);
//Ok, if the acceptance returned false, we are done
if (found == false)
{
// message logged above
return false;
}
//Final step check if it is top formed or bottom formed
bool topFormed = (first->taken != 0 && first->taken->hidden == true) ||
(first->fallThrough != 0 && first->fallThrough->hidden == true);
if (topFormed == false)
{
//If it isn't top formed, it must be bottom formed
bool res = isBottomFormed (cUnit, first);
if (res == false && cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: not top or bottom formed",
cUnit->entryBlock->startOffset);
}
return res;
}
return true;
}
bool dvmCompilerFilterLoopBlocks(CompilationUnit *cUnit)
{
BasicBlock *firstBB = cUnit->entryBlock->fallThrough;
//We should only have one exit chaining cell of the loop
bool normalChainingAdded = false;
int numPred = dvmCountSetBits(firstBB->predecessors);
/*
* A loop body should have at least two incoming edges.
*/
if (numPred < 2) {
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x not a loop: only one predecessor",
cUnit->entryBlock->startOffset);
}
return false;
}
//Let us see if we can accept the loop
//We have two loop acceptance systems: the new system and the old one, which one do we want?
bool acceptIt = false;
if (gDvmJit.oldLoopDetection == false)
{
acceptIt = acceptCFGLoops (cUnit);
}
else
{
acceptIt = acceptOldLoops (cUnit);
}
//If the acceptance bailed on us, we bail as well
if (acceptIt == false)
{
return false;
}
/* Now mark blocks not included in the loop as hidden */
GrowableList *blockList = &cUnit->blockList;
GrowableListIterator iterator;
dvmGrowableListIteratorInit(blockList, &iterator);
while (true) {
BasicBlock *bb = (BasicBlock *) dvmGrowableListIteratorNext(&iterator);
if (bb == NULL) break;
if (!dvmIsBitSet(cUnit->tempBlockV, bb->id)) {
bb->hidden = true;
/* Clear the insn list */
bb->firstMIRInsn = bb->lastMIRInsn = NULL;
resetBlockEdges(bb);
}
}
dvmCompilerDataFlowAnalysisDispatcher(cUnit, clearPredecessorVector,
kAllNodes, false /* isIterative */);
dvmGrowableListIteratorInit(blockList, &iterator);
while (true) {
BasicBlock *bb = (BasicBlock *) dvmGrowableListIteratorNext(&iterator);
if (bb == NULL) break;
if (dvmIsBitSet(cUnit->tempBlockV, bb->id)) {
if (bb->taken) {
/*
* exit block means we run into control-flow that we don't want
* to handle.
*/
if (bb->taken == cUnit->exitBlock) {
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x taken branch to exit block",
cUnit->entryBlock->startOffset);
}
return false;
}
if (bb->taken->hidden) {
//We should only be adding one loop exit
if (normalChainingAdded == true)
{
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x more than one loop exit",
cUnit->entryBlock->startOffset);
}
return false;
}
bb->taken->blockType = kChainingCellNormal;
normalChainingAdded = true;
bb->taken->hidden = false;
//We unhide some BB, so we need to clear its predecessor info
clearPredecessorVector (cUnit, bb->taken);
}
dvmCompilerSetBit(bb->taken->predecessors, bb->id);
}
if (bb->fallThrough) {
/*
* exit block means we run into control-flow that we don't want
* to handle.
*/
if (bb->fallThrough == cUnit->exitBlock) {
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x fallthrough to exit block",
cUnit->entryBlock->startOffset);
}
return false;
}
if (bb->fallThrough->hidden) {
//We should only be adding one loop exit
if (normalChainingAdded == true) {
if (cUnit->printMe == true)
{
ALOGD("JIT_INFO: Loop trace @ offset %04x fallthrough to more than one loop exit",
cUnit->entryBlock->startOffset);
}
return false;
}
bb->fallThrough->blockType = kChainingCellNormal;
normalChainingAdded = true;
bb->fallThrough->hidden = false;
//We unhide some BB, so we need to clear its predecessor info
clearPredecessorVector (cUnit, bb->fallThrough);
}
dvmCompilerSetBit(bb->fallThrough->predecessors, bb->id);
}
/* Loop blocks shouldn't contain any successor blocks (yet) */
assert(bb->successorBlockList.blockListType == kNotUsed);
}
}
return true;
}
#ifdef ARCH_IA32
/*
* Main entry point to do loop, trace, method optimizations
* Name is remaining the same as ARM for the moment...
*/
bool dvmCompilerLoopOpt(CompilationUnit *cUnit)
{
dvmCompilerLaunchPassDriver (cUnit);
return true;
}
#else
#ifdef DEBUG_LOOP_ON
/* Debugging routines */
static void dumpConstants(CompilationUnit *cUnit)
{
int i;
ALOGE("LOOP starting offset: %x", cUnit->entryBlock->startOffset);
for (i = 0; i < cUnit->numSSARegs; i++) {
if (dvmIsBitSet(cUnit->isConstantV, i)) {
int subNReg = dvmConvertSSARegToDalvik(cUnit, i);
ALOGE("CONST: s%d(v%d_%d) has %d", i,
DECODE_REG(subNReg), DECODE_SUB(subNReg),
(*cUnit->constantValues)[i]);
}
}
}
static void dumpIVList(CompilationUnit *cUnit)
{
unsigned int i;
GrowableList *ivList = cUnit->loopAnalysis->ivList;
for (i = 0; i < ivList->numUsed; i++) {
InductionVariableInfo *ivInfo =
(InductionVariableInfo *) ivList->elemList[i];
int iv = dvmConvertSSARegToDalvik(cUnit, ivInfo->ssaReg);
/* Basic IV */
if (ivInfo->ssaReg == ivInfo->basicSSAReg) {
ALOGE("BIV %d: s%d(v%d_%d) + %d", i,
ivInfo->ssaReg,
DECODE_REG(iv), DECODE_SUB(iv),
ivInfo->loopIncrement);
/* Dependent IV */
} else {
int biv = dvmConvertSSARegToDalvik(cUnit, ivInfo->basicSSAReg);
ALOGE("DIV %d: s%d(v%d_%d) = %d * s%d(v%d_%d) + %d", i,
ivInfo->ssaReg,
DECODE_REG(iv), DECODE_SUB(iv),
ivInfo->m,
ivInfo->basicSSAReg,
DECODE_REG(biv), DECODE_SUB(biv),
ivInfo->constant);
}
}
}
static void dumpHoistedChecks(CompilationUnit *cUnit)
{
LoopAnalysis *loopAnalysis = cUnit->loopAnalysis;
unsigned int i;
for (i = 0; i < loopAnalysis->arrayAccessInfo->numUsed; i++) {
ArrayAccessInfo *arrayAccessInfo =
GET_ELEM_N(loopAnalysis->arrayAccessInfo,
ArrayAccessInfo*, i);
int arrayReg = DECODE_REG(
dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->arrayReg));
int idxReg = DECODE_REG(
dvmConvertSSARegToDalvik(cUnit, arrayAccessInfo->ivReg));
ALOGE("Array access %d", i);
ALOGE(" arrayReg %d", arrayReg);
ALOGE(" idxReg %d", idxReg);
ALOGE(" endReg %d", loopAnalysis->endConditionReg);
ALOGE(" maxC %d", arrayAccessInfo->maxC);
ALOGE(" minC %d", arrayAccessInfo->minC);
ALOGE(" opcode %d", loopAnalysis->loopBranchOpcode);
}
}
#endif
/*
* Main entry point to do loop optimization.
* Return false if sanity checks for loop formation/optimization failed.
*/
bool dvmCompilerLoopOpt(CompilationUnit *cUnit)
{
LoopAnalysis *loopAnalysis =
(LoopAnalysis *)dvmCompilerNew(sizeof(LoopAnalysis), true);
cUnit->loopAnalysis = loopAnalysis;
dvmCompilerDataFlowAnalysisDispatcher(cUnit,
dvmCompilerDoConstantPropagation,
kAllNodes,
false /* isIterative */);
DEBUG_LOOP(dumpConstants(cUnit);)
/* Find induction variables - basic and dependent */
loopAnalysis->ivList =
(GrowableList *)dvmCompilerNew(sizeof(GrowableList), true);
dvmInitGrowableList(loopAnalysis->ivList, 4);
loopAnalysis->isIndVarV = dvmCompilerAllocBitVector(cUnit->numSSARegs, false);
dvmCompilerDataFlowAnalysisDispatcher(cUnit,
dvmCompilerFindInductionVariables,
kAllNodes,
false /* isIterative */);
DEBUG_LOOP(dumpIVList(cUnit);)
/* Only optimize array accesses for simple counted loop for now */
if (!isSimpleCountedLoop(cUnit))
return false;
loopAnalysis->arrayAccessInfo =
(GrowableList *)dvmCompilerNew(sizeof(GrowableList), true);
dvmInitGrowableList(loopAnalysis->arrayAccessInfo, 4);
loopAnalysis->bodyIsClean = doLoopBodyCodeMotion(cUnit);
DEBUG_LOOP(dumpHoistedChecks(cUnit);)
/*
* Convert the array access information into extended MIR code in the loop
* header.
*/
genHoistedChecks(cUnit);
return true;
}
/*
* Select the target block of the backward branch.
*/
bool dvmCompilerInsertBackwardChaining(CompilationUnit *cUnit)
{
/*
* If we are not in self-verification or profiling mode, the backward
* branch can go to the entryBlock->fallThrough directly. Suspend polling
* code will be generated along the backward branch to honor the suspend
* requests.
*/
#ifndef ARCH_IA32
#if !defined(WITH_SELF_VERIFICATION)
if (gDvmJit.profileMode != kTraceProfilingContinuous &&
gDvmJit.profileMode != kTraceProfilingPeriodicOn) {
return false;
}
#endif
#endif
/*
* In self-verification or profiling mode, the backward branch is altered
* to go to the backward chaining cell. Without using the backward chaining
* cell we won't be able to do check-pointing on the target PC, or count the
* number of iterations accurately.
*/
BasicBlock *firstBB = cUnit->entryBlock->fallThrough;
BasicBlock *backBranchBB = findPredecessorBlock(cUnit, firstBB);
//Backward branching can fail if findPredecessorBlock returns 0, if it does report the failure
if (backBranchBB == NULL)
{
return false;
}
if (backBranchBB->taken == firstBB) {
backBranchBB->taken = cUnit->backChainBlock;
} else {
//Paranoid: if fallThrough is not firstBB, we have an issue: neither taken or fallthrough went to firstBB...
if (backBranchBB->fallThrough != firstBB)
{
//Report it as a failure
return false;
}
backBranchBB->fallThrough = cUnit->backChainBlock;
}
cUnit->backChainBlock->startOffset = firstBB->startOffset;
//Report success
return true;
}
#endif
/**
* @brief Recursive function to find the minimum offset of a loop: it is located in the BasicBlock with the smallest startOffset
* @param cUnit the CompilationUnit
* @param bb the current BasicBlock
* @return the minimum offset BasicBlock
*/
static BasicBlock *findMinimumHelper (CompilationUnit *cUnit, BasicBlock *bb)
{
//If null, not dalvik byte code, or visited, return 0
if (bb == 0 || (bb->blockType != kDalvikByteCode) || (bb->visited == true))
{
return 0;
}
//Mark it
bb->visited = true;
//Paranoid
if (bb->predecessors == 0)
{
return 0;
}
//Suppose the minimum is bb
BasicBlock *min = bb;
//Go through the predecessors
BitVectorIterator bvIterator;
dvmBitVectorIteratorInit(bb->predecessors, &bvIterator);
while (true) {
int blockIdx = dvmBitVectorIteratorNext(&bvIterator);
if (blockIdx == -1)
{
break;
}
BasicBlock *predBB = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, blockIdx);
BasicBlock *curMin = findMinimumHelper (cUnit, predBB);
if (curMin != 0 && curMin->startOffset < min->startOffset)
{
min = curMin;
}
}
//Return minium
return min;
}
/**
* @brief Function to the minimum offset of a loop
* @param cUnit the CompilationUnit
* @return the minimum offset BasicBlock of cUnit
*/
static BasicBlock *findMinimum (CompilationUnit *cUnit)
{
//Reset flags
dvmCompilerDataFlowAnalysisDispatcher(cUnit, dvmCompilerClearVisitedFlag, kAllNodes, false);
//Call recursive function
return findMinimumHelper (cUnit, cUnit->entryBlock->fallThrough);
}
/**
* @brief Mark the BasicBlock in the loop cache
* The loop cache is used to know if an offset is a loop head or not. It helps reduce compilation time.
* The loop cache contains all the BasicBlocks that are NOT loop heads
* @param cUnit the CompilationUnit
* @param bb the BasicBlock
* @return returns false, the function does not change the BasicBlock
*/
static bool markBasicBlocksInLoopCache (CompilationUnit *cUnit, BasicBlock *bb)
{
//Only care about dalvik byte code
if (bb->blockType == kDalvikByteCode)
{
gDvmJit.knownNonLoopHeaderCache[cUnit->method->insns + bb->startOffset];
}
//We did not change anything to bb
return false;
}
/**
* @brief Mark off any BasicBlock, which is not a loop header
* @param cUnit the CompilationUnit
* @param bb the BasicBlock
* @return always return false, we don't change the BasicBlock
*/
static bool markOffNonHeadersHelper (CompilationUnit *cUnit, BasicBlock *bb)
{
BitVectorIterator bvIterator;
//Paranoid
assert (bb->predecessors != 0);
//Get predecessors
dvmBitVectorIteratorInit(bb->predecessors, &bvIterator);
//Only mark off BasicBlocks that are dalvik code
if (bb->blockType != kDalvikByteCode)
{
return false;
}
//Did we find a BasicBlock being a backward branch
while (true) {
//Get the next iterator
int blockIdx = dvmBitVectorIteratorNext(&bvIterator);
//If it is finished, exit
if (blockIdx == -1)
{
break;
}
BasicBlock *predBB = (BasicBlock*) (dvmGrowableListGetElement(&cUnit->blockList, blockIdx));
//Paranoid
if (predBB == 0)
{
break;
}
//If no dominator information, skip it
if (predBB->dominators == 0)
{
continue;
}
//If the predecessor is dominated by this one, it is a backward branch
if (dvmIsBitSet (predBB->dominators, bb->id) == true)
{
unsigned int entryOffset = cUnit->entryBlock->startOffset;
//Now here are some assumptions:
// If bb is the startOffset of cUnit->entryBlock, it is the original head
if (entryOffset == bb->startOffset)
{
predBB->loopTraversalType.walkBackward = true;
predBB->loopTraversalType.relativeTo = bb;
}
else
{
//Now the if handled top loop cases where the head of the loop is
//actually the head of the trace. Sometimes it happens that the branch
//into the loop is the head. Check this here
//First do we have only one branch towards it:
if (bb->taken != 0 && bb->fallThrough == 0 && bb->taken->startOffset == entryOffset)
{
bb->loopTraversalType.walkForward = true;
bb->loopTraversalType.relativeTo = bb->taken;
}
else
{
//Same but the other side
if (bb->fallThrough != 0 && bb->taken == 0 && bb->fallThrough->startOffset == entryOffset)
{
bb->loopTraversalType.walkForward = true;
bb->loopTraversalType.relativeTo = bb->fallThrough;
}
else
{
//Otherwise, we have two children and that means this is exiting the loop
bb->loopTraversalType.walkBackward = true;
bb->loopTraversalType.relativeTo = predBB;
}
}
}
//Now mark it as a potential loop head and its children
gDvmJit.knownNonLoopHeaderCache.erase (cUnit->method->insns + bb->startOffset);
//Now we mark both children because we don't know which one is towards a loop
//A subsequent call will handle it
if (bb->taken != 0)
{
if (dvmIsBitSet (predBB->dominators, bb->taken->id) == true)
{
gDvmJit.knownNonLoopHeaderCache.erase (cUnit->method->insns + bb->taken->startOffset);
}
}
if (bb->fallThrough != 0)
{
if (dvmIsBitSet (predBB->dominators, bb->fallThrough->id) == true)
{
gDvmJit.knownNonLoopHeaderCache.erase (cUnit->method->insns + bb->fallThrough->startOffset);
}
}
}
}
//We did not change the BasicBlock
return false;
}
/**
* @brief Clear predecessor information
* @param cUnit the CompilationUnit
* @param bb the BasicBlock
* @return returns whether we changed something in the BasicBlock or not
*/
static bool clearPredecessors (CompilationUnit *cUnit, BasicBlock *bb)
{
//We only need to set it if there is a bit set,
//normally we wouldn't care about this test but the dispatcher might care
if (dvmCountSetBits (bb->predecessors) != 0)
{
dvmClearAllBits (bb->predecessors);
return true;
}
return false;
}
/**
* @brief Calculate Predecessor Information Helper
* @param cUnit the CompilationUnit
* @param bb the BasicBlock
* @return returns false, the BasicBlock is not changed
*/
static bool calculatePredecessorsHelper (CompilationUnit *cUnit, BasicBlock *bb)
{
//We only care about non hidden blocks
if (bb->hidden == true)
{
return false;
}
//Create iterator for visiting children
ChildBlockIterator childIter (bb);
//Now iterate through the children to set the predecessor bits
for (BasicBlock **childPtr = childIter.getNextChildPtr (); childPtr != 0; childPtr = childIter.getNextChildPtr ())
{
BasicBlock *child = *childPtr;
assert (child != 0);
dvmCompilerSetBit (child->predecessors, bb->id);
}
//We did change something but not our own basic block
return false;
}
/**
* @brief Calculate Predecessor Information
* @param cUnit the CompilationUnit
*/
void dvmCompilerCalculatePredecessors (CompilationUnit *cUnit)
{
//First job is to clear the predecessors
dvmCompilerDataFlowAnalysisDispatcher (cUnit, clearPredecessors, kAllNodes, false);
//Second part is to calculate them again
dvmCompilerDataFlowAnalysisDispatcher (cUnit, calculatePredecessorsHelper, kAllNodes, false);
}
/**
* @brief Mark off BasicBlocks from the loop cache
* @param cUnit the CompilationUnit
*/
void dvmCompilerLoopMarkOffNonHeaderBlocks (CompilationUnit *cUnit)
{
//Recalculate the predecessors with this new formation
dvmCompilerCalculatePredecessors (cUnit);
//Find the minimum offset
BasicBlock *minimum = findMinimum (cUnit);
//Now entry should temporarily go to the minimum
BasicBlock *tmpEntry = cUnit->entryBlock->fallThrough;
cUnit->entryBlock->fallThrough = minimum;
//Recalculate the predecessors with this new formation
dvmCompilerCalculatePredecessors (cUnit);
//Ok, now we can calculate dominators
dvmCompilerBuildDomination (cUnit);
//Clear the temporary bits
dvmClearAllBits (cUnit->tempBlockV);
dvmCompilerDataFlowAnalysisDispatcher(cUnit,
markBasicBlocksInLoopCache,
kAllNodes,
false /* isIterative */);
//Now we can go through the BasicBlocks and mark off those that are not loops
dvmCompilerDataFlowAnalysisDispatcher(cUnit,
markOffNonHeadersHelper,
kAllNodes,
false /* isIterative */);
//Put it back as it was, and recalculate the predecessors
cUnit->entryBlock->fallThrough = tmpEntry;
dvmCompilerCalculatePredecessors (cUnit);
//Domination is done later so no need here
}
#ifdef ARCH_IA32
/**
* @brief Looks through backward's predecessors and inserts a new block in
* between. It also ensures that new block is the taken branch and flips
* condition in bytecode if needed.
* @details Creates a new block and copies relevant information from backward.
* @param cUnit the Compilation Unit
* @param backward the backward branch chaining cell
*/
static void insertBlockBeforeBackwardHelper (CompilationUnit *cUnit,
BasicBlock *backward)
{
//Checking preconditions
assert(backward != 0);
//Only insert prebackward if backward branch CC is involved
if (backward->blockType != kChainingCellBackwardBranch)
{
return;
}
BitVector *predecessors = backward->predecessors;
//Paranoid
if (predecessors == 0)
{
return;
}
//Ok, there is currently no way a backward branch can have more than one predecessor
//Something went terribly wrong if it did, so get out
//Note that if we remove this check we need to revisit to code below, cosidering loop
//over predecessors.
if (dvmCountSetBits (predecessors) != 1)
{
PASS_LOG (ALOGD, cUnit, "JIT_INFO: Backward branch has more than one predecessor");
cUnit->quitLoopMode = true;
return;
}
// We have only one predecessor so take it
int blockIdx = dvmHighestBitSet (predecessors);
//Get the predecessor block
BasicBlock *predecessor =
reinterpret_cast<BasicBlock *> (dvmGrowableListGetElement (
&cUnit->blockList, blockIdx));
//Paranoid
assert (predecessor != 0);
//Create a preBackward block
BasicBlock *preBackward = dvmCompilerNewBBinCunit (cUnit,
kPreBackwardBlock);
//Paranoid
assert(preBackward != 0);
//Now we copy the relevant parts
preBackward->startOffset = backward->startOffset;
preBackward->firstMIRInsn = backward->firstMIRInsn;
preBackward->lastMIRInsn = backward->lastMIRInsn;
preBackward->containingMethod = backward->containingMethod;
//We also need to make a copy of the write back requests
preBackward->requestWriteBack = dvmCompilerAllocBitVector (1, true);
dvmCopyBitVector (preBackward->requestWriteBack,
backward->requestWriteBack);
//We want the new block to be the taken branch.
//So if backward used to be the fallthrough, make it the taken.
if(predecessor->fallThrough == backward)
{
MIR *ifMir = predecessor->lastMIRInsn;
//It is unexpected if we have a null MIR, so bail out
if (ifMir == 0)
{
cUnit->quitLoopMode = true;
return;
}
//Paranoid, we should have an if at the end
assert(ifMir != 0 && ifMir->dalvikInsn.opcode >= OP_IF_EQ
&& ifMir->dalvikInsn.opcode <= OP_IF_LEZ);
Opcode negated;
bool canNegate = negateOpcode (ifMir->dalvikInsn.opcode, negated);
//If we can negate the bytecode condition, then we can swap
//the children
if (canNegate == true)
{
//Update opcode
ifMir->dalvikInsn.opcode = negated;
//Set the fallthrough to be the old taken
dvmCompilerReplaceChildBasicBlock (predecessor->taken, predecessor, kChildTypeFallthrough);
//Make the backward be the new taken
dvmCompilerReplaceChildBasicBlock (backward, predecessor, kChildTypeTaken);
}
}
//Insert the preBackward block between predecessor and backward CC
bool res = dvmCompilerInsertBasicBlockBetween (preBackward, predecessor,
backward);
//If we failed inserting, that's not good and we bail out
if (res == false)
{
cUnit->quitLoopMode = true;
return;
}
//Clear fields from backward
backward->firstMIRInsn = 0;
backward->lastMIRInsn = 0;
//Update parent of the MIRs
for (MIR *mir = preBackward->firstMIRInsn; mir != 0; mir = mir->next)
{
mir->bb = preBackward;
}
}
/**
* @brief Finds all of the backward branch chaining cells and then inserts
* a block before each of them.
* @param cUnit the Compilation Unit
* @param info the information of Loop we are looking at
* @param data required by interface (not used)
* @return true to continue iteration over loops
*/
static bool insertBlockBeforeBackward (CompilationUnit *cUnit,
LoopInformation *info, void *data = 0)
{
//We want to look through all of the backward chaining cells
const BitVector *backwards = info->getBackwardBranches ();
//Const cast due to incompatibility here
BitVector *tmp = const_cast<BitVector *> (backwards);
//Initialize iterator
BitVectorIterator bvIterator;
dvmBitVectorIteratorInit (tmp, &bvIterator);
while (true)
{
//Get the block index
int blockIdx = dvmBitVectorIteratorNext (&bvIterator);
//Break if we are done
if (blockIdx == -1)
{
break;
}
//Get the backward block
BasicBlock *backward =
reinterpret_cast<BasicBlock *> (dvmGrowableListGetElement (
&cUnit->blockList, blockIdx));
//Paranoid
if (backward == 0)
{
continue;
}
insertBlockBeforeBackwardHelper (cUnit, backward);
}
return true;
}
/**
* @brief Add a block before the preheader of type kFromInterpreter
* @param cUnit the Compilation Unit
* @param info the information of Loop we are looking at
* @param data required by interface (not used)
* @return true to continue iteration over loops
*/
static bool insertBlockFromInterpreter (CompilationUnit *cUnit, LoopInformation *info, void *data)
{
//Get the preheader
BasicBlock *preHeader = info->getPreHeader ();
//Get one of the backward blocks since we want to get offset from it
int backwardIdx = dvmHighestBitSet (info->getBackwardBranches ());
BasicBlock *backward = reinterpret_cast<BasicBlock *> (dvmGrowableListGetElement (&cUnit->blockList, backwardIdx));
assert (backward != 0);
if (backward == 0)
{
PASS_LOG (ALOGD, cUnit, "Insert_LoopHelper_Blocks: FromInterpreter cannot be properly inserting "
"without offset from backward CC.");
cUnit->quitLoopMode = true;
return false;
}
if (preHeader != 0)
{
//Also add a from interpreter node
BasicBlock *fromInterpreter = dvmCompilerNewBBinCunit (cUnit, kFromInterpreter);
//Set the correct offset
fromInterpreter->startOffset = backward->startOffset;
//Link fromInterpreter to preHeader
dvmCompilerReplaceChildBasicBlock (preHeader, fromInterpreter, kChildTypeFallthrough);
}
//Unused parameter
(void) data;
//Continue iterating
return true;
}
/**
* @brief Inserts a basic block before Backward Chaining Cell and one before the preheader.
* @details The newly inserted basic blocks takes the write back requests and
* MIRs from chaining cell in order to help backend which cannot handle
* Backward Chaining Cell like a bytecode block. It also ensures that the
* newly inserted block is the taken branch, so if the backward was fallthrough
* it flips the condition.
* @param cUnit the CompilationUnit
* @param currentPass the Pass
*/
void dvmCompilerInsertLoopHelperBlocks (CompilationUnit *cUnit, Pass *currentPass)
{
//Now let's go through the loop information
LoopInformation *info = cUnit->loopInformation;
//If info is 0, there is nothing to do
if (info == 0)
{
return;
}
//Actually do the work
info->iterate (cUnit, insertBlockBeforeBackward);
//Now do it for the from interpreter
info->iterate (cUnit, insertBlockFromInterpreter);
//Unused argument
(void) currentPass;
}
#endif
| 34.159792
| 152
| 0.587969
|
HazouPH
|
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
|
c22acce4897c7e29eb52e25c5489caea137e48cd
| 1,102
|
cpp
|
C++
|
OIandACM/OJ/Codeforces/1451C.cpp
|
ASC8384/-
|
8d8fb4c1d4c10aca1e10a0faf5ab2b687fd936d2
|
[
"CC0-1.0"
] | 8
|
2019-08-09T14:28:13.000Z
|
2021-02-23T03:22:15.000Z
|
OIandACM/OJ/Codeforces/1451C.cpp
|
ASC8384/Template
|
8d8fb4c1d4c10aca1e10a0faf5ab2b687fd936d2
|
[
"CC0-1.0"
] | null | null | null |
OIandACM/OJ/Codeforces/1451C.cpp
|
ASC8384/Template
|
8d8fb4c1d4c10aca1e10a0faf5ab2b687fd936d2
|
[
"CC0-1.0"
] | 4
|
2019-08-16T12:00:41.000Z
|
2019-11-29T12:01:17.000Z
|
/*
** Author: ASC_8384
** Website: www.ASC8384.top
** License: CC0
** Time: 2020-11-21 22:55:51
*/
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
const int size = 2e5 + 9;
const ll mod = 1e9 + 7;
int a[size];
string s1, s2;
//unordered_map<char, int> mp1, mp2;
int mp1[33];
int mp2[33];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
s1.clear();
s2.clear();
memset(mp1, 0, sizeof(mp1));
memset(mp2, 0, sizeof(mp2));
// mp1.clear();
// mp2.clear();
int n, k;
cin >> n >> k;
cin >> s1 >> s2;
for(int i = 0; i < n; i++)
mp1[s1[i] - 'a']++, mp2[s2[i] - 'a']++;
bool flg = true;
for(int i = 0; i <= 30; i++) {
if(mp1[i] == mp2[i])
continue;
if(mp1[i] < mp2[i]) {
flg = false;
goto ANS;
}
if((mp1[i] - mp2[i]) % k == 0) {
mp1[i + 1] += k * ((mp1[i] - mp2[i]) / k);
} else {
flg = false;
goto ANS;
}
}
ANS:
if(flg)
cout << "Yes\n";
else
cout << "No\n";
}
return 0;
}
| 16.69697
| 68
| 0.513612
|
ASC8384
|
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
|
ea5fc3262d4b79008225d3b325d0a3fe8a01ca37
| 4,058
|
cc
|
C++
|
mysql-server/sql/rpl_info.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/sql/rpl_info.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/sql/rpl_info.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql/rpl_info.h"
#include "m_string.h" // strmake
#include "mysql/psi/mysql_cond.h"
#include "mysql/psi/mysql_mutex.h"
#include "thr_mutex.h"
Rpl_info::Rpl_info(const char *type,
#ifdef HAVE_PSI_INTERFACE
PSI_mutex_key *param_key_info_run_lock,
PSI_mutex_key *param_key_info_data_lock,
PSI_mutex_key *param_key_info_sleep_lock,
PSI_mutex_key *param_key_info_thd_lock,
PSI_mutex_key *param_key_info_data_cond,
PSI_mutex_key *param_key_info_start_cond,
PSI_mutex_key *param_key_info_stop_cond,
PSI_mutex_key *param_key_info_sleep_cond,
#endif
uint param_id, const char *param_channel)
: Slave_reporting_capability(type),
#ifdef HAVE_PSI_INTERFACE
key_info_run_lock(param_key_info_run_lock),
key_info_data_lock(param_key_info_data_lock),
key_info_sleep_lock(param_key_info_sleep_lock),
key_info_thd_lock(param_key_info_thd_lock),
key_info_data_cond(param_key_info_data_cond),
key_info_start_cond(param_key_info_start_cond),
key_info_stop_cond(param_key_info_stop_cond),
key_info_sleep_cond(param_key_info_sleep_cond),
#endif
info_thd(nullptr),
inited(false),
abort_slave(false),
slave_running(0),
slave_run_id(0),
handler(nullptr),
internal_id(param_id) {
#ifdef HAVE_PSI_INTERFACE
mysql_mutex_init(*key_info_run_lock, &run_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(*key_info_data_lock, &data_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(*key_info_sleep_lock, &sleep_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(*key_info_thd_lock, &info_thd_lock, MY_MUTEX_INIT_FAST);
mysql_cond_init(*key_info_data_cond, &data_cond);
mysql_cond_init(*key_info_start_cond, &start_cond);
mysql_cond_init(*key_info_stop_cond, &stop_cond);
mysql_cond_init(*key_info_sleep_cond, &sleep_cond);
#else
mysql_mutex_init(nullptr, &run_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(nullptr, &data_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(nullptr, &sleep_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(nullptr, &info_thd_lock, MY_MUTEX_INIT_FAST);
mysql_cond_init(nullptr, &data_cond);
mysql_cond_init(nullptr, &start_cond);
mysql_cond_init(nullptr, &stop_cond);
mysql_cond_init(nullptr, &sleep_cond);
#endif
if (param_channel)
strmake(channel, param_channel, sizeof(channel) - 1);
else
/*create a default empty channel*/
strmake(channel, "", sizeof(channel) - 1);
}
Rpl_info::~Rpl_info() {
delete handler;
mysql_mutex_destroy(&run_lock);
mysql_mutex_destroy(&data_lock);
mysql_mutex_destroy(&sleep_lock);
mysql_mutex_destroy(&info_thd_lock);
mysql_cond_destroy(&data_cond);
mysql_cond_destroy(&start_cond);
mysql_cond_destroy(&stop_cond);
mysql_cond_destroy(&sleep_cond);
}
| 40.989899
| 79
| 0.750123
|
silenc3502
|
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
|
ea6c81c35e56716575c82f45d8960b1f546f0b36
| 6,855
|
cc
|
C++
|
src/camera/test/camera_streaming_test/camera_streaming_test.cc
|
winksaville/Fuchsia
|
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
|
[
"BSD-3-Clause"
] | 3
|
2020-08-02T04:46:18.000Z
|
2020-08-07T10:10:53.000Z
|
src/camera/test/camera_streaming_test/camera_streaming_test.cc
|
winksaville/Fuchsia
|
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
|
[
"BSD-3-Clause"
] | null | null | null |
src/camera/test/camera_streaming_test/camera_streaming_test.cc
|
winksaville/Fuchsia
|
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
|
[
"BSD-3-Clause"
] | 1
|
2020-08-07T10:11:49.000Z
|
2020-08-07T10:11:49.000Z
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <button_checker.h>
#include <fcntl.h>
#include <fuchsia/camera/test/cpp/fidl.h>
#include <fuchsia/camera2/cpp/fidl.h>
#include <lib/devmgr-integration-test/fixture.h> // For RecursiveWaitForFile
#include <lib/fdio/fdio.h>
#include <lib/zx/vmar.h>
#include <unistd.h>
#include <zircon/status.h>
#include <zircon/types.h>
#include <array>
#include <atomic>
#include <string>
#include <fbl/unique_fd.h>
#include <openssl/sha.h>
#include "garnet/public/lib/gtest/real_loop_fixture.h"
// fx run-test camera_full_on_device_test -t camera_streaming_test
class CameraStreamingTest : public gtest::RealLoopFixture {
protected:
CameraStreamingTest() {}
~CameraStreamingTest() override {}
virtual void SetUp() override;
void BindIspTester(fuchsia::camera::test::IspTesterSyncPtr& ptr);
};
// Returns the formatted sha512 string of a buffer.
std::string Hash(const void* data, size_t size) {
static const char* table = "0123456789abcdef";
uint8_t md[SHA512_DIGEST_LENGTH]{};
SHA512(reinterpret_cast<const uint8_t*>(data), size, md);
std::string ret(2 * sizeof(md) + 1, 0);
for (uint32_t i = 0; i < SHA512_DIGEST_LENGTH; ++i) {
ret[2 * i] = table[(md[i] >> 4) & 0xF];
ret[2 * i + 1] = table[md[i] & 0xF];
}
return ret;
}
void CameraStreamingTest::SetUp() {
if (!VerifyDeviceUnmuted()) {
GTEST_SKIP();
}
}
// Connect to the ISP test device.
void CameraStreamingTest::BindIspTester(fuchsia::camera::test::IspTesterSyncPtr& ptr) {
static const char* kIspTesterDir = "/dev/class/isp-device-test";
int result = open(kIspTesterDir, O_RDONLY);
ASSERT_GE(result, 0) << "Error opening " << kIspTesterDir;
fbl::unique_fd dir_fd(result);
fbl::unique_fd fd;
ASSERT_EQ(devmgr_integration_test::RecursiveWaitForFile(dir_fd, "000", &fd), ZX_OK);
zx::channel channel;
ASSERT_EQ(fdio_get_service_handle(fd.get(), channel.reset_and_get_address()), ZX_OK);
ptr.Bind(std::move(channel));
}
// Validate the contents of the stream coming from the ISP.
TEST_F(CameraStreamingTest, CheckStreamFromIsp) {
// Pick something large enough that it's likely larger than any internal ring buffers, but small
// enough that the test completes relatively quickly.
static const uint32_t kFramesToCheck = 42;
// Connect to the tester.
fuchsia::camera::test::IspTesterSyncPtr tester;
ASSERT_NO_FATAL_FAILURE(BindIspTester(tester));
ASSERT_TRUE(tester.is_bound());
// Request a stream.
fuchsia::camera2::StreamPtr stream;
fuchsia::sysmem::BufferCollectionInfo_2 buffers;
fuchsia::sysmem::ImageFormat_2 format;
ASSERT_EQ(tester->CreateStream(stream.NewRequest(), &buffers, &format), ZX_OK);
std::atomic_bool stream_alive = true;
stream.set_error_handler([&](zx_status_t status) {
ADD_FAILURE_AT(__FILE__, __LINE__) << "Stream disconnected: " << zx_status_get_string(status);
stream_alive = false;
});
// Populate a set of known hashes to constant-value frame data.
std::map<std::string, uint8_t> known_hashes;
{
// Try known transients 0x00 and 0xFF, as well as other likely transients near values k*2^N.
static constexpr const std::array<uint8_t, 10> kValuesToCheck{0x00, 0xFF, 0x01, 0xFE, 0x7F,
0x80, 0x3F, 0x40, 0xBF, 0xC0};
std::vector<uint8_t> known_frame(buffers.settings.buffer_settings.size_bytes);
for (size_t i = 0; i < kValuesToCheck.size(); ++i) {
auto value = kValuesToCheck[i];
std::cout << "\rCalculating hash for fixed value " << static_cast<uint32_t>(value) << " ("
<< i + 1 << "/" << kValuesToCheck.size() << ")";
std::cout.flush();
memset(known_frame.data(), value, known_frame.size());
known_hashes[Hash(known_frame.data(), known_frame.size())] = value;
}
std::cout << std::endl;
}
// Register a frame event handler.
std::map<std::string, uint32_t> frame_hashes;
std::vector<bool> buffer_owned(buffers.buffer_count, false);
std::atomic_uint32_t frames_received{0};
stream.events().OnFrameAvailable = [&](fuchsia::camera2::FrameAvailableInfo event) {
if (++frames_received > kFramesToCheck) {
// If we've reached the target number of frames, just release the frame and return.
stream->ReleaseFrame(event.buffer_id);
return;
}
// Check ownership validity of the buffer.
ASSERT_LT(event.buffer_id, buffers.buffer_count);
EXPECT_FALSE(buffer_owned[event.buffer_id])
<< "Server sent frame " << event.buffer_id << " again without the client releasing it.";
buffer_owned[event.buffer_id] = true;
// Map and hash the entire contents of the buffer.
uintptr_t mapped_addr = 0;
ASSERT_EQ(zx::vmar::root_self()->map(0, buffers.buffers[event.buffer_id].vmo, 0,
buffers.settings.buffer_settings.size_bytes,
ZX_VM_PERM_READ, &mapped_addr),
ZX_OK);
std::cout << "\rCalculating hash for frame " << frames_received << "/" << kFramesToCheck;
std::cout.flush();
auto hash =
Hash(reinterpret_cast<void*>(mapped_addr), buffers.settings.buffer_settings.size_bytes);
ASSERT_EQ(
zx::vmar::root_self()->unmap(mapped_addr, buffers.settings.buffer_settings.size_bytes),
ZX_OK);
// Verify the hash does not match a prior or known hash. Even with a static scene, thermal
// noise should prevent any perfectly identical frames. As a result, this check should only
// fail if the frames are not actually coming from the sensor, or are being recycled
// incorrectly.
auto it = known_hashes.find(hash);
if (it != known_hashes.end()) {
ADD_FAILURE_AT(__FILE__, __LINE__)
<< "Frame " << frames_received
<< " does not contain valid image data - it is just the constant byte value "
<< it->second;
} else {
auto it = frame_hashes.find(hash);
if (it == frame_hashes.end()) {
frame_hashes.emplace(hash, frames_received);
} else {
ADD_FAILURE_AT(__FILE__, __LINE__)
<< "Duplicate frame - the contents of frames " << it->second << " and "
<< frames_received << " both hash to 0x" << hash;
}
}
buffer_owned[event.buffer_id] = false;
stream->ReleaseFrame(event.buffer_id);
};
// Start the stream.
stream->Start();
// Begin the message loop, exiting when a certain number of frames are received, or the stream
// connection dies.
RunLoopUntil([&]() { return !stream_alive || frames_received >= kFramesToCheck; });
std::cout << std::endl;
ASSERT_TRUE(stream_alive);
// Stop the stream.
stream->Stop();
RunLoopUntilIdle();
}
| 38.083333
| 98
| 0.677316
|
winksaville
|
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
|
ea6f5953820a8adb5dc11604f040d6b41a602292
| 2,649
|
hpp
|
C++
|
libvast/vast/access.hpp
|
ngrodzitski/vast
|
5d114f53d51db8558f673c7f873bd92ded630bf6
|
[
"BSD-3-Clause"
] | null | null | null |
libvast/vast/access.hpp
|
ngrodzitski/vast
|
5d114f53d51db8558f673c7f873bd92ded630bf6
|
[
"BSD-3-Clause"
] | 1
|
2019-11-29T12:43:41.000Z
|
2019-11-29T12:43:41.000Z
|
libvast/vast/access.hpp
|
ngrodzitski/vast
|
5d114f53d51db8558f673c7f873bd92ded630bf6
|
[
"BSD-3-Clause"
] | null | null | null |
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include <type_traits>
namespace vast {
/// Wrapper to encapsulate the implementation of concepts requiring access to
/// private state.
struct access {
template <class, class = void>
struct state;
template <class, class = void>
struct parser;
template <class, class = void>
struct printer;
template <class, class = void>
struct converter;
};
namespace detail {
struct has_access_state {
template <class T>
static auto test(T* x) -> decltype(access::state<T>{}, std::true_type());
template <class>
static auto test(...) -> std::false_type;
};
struct has_access_parser {
template <class T>
static auto test(T* x) -> decltype(access::parser<T>{}, std::true_type());
template <class>
static auto test(...) -> std::false_type;
};
struct has_access_printer {
template <class T>
static auto test(T* x) -> decltype(access::printer<T>{}, std::true_type());
template <class>
static auto test(...) -> std::false_type;
};
struct has_access_converter {
template <class T>
static auto test(T* x) -> decltype(access::converter<T>{}, std::true_type());
template <class>
static auto test(...) -> std::false_type;
};
} // namespace detail
template <class T>
constexpr bool has_access_state_v
= decltype(detail::has_access_state::test<T>(0))::value;
template <class T>
constexpr bool has_access_parser_v
= decltype(detail::has_access_parser::test<T>(0))::value;
template <class T>
constexpr bool has_access_printer_v
= decltype(detail::has_access_printer::test<T>(0))::value;
template <class T>
constexpr bool has_access_converter_v
= decltype(detail::has_access_converter::test<T>(0))::value;
} // namespace vast
| 29.433333
| 80
| 0.563609
|
ngrodzitski
|
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
|
ea7a37cc9433bda075599a80bb98df3466fa4f70
| 5,403
|
cc
|
C++
|
xrtl/testing/diffing/diff_provider.cc
|
google/xrtl
|
8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe
|
[
"Apache-2.0"
] | 132
|
2017-03-30T03:26:57.000Z
|
2021-11-18T09:18:04.000Z
|
xrtl/testing/diffing/diff_provider.cc
|
google/xrtl
|
8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe
|
[
"Apache-2.0"
] | 36
|
2017-04-02T22:57:53.000Z
|
2018-06-27T04:20:30.000Z
|
xrtl/testing/diffing/diff_provider.cc
|
google/xrtl
|
8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe
|
[
"Apache-2.0"
] | 24
|
2017-04-09T12:48:13.000Z
|
2021-10-20T02:20:07.000Z
|
// Copyright 2017 Google Inc.
//
// 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 "xrtl/testing/diffing/diff_provider.h"
#include "absl/strings/str_join.h"
#include "xrtl/base/logging.h"
#include "xrtl/testing/file_util.h"
namespace xrtl {
namespace testing {
namespace diffing {
DiffProvider::DiffProvider() = default;
DiffProvider::~DiffProvider() = default;
bool DiffProvider::Initialize(absl::string_view golden_base_path) {
golden_base_path_ = std::string(golden_base_path);
return true;
}
bool DiffProvider::CheckIfPublishRequired(DiffPublishMode publish_mode,
DiffResult diff_result) {
// Determine if we should be publishing the result.
bool did_pass = diff_result == DiffResult::kEquivalent;
bool needs_publish = false;
switch (publish_mode) {
case DiffPublishMode::kAlways:
VLOG(1) << "Forcing publish because publish mode is kAlways";
needs_publish = true;
break;
case DiffPublishMode::kNever:
VLOG(1) << "Skipping publish because publish mode is kNever";
needs_publish = false;
break;
case DiffPublishMode::kFailure:
needs_publish = !did_pass;
break;
}
return needs_publish;
}
std::string DiffProvider::MakeGoldenFilePath(absl::string_view test_key,
absl::string_view suffix) {
std::string relative_path = FileUtil::JoinPathParts(
golden_base_path_, absl::StrJoin({test_key, suffix}, ""));
return relative_path;
}
std::string DiffProvider::ResolveGoldenOutputFilePath(
absl::string_view test_key, absl::string_view suffix) {
std::string relative_path = MakeGoldenFilePath(test_key, suffix);
return FileUtil::MakeOutputFilePath(relative_path);
}
DiffResult DiffProvider::CompareText(absl::string_view test_key,
absl::string_view text_value,
DiffPublishMode publish_mode,
TextDiffer::Options options) {
// Load reference file.
std::string golden_file_path = MakeGoldenFilePath(test_key, ".txt");
auto golden_text_buffer = FileUtil::LoadTextFile(golden_file_path);
if (!golden_text_buffer) {
LOG(ERROR) << "Unable to find reference file at " << golden_file_path;
return PublishTextResult(publish_mode, test_key, text_value, {},
DiffResult::kMissingReference);
}
// Diff the text.
auto result =
TextDiffer::DiffStrings(golden_text_buffer.value(), text_value, options);
return PublishTextResult(
publish_mode, test_key, text_value, result,
result.equivalent ? DiffResult::kEquivalent : DiffResult::kDifferent);
}
DiffResult DiffProvider::CompareData(absl::string_view test_key,
const void* data, size_t data_length,
DiffPublishMode publish_mode,
DataDiffer::Options options) {
// Load reference file.
std::string golden_file_path = MakeGoldenFilePath(test_key, ".bin");
auto golden_data_buffer = FileUtil::LoadFile(golden_file_path);
if (!golden_data_buffer) {
LOG(ERROR) << "Unable to find reference file at " << golden_file_path;
return PublishDataResult(publish_mode, test_key, data, data_length, {},
DiffResult::kMissingReference);
}
// Diff the data.
auto result = DataDiffer::DiffBuffers(golden_data_buffer.value().data(),
golden_data_buffer.value().size(), data,
data_length, options);
return PublishDataResult(
publish_mode, test_key, data, data_length, result,
result.equivalent ? DiffResult::kEquivalent : DiffResult::kDifferent);
}
DiffResult DiffProvider::CompareImage(absl::string_view test_key,
ImageBuffer* image_buffer,
DiffPublishMode publish_mode,
ImageDiffer::Options options) {
// Load reference image.
std::string golden_file_path = MakeGoldenFilePath(test_key, ".png");
auto golden_image_buffer =
ImageBuffer::Load(golden_file_path, image_buffer->channels());
if (!golden_image_buffer) {
LOG(ERROR) << "Unable to find reference file at " << golden_file_path;
return PublishImageResult(publish_mode, test_key, image_buffer, {},
DiffResult::kMissingReference);
}
// Diff the images.
auto result = ImageDiffer::DiffImageBuffers(golden_image_buffer.get(),
image_buffer, options);
return PublishImageResult(
publish_mode, test_key, image_buffer, result,
result.equivalent ? DiffResult::kEquivalent : DiffResult::kDifferent);
}
} // namespace diffing
} // namespace testing
} // namespace xrtl
| 39.727941
| 80
| 0.661484
|
google
|
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 (hazard_x@gmx.net / 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
|
ea7dd9dd3c1b7ac86e0cdb252dae94f7ac696cb1
| 311
|
cpp
|
C++
|
aql/benchmark/lib_62/class_2.cpp
|
menify/sandbox
|
32166c71044f0d5b414335b2b6559adc571f568c
|
[
"MIT"
] | null | null | null |
aql/benchmark/lib_62/class_2.cpp
|
menify/sandbox
|
32166c71044f0d5b414335b2b6559adc571f568c
|
[
"MIT"
] | null | null | null |
aql/benchmark/lib_62/class_2.cpp
|
menify/sandbox
|
32166c71044f0d5b414335b2b6559adc571f568c
|
[
"MIT"
] | null | null | null |
#include "class_2.h"
#include "class_1.h"
#include "class_3.h"
#include "class_0.h"
#include "class_4.h"
#include "class_6.h"
#include <lib_47/class_0.h>
#include <lib_1/class_6.h>
#include <lib_11/class_4.h>
#include <lib_54/class_5.h>
#include <lib_47/class_7.h>
class_2::class_2() {}
class_2::~class_2() {}
| 20.733333
| 27
| 0.713826
|
menify
|
ea80e7c266e18e5c6edc47648b5ddc46e50938b5
| 740
|
cpp
|
C++
|
1697_hide_and_seek.cpp
|
harrydrippin/baekjoon
|
4ee6b6796d9dece8860e777b38cf90c2c6b13132
|
[
"MIT"
] | null | null | null |
1697_hide_and_seek.cpp
|
harrydrippin/baekjoon
|
4ee6b6796d9dece8860e777b38cf90c2c6b13132
|
[
"MIT"
] | null | null | null |
1697_hide_and_seek.cpp
|
harrydrippin/baekjoon
|
4ee6b6796d9dece8860e777b38cf90c2c6b13132
|
[
"MIT"
] | 1
|
2020-07-25T07:41:12.000Z
|
2020-07-25T07:41:12.000Z
|
#include <iostream>
#include <queue>
using namespace std;
int main() {
int m[100001];
fill_n(m, 100001, 100002);
int n, k;
cin >> n >> k;
m[n] = 0;
queue<int> q;
q.push(n);
while (!q.empty()) {
int cur = q.front();
q.pop();
if (cur + 1 < 100001 && m[cur + 1] > m[cur] + 1) {
m[cur + 1] = m[cur] + 1;
q.push(cur + 1);
}
if (cur - 1 >= 0 && m[cur - 1] > m[cur] + 1) {
m[cur - 1] = m[cur] + 1;
q.push(cur - 1);
}
if (cur * 2 < 100001 && cur * 2 != 0 && m[cur * 2] > m[cur] + 1) {
m[cur * 2] = m[cur] + 1;
q.push(cur * 2);
}
}
cout << m[k];
return 0;
}
| 19.473684
| 74
| 0.366216
|
harrydrippin
|
ea84617d10d67475381a3078add0ceff0b390d4d
| 141
|
cpp
|
C++
|
Tutorial PNG/Tutorial PNG/DemoApp/main.cpp
|
0lidaxiang/openGL_homework
|
895620aad85d750ba9c78ea54fb4ab8bd69bf187
|
[
"MIT"
] | 1
|
2017-02-04T03:08:40.000Z
|
2017-02-04T03:08:40.000Z
|
Tutorial PNG/Tutorial PNG/DemoApp/main.cpp
|
0lidaxiang/openGL_homework
|
895620aad85d750ba9c78ea54fb4ab8bd69bf187
|
[
"MIT"
] | null | null | null |
Tutorial PNG/Tutorial PNG/DemoApp/main.cpp
|
0lidaxiang/openGL_homework
|
895620aad85d750ba9c78ea54fb4ab8bd69bf187
|
[
"MIT"
] | null | null | null |
#include "DemoApp.h"
int main(int *arg, char **argv)
{
DempApp app;
std::cout<<"Enter: Screen Shot"<<std::endl;
app.Start();
return 0;
}
| 15.666667
| 44
| 0.638298
|
0lidaxiang
|
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
|
ea881b2fdd8f30bd40268d30f48545131c5d8ad1
| 19,128
|
cpp
|
C++
|
LibCarla/source/carla/rss/RssCheck.cpp
|
youngsend/carla
|
c918f4b73b6b845dc66ccf3ffe3f011e800607ec
|
[
"MIT"
] | 103
|
2020-03-10T04:21:50.000Z
|
2022-03-29T13:26:57.000Z
|
LibCarla/source/carla/rss/RssCheck.cpp
|
630156145/carla
|
b9fbbf7fd03ee2a4f3a7baf4343a28381cfe81ef
|
[
"MIT"
] | 12
|
2020-04-11T11:36:01.000Z
|
2021-12-09T11:35:56.000Z
|
LibCarla/source/carla/rss/RssCheck.cpp
|
630156145/carla
|
b9fbbf7fd03ee2a4f3a7baf4343a28381cfe81ef
|
[
"MIT"
] | 8
|
2020-11-21T07:47:12.000Z
|
2022-03-25T13:41:05.000Z
|
// Copyright (c) 2019 Intel Corporation
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "carla/rss/RssCheck.h"
#include "carla/client/Map.h"
#include "carla/client/Vehicle.h"
#include "carla/client/Waypoint.h"
#include "carla/road/element/RoadInfoLaneWidth.h"
#include "ad_rss/core/RssResponseResolving.hpp"
#include "ad_rss/core/RssResponseTransformation.hpp"
#include "ad_rss/core/RssSituationChecking.hpp"
#include "ad_rss/core/RssSituationExtraction.hpp"
#include "ad_rss/state/RssStateOperation.hpp"
#include <algorithm>
#include <cmath>
#include <vector>
namespace carla {
namespace rss {
namespace csd = carla::sensor::data;
// constants for deg-> rad conversion PI / 180
constexpr float toRadians = static_cast<float>(M_PI) / 180.0f;
inline float calculateAngleDelta(const float angle1, const float angle2) {
float delta = angle1 - angle2;
delta -= std::floor((delta + 180.f) / 360.f) * 360.f;
return delta;
}
RssCheck::RssCheck() {
_rssSituationExtraction = std::make_shared<::ad_rss::core::RssSituationExtraction>();
_rssSituationChecking = std::make_shared<::ad_rss::core::RssSituationChecking>();
_rssResponseResolving = std::make_shared<::ad_rss::core::RssResponseResolving>();
_egoVehicleDynamics = std::make_shared<::ad_rss::world::RssDynamics>();
_otherVehicleDynamics = std::make_shared<::ad_rss::world::RssDynamics>();
::ad_rss::world::RssDynamics defaultDynamics;
defaultDynamics.alphaLon.accelMax = ::ad_rss::physics::Acceleration(3.5);
defaultDynamics.alphaLon.brakeMax = ::ad_rss::physics::Acceleration(8.);
defaultDynamics.alphaLon.brakeMin = ::ad_rss::physics::Acceleration(4.);
defaultDynamics.alphaLon.brakeMinCorrect = ::ad_rss::physics::Acceleration(3);
defaultDynamics.alphaLat.accelMax = ::ad_rss::physics::Acceleration(0.2);
defaultDynamics.alphaLat.brakeMin = ::ad_rss::physics::Acceleration(0.8);
defaultDynamics.responseTime = ::ad_rss::physics::Duration(1.);
*_egoVehicleDynamics = defaultDynamics;
*_otherVehicleDynamics = defaultDynamics;
}
RssCheck::~RssCheck() = default;
const ::ad_rss::world::RssDynamics &RssCheck::getEgoVehicleDynamics() const {
return *_egoVehicleDynamics;
}
void RssCheck::setEgoVehicleDynamics(const ::ad_rss::world::RssDynamics &dynamics) {
*_egoVehicleDynamics = dynamics;
}
const ::ad_rss::world::RssDynamics &RssCheck::getOtherVehicleDynamics() const {
return *_otherVehicleDynamics;
}
void RssCheck::setOtherVehicleDynamics(const ::ad_rss::world::RssDynamics &dynamics) {
*_otherVehicleDynamics = dynamics;
}
bool RssCheck::checkObjects(cc::Timestamp const & timestamp, cc::World &world,
carla::SharedPtr<cc::ActorList> const & vehicles,
carla::SharedPtr<cc::Actor> const & carlaEgoActor,
carla::SharedPtr<cc::Map> const & clientMap,
::ad_rss::state::ProperResponse &response,
::ad_rss::world::AccelerationRestriction &accelerationRestriction,
::ad_rss::world::Velocity &rssEgoVelocity, bool visualizeResults) {
const auto carlaEgoVehicle = boost::dynamic_pointer_cast<cc::Vehicle>(carlaEgoActor);
::ad_rss::world::WorldModel worldModel;
worldModel.timeIndex = timestamp.frame;
::ad_rss::world::Object egoVehicle;
::ad_rss::world::RssDynamics egoDynamics;
initVehicle(egoVehicle);
initEgoVehicleDynamics(egoDynamics);
egoVehicle.objectId = carlaEgoVehicle->GetId();
egoVehicle.objectType = ::ad_rss::world::ObjectType::EgoVehicle;
cg::Location egoVehicleLocation = carlaEgoVehicle->GetLocation();
auto egoClientWaypoint = clientMap->GetWaypoint(egoVehicleLocation, false);
if (egoClientWaypoint != nullptr) {
// ego vehicle is located on a lane marked for driving
auto egoWaypointLoc = egoClientWaypoint->GetTransform();
auto egoLaneId = egoClientWaypoint->GetLaneId();
auto egoVelocity = carlaEgoVehicle->GetVelocity();
auto egoVehicleTransform = carlaEgoVehicle->GetTransform();
// calculate driving direction
auto yawDiff = calculateAngleDelta(egoWaypointLoc.rotation.yaw, egoVehicleTransform.rotation.yaw);
bool drivingInLaneDirection = true;
if (std::abs(yawDiff) > 45.f) {
drivingInLaneDirection = false;
}
// calculate road direction
bool drivingInRoadDirection = (egoLaneId > 0) ^ drivingInLaneDirection;
auto &carlaRoadMap = clientMap->GetMap();
auto egoWaypoint = carlaRoadMap.GetWaypoint(egoVehicleLocation);
auto &egoLane = carlaRoadMap.GetLane(*egoWaypoint);
auto egoRoad = egoLane.GetRoad();
::ad_rss::world::RoadArea roadArea;
::ad_rss::world::RoadSegment roadSegment;
// generate road area
for (auto &laneSection : egoRoad->GetLaneSections()) {
for (const auto &pair : laneSection.GetLanes()) {
const auto &lane = pair.second;
if ((static_cast<uint32_t>(lane.GetType()) &
static_cast<uint32_t>(carla::road::Lane::LaneType::Driving)) > 0) {
::ad_rss::world::LaneSegment laneSegment;
// assumption: only one segment per road
auto laneLength = lane.GetLength();
// evaluate width at lane start
double pos = laneSection.GetDistance();
const auto lane_width_info = lane.GetInfo<carla::road::element::RoadInfoLaneWidth>(pos);
double laneWidth = 0.0;
if (lane_width_info != nullptr) {
laneWidth = lane_width_info->GetPolynomial().Evaluate(pos);
}
convertAndSetLaneSegmentId(lane, laneSegment);
if ((lane.GetId() < 0) ^ drivingInRoadDirection) {
laneSegment.drivingDirection = ::ad_rss::world::LaneDrivingDirection::Negative;
} else {
laneSegment.drivingDirection = ::ad_rss::world::LaneDrivingDirection::Positive;
}
// lane segment is assumed to be strait and evenly wide, so minimum
// and maximum length and width are set to the same values
laneSegment.length.minimum = ::ad_rss::physics::Distance(laneLength);
laneSegment.length.maximum = laneSegment.length.minimum;
laneSegment.width.minimum = ::ad_rss::physics::Distance(laneWidth);
laneSegment.width.maximum = laneSegment.width.minimum;
roadSegment.push_back(laneSegment);
}
}
std::sort(
roadSegment.begin(), roadSegment.end(),
[&drivingInRoadDirection](::ad_rss::world::LaneSegment const &f,
::ad_rss::world::LaneSegment const &s) {
return (f.id <= s.id) ^ drivingInRoadDirection;
});
roadArea.push_back(roadSegment);
}
calculateLatLonVelocities(egoWaypointLoc, egoVelocity, egoVehicle, !drivingInLaneDirection);
rssEgoVelocity = egoVehicle.velocity;
auto egoBounds = getVehicleBounds(*carlaEgoVehicle);
calculateOccupiedRegions(egoBounds, egoVehicle.occupiedRegions, carlaRoadMap, drivingInRoadDirection,
egoVehicleTransform);
for (const auto &actor : *vehicles) {
const auto vehicle = boost::dynamic_pointer_cast<cc::Vehicle>(actor);
if (vehicle == nullptr) {
continue;
}
if (vehicle->GetId() == carlaEgoVehicle->GetId()) {
continue;
}
::ad_rss::world::Object otherVehicle;
::ad_rss::world::RssDynamics otherDynamics;
initVehicle(otherVehicle);
initOtherVehicleDynamics(otherDynamics);
otherVehicle.objectId = vehicle->GetId();
otherVehicle.objectType = ::ad_rss::world::ObjectType::OtherVehicle;
auto otherVehicleLoc = vehicle->GetLocation();
auto otherVehicleClientWaypoint = clientMap->GetWaypoint(otherVehicleLoc);
// same road
if (egoClientWaypoint->GetRoadId() == otherVehicleClientWaypoint->GetRoadId()) {
auto otherVehicleTransform = vehicle->GetTransform();
auto otherBounds = getVehicleBounds(*vehicle);
auto otherWaypointLoc = otherVehicleClientWaypoint->GetTransform();
auto otherVelocity = vehicle->GetVelocity();
calculateLatLonVelocities(otherWaypointLoc, otherVelocity, otherVehicle, false);
::ad_rss::world::Scene scene;
calculateOccupiedRegions(otherBounds, otherVehicle.occupiedRegions, carlaRoadMap, drivingInRoadDirection,
otherVehicleTransform);
auto vehicleDirectionDiff =
calculateAngleDelta(otherVehicleTransform.rotation.yaw, egoVehicleTransform.rotation.yaw);
bool drivingInSameDirection = true;
if (std::abs(vehicleDirectionDiff) > 90.f) {
drivingInSameDirection = false;
}
if (drivingInSameDirection) {
scene.situationType = ad_rss::situation::SituationType::SameDirection;
} else {
scene.situationType = ad_rss::situation::SituationType::OppositeDirection;
}
scene.object = otherVehicle;
scene.objectRssDynamics = otherDynamics;
scene.egoVehicle = egoVehicle;
scene.egoVehicleRoad = roadArea;
worldModel.scenes.push_back(scene);
}
}
worldModel.egoVehicleRssDynamics = egoDynamics;
::ad_rss::situation::SituationSnapshot situationSnapshot;
bool result = _rssSituationExtraction->extractSituations(worldModel, situationSnapshot);
::ad_rss::state::RssStateSnapshot stateSnapshot;
if (result) {
result = _rssSituationChecking->checkSituations(situationSnapshot, stateSnapshot);
}
if (result) {
result = _rssResponseResolving->provideProperResponse(stateSnapshot, response);
}
if (result) {
result = ::ad_rss::core::RssResponseTransformation::transformProperResponse(worldModel, response,
accelerationRestriction);
}
if (result && visualizeResults) {
visualizeRssResults(stateSnapshot, egoVehicleLocation, egoVehicleTransform, world);
}
return result;
}
return false;
}
void RssCheck::initVehicle(::ad_rss::world::Object &vehicle) const {
vehicle.velocity.speedLon = ::ad_rss::physics::Speed(0.);
vehicle.velocity.speedLat = ::ad_rss::physics::Speed(0.);
}
void RssCheck::initEgoVehicleDynamics(::ad_rss::world::RssDynamics &egoDynamics) const {
egoDynamics = getEgoVehicleDynamics();
}
void RssCheck::initOtherVehicleDynamics(::ad_rss::world::RssDynamics &dynamics) const {
dynamics = getOtherVehicleDynamics();
}
void RssCheck::calculateLatLonVelocities(const cg::Transform &laneLocation,
const cg::Vector3D &velocity, ::ad_rss::world::Object &rssObject,
bool inverseDirection) const {
double roadDirSine = std::sin(laneLocation.rotation.yaw * toRadians);
double roadDirCosine = std::cos(laneLocation.rotation.yaw * toRadians);
double factor = 1.0;
if (inverseDirection) {
factor = -1.0;
}
rssObject.velocity.speedLon =
::ad_rss::physics::Speed(std::abs(roadDirCosine * velocity.x + roadDirSine * velocity.y));
rssObject.velocity.speedLat =
::ad_rss::physics::Speed(factor * (-1.0 * roadDirSine * velocity.x + roadDirCosine * velocity.y));
}
void RssCheck::convertAndSetLaneSegmentId(const carla::road::Lane &lane,
::ad_rss::world::LaneSegment &laneSegment) const {
uint64_t laneSegmentId = calculateLaneSegmentId(lane);
laneSegment.id = laneSegmentId;
}
// return front right, back right, back left, front left bounds
std::array<cg::Location,
4u> RssCheck::getVehicleBounds(const cc::Vehicle &vehicle) const {
const auto &box = vehicle.GetBoundingBox();
const auto &transform = vehicle.GetTransform();
const auto location = transform.location + box.location;
const auto yaw = transform.rotation.yaw * toRadians;
const float cosine = std::cos(yaw);
const float sine = std::sin(yaw);
cg::Location frontExtent{cosine *box.extent.x, sine *box.extent.x, 0.0f};
cg::Location rightExtent{-sine * box.extent.y, cosine *box.extent.y, 0.0f};
return {location + frontExtent + rightExtent, location - frontExtent + rightExtent,
location - frontExtent - rightExtent, location + frontExtent - rightExtent};
}
uint64_t RssCheck::calculateLaneSegmentId(const carla::road::Lane &lane) const {
uint64_t laneSegmentId = lane.GetRoad()->GetId();
laneSegmentId = laneSegmentId << 32;
uint32_t sectionAndLane = lane.GetLaneSection()->GetId();
sectionAndLane <<= 16;
int16_t laneId = static_cast<int16_t>(lane.GetId());
sectionAndLane |= (0xffff & (laneId + 256));
laneSegmentId |= sectionAndLane;
return laneSegmentId;
}
void RssCheck::calculateOccupiedRegions(const std::array<cg::Location, 4u> &bounds,
::ad_rss::world::OccupiedRegionVector &occupiedRegions,
const carla::road::Map &carlaRoadMap, const bool drivingInRoadDirection,
const cg::Transform &vehicleTransform) const {
bool regionValid = true;
for (const auto &bound : bounds) {
auto boundWaypoint = carlaRoadMap.GetWaypoint(bound);
if (!boundWaypoint.has_value()) {
// vehicle not entirely on road --> stop evaluation
regionValid = false;
break;
}
auto &lane = carlaRoadMap.GetLane(*boundWaypoint);
auto road = lane.GetRoad();
uint64_t laneSegmentId = calculateLaneSegmentId(carlaRoadMap.GetLane(*boundWaypoint));
auto length = road->GetLength();
auto lonPos = boundWaypoint->s;
if (!drivingInRoadDirection) {
lonPos = length - lonPos;
}
double lon = std::max(0.0, std::min(lonPos / length, 1.0));
auto waypointLocation = carlaRoadMap.ComputeTransform(*boundWaypoint);
double headingSine = std::sin(waypointLocation.rotation.yaw * toRadians);
double headingCosine = std::cos(waypointLocation.rotation.yaw * toRadians);
auto yawDelta = calculateAngleDelta(waypointLocation.rotation.yaw, vehicleTransform.rotation.yaw);
bool inLaneDirection = true;
if (std::abs(yawDelta) > 45.f) {
inLaneDirection = false;
}
auto width = carlaRoadMap.GetLaneWidth(*boundWaypoint);
double latOffset = (headingSine * (waypointLocation.location.x - bound.x) -
headingCosine * (waypointLocation.location.y - bound.y));
if (!inLaneDirection) {
latOffset *= -1.0;
}
double lat = std::max(0.0, std::min(0.5 + latOffset / width, 1.0));
// find or create occupied region
auto regionIt = std::find_if(
occupiedRegions.begin(), occupiedRegions.end(),
[laneSegmentId](const ::ad_rss::world::OccupiedRegion ®ion) {
return region.segmentId == laneSegmentId;
});
if (regionIt == occupiedRegions.end()) {
::ad_rss::world::OccupiedRegion newRegion;
newRegion.segmentId = laneSegmentId;
newRegion.lonRange.minimum = ::ad_rss::physics::ParametricValue(lon);
newRegion.lonRange.maximum = newRegion.lonRange.minimum;
newRegion.latRange.minimum = ::ad_rss::physics::ParametricValue(lat);
newRegion.latRange.maximum = newRegion.latRange.minimum;
occupiedRegions.push_back(newRegion);
} else {
::ad_rss::physics::ParametricValue const lonParam(lon);
::ad_rss::physics::ParametricValue const latParam(lat);
regionIt->lonRange.minimum = std::min(regionIt->lonRange.minimum, lonParam);
regionIt->lonRange.maximum = std::max(regionIt->lonRange.maximum, lonParam);
regionIt->latRange.minimum = std::min(regionIt->latRange.minimum, latParam);
regionIt->latRange.maximum = std::max(regionIt->latRange.maximum, latParam);
}
}
// expand regions if more than one, ordered from right to left
::ad_rss::physics::ParametricValue lonMinParam(1.0);
::ad_rss::physics::ParametricValue lonMaxParam(0.0);
for (auto ®ion : occupiedRegions) {
lonMinParam = std::min(lonMinParam, region.lonRange.minimum);
lonMaxParam = std::max(lonMaxParam, region.lonRange.maximum);
if (region != occupiedRegions.front()) {
// not the most right one, so extend lat maximum
region.latRange.maximum = ::ad_rss::physics::ParametricValue(1.0);
}
if (region != occupiedRegions.back()) {
// not the most left one, so extend lat minimum
region.latRange.minimum = ::ad_rss::physics::ParametricValue(0.0);
}
}
for (auto ®ion : occupiedRegions) {
region.lonRange.minimum = lonMinParam;
region.lonRange.maximum = lonMaxParam;
}
}
void RssCheck::visualizeRssResults(::ad_rss::state::RssStateSnapshot stateSnapshot,
const cg::Location &egoVehicleLocation,
const cg::Transform &egoVehicleTransform,
cc::World &world) const {
cc::DebugHelper dh = world.MakeDebugHelper();
for (std::size_t i = 0; i < stateSnapshot.individualResponses.size(); ++i) {
::ad_rss::state::RssState &state = stateSnapshot.individualResponses[i];
carla::rpc::ActorId vehicleId = static_cast<carla::rpc::ActorId>(state.objectId);
carla::SharedPtr<cc::ActorList> vehicleList =
world.GetActors(std::vector<carla::rpc::ActorId>{vehicleId});
cg::Location egoPoint = egoVehicleLocation;
egoPoint.z += 0.05f;
const auto yaw = egoVehicleTransform.rotation.yaw;
const float cosine = std::cos(yaw * toRadians);
const float sine = std::sin(yaw * toRadians);
cg::Location lineOffset{-sine * 0.1f, cosine * 0.1f, 0.0f};
for (const auto &actor : *vehicleList) {
const auto vehicle = boost::dynamic_pointer_cast<cc::Vehicle>(actor);
cg::Location point = vehicle->GetLocation();
point.z += 0.05f;
csd::Color lonColor{0u, 255u, 0u};
csd::Color latLColor = lonColor;
csd::Color latRColor = lonColor;
csd::Color indicatorColor = lonColor;
bool dangerous = ::ad_rss::state::isDangerous(state);
if (dangerous) {
indicatorColor = csd::Color{255u, 0u, 0u};
}
if (!state.longitudinalState.isSafe) {
lonColor.r = 255u;
if (dangerous) {
lonColor.g = 0u;
} else {
lonColor.g = 255u;
}
}
if (!state.lateralStateLeft.isSafe) {
latLColor.r = 255u;
if (dangerous) {
latLColor.g = 0u;
} else {
latLColor.g = 255u;
}
}
if (!state.lateralStateRight.isSafe) {
latRColor.r = 255u;
if (dangerous) {
latRColor.g = 0u;
} else {
latRColor.g = 255u;
}
}
dh.DrawLine(egoPoint, point, 0.1f, lonColor, 0.02f, false);
dh.DrawLine(egoPoint - lineOffset, point - lineOffset, 0.1f, latLColor, 0.02f, false);
dh.DrawLine(egoPoint + lineOffset, point + lineOffset, 0.1f, latRColor, 0.02f, false);
point.z += 3.f;
dh.DrawPoint(point, 0.2f, indicatorColor, 0.02f, false);
}
}
}
} // namespace rss
} // namespace carla
| 41.04721
| 115
| 0.672261
|
youngsend
|
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
|
ea88af00d49222b327902c88695f517acf477c1c
| 956
|
cpp
|
C++
|
SDIDoc.cpp
|
chrisoldwood/WCL
|
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
|
[
"MIT"
] | 5
|
2017-10-02T04:10:35.000Z
|
2021-07-26T04:45:35.000Z
|
SDIDoc.cpp
|
chrisoldwood/WCL
|
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
|
[
"MIT"
] | null | null | null |
SDIDoc.cpp
|
chrisoldwood/WCL
|
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
|
[
"MIT"
] | null | null | null |
/******************************************************************************
** (C) Chris Oldwood
**
** MODULE: SDIDOC.CPP
** COMPONENT: Windows C++ Library.
** DESCRIPTION: CSDIDoc class definition.
**
*******************************************************************************
*/
#include "Common.hpp"
#include "SDIDoc.hpp"
/******************************************************************************
** Method: Constructor.
**
** Description: .
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
CSDIDoc::CSDIDoc()
: m_pView(nullptr)
{
}
/******************************************************************************
** Method: Destructor.
**
** Description: .
**
** Parameters: None.
**
** Returns: Nothing.
**
*******************************************************************************
*/
CSDIDoc::~CSDIDoc()
{
ASSERT(m_pView == nullptr);
}
| 20.340426
| 79
| 0.303347
|
chrisoldwood
|
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
|
ea942c5357bd877b134b4d92e147782588e3f3c6
| 5,051
|
cpp
|
C++
|
source/smeardeformer/SmearHistory.cpp
|
youdiaozi/c4d-nr-toolbox
|
ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6
|
[
"BSD-3-Clause"
] | 16
|
2018-09-12T10:38:26.000Z
|
2021-06-28T22:57:30.000Z
|
source/smeardeformer/SmearHistory.cpp
|
youdiaozi/c4d-nr-toolbox
|
ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6
|
[
"BSD-3-Clause"
] | 10
|
2018-09-11T17:20:09.000Z
|
2020-06-02T04:11:01.000Z
|
source/smeardeformer/SmearHistory.cpp
|
NiklasRosenstein/c4d-nr-toolbox
|
28197ea7fcf396b5941277b049168d7faf00bfbf
|
[
"BSD-3-Clause"
] | 6
|
2018-11-30T23:34:49.000Z
|
2021-04-02T15:03:23.000Z
|
/**
* Copyright (C) 2013, Niklas Rosenstein
* All rights reserved.
*
* SmearHistory.cpp
*/
#include "SmearHistory.h"
#include "nrUtils/Memory.h"
#include "nrUtils/Normals.h"
using namespace nr::memory;
Bool SmearState::Resize(Int32 count) {
Bool success = true;
success = success && Realloc<Vector>(original_vertices, count);
success = success && Realloc<Vector>(original_normals, count);
success = success && Realloc<Vector>(deformed_vertices, count);
success = success && Realloc<Vector>(deformed_normals, count);
success = success && Realloc<Float32>(weights, count);
vertex_count = count;
initialized = success;
return success;
}
void SmearState::Flush() {
Free(original_vertices);
Free(original_normals);
Free(deformed_vertices);
Free(deformed_normals);
vertex_count = 0;
initialized = false;
}
SmearSession* SmearHistory::NewSession(Int32 max_history_count, Bool fake_session) {
if (max_history_count < 1) max_history_count = 1;
m_level_override = -1;
SmearState state;
SmearState* ptr = nullptr;
if (!fake_session || GetHistoryCount() <= 0) {
fake_session = false;
// Remove all superfluos history elements. One item is implicit.
while (m_states.GetCount() > max_history_count) {
if (state.initialized) state.Flush();
m_states.Pop(&state);
}
iferr (auto&& r = m_states.Insert(0, std::move(state)))
return nullptr;
ptr = &r;
}
else {
m_level_override = max_history_count + 1;
ptr = &m_states[0];
}
if (ptr) {
return NewObjClear(SmearSession, this, ptr, fake_session);
}
return nullptr; // memory error
}
SmearHistory::~SmearHistory() {
Reset();
}
void SmearHistory::FreeSession(SmearSession*& session) {
// If the session was not updated (ie. all data is stored
// successfully), we remove the state which has been created for
// that sessions.
if (!session->IsUpToDate()) {
GePrint(String(__FUNCTION__) + ": Smear state is not up to date.");
m_states.Pop(0);
}
DeleteMem(session);
session = nullptr;
}
Int32 SmearHistory::GetHistoryCount() const {
Int32 count = m_states.GetCount();
if (m_level_override > 0 && count > m_level_override) {
count = m_level_override + 1;
}
return count;
}
const SmearState* SmearHistory::GetState(Int32 index) const {
if (index < 0 || index >= GetHistoryCount()) {
return nullptr;
}
if (m_level_override > 0 && index >= m_level_override) {
return nullptr;
}
if (!m_enabled && index != 0) {
return nullptr;
}
return &m_states[index];
}
void SmearHistory::Reset() {
StateArray::Iterator it = m_states.Begin();
for (; it != m_states.End(); it++) {
it->Flush();
}
m_states.Flush();
}
SmearSession::SmearSession(SmearHistory* history, SmearState* state, Bool fake)
: m_state(state), m_created(false), m_updated(false),
m_vertices(nullptr), m_vertex_count(0), m_faces(nullptr), m_face_count(0),
m_fake(fake) {
}
SmearSession::~SmearSession() {
}
Bool SmearSession::CreateState(
const Matrix& mg,
const Vector* vertices, Int32 vertex_count,
const CPolygon* faces, Int32 face_count) {
if (m_created) {
return false;
}
m_vertices = vertices;
m_vertex_count = vertex_count;
m_faces = faces;
m_face_count = face_count;
if (!m_fake) {
m_state->mg = mg;
if (!m_state->Resize(vertex_count)) {
return false;
}
// Copy the vertices to the storage in the SmearState.
for (Int32 i=0; i < vertex_count; i++) {
m_state->original_vertices[i] = m_state->mg * vertices[i];
}
// And compute the vertex normals. These are independent from
// the global position of the vertices as long as their relations
// are the same.
if (!nr::ComputeVertexNormals(
m_vertices, m_vertex_count, m_faces,
m_face_count, m_state->original_normals)) {
return false;
}
}
m_created = true;
return true;
}
Bool SmearSession::DeformationComplete(const Matrix& mg) {
if (!m_created || m_updated) {
GePrint(String(__FUNCTION__) + ": Not yet created or already updated.");
return false;
}
// m_state->mg = mg;
// Copy the vertices to the deformed storage in the SmearState
// using the pointers passed to `CreateState()`.
for (Int32 i=0; i < m_vertex_count; i++) {
m_state->deformed_vertices[i] = /* m_state-> */ mg * m_vertices[i];
}
// And calculate the vertex normals of the deformed points.
if (!nr::ComputeVertexNormals(
m_vertices, m_vertex_count, m_faces,
m_face_count, m_state->deformed_normals)) {
GePrint(String(__FUNCTION__) + ": Vertex normals not calculated.");
return false;
}
m_updated = true;
return true;
}
| 27.302703
| 84
| 0.627005
|
youdiaozi
|
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
|
ea9ade0c56314e1bfda94a363688fb429a691edd
| 10,578
|
cc
|
C++
|
centreon-engine/src/configuration/hostextinfo.cc
|
centreon/centreon-collect
|
e63fc4d888a120d588a93169e7d36b360616bdee
|
[
"Unlicense"
] | 8
|
2020-07-26T09:12:02.000Z
|
2022-03-30T17:24:29.000Z
|
centreon-engine/src/configuration/hostextinfo.cc
|
centreon/centreon-collect
|
e63fc4d888a120d588a93169e7d36b360616bdee
|
[
"Unlicense"
] | 47
|
2020-06-18T12:11:37.000Z
|
2022-03-16T10:28:56.000Z
|
centreon-engine/src/configuration/hostextinfo.cc
|
centreon/centreon-collect
|
e63fc4d888a120d588a93169e7d36b360616bdee
|
[
"Unlicense"
] | 5
|
2020-06-29T14:22:02.000Z
|
2022-03-17T10:34:10.000Z
|
/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include "com/centreon/engine/configuration/hostextinfo.hh"
#include "com/centreon/engine/exceptions/error.hh"
#include "com/centreon/engine/string.hh"
using namespace com::centreon;
using namespace com::centreon::engine::configuration;
#define SETTER(type, method) \
&object::setter<hostextinfo, type, &hostextinfo::method>::generic
std::unordered_map<std::string, hostextinfo::setter_func> const
hostextinfo::_setters{
{"host_name", SETTER(std::string const&, _set_hosts)},
{"hostgroup", SETTER(std::string const&, _set_hostgroups)},
{"hostgroup_name", SETTER(std::string const&, _set_hostgroups)},
{"notes", SETTER(std::string const&, _set_notes)},
{"notes_url", SETTER(std::string const&, _set_notes_url)},
{"action_url", SETTER(std::string const&, _set_action_url)},
{"icon_image", SETTER(std::string const&, _set_icon_image)},
{"icon_image_alt", SETTER(std::string const&, _set_icon_image_alt)},
{"vrml_image", SETTER(std::string const&, _set_vrml_image)},
{"gd2_image", SETTER(std::string const&, _set_statusmap_image)},
{"statusmap_image", SETTER(std::string const&, _set_statusmap_image)},
{"2d_coords", SETTER(std::string const&, _set_coords_2d)},
{"3d_coords", SETTER(std::string const&, _set_coords_3d)}};
// Default values.
static point_2d const default_coords_2d(-1, -1);
static point_3d const default_coords_3d(0.0, 0.0, 0.0);
/**
* Default constructor.
*/
hostextinfo::hostextinfo()
: object(object::hostextinfo),
_coords_2d(default_coords_2d),
_coords_3d(default_coords_3d) {}
/**
* Copy constructor.
*
* @param[in] right The hostextinfo to copy.
*/
hostextinfo::hostextinfo(hostextinfo const& right) : object(right) {
operator=(right);
}
/**
* Destructor.
*/
hostextinfo::~hostextinfo() throw() {}
/**
* Copy constructor.
*
* @param[in] right The hostextinfo to copy.
*
* @return This hostextinfo.
*/
hostextinfo& hostextinfo::operator=(hostextinfo const& right) {
if (this != &right) {
object::operator=(right);
_action_url = right._action_url;
_coords_2d = right._coords_2d;
_coords_3d = right._coords_3d;
_hostgroups = right._hostgroups;
_hosts = right._hosts;
_icon_image = right._icon_image;
_icon_image_alt = right._icon_image_alt;
_notes = right._notes;
_notes_url = right._notes_url;
_statusmap_image = right._statusmap_image;
_vrml_image = right._vrml_image;
}
return *this;
}
/**
* Equal operator.
*
* @param[in] right The hostextinfo to compare.
*
* @return True if is the same hostextinfo, otherwise false.
*/
bool hostextinfo::operator==(hostextinfo const& right) const throw() {
return (object::operator==(right) && _action_url == right._action_url &&
_coords_2d == right._coords_2d && _coords_3d == right._coords_3d &&
_hostgroups == right._hostgroups && _hosts == right._hosts &&
_icon_image == right._icon_image &&
_icon_image_alt == right._icon_image_alt && _notes == right._notes &&
_notes_url == right._notes_url &&
_statusmap_image == right._statusmap_image &&
_vrml_image == right._vrml_image);
}
/**
* Equal operator.
*
* @param[in] right The hostextinfo to compare.
*
* @return True if is not the same hostextinfo, otherwise false.
*/
bool hostextinfo::operator!=(hostextinfo const& right) const throw() {
return !operator==(right);
}
/**
* @brief Check if the object is valid.
*
* If the object is not valid, an exception is thrown.
*/
void hostextinfo::check_validity() const {
if (_hostgroups->empty() && _hosts->empty())
throw(engine_error()
<< "Host extended information is not attached"
<< " to any host or host group (properties 'host_name' or "
<< "'hostgroup_name', respectively)");
return;
}
/**
* Merge object.
*
* @param[in] obj The object to merge.
*/
void hostextinfo::merge(object const& obj) {
if (obj.type() != _type)
throw(engine_error() << "Cannot merge host extended information with '"
<< obj.type() << "'");
hostextinfo const& tmpl(static_cast<hostextinfo const&>(obj));
MRG_DEFAULT(_action_url);
MRG_OPTION(_coords_2d);
MRG_OPTION(_coords_3d);
MRG_INHERIT(_hostgroups);
MRG_INHERIT(_hosts);
MRG_DEFAULT(_icon_image);
MRG_DEFAULT(_icon_image_alt);
MRG_DEFAULT(_notes);
MRG_DEFAULT(_notes_url);
MRG_DEFAULT(_statusmap_image);
MRG_DEFAULT(_vrml_image);
}
/**
* Parse and set the hostextinfo property.
*
* @param[in] key The property name.
* @param[in] value The property value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::parse(char const* key, char const* value) {
std::unordered_map<std::string, hostextinfo::setter_func>::const_iterator it{
_setters.find(key)};
if (it != _setters.end())
return (it->second)(*this, value);
return false;
}
/**
* Get action_url.
*
* @return The action_url.
*/
std::string const& hostextinfo::action_url() const throw() {
return _action_url;
}
/**
* Get coords_2d.
*
* @return The coords_2d.
*/
point_2d const& hostextinfo::coords_2d() const throw() {
return _coords_2d.get();
}
/**
* Get 3d_coords.
*
* @return The 3d_coords.
*/
point_3d const& hostextinfo::coords_3d() const throw() {
return _coords_3d.get();
}
/**
* Get hostgroups.
*
* @return The hostgroups.
*/
set_string const& hostextinfo::hostgroups() const throw() {
return *_hostgroups;
}
/**
* Get hosts.
*
* @return The hosts.
*/
set_string const& hostextinfo::hosts() const throw() {
return *_hosts;
}
/**
* Get icon_image.
*
* @return The icon_image.
*/
std::string const& hostextinfo::icon_image() const throw() {
return _icon_image;
}
/**
* Get icon_image_alt.
*
* @return The icon_image_alt.
*/
std::string const& hostextinfo::icon_image_alt() const throw() {
return _icon_image_alt;
}
/**
* Get notes.
*
* @return The notes.
*/
std::string const& hostextinfo::notes() const throw() {
return _notes;
}
/**
* Get notes_url.
*
* @return The notes_url.
*/
std::string const& hostextinfo::notes_url() const throw() {
return _notes_url;
}
/**
* Get statusmap_image.
*
* @return The statusmap_image.
*/
std::string const& hostextinfo::statusmap_image() const throw() {
return _statusmap_image;
}
/**
* Get vrml_image.
*
* @return The vrml_image.
*/
std::string const& hostextinfo::vrml_image() const throw() {
return _vrml_image;
}
/**
* Set action_url value.
*
* @param[in] value The new action_url value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_action_url(std::string const& value) {
_action_url = value;
return true;
}
/**
* Set coords_2s value.
*
* @param[in] value The new coords_2d value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_coords_2d(std::string const& value) {
std::list<std::string> coords;
string::split(value, coords, ',');
if (coords.size() != 2)
return false;
int x;
if (!string::to(string::trim(coords.front()).c_str(), x))
return false;
coords.pop_front();
int y;
if (!string::to(string::trim(coords.front()).c_str(), y))
return false;
_coords_2d = point_2d(x, y);
return true;
}
/**
* Set coords_3d value.
*
* @param[in] value The new coords_3d value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_coords_3d(std::string const& value) {
std::list<std::string> coords;
string::split(value, coords, ',');
if (coords.size() != 3)
return false;
double x;
if (!string::to(string::trim(coords.front()).c_str(), x))
return false;
coords.pop_front();
double y;
if (!string::to(string::trim(coords.front()).c_str(), y))
return false;
coords.pop_front();
double z;
if (!string::to(string::trim(coords.front()).c_str(), z))
return false;
_coords_3d = point_3d(x, y, z);
return true;
}
/**
* Set hostgroups value.
*
* @param[in] value The new hostgroups value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_hostgroups(std::string const& value) {
_hostgroups = value;
return true;
}
/**
* Set hosts value.
*
* @param[in] value The new hosts value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_hosts(std::string const& value) {
_hosts = value;
return true;
}
/**
* Set icon_image value.
*
* @param[in] value The new icon_image value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_icon_image(std::string const& value) {
_icon_image = value;
return true;
}
/**
* Set icon_image_alt value.
*
* @param[in] value The new icon_image_alt value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_icon_image_alt(std::string const& value) {
_icon_image_alt = value;
return true;
}
/**
* Set notes value.
*
* @param[in] value The new notes value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_notes(std::string const& value) {
_notes = value;
return true;
}
/**
* Set notes_url value.
*
* @param[in] value The new notes_url value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_notes_url(std::string const& value) {
_notes_url = value;
return true;
}
/**
* Set statusmap_image value.
*
* @param[in] value The new statusmap_image value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_statusmap_image(std::string const& value) {
_statusmap_image = value;
return true;
}
/**
* Set vrml_image value.
*
* @param[in] value The new vrml_image value.
*
* @return True on success, otherwise false.
*/
bool hostextinfo::_set_vrml_image(std::string const& value) {
_vrml_image = value;
return true;
}
| 23.878104
| 79
| 0.668179
|
centreon
|
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
|
eaad671f1b22cc1c7ff643fabefdcc78702fd9d4
| 852
|
cpp
|
C++
|
codeforces/354/C/test.cpp
|
rdragos/work
|
aed4c9ace3fad6b0c63caadee69de2abde108b40
|
[
"MIT"
] | 2
|
2020-05-30T17:11:47.000Z
|
2021-09-25T08:16:48.000Z
|
codeforces/354/C/test.cpp
|
rdragos/work
|
aed4c9ace3fad6b0c63caadee69de2abde108b40
|
[
"MIT"
] | null | null | null |
codeforces/354/C/test.cpp
|
rdragos/work
|
aed4c9ace3fad6b0c63caadee69de2abde108b40
|
[
"MIT"
] | 1
|
2021-09-24T11:14:27.000Z
|
2021-09-24T11:14:27.000Z
|
#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define ll long long
using namespace std;
int main() {
/*
ifstream cin("test.in");
ofstream cout("test.out");
*/
int N, K; cin >> N >> K;
string S; cin >> S;
int answer = 0;
vector <char> sel{'a', 'b'};
for (auto x: sel) {
queue <int> Q;
int cur_begin = 0;
for (int i = 0; i < N; ++i) {
if (S[i] != x) {
Q.push(i);
}
while(Q.size() > K) {
int el = Q.front();
Q.pop();
cur_begin = el + 1;
}
answer = max(answer, i - cur_begin + 1);
}
}
cout << answer << "\n";
return 0;
}
| 16.384615
| 46
| 0.539906
|
rdragos
|