hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
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
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
900bec79bda00185ffaccaf6ed5f5ac0b79c3355
| 618
|
hpp
|
C++
|
include/Analyzer.hpp
|
pinxau1000/Simple-Buffer-Analyzer
|
7df52a5a6f557ba7ec95f7a8d0e32b2338b012c2
|
[
"MIT"
] | null | null | null |
include/Analyzer.hpp
|
pinxau1000/Simple-Buffer-Analyzer
|
7df52a5a6f557ba7ec95f7a8d0e32b2338b012c2
|
[
"MIT"
] | null | null | null |
include/Analyzer.hpp
|
pinxau1000/Simple-Buffer-Analyzer
|
7df52a5a6f557ba7ec95f7a8d0e32b2338b012c2
|
[
"MIT"
] | null | null | null |
//
// Created by pinxau1000 on 12/07/21.
//
#ifndef MAIN_ANALYZER_HPP
#define MAIN_ANALYZER_HPP
#include <iostream>
#include <exception>
#include <vector>
#include <string>
#include <cmath>
#include <ctime>
#include "Buffer.hpp"
#include "Bitstream.hpp"
#include "Definitions.hpp"
Buffer analyze(std::string arg_csv_file, double arg_bit_rate, double arg_buffer_length, double arg_init_buffer_length = 0,
int arg_fps = 0, std::string arg_unit = "b", std::string arg_generate_csv = "",
std::string arg_generate_plot = "", int arg_verbose = VERBOSE_STANDARD);
#endif //MAIN_ANALYZER_HPP
| 26.869565
| 122
| 0.721683
|
pinxau1000
|
900befff6025f7b5c413a811831768e78c2d4a0c
| 168
|
hpp
|
C++
|
src/EventHandler.hpp
|
tblyons/goon
|
fd5fbdda14fe1b4869e365c7cebec2bcb7de06e3
|
[
"Unlicense"
] | 1
|
2021-03-14T01:27:42.000Z
|
2021-03-14T01:27:42.000Z
|
apps/Goon/src/EventHandler.hpp
|
tybl/tybl
|
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
|
[
"Unlicense"
] | 15
|
2021-08-21T13:41:29.000Z
|
2022-03-08T14:13:43.000Z
|
apps/Goon/src/EventHandler.hpp
|
tybl/tybl
|
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
|
[
"Unlicense"
] | null | null | null |
// License: The Unlicense (https://unlicense.org)
#ifndef GOON_EVENTHANDLER_HPP
#define GOON_EVENTHANDLER_HPP
void SetUpEvents(void);
#endif // GOON_EVENTHANDLER_HPP
| 21
| 49
| 0.803571
|
tblyons
|
90144adc4e684ba0b37255dcb76a4200d471c0ad
| 3,114
|
cpp
|
C++
|
src/set_fen.cpp
|
dave7895/libchess
|
f32d66249830c0cb2c378121dcca473c49b17e3e
|
[
"MIT"
] | null | null | null |
src/set_fen.cpp
|
dave7895/libchess
|
f32d66249830c0cb2c378121dcca473c49b17e3e
|
[
"MIT"
] | null | null | null |
src/set_fen.cpp
|
dave7895/libchess
|
f32d66249830c0cb2c378121dcca473c49b17e3e
|
[
"MIT"
] | 2
|
2022-02-15T15:19:55.000Z
|
2022-02-21T22:54:13.000Z
|
#include <cassert>
#include <sstream>
#include "libchess/position.hpp"
namespace libchess {
void Position::set_fen(const std::string &fen) noexcept {
if (fen == "startpos") {
set_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
return;
}
clear();
std::stringstream ss{fen};
std::string word;
ss >> word;
int i = 56;
for (const auto &c : word) {
switch (c) {
case 'P':
set(Square(i), Side::White, Piece::Pawn);
i++;
break;
case 'p':
set(Square(i), Side::Black, Piece::Pawn);
i++;
break;
case 'N':
set(Square(i), Side::White, Piece::Knight);
i++;
break;
case 'n':
set(Square(i), Side::Black, Piece::Knight);
i++;
break;
case 'B':
set(Square(i), Side::White, Piece::Bishop);
i++;
break;
case 'b':
set(Square(i), Side::Black, Piece::Bishop);
i++;
break;
case 'R':
set(Square(i), Side::White, Piece::Rook);
i++;
break;
case 'r':
set(Square(i), Side::Black, Piece::Rook);
i++;
break;
case 'Q':
set(Square(i), Side::White, Piece::Queen);
i++;
break;
case 'q':
set(Square(i), Side::Black, Piece::Queen);
i++;
break;
case 'K':
set(Square(i), Side::White, Piece::King);
i++;
break;
case 'k':
set(Square(i), Side::Black, Piece::King);
i++;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
i += c - '1' + 1;
break;
case '/':
i -= 16;
break;
default:
break;
}
}
// Side to move
ss >> word;
if (word == "w") {
to_move_ = Side::White;
} else {
to_move_ = Side::Black;
}
// Castling perms
ss >> word;
for (const auto &c : word) {
if (c == 'K') {
castling_[0] = true;
} else if (c == 'Q') {
castling_[1] = true;
} else if (c == 'k') {
castling_[2] = true;
} else if (c == 'q') {
castling_[3] = true;
}
}
// En passant
ss >> word;
if (word != "-") {
ep_ = Square(word);
}
// Halfmove clock
ss >> halfmove_clock_;
// Fullmove clock
ss >> fullmove_clock_;
// Calculate hash
#ifdef NO_HASH
hash_ = 0;
#else
hash_ = calculate_hash();
#endif
assert(valid());
}
} // namespace libchess
| 23.413534
| 76
| 0.376044
|
dave7895
|
901a35832d897d880e5cd9bbfdd6b38dd7fe5609
| 4,263
|
cpp
|
C++
|
src/LongVector.cpp
|
TheReincarnator/glaziery
|
f688943163b73cea7034e929539fff8aa39d63e5
|
[
"MIT"
] | null | null | null |
src/LongVector.cpp
|
TheReincarnator/glaziery
|
f688943163b73cea7034e929539fff8aa39d63e5
|
[
"MIT"
] | null | null | null |
src/LongVector.cpp
|
TheReincarnator/glaziery
|
f688943163b73cea7034e929539fff8aa39d63e5
|
[
"MIT"
] | null | null | null |
/*
* This file is part of the Glaziery.
* Copyright Thomas Jacob.
*
* READ README.TXT BEFORE USE!!
*/
// Main header file
#include <Glaziery/src/Headers.h>
LongVector::LongVector() : x(0), y(0)
{
ASSERTION_COBJECT(this);
}
LongVector::LongVector(long x, long y) : x(x), y(y)
{
ASSERTION_COBJECT(this);
}
LongVector::LongVector(const LongVector & vector) : x(vector.x), y(vector.y)
{
ASSERTION_COBJECT(this);
}
LongVector::LongVector(const Vector & vector) : x(vector.x), y(vector.y)
{
ASSERTION_COBJECT(this);
}
LongVector LongVector::operator +() const
{
ASSERTION_COBJECT(this);
return LongVector(*this);
}
LongVector LongVector::operator +(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return LongVector(x + vector.x, y + vector.y);
}
void LongVector::operator +=(const LongVector & vector)
{
ASSERTION_COBJECT(this);
x += vector.x;
y += vector.y;
}
LongVector LongVector::operator -() const
{
ASSERTION_COBJECT(this);
return LongVector(-x, -y);
}
LongVector LongVector::operator -(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return LongVector(x - vector.x, y - vector.y);
}
void LongVector::operator -=(const LongVector & vector)
{
ASSERTION_COBJECT(this);
x -= vector.x;
y -= vector.y;
}
LongVector LongVector::operator *(long scale) const
{
ASSERTION_COBJECT(this);
return LongVector(x * scale, y * scale);
}
LongVector LongVector::operator *(double scale) const
{
ASSERTION_COBJECT(this);
return LongVector((long) (x * scale + 0.5), (long) (y * scale + 0.5));
}
void LongVector::operator *=(long scale)
{
ASSERTION_COBJECT(this);
x *= scale;
y *= scale;
}
void LongVector::operator *=(double scale)
{
ASSERTION_COBJECT(this);
x = (long) (x * scale + 0.5);
y = (long) (y * scale + 0.5);
}
LongVector LongVector::operator /(long scale) const
{
ASSERTION_COBJECT(this);
return LongVector(x / scale, y / scale);
}
LongVector LongVector::operator /(double scale) const
{
ASSERTION_COBJECT(this);
return LongVector((long) (x / scale + 0.5), (long) (y / scale + 0.5));
}
void LongVector::operator /=(long scale)
{
ASSERTION_COBJECT(this);
x /= scale;
y /= scale;
}
void LongVector::operator /=(double scale)
{
ASSERTION_COBJECT(this);
x = (long) (x / scale + 0.5);
y = (long) (y / scale + 0.5);
}
void LongVector::operator =(const LongVector & vector)
{
ASSERTION_COBJECT(this);
x = vector.x;
y = vector.y;
}
bool LongVector::operator ==(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x == vector.x && y == vector.y;
}
bool LongVector::operator !=(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x != vector.x || y != vector.y;
}
bool LongVector::operator >(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x > vector.x && y > vector.y;
}
bool LongVector::operator >=(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x >= vector.x && y >= vector.y;
}
bool LongVector::operator <(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x < vector.x && y < vector.y;
}
bool LongVector::operator <=(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x <= vector.x && y <= vector.y;
}
LongVector LongVector::absolute() const
{
ASSERTION_COBJECT(this);
return LongVector(abs(x), abs(y));
}
bool LongVector::constrain(LongVector from, LongVector to)
{
ASSERTION_COBJECT(this);
if (from.x > to.x)
{
long buffer = from.x;
from.x = to.x;
to.x = buffer;
}
if (from.y > to.y)
{
long buffer = from.y;
from.y = to.y;
to.y = buffer;
}
bool changed = false;
if (x > to.x)
{
x = to.x;
changed = true;
}
if (y > to.y)
{
y = to.y;
changed = true;
}
if (x < from.x)
{
x = from.x;
changed = true;
}
if (y < from.y)
{
y = from.y;
changed = true;
}
return changed;
}
double LongVector::getLength()
{
ASSERTION_COBJECT(this);
return sqrt((double) (x*x + y*y));
}
#if defined(_DEBUG) && (defined(_AFX) || defined(_AFXDLL))
IMPLEMENT_DYNAMIC(LongVector, CObject);
#endif
bool LongVector::isZero() const
{
ASSERTION_COBJECT(this);
return x == 0 && y == 0;
}
String LongVector::toString()
{
ASSERTION_COBJECT(this);
String string;
string.Format("LongVector(%d,%d)", x, y);
return string;
}
| 17.052
| 76
| 0.665259
|
TheReincarnator
|
901dc2e6bc4b2cef7f026b31d38a488172ce7c11
| 12,444
|
cpp
|
C++
|
Source/Core/Visualization/Renderer/StochasticRenderingCompositor.cpp
|
GoTamura/KVS
|
121ede0b9b81da56e9ea698a45ccfd71ff64ed41
|
[
"BSD-3-Clause"
] | null | null | null |
Source/Core/Visualization/Renderer/StochasticRenderingCompositor.cpp
|
GoTamura/KVS
|
121ede0b9b81da56e9ea698a45ccfd71ff64ed41
|
[
"BSD-3-Clause"
] | null | null | null |
Source/Core/Visualization/Renderer/StochasticRenderingCompositor.cpp
|
GoTamura/KVS
|
121ede0b9b81da56e9ea698a45ccfd71ff64ed41
|
[
"BSD-3-Clause"
] | null | null | null |
/*****************************************************************************/
/**
* @file StochasticRenderingCompositor.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "StochasticRenderingCompositor.h"
#include <kvs/Assert>
#include <kvs/OpenGL>
#include <kvs/PaintEvent>
#include <kvs/EventHandler>
#include <kvs/ScreenBase>
#include <kvs/Scene>
#include <kvs/Camera>
#include <kvs/Light>
#include <kvs/Background>
#include <kvs/ObjectManager>
#include <kvs/RendererManager>
#include <kvs/IDManager>
#include "StochasticRendererBase.h"
#include "ParticleBasedRenderer.h"
namespace kvs
{
/*===========================================================================*/
/**
* @brief Constructs a new StochasticRenderingCompositor class.
* @param scene [in] pointer to the scene
*/
/*===========================================================================*/
StochasticRenderingCompositor::StochasticRenderingCompositor( kvs::Scene* scene ):
m_scene( scene ),
m_width( 0 ),
m_height( 0 ),
m_repetition_level( 1 ),
m_coarse_level( 1 ),
m_enable_lod( false ),
m_enable_refinement( false )
{
}
/*===========================================================================*/
/**
* @brief Updates the scene.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::update()
{
KVS_ASSERT( m_scene );
kvs::OpenGL::WithPushedMatrix p( GL_MODELVIEW );
p.loadIdentity();
{
m_scene->updateGLProjectionMatrix();
m_scene->updateGLViewingMatrix();
m_scene->updateGLLightParameters();
m_scene->background()->apply();
if ( m_scene->objectManager()->hasObject() )
{
this->draw();
}
else
{
m_scene->updateGLModelingMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Draws the objects with stochastic renderers.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::draw()
{
m_timer.start();
kvs::OpenGL::WithPushedAttrib p( GL_ALL_ATTRIB_BITS );
this->check_window_created();
this->check_window_resized();
this->check_object_changed();
// LOD control.
size_t repetitions = m_repetition_level;
kvs::Vec3 camera_position = m_scene->camera()->position();
kvs::Vec3 light_position = m_scene->light()->position();
kvs::Mat4 object_xform = this->object_xform();
if ( m_camera_position != camera_position ||
m_light_position != light_position ||
m_object_xform != object_xform )
{
if ( m_enable_lod )
{
repetitions = m_coarse_level;
}
m_camera_position = camera_position;
m_light_position = light_position;
m_object_xform = object_xform;
m_ensemble_buffer.clear();
}
// Setup engine.
this->engines_setup();
// Ensemble rendering.
const bool reset_count = !m_enable_refinement;
if ( reset_count ) m_ensemble_buffer.clear();
for ( size_t i = 0; i < repetitions; i++ )
{
m_ensemble_buffer.bind();
this->engines_draw();
m_ensemble_buffer.unbind();
m_ensemble_buffer.add();
}
m_ensemble_buffer.draw();
kvs::OpenGL::Finish();
m_timer.stop();
}
/*===========================================================================*/
/**
* @brief Check whether the window is created and initialize the parameters.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::check_window_created()
{
const bool window_created = m_width == 0 && m_height == 0;
if ( window_created )
{
const size_t width = m_scene->camera()->windowWidth();
const size_t height = m_scene->camera()->windowHeight();
m_width = width;
m_height = height;
m_ensemble_buffer.create( width, height );
m_ensemble_buffer.clear();
m_object_xform = this->object_xform();
m_camera_position = m_scene->camera()->position();
m_light_position = m_scene->light()->position();
this->engines_create();
}
}
/*===========================================================================*/
/**
* @brief Check whether the window is resized and update the parameters.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::check_window_resized()
{
const size_t width = m_scene->camera()->windowWidth();
const size_t height = m_scene->camera()->windowHeight();
const bool window_resized = m_width != width || m_height != height;
if ( window_resized )
{
m_width = width;
m_height = height;
m_ensemble_buffer.release();
m_ensemble_buffer.create( width, height );
m_ensemble_buffer.clear();
this->engines_update();
}
}
/*===========================================================================*/
/**
* @brief Check whether the object is changed and recreated the engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::check_object_changed()
{
typedef kvs::StochasticRendererBase Renderer;
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
const bool object_changed = stochastic_renderer->engine().object() != object;
if ( object_changed )
{
m_ensemble_buffer.clear();
if ( stochastic_renderer->engine().object() ) stochastic_renderer->engine().release();
stochastic_renderer->engine().setDepthTexture( m_ensemble_buffer.currentDepthTexture() );
stochastic_renderer->engine().setShader( &stochastic_renderer->shader() );
stochastic_renderer->engine().setRepetitionLevel( m_repetition_level );
stochastic_renderer->engine().setEnabledShading( stochastic_renderer->isEnabledShading() );
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().create( object, m_scene->camera(), m_scene->light() );
kvs::OpenGL::PopMatrix();
}
}
}
}
/*===========================================================================*/
/**
* @brief Returns the xform matrix of the active object.
* @return xform matrix
*/
/*===========================================================================*/
kvs::Mat4 StochasticRenderingCompositor::object_xform()
{
return m_scene->objectManager()->hasActiveObject() ?
m_scene->objectManager()->activeObject()->xform().toMatrix() :
m_scene->objectManager()->xform().toMatrix();
}
/*===========================================================================*/
/**
* @brief Calls the create method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_create()
{
typedef kvs::StochasticRendererBase Renderer;
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
stochastic_renderer->engine().setDepthTexture( m_ensemble_buffer.currentDepthTexture() );
stochastic_renderer->engine().setShader( &stochastic_renderer->shader() );
stochastic_renderer->engine().setRepetitionLevel( m_repetition_level );
stochastic_renderer->engine().setEnabledShading( stochastic_renderer->isEnabledShading() );
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().create( object, m_scene->camera(), m_scene->light() );
kvs::OpenGL::PopMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Calls the update method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_update()
{
typedef kvs::StochasticRendererBase Renderer;
kvs::Camera* camera = m_scene->camera();
kvs::Light* light = m_scene->light();
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().update( object, camera, light );
kvs::OpenGL::PopMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Calls the setup method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_setup()
{
typedef kvs::StochasticRendererBase Renderer;
kvs::Camera* camera = m_scene->camera();
kvs::Light* light = m_scene->light();
const bool reset_count = !m_enable_refinement;
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
if ( reset_count ) stochastic_renderer->engine().resetRepetitions();
stochastic_renderer->engine().setup( object, camera, light );
kvs::OpenGL::PopMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Calls the draw method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_draw()
{
typedef kvs::StochasticRendererBase Renderer;
kvs::Camera* camera = m_scene->camera();
kvs::Light* light = m_scene->light();
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
if ( object->isShown() )
{
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().draw( object, camera, light );
stochastic_renderer->engine().countRepetitions();
kvs::OpenGL::PopMatrix();
}
}
}
}
} // end of namespace kvs
| 35.758621
| 107
| 0.530698
|
GoTamura
|
901f216b738ef752e13af09fd49db08fcdc3d643
| 19,363
|
cpp
|
C++
|
test/unit/stack/intrusive_fcstack.cpp
|
Nemo1369/libcds
|
6c96ab635067b2018b14afe5dd0251b9af3ffddf
|
[
"BSD-2-Clause"
] | null | null | null |
test/unit/stack/intrusive_fcstack.cpp
|
Nemo1369/libcds
|
6c96ab635067b2018b14afe5dd0251b9af3ffddf
|
[
"BSD-2-Clause"
] | 1
|
2017-11-12T06:43:27.000Z
|
2017-11-12T06:43:27.000Z
|
test/unit/stack/intrusive_fcstack.cpp
|
Nemo1369/libcds
|
6c96ab635067b2018b14afe5dd0251b9af3ffddf
|
[
"BSD-2-Clause"
] | 2
|
2020-10-01T04:12:27.000Z
|
2021-07-01T07:46:19.000Z
|
/*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cds_test/ext_gtest.h>
#include <cds/intrusive/fcstack.h>
#include <boost/intrusive/list.hpp>
namespace {
class IntrusiveFCStack : public ::testing::Test
{
protected:
template <typename Hook>
struct base_hook_item : public Hook
{
int nVal;
int nDisposeCount;
base_hook_item()
: nDisposeCount( 0 )
{}
};
template <typename Hook>
struct member_hook_item
{
int nVal;
int nDisposeCount;
Hook hMember;
member_hook_item()
: nDisposeCount( 0 )
{}
};
struct mock_disposer
{
template <typename T>
void operator ()( T * p )
{
++p->nDisposeCount;
}
};
template <class Stack>
void test()
{
typedef typename Stack::value_type value_type;
Stack stack;
ASSERT_TRUE( stack.empty());
value_type v1, v2, v3;
v1.nVal = 1;
v2.nVal = 2;
v3.nVal = 3;
ASSERT_TRUE( stack.push( v1 ));
ASSERT_TRUE( !stack.empty());
ASSERT_TRUE( stack.push( v2 ));
ASSERT_TRUE( !stack.empty());
ASSERT_TRUE( stack.push( v3 ));
ASSERT_TRUE( !stack.empty());
value_type * pv;
pv = stack.pop();
ASSERT_TRUE( pv != nullptr );
ASSERT_EQ( pv->nVal, 3 );
ASSERT_TRUE( !stack.empty());
pv = stack.pop();
ASSERT_TRUE( pv != nullptr );
ASSERT_EQ( pv->nVal, 2 );
ASSERT_TRUE( !stack.empty());
pv = stack.pop();
ASSERT_TRUE( pv != nullptr );
ASSERT_EQ( pv->nVal, 1 );
ASSERT_TRUE( stack.empty());
pv = stack.pop();
ASSERT_TRUE( pv == nullptr );
ASSERT_TRUE( stack.empty());
if ( !std::is_same<typename Stack::disposer, cds::intrusive::opt::v::empty_disposer>::value ) {
int v1disp = v1.nDisposeCount;
int v2disp = v2.nDisposeCount;
int v3disp = v3.nDisposeCount;
ASSERT_TRUE( stack.push( v1 ));
ASSERT_TRUE( stack.push( v2 ));
ASSERT_TRUE( stack.push( v3 ));
stack.clear();
ASSERT_TRUE( stack.empty());
EXPECT_EQ( v1.nDisposeCount, v1disp);
EXPECT_EQ( v2.nDisposeCount, v2disp);
EXPECT_EQ( v3.nDisposeCount, v3disp);
ASSERT_TRUE( stack.push( v1 ));
ASSERT_TRUE( stack.push( v2 ));
ASSERT_TRUE( stack.push( v3 ));
ASSERT_TRUE( !stack.empty());
stack.clear( true );
ASSERT_TRUE( stack.empty());
EXPECT_EQ( v1.nDisposeCount, v1disp + 1 );
EXPECT_EQ( v2.nDisposeCount, v2disp + 1 );
EXPECT_EQ( v3.nDisposeCount, v3disp + 1 );
}
}
};
TEST_F( IntrusiveFCStack, slist )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_empty_wait_strategy )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::empty wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_single_condvar )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_multi_condvar )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_multi_mutex_multi_condvar )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_single_condvar_2ms )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<2> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_multi_condvar_3ms )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<3> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_multi_mutex_multi_condvar_2ms )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<2> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_disposer )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public cds::intrusive::fcstack::traits
{
typedef mock_disposer disposer;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_mutex )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public cds::intrusive::fcstack::traits
{
typedef std::mutex lock_type;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_elimination )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public
cds::intrusive::fcstack::make_traits <
cds::opt::enable_elimination < true >
> ::type
{};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_elimination_disposer )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public
cds::intrusive::fcstack::make_traits <
cds::opt::enable_elimination < true >,
cds::intrusive::opt::disposer< mock_disposer >,
cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
> ::type
{};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_elimination_stat )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_empty_wait_strategy )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::empty wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_single_mutex_single_condvar )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_single_mutex_multi_condvar )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_multi_mutex_multi_condvar )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_disposer )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits : public cds::intrusive::fcstack::traits
{
typedef mock_disposer disposer;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_elimination )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_elimination_stat )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_mutex )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::lock_type< std::mutex >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_elimination )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_elimination_stat )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_member )
{
typedef member_hook_item< boost::intrusive::list_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::list_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type, member_option > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_member_elimination )
{
typedef member_hook_item< boost::intrusive::list_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::list_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_member_elimination_stat )
{
typedef member_hook_item< boost::intrusive::list_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::list_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
} // namespace
| 41.462527
| 133
| 0.644063
|
Nemo1369
|
9025836f7f09dec7a6699cfa2840b3256db101c9
| 27,997
|
cpp
|
C++
|
src/cellgrid.cpp
|
machinelevel/bens-game
|
e265d9a045426e71c86585503566e3572372f5a7
|
[
"MIT"
] | null | null | null |
src/cellgrid.cpp
|
machinelevel/bens-game
|
e265d9a045426e71c86585503566e3572372f5a7
|
[
"MIT"
] | null | null | null |
src/cellgrid.cpp
|
machinelevel/bens-game
|
e265d9a045426e71c86585503566e3572372f5a7
|
[
"MIT"
] | null | null | null |
/************************************************************\
cellgrid.cpp
Files for controlling the grid of cells in Ben's project
\************************************************************/
#include <stdio.h>
#include <stdint.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/gl.h>
#include <string.h>
#include "genincludes.h"
#include "upmath.h"
#include "camera.h"
#include "controls.h"
#include "timer.h"
#include "random.h"
#include "cellgrid.h"
#include "cellport.h"
#include "glider.h"
#include "texture.h"
#include "hud.h"
#include "slides.h"
#include "sound.h"
#include "wallmaps.h"
CellGrid *gCells = NULL;
const float hexContract = 0.866f; /**** sqrt(3)/2 ****/
float gHalfPipeRadius = 10.0f;
int gSizzleCycle = 0;
CellGrid::CellGrid(int32 hSize, int32 vSize)
{
hSize = vSize = 80;
mLifeUpdateTimer = 0.0f;
mLifeUpdateTimeInterval = 0.1f;
mLifeUpdateTimeInterval = 0.5f;
mHSize = hSize;
mVSize = vSize;
mCellSize = 2.0f;
mNumCells = hSize * vSize;
mCells = new OneCell[mNumCells];
pfSetVec3(mCenter, 0.0f, 0.0f, 0.0f);
Clear();
mNumWalls = 0;
}
void CellGrid::Clear(void)
{
extern int32 gBadHistorySamples;
int32 i;
gBadHistorySamples = 0;
for (i = 0; i < mNumCells; i++) {
mCells[i].shift = 0;
mCells[i].flags = 0;
mCells[i].goodTimer = 0;
}
}
#define MAP_WD 39
#define MAP_HT 19
void CellGrid::DrawBackdrop(void)
{
int i;
pfVec4 hue;
static float ctime[3] = {0,0,0};
float cfreq[3] = {0.01f,0.02f,0.03f};
float sval, cval;
float hSize = 200.0f;
float vSize = 200.0f;
for (i = 0; i < 3; i++) {
ctime[i] += 360.0f * DeltaTime * cfreq[i];
if (ctime[i] > 360.0f) ctime[i] -= 360.0f;
pfSinCos(ctime[i], &sval, &cval);
hue[i] = (sval+1.0f)*0.15f;
}
hue[3] = 1.0f;
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glDepthMask(false);
glBegin(GL_TRIANGLE_STRIP);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, vSize);
glColor4fv(hue); glVertex3f(-hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, hSize, vSize);
glColor4fv(hue); glVertex3f(-hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, -hSize, vSize);
glColor4fv(hue); glVertex3f( hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, -hSize, vSize);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, vSize);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, -vSize);
glColor4fv(hue); glVertex3f(-hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, hSize, -vSize);
glColor4fv(hue); glVertex3f(-hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, -hSize, -vSize);
glColor4fv(hue); glVertex3f( hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, -hSize, -vSize);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, -vSize);
glEnd();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glDepthMask(true);
}
void CellGrid::SetupWalls(void)
{
char map[MAP_HT*MAP_WD+1], tag;
int32 i, j, wall = 0;
float xsize = 70, ysize = 60, x1, y1, x2, y2;
float xscale = xsize / (MAP_WD / 2);
float yscale = ysize / (MAP_HT / 2);
bool found;
int mapID;
mapID = 7 * gDifficultySetting;
mapID += gLevels[gCurrentLevel].mLevelNumber;
strcpy(map, gWallMaps[mapID]);
for (i = 0; i < MAP_HT*MAP_WD; i++) {
tag = map[i];
found = false;
if (tag != '.' && tag != '=' && tag != '|') {
for (j = i+1; j < MAP_HT*MAP_WD && !found; j++) {
if (map[j] == tag) {
x1 = ((i % MAP_WD) - (MAP_WD / 2)) * xscale;
y1 = ((i / MAP_WD) - (MAP_HT / 2)) * yscale;
x2 = ((j % MAP_WD) - (MAP_WD / 2)) * xscale;
y2 = ((j / MAP_WD) - (MAP_HT / 2)) * yscale;
pfSetVec3(mWalls[wall][0], x1, y1, 0);
pfSetVec3(mWalls[wall][1], x2, y2, 0);
wall++;
//map[i] = map[j] = '.';
found = true;
}
}
}
}
mNumWalls = wall;
}
void CellGrid::DrawWalls(void)
{
int32 i;
pfVec4 hue;
float *f1, *f2;
float zmin = 0.1f, zmax = 2.0f;
static float ttimer = 0.0f, toff = 0.0f;
float toffset1, toffset2;
float stretch;
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
UseLibTexture(TEXID_ZAP);
ttimer += 20.0f * DeltaTime;
if (ttimer > 1.0f) {
ttimer -= 1.0f;
toff += 0.25f;
if (toff >= 1.0f) toff = 0.0f;
}
glBegin(GL_QUADS);
for (i = 0; i < mNumWalls; i++) {
stretch = RANDOM_IN_RANGE(-2.0f, 1.0f);
toffset1 = toff;
toffset2 = toff + 0.25f;
f1 = (float*)mWalls[i][0];
f2 = (float*)mWalls[i][1];
// PFCOPY_VEC4(hue, healthFillColor[mWallTypes[i]]);
PFSET_VEC4(hue, 1.0f, 1.0f, 1.0f, 1.0f);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(0.0f, toffset1);
glVertex3f(f1[PF_X], f1[PF_Y], zmin - stretch);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(0.0f, toffset2);
glVertex3f(f1[PF_X], f1[PF_Y], zmax + stretch);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(1.0f, toffset2);
glVertex3f(f2[PF_X], f2[PF_Y], zmax + stretch);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(1.0f, toffset1);
glVertex3f(f2[PF_X], f2[PF_Y], zmin - stretch);
}
glEnd();
glDisable(GL_TEXTURE_2D);
glBegin(GL_LINES);
for (i = 0; i < mNumWalls; i++) {
f1 = (float*)mWalls[i][0];
f2 = (float*)mWalls[i][1];
PFSET_VEC4(hue, 1.0f, 1.0f, 1.0f, 1.0f);
glColor4fv(hue);
glVertex3f(f1[PF_X], f1[PF_Y], zmin);
glVertex3f(f1[PF_X], f1[PF_Y], zmax);
glVertex3f(f2[PF_X], f2[PF_Y], zmax);
glVertex3f(f2[PF_X], f2[PF_Y], zmin);
}
glEnd();
}
void CellGrid::DrawHalfPipe(void)
{
int32 i;
pfVec4 hue = {1.0f, 1.0f, 1.0f, 0.5f};
float up, out, angle, sval, cval;
float lineAngle = 5.0f;
float xmin, xmax;
float ymin, ymax;
float zmin = 0.0f;
float u1 = 30.0f, v1 = 1.0f;
float lastUp, lastOut;
GetBounds(&xmin, &xmax, &ymin, &ymax);
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glDisable(GL_DEPTH_TEST);
glDepthMask(false);
UseLibTexture(TEXID_GRID);
for (angle = 0.0f; angle <= 90.0f; angle += lineAngle) {
pfSinCos(angle, &sval, &cval);
up = gHalfPipeRadius * (1.0f - cval);
out = gHalfPipeRadius * sval;
if (angle > 0.0f) {
glColor4fv(hue);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(xmin - out, ymin - out, zmin + up);
glTexCoord2f(0.0f, v1);
glVertex3f(xmin - lastOut, ymin - lastOut, zmin + lastUp);
glTexCoord2f(u1, 0.0f);
glVertex3f(xmax + out, ymin - out, zmin + up);
glTexCoord2f(u1, v1);
glVertex3f(xmax + lastOut, ymin - lastOut, zmin + lastUp);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(xmax + out, ymax + out, zmin + up);
glTexCoord2f(0.0f, v1);
glVertex3f(xmax + lastOut, ymax + lastOut, zmin + lastUp);
glTexCoord2f(u1, 0.0f);
glVertex3f(xmin - out, ymax + out, zmin + up);
glTexCoord2f(u1, v1);
glVertex3f(xmin - lastOut, ymax + lastOut, zmin + lastUp);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(xmin - out, ymin - out, zmin + up);
glTexCoord2f(0.0f, v1);
glVertex3f(xmin - lastOut, ymin - lastOut, zmin + lastUp);
glEnd();
}
lastUp = up;
lastOut = out;
}
glDepthMask(true);
}
void CellGrid::DrawCorners(void)
{
int32 i;
pfVec4 hue;
float *f1, *f2;
float xmin, xmax;
float ymin, ymax;
float zmin = 0.0f, zmax = 8.0f;
float x, y;
float close = 10.0f, dist;
float width = 2.0f;
static bool strobe = true;
strobe = !strobe;
glDisable(GL_CULL_FACE);
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
UseLibTexture(TEXID_ZAP);
GetBounds(&xmin, &xmax, &ymin, &ymax);
glBegin(GL_TRIANGLES);
// gx = gGlider->mMatrix[PF_T][PF_X];
// gy = gGlider->mMatrix[PF_T][PF_Y];
x = xmin;
y = ymin;
PFCOPY_VEC4(hue, healthFillColor[HEALTH_TYPE_ATTITUDE]);
hue[3] = 1.0f;
glColor4fv(hue);
glVertex3f(x, y, zmin);
hue[3] = 0.0f;
// dist = (x-gx)*(x-gx)+(y-gy)*(y-gy);
// if (dist < close*close) {
// gHealthLevel[HEALTH_TYPE_ATTITUDE] = 1.0f;
// hue[3] = 0.25f;
// }
glColor4fv(hue);
glVertex3f(x-width, y+width, zmax);
glVertex3f(x+width, y-width, zmax);
x = xmax;
y = ymin;
PFCOPY_VEC4(hue, healthFillColor[HEALTH_TYPE_HEALTH]);
hue[3] = 1.0f;
glColor4fv(hue);
glVertex3f(x, y, zmin);
hue[3] = 0.0f;
// dist = (x-gx)*(x-gx)+(y-gy)*(y-gy);
// if (dist < close*close) {
// gHealthLevel[HEALTH_TYPE_HEALTH] = 1.0f;
// hue[3] = 0.25f;
// }
glColor4fv(hue);
glVertex3f(x+width, y+width, zmax);
glVertex3f(x-width, y-width, zmax);
x = xmin;
y = ymax;
PFCOPY_VEC4(hue, healthFillColor[HEALTH_TYPE_AMMO]);
hue[3] = 1.0f;
glColor4fv(hue);
glVertex3f(x, y, zmin);
hue[3] = 0.0f;
// dist = (x-gx)*(x-gx)+(y-gy)*(y-gy);
// if (dist < close*close) {
// gHealthLevel[HEALTH_TYPE_AMMO] = 1.0f;
// hue[3] = 0.25f;
// }
glColor4fv(hue);
glVertex3f(x-width, y-width, zmax);
glVertex3f(x+width, y+width, zmax);
glEnd();
}
void CellGrid::Mutate(void)
{
int32 h, v;
OneCell *pcell;
for (v = 1; v < mVSize - 1; v++) {
for (h = 1; h < mHSize - 1; h++) {
pcell = &(mCells[h + (v * mHSize)]);
if (RANDOM0TO1 < 0.05f) SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
}
}
OneCell *CellGrid::GetHVCell(int32 h, int32 v, int32 *pIndex)
{
int32 index;
if (pIndex) *pIndex = -1;
if (h < 0 || h >= mHSize) return(NULL);
if (v < 0 || v >= mVSize) return(NULL);
index = (v * mHSize) + h;
if (pIndex) *pIndex = index;
return(mCells + index);
}
/**********************************************************\
CellGrid::GetClosestIndex
Given a position, return a pointer to the closest cell.
Also, fill pRow and pCol, for convenience, if they're
not NULL.
\**********************************************************/
OneCell *CellGrid::GetClosestCell(pfVec3 pos, int32 *pCol, int32 *pRow, int32 *pIndex)
{
float frow, fcol;
int32 row, col, index;
OneCell *pcell;
pfVec3 v;
pfSubVec3(v, pos, mCenter);
frow = ( v[PF_Y] / (mCellSize * hexContract)) + (mVSize / 2);
fcol = ( v[PF_X] / mCellSize) + (mHSize / 2);
frow += 0.5f;
fcol += 0.5f;
row = (int32)frow;
if (row & 1) fcol -= 0.5f;
col = (int32)fcol;
if (row < 0) row = 0;
if (col < 0) col = 0;
if (row > mVSize-1) row = mVSize-1;
if (col > mHSize-1) col = mHSize-1;
index = col + (mHSize * row);
pcell = &(mCells[index]);
if (pRow) *pRow = row;
if (pCol) *pCol = col;
if (pIndex) *pIndex = index;
return(pcell);
}
bool CellGrid::KillCellsInRange(pfVec3 center, int32 range, int32 flags)
{
bool retval = false;
int32 h, v, hc, vc, ic;
OneCell *pcell, *pcell2;
/**** Infect the nearby cells ****/
pcell = gCells->GetClosestCell(center, &hc, &vc, &ic);
if (pcell) {
for (v = vc - range; v <= vc + range; v++) {
for (h = hc - range; h <= hc + range; h++) {
pcell2 = gCells->GetHVCell(h, v, &ic);
if (pcell2) {
if (pcell2->shift & (CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT)) {
retval = true;
SETFLAG(pcell2->flags, CELL_FLAG_SHOT);
CLRFLAG(pcell2->shift, CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT);
}
}
}
}
}
return(retval);
}
void CellGrid::GetBounds(float *pXMin, float *pXMax, float *pYMin, float *pYMax)
{
if (pXMin) *pXMin = mCenter[PF_X] - (mCellSize * mHSize * 0.5f);
if (pXMax) *pXMax = mCenter[PF_X] + (mCellSize * mHSize * 0.5f);
if (pYMin) *pYMin = mCenter[PF_Y] - (mCellSize * mHSize * 0.5f * hexContract);
if (pYMax) *pYMax = mCenter[PF_Y] + (mCellSize * mHSize * 0.5f * hexContract);
}
void CellGrid::GetPosFromIndex(int32 index, pfVec3 dest)
{
int32 h, v;
float fieldH = mHSize * mCellSize;
float fieldV = mVSize * mCellSize * hexContract;
h = index % mHSize;
v = index / mHSize;
pfCopyVec3(dest, mCenter);
dest[PF_X] -= fieldH * 0.5f;
dest[PF_Y] -= fieldV * 0.5f;
// dest[PF_X] += x * mCellSize;
// dest[PF_Y] += y * mCellSize * hexContract;
if (1) { //hex grid
pfSetVec3(dest, dest[PF_X] + (h * mCellSize), dest[PF_Y] + (v * mCellSize * hexContract), dest[PF_Z]);
if (v & 1) dest[PF_X] += mCellSize * 0.5f;
} else { //rect grid
pfSetVec3(dest, dest[PF_X] + (h * mCellSize), dest[PF_Y] + (v * mCellSize), dest[PF_Z]);
}
}
void CellGrid::Think(void)
{
if (KeysDown['1']) mLifeUpdateTimeInterval += DeltaTime * 1.0f;
if (KeysDown['2']) mLifeUpdateTimeInterval -= DeltaTime * 1.0f;
if (mLifeUpdateTimeInterval < 0.05f) mLifeUpdateTimeInterval = 0.05f;
if (mLifeUpdateTimeInterval > 10.0f) mLifeUpdateTimeInterval = 10.0f;
LifeUpdate();
}
CellGrid::~CellGrid()
{
if (mCells) {
delete[] mCells;
mCells = NULL;
}
}
void CellGrid::Draw(void)
{
int32 h, v;
uint8 shift, flags;
pfVec3 pos, cpos, vertex, toCam, up, over;
OneCell *pcell;
float t, alt, alt1, alt2;
float *c1, *c2;
pfVec4 color, mix1, mix2;
pfVec4 hueGood = {0.0f, 1.0f, 1.0f, 1.0f};
pfVec4 hueDarkGood = {0.0f, 0.7f, 0.7f, 1.0f};
pfVec4 hueCancer = {1.0f, 0.0f, 0.0f, 1.0f};
pfVec4 hueHealthy = {1.0f, 1.0f, 1.0f, 0.2f};
pfVec4 hueDark = {0.7f, 0.0f, 0.0f, 1.0f};
pfVec4 hueBack = {0.3f, 0.3f, 0.8f, 1.0f};
// pfVec4 hueDark = {1.0f, 1.0f, 1.0f, 0.5f};
pfVec4 BhueCancer = {1.0f, 0.3f, 0.0f, 0.4f};
pfVec4 BhueHealthy = {1.0f, 1.0f, 1.0f, 0.0f};
pfVec4 BhueDark = {0.7f, 0.0f, 0.0f, 0.2f};
float bright;
float fieldH = mHSize * mCellSize;
float fieldV = mVSize * mCellSize * hexContract;
float sval, cval;
static float waveTime = 0.0f;
// int32 hClose, vClose, iClose;
pfVec3 camPos, posClose;
pfCopyVec3(camPos, GlobalCameraMatrix[PF_T]);
// GetClosestCell(gGlider->mMatrix[PF_T], &hClose, &vClose, &iClose);
// GetPosFromIndex(iClose, posClose);
waveTime += 0.1f * DeltaTime;
if (waveTime > 1.0f) waveTime -= 1.0f;
pfCopyVec3(pos, mCenter);
pos[PF_X] -= fieldH * 0.5f;
pos[PF_Y] -= fieldV * 0.5f;
pcell = mCells;
t = mLifeUpdateTimer / mLifeUpdateTimeInterval;
if (t < 0.0f) t = 0.0f;
if (t > 1.0f) t = 1.0f;
if (1) {
/**** draw the underlay ****/
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDepthMask(true);
glColor4fv(hueBack);
glBegin(GL_QUADS);
glVertex3f(mCenter[PF_X] - (0.5f * fieldH), mCenter[PF_Y] - (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glVertex3f(mCenter[PF_X] + (0.5f * fieldH), mCenter[PF_Y] - (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glVertex3f(mCenter[PF_X] + (0.5f * fieldH), mCenter[PF_Y] + (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glVertex3f(mCenter[PF_X] - (0.5f * fieldH), mCenter[PF_Y] + (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glEnd();
}
DrawCorners();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glDepthMask(true);
UseLibTexture(TEXID_CELL);
glBegin(GL_QUADS);
for (v = 0; v < mVSize; v++) {
pfSinCos((360.0f * waveTime) + (720.0f * (float)v/(float)mVSize), &sval, &cval);
if (!gOptionWaves) sval = cval = 0.0f;
for (h = 0; h < mHSize; h++) {
shift = pcell->shift;
flags = pcell->flags;
if (1) { //hex grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize * hexContract), pos[PF_Z]);
if (v & 1) cpos[PF_X] += mCellSize * 0.5f;
} else { //rect grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize), pos[PF_Z]);
}
cpos[PF_Z] += 0.6f * sval;
// if (h == hClose && v == vClose) {
// cpos[PF_Z] += 1.0f;
// }
#if 1
/******************\
L N
000 h-h
001 h-c
010 c-d
011 c-c
100 d-h
101 d-c
110 c-d
111 c-c
\******************/
// if (flags & CELL_FLAG_GOOD) {
// switch (shift & 0x07) {
// case 0: c1 = hueHealthy; c2 = hueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
// case 1: c1 = hueHealthy; c2 = hueGood; alt1 = 0.0f; alt2 = 1.0f; break;
// case 2: c1 = hueGood; c2 = hueDarkGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 3: c1 = hueGood; c2 = hueGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 4: c1 = hueDarkGood; c2 = hueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
// case 5: c1 = hueDarkGood; c2 = hueGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 6: c1 = hueGood; c2 = hueDarkGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 7: c1 = hueGood; c2 = hueGood; alt1 = 1.0f; alt2 = 1.0f; break;
// default: c1 = c2 = hueHealthy; break;
// }
// } else {
switch (shift & 0x07) {
case 0: c1 = hueHealthy; c2 = hueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
case 1: c1 = hueHealthy; c2 = hueCancer; alt1 = 0.0f; alt2 = 1.0f; break;
case 2: c1 = hueCancer; c2 = hueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 3: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 4: c1 = hueDark; c2 = hueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
case 5: c1 = hueDark; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 6: c1 = hueCancer; c2 = hueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 7: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
default: c1 = c2 = hueHealthy; break;
}
// }
#else
/******************\
L N
000 h-h
001 h-c
010 c-h
011 c-c
100 h-h
101 h-c
110 c-h
111 c-c
\******************/
switch (shift & 0x07) {
case 0: c1 = hueHealthy; c2 = hueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
case 1: c1 = hueHealthy; c2 = hueCancer; alt1 = 0.0f; alt2 = 1.0f; break;
case 2: c1 = hueCancer; c2 = hueHealthy; alt1 = 1.0f; alt2 = 1.0f; break;
case 3: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 4: c1 = hueHealthy; c2 = hueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
case 5: c1 = hueHealthy; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 6: c1 = hueCancer; c2 = hueHealthy; alt1 = 1.0f; alt2 = 1.0f; break;
case 7: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
default: c1 = c2 = hueHealthy; break;
}
#endif
/**** move bad cells up for a cool effect ****/
alt = ((1.0f - t) * alt1) + (t * alt2);
cpos[PF_Z] += alt;
pfScaleVec4(mix1, 1.0f - t, c1);
pfScaleVec4(mix2, t, c2);
PFADD_VEC4(color, mix1, mix2);
color[3] += 0.1f * sval;
if (color[3] < 0.0f) color[3] = 0.0f;
if (color[3] > 1.0f) color[3] = 1.0f;
if (gCells->mTotalBadCells == 0) {
if (RANDOM0TO1 < 0.005f) {
pfSetVec4(color, 1.0f, 1.0f, 1.0f, 1.0f);
}
}
if (flags & CELL_FLAG_BOSS) {
bright = RANDOM_IN_RANGE(0.4f, 0.5f);
color[0] = bright;
color[1] = color[2] = bright * 0.5f;
color[3] = 1.0f;
}
if (flags & CELL_FLAG_GOOD) {
float f = pcell->goodTimer;
if (f > 1.0f) f = 1.0f;
pfScaleVec4(mix1, 1.0f - f, color);
pfScaleVec4(mix2, f, hueGood);
PFADD_VEC4(color, mix1, mix2);
}
if (flags & CELL_FLAG_SHOT) {
bright = RANDOM_IN_RANGE(0.7f, 1.0f);
color[0] = color[1] = color[2] = bright;
color[3] = 1.0f;
}
glColor4fv(color);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(cpos[PF_X]-(0.5f*mCellSize), cpos[PF_Y]-(0.5f*mCellSize), cpos[PF_Z]);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(cpos[PF_X]+(0.5f*mCellSize), cpos[PF_Y]-(0.5f*mCellSize), cpos[PF_Z]);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(cpos[PF_X]+(0.5f*mCellSize), cpos[PF_Y]+(0.5f*mCellSize), cpos[PF_Z]);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(cpos[PF_X]-(0.5f*mCellSize), cpos[PF_Y]+(0.5f*mCellSize), cpos[PF_Z]);
pcell++;
}
}
glEnd();
if (1) {
/**** Draw the bubbles ****/
pcell = mCells;
glEnable(GL_DEPTH_TEST);
glDepthMask(false);
UseLibTexture(TEXID_BUBBLE);
glBegin(GL_QUADS);
for (v = 0; v < mVSize; v++) {
pfSinCos((360.0f * waveTime) + (720.0f * (float)v/(float)mVSize), &sval, &cval);
for (h = 0; h < mHSize; h++) {
shift = pcell->shift;
flags = pcell->flags;
if (/*(shift & 7) || */(flags & (CELL_FLAG_SHOT|CELL_FLAG_BOUNCE))) { /**** Only if cancer ****/
if (1) { //hex grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize * hexContract), pos[PF_Z]);
if (v & 1) cpos[PF_X] += mCellSize * 0.5f;
} else { //rect grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize), pos[PF_Z]);
}
cpos[PF_Z] += 0.3f * sval;
// cpos[PF_Z] += 0.25f * mCellSize;
switch (shift & 0x07) {
case 0: c1 = BhueHealthy; c2 = BhueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
case 1: c1 = BhueHealthy; c2 = BhueCancer; alt1 = 0.0f; alt2 = 1.0f; break;
case 2: c1 = BhueCancer; c2 = BhueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 3: c1 = BhueCancer; c2 = BhueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 4: c1 = BhueDark; c2 = BhueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
case 5: c1 = BhueDark; c2 = BhueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 6: c1 = BhueCancer; c2 = BhueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 7: c1 = BhueCancer; c2 = BhueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
default: c1 = c2 = BhueHealthy; break;
}
/**** move bad cells up for a cool effect ****/
alt = ((1.0f - t) * alt1) + (t * alt2);
cpos[PF_Z] += alt;
pfScaleVec4(mix1, 1.0f - t, c1);
pfScaleVec4(mix2, t, c2);
PFADD_VEC4(color, mix1, mix2);
color[3] += 0.1f * sval;
if (color[3] < 0.0f) color[3] = 0.0f;
if (color[3] > 1.0f) color[3] = 1.0f;
// pfSetVec4(color, 1.0f, 1.0f, 1.0f, 0.5f);
if (flags & CELL_FLAG_SHOT) {
bright = RANDOM_IN_RANGE(0.7f, 1.0f);
color[0] = color[1] = color[2] = bright;
color[3] = 0.4f * (1.0f - t);
} else if (flags & CELL_FLAG_BOUNCE) {
bright = RANDOM_IN_RANGE(0.7f, 1.0f);
color[0] = color[1] = color[2] = bright;
color[3] = 0.4f;
}
glColor4fv(color);
/**** Now construct our up and over vectors ****/
pfSubVec3(toCam, camPos, cpos);
pfCrossVec3(over, toCam, GlobalCameraMatrix[PF_Z]);
pfCrossVec3(up, over, toCam);
pfNormalizeVec3(up);
pfNormalizeVec3(over);
if (flags & CELL_FLAG_SHOT) {
pfScaleVec3(up, (0.95f + t*5.0f) * mCellSize, up);
pfScaleVec3(over, (0.95f + t*5.0f) * mCellSize, over);
} else {
pfScaleVec3(up, (0.95f) * mCellSize, up);
pfScaleVec3(over, (0.95f) * mCellSize, over);
}
pfAddScaledVec3(vertex, cpos, -0.5f, up);
pfAddScaledVec3(vertex, vertex, -0.5f, over);
glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vertex);
pfAddVec3(vertex, vertex, over);
glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vertex);
pfAddVec3(vertex, vertex, up);
glTexCoord2f(1.0f, 1.0f);
glVertex3fv(vertex);
pfSubVec3(vertex, vertex, over);
glTexCoord2f(0.0f, 1.0f);
glVertex3fv(vertex);
}
pcell++;
}
}
glEnd();
}
}
void CellGrid::LifeUpdate(void)
{
int32 i, h, v, count, nugcount, wasShot = 0;
OneCell *pcell, *phi, *plo, *plolo;
for (i = 0; i < mNumCells; i++) {
CLRFLAG(mCells[i].flags, CELL_FLAG_BOSS);
wasShot |= (mCells[i].flags & CELL_FLAG_SHOT);
// if (mCells[i].shift & (CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT)) {
// } else {
// CLRFLAG(mCells[i].flags, CELL_FLAG_GOOD);
// }
}
if (wasShot && (gSizzleCycle < 1)) {
playSound2D(SOUND_SIZZLE_1, 0.85f, RANDOM_IN_RANGE(0.9f, 1.1f));
gSizzleCycle++;
}
/**** count up the bad cells ****/
mTotalBadCells = 0;
for (i = 0; i < mNumCells; i++) {
pcell = &(mCells[i]);
if (pcell->shift & (CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT)) {
mTotalBadCells++;
}
if (pcell->flags & CELL_FLAG_GOOD) {
pcell->goodTimer -= DeltaTime;
if (pcell->goodTimer <= 0.0f) {
pcell->goodTimer = 0.0f;
CLRFLAG(pcell->flags, CELL_FLAG_GOOD);
} else {
CLRFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
}
}
mLifeUpdateTimer += DeltaTime;
while (1) {
if (mLifeUpdateTimer < mLifeUpdateTimeInterval) return;
mLifeUpdateTimer -= mLifeUpdateTimeInterval;
for (i = 0; i < mNumCells; i++) {
mCells[i].shift <<= 1;
CLRFLAG(mCells[i].flags, CELL_FLAG_SHOT|CELL_FLAG_BOUNCE|CELL_FLAG_BOSS);
}
gSizzleCycle = 0;
for (v = 1; v < mVSize - 1; v++) {
for (h = 1; h < mHSize - 1; h++) {
pcell = &(mCells[h + (v * mHSize)]);
phi = pcell - mHSize;
plo = pcell + mHSize;
plolo = plo + mHSize;
count = 0;
count += phi[-1].shift & CELL_SHIFT_ON;
count += phi[ 0].shift & CELL_SHIFT_ON;
count += phi[ 1].shift & CELL_SHIFT_ON;
count += pcell[-1].shift & CELL_SHIFT_ON;
count += pcell[ 1].shift & CELL_SHIFT_ON;
count += plo[-1].shift & CELL_SHIFT_ON;
count += plo[ 0].shift & CELL_SHIFT_ON;
count += plo[ 1].shift & CELL_SHIFT_ON;
count >>= 1; /**** because CELL_SHIFT_ON is actually bit 2 ****/
if (pcell->shift & CELL_SHIFT_ON) {
if (count == 2 || count == 3) {
SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
} else {
if (count == 3) {
SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
}
/**** Detect 2x2 "nuggets" and turn them into gliders ****/
if (pcell->shift & CELL_SHIFT_ON) {
if (h < mHSize-2 && v < mVSize-2) {
nugcount = 0;
nugcount += pcell[ 0].shift & CELL_SHIFT_ON;
nugcount += pcell[ 1].shift & CELL_SHIFT_ON;
nugcount += plo[ 0].shift & CELL_SHIFT_ON;
nugcount += plo[ 1].shift & CELL_SHIFT_ON;
nugcount >>= 1; /**** because CELL_SHIFT_ON is actually bit 2 ****/
if (nugcount == 4) {
nugcount = 0;
nugcount += phi[-1].shift & CELL_SHIFT_ON;
nugcount += phi[ 0].shift & CELL_SHIFT_ON;
nugcount += phi[ 1].shift & CELL_SHIFT_ON;
nugcount += phi[ 2].shift & CELL_SHIFT_ON;
nugcount += pcell[-1].shift & CELL_SHIFT_ON;
nugcount += pcell[ 2].shift & CELL_SHIFT_ON;
nugcount += plo[-1].shift & CELL_SHIFT_ON;
nugcount += plo[ 2].shift & CELL_SHIFT_ON;
nugcount += plolo[-1].shift & CELL_SHIFT_ON;
nugcount += plolo[ 0].shift & CELL_SHIFT_ON;
nugcount += plolo[ 1].shift & CELL_SHIFT_ON;
nugcount += plolo[ 2].shift & CELL_SHIFT_ON;
nugcount >>= 1; /**** because CELL_SHIFT_ON is actually bit 2 ****/
if (nugcount == 0) {
/**** okay, it's a nugget. ****/
if (h < mHSize/2) {
if (v < mVSize/2) {
CLRFLAG(pcell[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(phi[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plo[-1].shift, CELL_SHIFT_ON_NEXT);
} else {
CLRFLAG(plo[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plolo[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(pcell[-1].shift, CELL_SHIFT_ON_NEXT);
}
} else {
if (v < mVSize/2) {
CLRFLAG(pcell[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(phi[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plo[2].shift, CELL_SHIFT_ON_NEXT);
} else {
CLRFLAG(plo[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plolo[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(pcell[2].shift, CELL_SHIFT_ON_NEXT);
}
}
}
}
}
}
/**** if it's surrounded by "good" mutated cells, make it good. ****/
// if (pcell->shift & (CELL_SHIFT_ON_NEXT | CELL_SHIFT_ON)) {
// int goodCount = 0;
// goodCount += phi[-1].flags & CELL_FLAG_GOOD;
// goodCount += phi[ 0].flags & CELL_FLAG_GOOD;
// goodCount += phi[ 1].flags & CELL_FLAG_GOOD;
// goodCount += pcell[-1].flags & CELL_FLAG_GOOD;
// goodCount += pcell[ 1].flags & CELL_FLAG_GOOD;
// goodCount += plo[-1].flags & CELL_FLAG_GOOD;
// goodCount += plo[ 0].flags & CELL_FLAG_GOOD;
// goodCount += plo[ 1].flags & CELL_FLAG_GOOD;
// goodCount /= CELL_FLAG_GOOD;
//
// if (goodCount > 1) {
// SETFLAG(pcell->flags, CELL_FLAG_GOOD);
// }
// if (goodCount > 1) {
// CLRFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
// }
// }
// if (pcell->flags & CELL_FLAG_GOOD) {
// SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
// }
/**** some mutation ****/
// if (count > 0) {
// if (RANDOM0TO1 < 0.0005f) {
// SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
// }
// }
}
}
}
}
| 29.133195
| 105
| 0.596814
|
machinelevel
|
902692ee3d6ef1f03b7ca71cec7c1f79eaa9fdc8
| 2,269
|
cpp
|
C++
|
src/cpp/sym_table.cpp
|
jacoburton104/perspective
|
556ef5fc5c74ff5c56cafa6b89804aff80a11fbd
|
[
"Apache-2.0"
] | 1
|
2021-07-09T05:21:15.000Z
|
2021-07-09T05:21:15.000Z
|
src/cpp/sym_table.cpp
|
netdebug/perspective
|
e725ea2b713a671544b2406189fe71358d7b66df
|
[
"Apache-2.0"
] | null | null | null |
src/cpp/sym_table.cpp
|
netdebug/perspective
|
e725ea2b713a671544b2406189fe71358d7b66df
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
*
* Copyright (c) 2017, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms of
* the Apache License 2.0. The full license can be found in the LICENSE file.
*
*/
#include <perspective/first.h>
#include <perspective/base.h>
#include <perspective/sym_table.h>
#include <perspective/column.h>
#include <unordered_map>
#include <functional>
#include <mutex>
namespace perspective {
std::mutex sym_table_mutex;
t_symtable::t_symtable() {}
t_symtable::~t_symtable() {
for (auto& kv : m_mapping) {
free(const_cast<char*>(kv.second));
}
}
const t_char*
t_symtable::get_interned_cstr(const t_char* s) {
auto iter = m_mapping.find(s);
if (iter != m_mapping.end()) {
return iter->second;
}
auto scopy = strdup(s);
m_mapping[scopy] = scopy;
return scopy;
}
t_tscalar
t_symtable::get_interned_tscalar(const t_char* s) {
if (t_tscalar::can_store_inplace(s)) {
t_tscalar rval;
rval.set(s);
return rval;
}
t_tscalar rval;
rval.set(get_interned_cstr(s));
return rval;
}
t_tscalar
t_symtable::get_interned_tscalar(const t_tscalar& s) {
if (!s.is_str() || s.is_inplace())
return s;
t_tscalar rval;
rval.set(get_interned_cstr(s.get_char_ptr()));
return rval;
}
t_uindex
t_symtable::size() const {
return m_mapping.size();
}
static t_symtable*
get_symtable() {
static t_symtable* sym = 0;
if (!sym) {
sym = new t_symtable;
}
return sym;
}
const t_char*
get_interned_cstr(const t_char* s) {
std::lock_guard<std::mutex> guard(sym_table_mutex);
auto sym = get_symtable();
return sym->get_interned_cstr(s);
}
t_tscalar
get_interned_tscalar(const t_char* s) {
if (t_tscalar::can_store_inplace(s)) {
t_tscalar rval;
rval.set(s);
return rval;
}
t_tscalar rval;
rval.set(get_interned_cstr(s));
return rval;
}
t_tscalar
get_interned_tscalar(const t_tscalar& s) {
if (!s.is_str() || s.is_inplace())
return s;
t_tscalar rval;
rval.set(get_interned_cstr(s.get_char_ptr()));
return rval;
}
} // end namespace perspective
| 20.441441
| 79
| 0.633759
|
jacoburton104
|
902da8ebf18cc52e8154d8340308434776985734
| 514
|
cpp
|
C++
|
SharpMedia.Graphics.Driver.Direct3D10/RenderTargetView.cpp
|
zigaosolin/SharpMedia
|
b7b594a4c9c64a03d94862877ba642b0460d1067
|
[
"Apache-2.0"
] | null | null | null |
SharpMedia.Graphics.Driver.Direct3D10/RenderTargetView.cpp
|
zigaosolin/SharpMedia
|
b7b594a4c9c64a03d94862877ba642b0460d1067
|
[
"Apache-2.0"
] | null | null | null |
SharpMedia.Graphics.Driver.Direct3D10/RenderTargetView.cpp
|
zigaosolin/SharpMedia
|
b7b594a4c9c64a03d94862877ba642b0460d1067
|
[
"Apache-2.0"
] | null | null | null |
#include "RenderTargetView.h"
#include "Helper.h"
namespace SharpMedia {
namespace Graphics {
namespace Driver {
namespace Direct3D10 {
D3D10RenderTargetView::D3D10RenderTargetView(ID3D10RenderTargetView* view)
{
this->view = view;
}
D3D10RenderTargetView::~D3D10RenderTargetView()
{
this->view->Release();
}
void D3D10RenderTargetView::Clear(ID3D10Device* device, Colour colour)
{
float c[] = { colour.R, colour.G, colour.B, colour.A };
device->ClearRenderTargetView(view, c);
}
}
}
}
}
| 16.580645
| 75
| 0.72179
|
zigaosolin
|
903103ab69cc91a1fc14c36b93042c3775559100
| 470
|
cpp
|
C++
|
Problems/Array/squareSortedArray.cpp
|
vishwajeet-hogale/LearnSTL
|
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
|
[
"MIT"
] | null | null | null |
Problems/Array/squareSortedArray.cpp
|
vishwajeet-hogale/LearnSTL
|
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
|
[
"MIT"
] | null | null | null |
Problems/Array/squareSortedArray.cpp
|
vishwajeet-hogale/LearnSTL
|
0cbfc12b66ba844de23d7966d18cadc7b2d5a77f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> sortedSquares(vector<int> &nums)
{
priority_queue<int, vector<int>,
greater<int>>
q;
vector<int> res;
for (int i : nums)
{
q.push(i * i);
}
while (!q.empty())
{
res.push_back(q.top());
q.pop();
}
return res;
}
};
| 19.583333
| 48
| 0.444681
|
vishwajeet-hogale
|
9031263f8cbc650f99e928e654511839a814face
| 3,314
|
cpp
|
C++
|
Source Code/GUI/GUIMessageBox.cpp
|
IonutCava/trunk
|
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
|
[
"MIT"
] | null | null | null |
Source Code/GUI/GUIMessageBox.cpp
|
IonutCava/trunk
|
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
|
[
"MIT"
] | null | null | null |
Source Code/GUI/GUIMessageBox.cpp
|
IonutCava/trunk
|
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Headers/GUIMessageBox.h"
namespace Divide {
GUIMessageBox::GUIMessageBox(const string& name,
const string& title,
const string& message,
const vec2<I32>& offsetFromCentre,
CEGUI::Window* parent)
: GUIElementBase(name, parent)
{
if (parent != nullptr) {
// Get a local pointer to the CEGUI Window Manager, Purely for convenience
// to reduce typing
CEGUI::WindowManager* pWindowManager = CEGUI::WindowManager::getSingletonPtr();
// load the messageBox Window from the layout file
_msgBoxWindow = pWindowManager->loadLayoutFromFile("messageBox.layout");
_msgBoxWindow->setName((title + "_MesageBox").c_str());
_msgBoxWindow->setTextParsingEnabled(false);
_parent->addChild(_msgBoxWindow);
CEGUI::PushButton* confirmBtn = dynamic_cast<CEGUI::PushButton*>(_msgBoxWindow->getChild("ConfirmBtn"));
_confirmEvent = confirmBtn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GUIMessageBox::onConfirm, this));
}
setTitle(title);
setMessage(message);
setOffset(offsetFromCentre);
GUIMessageBox::active(true);
GUIMessageBox::visible(false);
}
GUIMessageBox::~GUIMessageBox()
{
if (_parent != nullptr) {
_parent->removeChild(_msgBoxWindow);
CEGUI::WindowManager::getSingletonPtr()->destroyWindow(_msgBoxWindow);
}
}
bool GUIMessageBox::onConfirm(const CEGUI::EventArgs& /*e*/) noexcept {
active(false);
visible(false);
return true;
}
void GUIMessageBox::visible(const bool& visible) noexcept {
if (_parent != nullptr) {
_msgBoxWindow->setVisible(visible);
_msgBoxWindow->setModalState(visible);
}
GUIElement::visible(visible);
}
void GUIMessageBox::active(const bool& active) noexcept {
if (_parent != nullptr) {
_msgBoxWindow->setEnabled(active);
}
GUIElement::active(active);
}
void GUIMessageBox::setTitle(const string& titleText) {
if (_parent != nullptr) {
_msgBoxWindow->setText(titleText.c_str());
}
}
void GUIMessageBox::setMessage(const string& message) {
if (_parent != nullptr) {
_msgBoxWindow->getChild("MessageText")->setText(message.c_str());
}
}
void GUIMessageBox::setOffset(const vec2<I32>& offsetFromCentre) {
if (_parent != nullptr) {
CEGUI::UVector2 crtPosition(_msgBoxWindow->getPosition());
crtPosition.d_x.d_offset += offsetFromCentre.x;
crtPosition.d_y.d_offset += offsetFromCentre.y;
_msgBoxWindow->setPosition(crtPosition);
}
}
void GUIMessageBox::setMessageType(const MessageType type) {
if (_parent != nullptr) {
switch (type) {
case MessageType::MESSAGE_INFO: {
_msgBoxWindow->setProperty("CaptionColour", "FFFFFFFF");
} break;
case MessageType::MESSAGE_WARNING: {
_msgBoxWindow->setProperty("CaptionColour", "00FFFFFF");
} break;
case MessageType::MESSAGE_ERROR: {
_msgBoxWindow->setProperty("CaptionColour", "FF0000FF");
} break;
}
}
}
};
| 33.816327
| 144
| 0.63096
|
IonutCava
|
90324190c5b67bd39c5f4884f3ad838afffe1788
| 1,322
|
cpp
|
C++
|
tests/clustering_tests.cpp
|
lgruelas/Graph
|
079ec1d42a30e66c47ecbce1228b6581ca56cf34
|
[
"MIT"
] | 7
|
2016-08-25T07:42:10.000Z
|
2019-10-30T09:05:29.000Z
|
tests/clustering_tests.cpp
|
lgruelas/Graph
|
079ec1d42a30e66c47ecbce1228b6581ca56cf34
|
[
"MIT"
] | 1
|
2018-08-16T20:38:26.000Z
|
2018-08-16T22:11:32.000Z
|
tests/clustering_tests.cpp
|
lgruelas/Graph
|
079ec1d42a30e66c47ecbce1228b6581ca56cf34
|
[
"MIT"
] | 10
|
2018-01-31T15:10:16.000Z
|
2018-08-16T18:15:20.000Z
|
#include "Clustering.hpp"
#include "CommonGraphs.hpp"
#include <gtest/gtest.h>
#include <iostream>
void assert_are_same_float(const std::vector<double>& A,
const std::vector<double>& B)
{
ASSERT_EQ(A.size(), B.size());
for (auto i : indices(A))
{
ASSERT_FLOAT_EQ(A[i], B[i]);
}
}
TEST(Clustering, Empty3)
{
Graph G(3);
ASSERT_EQ(num_triangles(G), 0);
ASSERT_EQ(clustering_global(G), 0);
std::vector<double> cl = {0, 0, 0};
assert_are_same_float(clustering_local(G), cl);
}
TEST(Clustering, K3)
{
Graph G = graphs::Complete(3);
ASSERT_EQ(num_triangles(G), 1);
ASSERT_EQ(clustering_global(G), 1);
std::vector<double> cl = {1, 1, 1};
assert_are_same_float(clustering_local(G), cl);
}
TEST(Clustering, K4minusedge)
{
Graph G = graphs::Complete(4);
G.remove_edge(1, 3);
ASSERT_EQ(num_triangles(G), 2);
ASSERT_EQ(clustering_global(G), 0.75);
std::vector<double> cl = {2.0/3.0, 1, 2.0/3.0, 1};
assert_are_same_float(clustering_local(G), cl);
}
TEST(Clustering, Petersen)
{
Graph G = graphs::Petersen();
std::vector<double> cl = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ASSERT_EQ(num_triangles(G), 0);
ASSERT_EQ(clustering_global(G), 0);
assert_are_same_float(clustering_local(G), cl);
}
| 20.984127
| 60
| 0.624811
|
lgruelas
|
903f9b1c677294829f94fbf55e9f8dc2ba5ed48a
| 4,926
|
cpp
|
C++
|
Source Code/Editor/Widgets/EditorOptionsWindow.cpp
|
IonutCava/trunk
|
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
|
[
"MIT"
] | null | null | null |
Source Code/Editor/Widgets/EditorOptionsWindow.cpp
|
IonutCava/trunk
|
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
|
[
"MIT"
] | null | null | null |
Source Code/Editor/Widgets/EditorOptionsWindow.cpp
|
IonutCava/trunk
|
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Headers/UndoManager.h"
#include "Headers/Utils.h"
#include "Editor/Headers/Editor.h"
#include "Headers/EditorOptionsWindow.h"
#include "Core/Headers/PlatformContext.h"
#include <IconFontCppHeaders/IconsForkAwesome.h>
namespace Divide {
EditorOptionsWindow::EditorOptionsWindow(PlatformContext& context)
: PlatformContextComponent(context),
_fileOpenDialog(false, true)
{
}
void EditorOptionsWindow::update([[maybe_unused]] const U64 deltaTimeUS) {
}
void EditorOptionsWindow::draw(bool& open) {
if (!open) {
return;
}
OPTICK_EVENT();
const U32 flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoDocking |
(_openDialog ? ImGuiWindowFlags_NoBringToFrontOnFocus : ImGuiWindowFlags_Tooltip);
Util::CenterNextWindow();
if (!ImGui::Begin("Editor options", nullptr, flags))
{
ImGui::End();
return;
}
F32 axisWidth = _context.editor().infiniteGridAxisWidth();
ImGui::Text(ICON_FK_PLUS_SQUARE_O);
ImGui::SameLine();
if (ImGui::SliderFloat("Grid axis width", &axisWidth, 0.01f, 10.0f, "%.3f")) {
_context.editor().infiniteGridAxisWidth(axisWidth);
}
ImGui::SameLine();
F32 gridLineWidth = 10.1f - _context.editor().infiniteGridScale();
if (ImGui::SliderFloat("Grid scale", &gridLineWidth, 1.f, 10.f, "%.3f")) {
_context.editor().infiniteGridScale(10.1f - gridLineWidth);
}
static UndoEntry<I32> undo = {};
const I32 crtThemeIdx = to_I32(Attorney::EditorOptionsWindow::getTheme(_context.editor()));
I32 selection = crtThemeIdx;
if (ImGui::Combo("Editor Theme", &selection, ImGui::GetDefaultStyleNames(), ImGuiStyle_Count)) {
ImGui::ResetStyle(static_cast<ImGuiStyleEnum>(selection));
Attorney::EditorOptionsWindow::setTheme(_context.editor(), static_cast<ImGuiStyleEnum>(selection));
undo._type = GFX::PushConstantType::INT;
undo._name = "Theme Selection";
undo._oldVal = crtThemeIdx;
undo._newVal = selection;
undo._dataSetter = [this](const I32& data) {
const ImGuiStyleEnum style = static_cast<ImGuiStyleEnum>(data);
ImGui::ResetStyle(style);
Attorney::EditorOptionsWindow::setTheme(_context.editor(), style);
};
_context.editor().registerUndoEntry(undo);
++_changeCount;
}
ImGui::Separator();
string externalTextEditorPath = Attorney::EditorOptionsWindow::externalTextEditorPath(_context.editor());
ImGui::InputText("Text Editor", externalTextEditorPath.data(), externalTextEditorPath.size(), ImGuiInputTextFlags_ReadOnly);
ImGui::SameLine();
const bool openDialog = ImGui::Button("Select");
if (openDialog) {
ImGuiFs::Dialog::WindowLTRBOffsets.x = 20;
ImGuiFs::Dialog::WindowLTRBOffsets.y = 20;
_openDialog = true;
}
ImGui::Separator();
ImGui::Separator();
if (ImGui::Button("Cancel", ImVec2(120, 0))) {
open = false;
assert(_changeCount <= _context.editor().UndoStackSize());
for (U16 i = 0; i < _changeCount; ++i) {
if (!_context.editor().Undo()) {
NOP();
}
}
_changeCount = 0u;
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button(ICON_FK_FLOPPY_O" Save", ImVec2(120, 0))) {
open = false;
_changeCount = 0u;
if (!_context.editor().saveToXML()) {
Attorney::EditorGeneralWidget::showStatusMessage(_context.editor(), "Save failed!", Time::SecondsToMilliseconds<F32>(3.0f), true);
}
}
ImGui::SameLine();
if (ImGui::Button("Defaults", ImVec2(120, 0))) {
_changeCount = 0u;
Attorney::EditorOptionsWindow::setTheme(_context.editor(), ImGuiStyle_DarkCodz01);
ImGui::ResetStyle(ImGuiStyle_DarkCodz01);
}
ImGui::End();
if (_openDialog) {
Util::CenterNextWindow();
const char* chosenPath = _fileOpenDialog.chooseFileDialog(openDialog, nullptr, nullptr, "Choose text editor", ImVec2(-1, -1), ImGui::GetMainViewport()->WorkPos);
if (strlen(chosenPath) > 0) {
Attorney::EditorOptionsWindow::externalTextEditorPath(_context.editor(), chosenPath);
}
if (_fileOpenDialog.hasUserJustCancelledDialog()) {
_openDialog = false;
}
}
}
}
| 38.787402
| 173
| 0.591758
|
IonutCava
|
903fadf042ed4431ad4c69cef2c56090e4b424d3
| 3,060
|
cpp
|
C++
|
test/test_disk_space_widget/widget.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
test/test_disk_space_widget/widget.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
test/test_disk_space_widget/widget.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "widget.hpp"
#include <cppdevtk/base/logger.hpp>
#include <cppdevtk/base/cassert.hpp>
#include <cppdevtk/base/verify.h>
#include <cppdevtk/base/dbc.hpp>
#include <cppdevtk/base/info_tr.hpp>
#include <QtGui/QIcon>
#include <QtCore/QDir>
#define CPPDEVTK_DETAIL_TEST_DISK_SPACE_WIDGET_PATH_EMPTY 0
namespace cppdevtk {
namespace test_disk_space_widget {
Widget::Widget(QWidget* pParent): QWidget(pParent), WidgetBase(), Ui::Widget() {
CPPDEVTK_LOG_TRACE_FUNCTION();
setupUi(this);
SetStyleSheetFromFileCross(":/cppdevtk/test_disk_space_widget/res/qss", "widget");
setWindowIcon(QIcon(":/cppdevtk/test_disk_space_widget/res/ico/application.ico"));
pDiskSpaceWidget_->SetDiskNameColor(Qt::darkRed);
pDiskSpaceWidget_->SetSpaceInfoColor(Qt::darkBlue);
pDiskSpaceWidget_->SetBold(true);
# if (!CPPDEVTK_DETAIL_TEST_DISK_SPACE_WIDGET_PATH_EMPTY)
const QString kPath = QDir::currentPath();
CPPDEVTK_LOG_DEBUG("setting path to: " << kPath);
pDiskSpaceWidget_->SetPath(kPath);
# endif
pSpinBoxAutoRefreshInterval_->setValue(pDiskSpaceWidget_->GetAutoRefreshInterval());
CPPDEVTK_VERIFY(connect(pPushButtonRefresh_, SIGNAL(clicked()),
pDiskSpaceWidget_, SLOT(Refresh())));
CPPDEVTK_VERIFY(connect(pGroupBoxAutoRefresh_, SIGNAL(toggled(bool)),
pDiskSpaceWidget_, SLOT(SetAutoRefreshEnabled(bool))));
CPPDEVTK_VERIFY(connect(pSpinBoxAutoRefreshInterval_, SIGNAL(valueChanged(int)),
SLOT(SetAutoRefreshInterval(int))));
adjustSize();
}
Widget::~Widget() {
CPPDEVTK_LOG_TRACE_FUNCTION();
}
void Widget::SetAutoRefreshInterval(int sec) {
pDiskSpaceWidget_->SetAutoRefreshInterval(sec);
}
void Widget::changeEvent(QEvent* pEvent) {
CPPDEVTK_DBC_CHECK_NON_NULL_ARGUMENT(pEvent);
QWidget::changeEvent(pEvent);
switch (pEvent->type()) {
case QEvent::LanguageChange:
retranslateUi(this);
break;
default:
break;
}
}
} // namespace test_disk_space_widget
} // namespace cppdevtk
| 33.626374
| 126
| 0.677124
|
CoSoSys
|
9044db185229421b97182ff0a27aa1ce2f73216f
| 7,758
|
cpp
|
C++
|
cpp/benchmarks/string/repeat_strings.cpp
|
res-life/cudf
|
94a5d4180b1281d4250e9f915e547789d8da3ce0
|
[
"Apache-2.0"
] | 1
|
2022-03-04T16:36:48.000Z
|
2022-03-04T16:36:48.000Z
|
cpp/benchmarks/string/repeat_strings.cpp
|
res-life/cudf
|
94a5d4180b1281d4250e9f915e547789d8da3ce0
|
[
"Apache-2.0"
] | 1
|
2022-02-28T05:17:59.000Z
|
2022-02-28T05:17:59.000Z
|
cpp/benchmarks/string/repeat_strings.cpp
|
res-life/cudf
|
94a5d4180b1281d4250e9f915e547789d8da3ce0
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2021-2022, NVIDIA 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 "string_bench_args.hpp"
#include <benchmark/benchmark.h>
#include <benchmarks/common/generate_input.hpp>
#include <benchmarks/fixture/benchmark_fixture.hpp>
#include <benchmarks/synchronization/synchronization.hpp>
#include <cudf/strings/repeat_strings.hpp>
#include <cudf/strings/strings_column_view.hpp>
static constexpr cudf::size_type default_repeat_times = 16;
static constexpr cudf::size_type min_repeat_times = -16;
static constexpr cudf::size_type max_repeat_times = 16;
static std::unique_ptr<cudf::table> create_data_table(cudf::size_type n_cols,
cudf::size_type n_rows,
cudf::size_type max_str_length)
{
CUDF_EXPECTS(n_cols == 1 || n_cols == 2, "Invalid number of columns.");
std::vector<cudf::type_id> dtype_ids{cudf::type_id::STRING};
data_profile table_profile;
table_profile.set_distribution_params(
cudf::type_id::STRING, distribution_id::NORMAL, 0, max_str_length);
if (n_cols == 2) {
dtype_ids.push_back(cudf::type_id::INT32);
table_profile.set_distribution_params(
cudf::type_id::INT32, distribution_id::NORMAL, min_repeat_times, max_repeat_times);
}
return create_random_table(dtype_ids, row_count{n_rows}, table_profile);
}
static void BM_repeat_strings_scalar_times(benchmark::State& state)
{
auto const n_rows = static_cast<cudf::size_type>(state.range(0));
auto const max_str_length = static_cast<cudf::size_type>(state.range(1));
auto const table = create_data_table(1, n_rows, max_str_length);
auto const strings_col = cudf::strings_column_view(table->view().column(0));
for ([[maybe_unused]] auto _ : state) {
[[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default);
cudf::strings::repeat_strings(strings_col, default_repeat_times);
}
state.SetBytesProcessed(state.iterations() * strings_col.chars_size());
}
static void BM_repeat_strings_column_times(benchmark::State& state)
{
auto const n_rows = static_cast<cudf::size_type>(state.range(0));
auto const max_str_length = static_cast<cudf::size_type>(state.range(1));
auto const table = create_data_table(2, n_rows, max_str_length);
auto const strings_col = cudf::strings_column_view(table->view().column(0));
auto const repeat_times_col = table->view().column(1);
for ([[maybe_unused]] auto _ : state) {
[[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default);
cudf::strings::repeat_strings(strings_col, repeat_times_col);
}
state.SetBytesProcessed(state.iterations() *
(strings_col.chars_size() + repeat_times_col.size() * sizeof(int32_t)));
}
static void BM_compute_output_strings_sizes(benchmark::State& state)
{
auto const n_rows = static_cast<cudf::size_type>(state.range(0));
auto const max_str_length = static_cast<cudf::size_type>(state.range(1));
auto const table = create_data_table(2, n_rows, max_str_length);
auto const strings_col = cudf::strings_column_view(table->view().column(0));
auto const repeat_times_col = table->view().column(1);
for ([[maybe_unused]] auto _ : state) {
[[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default);
cudf::strings::repeat_strings_output_sizes(strings_col, repeat_times_col);
}
state.SetBytesProcessed(state.iterations() *
(strings_col.chars_size() + repeat_times_col.size() * sizeof(int32_t)));
}
static void BM_repeat_strings_column_times_precomputed_sizes(benchmark::State& state)
{
auto const n_rows = static_cast<cudf::size_type>(state.range(0));
auto const max_str_length = static_cast<cudf::size_type>(state.range(1));
auto const table = create_data_table(2, n_rows, max_str_length);
auto const strings_col = cudf::strings_column_view(table->view().column(0));
auto const repeat_times_col = table->view().column(1);
[[maybe_unused]] auto const [sizes, total_bytes] =
cudf::strings::repeat_strings_output_sizes(strings_col, repeat_times_col);
for ([[maybe_unused]] auto _ : state) {
[[maybe_unused]] cuda_event_timer raii(state, true, rmm::cuda_stream_default);
cudf::strings::repeat_strings(strings_col, repeat_times_col, *sizes);
}
state.SetBytesProcessed(state.iterations() *
(strings_col.chars_size() + repeat_times_col.size() * sizeof(int32_t)));
}
static void generate_bench_args(benchmark::internal::Benchmark* b)
{
int const min_rows = 1 << 8;
int const max_rows = 1 << 18;
int const row_mult = 4;
int const min_strlen = 1 << 4;
int const max_strlen = 1 << 8;
int const len_mult = 4;
generate_string_bench_args(b, min_rows, max_rows, row_mult, min_strlen, max_strlen, len_mult);
}
class RepeatStrings : public cudf::benchmark {
};
#define REPEAT_STRINGS_SCALAR_TIMES_BENCHMARK_DEFINE(name) \
BENCHMARK_DEFINE_F(RepeatStrings, name) \
(::benchmark::State & st) { BM_repeat_strings_scalar_times(st); } \
BENCHMARK_REGISTER_F(RepeatStrings, name) \
->Apply(generate_bench_args) \
->UseManualTime() \
->Unit(benchmark::kMillisecond);
#define REPEAT_STRINGS_COLUMN_TIMES_BENCHMARK_DEFINE(name) \
BENCHMARK_DEFINE_F(RepeatStrings, name) \
(::benchmark::State & st) { BM_repeat_strings_column_times(st); } \
BENCHMARK_REGISTER_F(RepeatStrings, name) \
->Apply(generate_bench_args) \
->UseManualTime() \
->Unit(benchmark::kMillisecond);
#define COMPUTE_OUTPUT_STRINGS_SIZES_BENCHMARK_DEFINE(name) \
BENCHMARK_DEFINE_F(RepeatStrings, name) \
(::benchmark::State & st) { BM_compute_output_strings_sizes(st); } \
BENCHMARK_REGISTER_F(RepeatStrings, name) \
->Apply(generate_bench_args) \
->UseManualTime() \
->Unit(benchmark::kMillisecond);
#define REPEAT_STRINGS_COLUMN_TIMES_PRECOMPUTED_SIZES_BENCHMARK_DEFINE(name) \
BENCHMARK_DEFINE_F(RepeatStrings, name) \
(::benchmark::State & st) { BM_repeat_strings_column_times_precomputed_sizes(st); } \
BENCHMARK_REGISTER_F(RepeatStrings, name) \
->Apply(generate_bench_args) \
->UseManualTime() \
->Unit(benchmark::kMillisecond);
REPEAT_STRINGS_SCALAR_TIMES_BENCHMARK_DEFINE(scalar_times)
REPEAT_STRINGS_COLUMN_TIMES_BENCHMARK_DEFINE(column_times)
COMPUTE_OUTPUT_STRINGS_SIZES_BENCHMARK_DEFINE(compute_output_strings_sizes)
REPEAT_STRINGS_COLUMN_TIMES_PRECOMPUTED_SIZES_BENCHMARK_DEFINE(precomputed_sizes)
| 45.905325
| 98
| 0.667827
|
res-life
|
904520de086348cf21afed8a702dc451e3b99645
| 3,346
|
cpp
|
C++
|
src/zipstream.cpp
|
robinmoussu/fastzip
|
85f71b7862af0940cadbafb44f80856581ecb023
|
[
"RSA-MD"
] | 2
|
2019-02-08T16:53:53.000Z
|
2021-03-21T05:09:13.000Z
|
src/zipstream.cpp
|
robinmoussu/fastzip
|
85f71b7862af0940cadbafb44f80856581ecb023
|
[
"RSA-MD"
] | null | null | null |
src/zipstream.cpp
|
robinmoussu/fastzip
|
85f71b7862af0940cadbafb44f80856581ecb023
|
[
"RSA-MD"
] | 3
|
2017-05-08T04:44:56.000Z
|
2018-12-01T16:12:44.000Z
|
#include "zipstream.h"
#include "utils.h"
#include "zipformat.h"
#include <cassert>
#include <ctime>
#include <sys/stat.h>
template <int BYTES> struct getType;
template <> struct getType<4>
{
using type = int32_t;
};
template <int BYTES, typename T = typename getType<BYTES>::type>
T readBytes(uint8_t const* ptr)
{
const T t = *(T*)ptr;
return t;
}
int64_t decodeInt(uint8_t const** ptr)
{
auto* data = *ptr;
auto sz = data[0];
*ptr = &data[sz + 1];
int64_t val = 0;
while (sz > 0) {
val <<= 8;
val |= data[sz];
sz--;
}
return val;
}
ZipStream::ZipStream(const std::string& zipName)
: zipName_(zipName), f_{zipName}
{
uint32_t id = 0;
// Find CD by scanning backwards from end
f_.seek(-22 + 5, SEEK_END);
int counter = 64 * 1024 + 8;
while (id != EndOfCD_SIG && counter > 0) {
f_.seek(-5, SEEK_CUR);
id = f_.Read<uint32_t>();
counter--;
}
if (counter <= 0) {
f_.close();
return;
}
auto start = f_.tell();
f_.seek(4, SEEK_CUR);
int64_t entryCount = f_.Read<uint16_t>();
f_.seek(2, SEEK_CUR);
/* auto cdSize = */ f_.Read<uint32_t>();
int64_t cdOffset = f_.Read<uint32_t>();
auto commentLen = f_.Read<uint16_t>();
if (commentLen > 0) {
comment_ = std::make_unique<char[]>(commentLen + 1);
f_.Read(comment_.get(), commentLen);
comment_[commentLen] = 0;
}
if (entryCount == 0xffff || cdOffset == 0xffffffff) {
// Find zip64 data
f_.seek(start - 6 * 4, SEEK_SET);
id = f_.Read<uint32_t>();
if (id != EndOfCD64Locator_SIG) {
return;
}
f_.seek(4, SEEK_CUR);
auto cdStart = f_.Read<int64_t>();
f_.seek(cdStart, SEEK_SET);
auto eocd64 = f_.Read<EndOfCentralDir64>();
cdOffset = eocd64.cdoffset;
entryCount = eocd64.entries;
}
entries_.reserve(entryCount);
f_.seek(cdOffset, SEEK_SET);
char fileName[65536];
for (auto i = 0L; i < entryCount; i++) {
auto const cd = f_.Read<CentralDirEntry>();
auto const rc = f_.Read(&fileName, cd.nameLen);
fileName[rc] = 0;
f_.seek(cd.nameLen - rc, SEEK_CUR);
int64_t offset = cd.offset;
int exLen = cd.exLen;
Extra extra{};
while (exLen > 0) {
f_.Read((uint8_t*)&extra, 4);
f_.Read(extra.data, extra.size);
if (extra.id == 0x01) {
offset = extra.zip64.offset;
} else if (extra.id == 0x7875) {
auto const* ptr = &extra.data[1];
uint32_t const uid = decodeInt(&ptr);
uint32_t const gid = decodeInt(&ptr);
printf("UID %x GID %x\n", uid, gid);
} else if (extra.id == 0x5455) {
// TODO: Read timestamps
} else
printf("**Warning: Ignoring extra block %04x\n", extra.id);
exLen -= (extra.size + 4);
}
f_.seek(cd.commLen, SEEK_CUR);
auto const flags = ((cd.attr1 & (S_IFREG >> 16)) == 0)
? // Some archives have broken attributes
0
: cd.attr1 >> 16;
entries_.emplace_back(fileName, offset, flags);
}
}
| 27.652893
| 75
| 0.5263
|
robinmoussu
|
90499cec06459321763dd15cb1cd75b010965b2b
| 752
|
cpp
|
C++
|
performance_tests.cpp
|
miguelrodriguesdossantos/CellularAutomata
|
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
|
[
"MIT"
] | null | null | null |
performance_tests.cpp
|
miguelrodriguesdossantos/CellularAutomata
|
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
|
[
"MIT"
] | null | null | null |
performance_tests.cpp
|
miguelrodriguesdossantos/CellularAutomata
|
1fdca34b6266c8b2a6c9604cc02d540f54ea5b80
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <string>
#include "board.hpp"
#include "command_line_options.h"
using namespace std;
using namespace RuleStrings;
/*
This file exists to aid quick comparison
between performances of two branches.
*/
int main(int argc, char** argv){
srand(time(NULL));
const unsigned int num_iterations = 1E3;
// Default values
unsigned int vertSize = 800;
unsigned int horiSize = 400;
double prob = 0.25;
std::string ruleString = ConwaysLife_rulestring;
Board B( Board::SizeV{vertSize}, Board::SizeH{horiSize}, ruleString);
B.setRandom(prob*vertSize*horiSize);
for( unsigned int i = 0; i < num_iterations && !B.isStable(); i++){
B.setNext();
}
std::cout << B;
return 0;
}
| 19.789474
| 70
| 0.704787
|
miguelrodriguesdossantos
|
904de316d86f53af738469b6c0987d5d272883a0
| 246
|
hpp
|
C++
|
src/LibCraft/renderEngine/include/vbo.hpp
|
Kenny38GH/Test
|
24c0277de8f98a3b0b3b8a90a300a321a485684c
|
[
"MIT"
] | null | null | null |
src/LibCraft/renderEngine/include/vbo.hpp
|
Kenny38GH/Test
|
24c0277de8f98a3b0b3b8a90a300a321a485684c
|
[
"MIT"
] | null | null | null |
src/LibCraft/renderEngine/include/vbo.hpp
|
Kenny38GH/Test
|
24c0277de8f98a3b0b3b8a90a300a321a485684c
|
[
"MIT"
] | null | null | null |
//
// Created by leodlplq on 18/11/2021.
//
#pragma once
#include "Vertex.hpp"
#include "glad/glad.h"
class vbo {
public:
GLuint _id;
vbo(Vertex* vertices, GLsizeiptr size);
void bind();
void unbind();
void deleteVbo();
};
| 13.666667
| 43
| 0.626016
|
Kenny38GH
|
905d99eda51c401b3210f38cc77d711274747bcd
| 53,452
|
cpp
|
C++
|
examples_tests/11.LoDSystem/main.cpp
|
deprilula28/Nabla
|
6b5de216221718191713dcf6de8ed6407182ddf0
|
[
"Apache-2.0"
] | null | null | null |
examples_tests/11.LoDSystem/main.cpp
|
deprilula28/Nabla
|
6b5de216221718191713dcf6de8ed6407182ddf0
|
[
"Apache-2.0"
] | null | null | null |
examples_tests/11.LoDSystem/main.cpp
|
deprilula28/Nabla
|
6b5de216221718191713dcf6de8ed6407182ddf0
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O.
// This file is part of the "Nabla Engine".
// For conditions of distribution and use, see copyright notice in nabla.h
#define _NBL_STATIC_LIB_
#include <nabla.h>
#include "../common/Camera.hpp"
#include "../common/CommonAPI.h"
#include "nbl/ext/ScreenShot/ScreenShot.h"
using namespace nbl;
using namespace core;
using namespace system;
using namespace asset;
using namespace ui;
using lod_library_t = scene::CLevelOfDetailLibrary<>;
using culling_system_t = scene::ICullingLoDSelectionSystem;
struct LoDLibraryData
{
core::vector<uint32_t> drawCallOffsetsIn20ByteStrides;
core::vector<uint32_t> drawCountOffsets;
core::vector<asset::DrawElementsIndirectCommand_t> drawCallData;
core::vector<uint32_t> drawCountData;
core::vector<uint32_t> lodInfoDstUvec2s;
core::vector<uint32_t> lodTableDstUvec4s;
scene::ILevelOfDetailLibrary::InfoContainerAdaptor<lod_library_t::LoDInfo> lodInfoData;
scene::ILevelOfDetailLibrary::InfoContainerAdaptor<scene::ILevelOfDetailLibrary::LoDTableInfo> lodTableData;
};
enum E_GEOM_TYPE
{
EGT_CUBE,
EGT_SPHERE,
EGT_CYLINDER,
EGT_COUNT
};
template<E_GEOM_TYPE geom, uint32_t LoDLevels>
void addLoDTable(
IAssetManager* assetManager,
const core::smart_refctd_ptr<ICPUDescriptorSetLayout>& cpuTransformTreeDSLayout,
const core::smart_refctd_ptr<ICPUDescriptorSetLayout>& cpuPerViewDSLayout,
const core::smart_refctd_ptr<ICPUSpecializedShader>* shaders,
nbl::video::IGPUObjectFromAssetConverter::SParams& cpu2gpuParams,
LoDLibraryData& lodLibraryData,
video::CDrawIndirectAllocator<>* drawIndirectAllocator,
lod_library_t* lodLibrary,
core::vector<video::CSubpassKiln::DrawcallInfo>& drawcallInfos,
const SBufferRange<video::IGPUBuffer>& perInstanceRedirectAttribs,
const core::smart_refctd_ptr<video::IGPURenderpass>& renderpass,
const video::IGPUDescriptorSet* transformTreeDS,
const core::smart_refctd_ptr<video::IGPUDescriptorSet>& perViewDS
)
{
constexpr auto perInstanceRedirectAttrID = 15u;
auto* const geometryCreator = assetManager->getGeometryCreator();
auto* const meshManipulator = assetManager->getMeshManipulator();
core::smart_refctd_ptr<ICPURenderpassIndependentPipeline> cpupipeline;
core::smart_refctd_ptr<ICPUMeshBuffer> cpumeshes[LoDLevels];
for (uint32_t poly = 4u, lod = 0u; lod < LoDLevels; lod++)
{
IGeometryCreator::return_type geomData;
switch (geom)
{
case EGT_CUBE:
geomData = geometryCreator->createCubeMesh(core::vector3df(2.f));
break;
case EGT_SPHERE:
geomData = geometryCreator->createSphereMesh(2.f, poly, poly, meshManipulator);
break;
case EGT_CYLINDER:
geomData = geometryCreator->createCylinderMesh(1.f, 4.f, poly, 0x0u, meshManipulator);
break;
default:
assert(false);
break;
}
// we'll stick instance data refs in the last attribute binding
assert((geomData.inputParams.enabledBindingFlags >> perInstanceRedirectAttrID) == 0u);
geomData.inputParams.enabledAttribFlags |= 0x1u << perInstanceRedirectAttrID;
geomData.inputParams.enabledBindingFlags |= 0x1u << perInstanceRedirectAttrID;
geomData.inputParams.attributes[perInstanceRedirectAttrID].binding = perInstanceRedirectAttrID;
geomData.inputParams.attributes[perInstanceRedirectAttrID].relativeOffset = 0u;
geomData.inputParams.attributes[perInstanceRedirectAttrID].format = asset::EF_R32G32_UINT;
geomData.inputParams.bindings[perInstanceRedirectAttrID].inputRate = asset::EVIR_PER_INSTANCE;
geomData.inputParams.bindings[perInstanceRedirectAttrID].stride = asset::getTexelOrBlockBytesize(asset::EF_R32G32_UINT);
if (!cpupipeline)
{
auto pipelinelayout = core::make_smart_refctd_ptr<ICPUPipelineLayout>(
nullptr, nullptr,
core::smart_refctd_ptr(cpuTransformTreeDSLayout),
core::smart_refctd_ptr(cpuPerViewDSLayout)
);
SRasterizationParams rasterParams = {};
if (geom == EGT_CYLINDER)
rasterParams.faceCullingMode = asset::EFCM_NONE;
cpupipeline = core::make_smart_refctd_ptr<ICPURenderpassIndependentPipeline>(
std::move(pipelinelayout), &shaders->get(), &shaders->get() + 2u,
geomData.inputParams, SBlendParams{}, geomData.assemblyParams, rasterParams
);
}
cpumeshes[lod] = core::make_smart_refctd_ptr<ICPUMeshBuffer>();
cpumeshes[lod]->setPipeline(core::smart_refctd_ptr(cpupipeline));
cpumeshes[lod]->setIndexType(geomData.indexType);
cpumeshes[lod]->setIndexCount(geomData.indexCount);
cpumeshes[lod]->setIndexBufferBinding(std::move(geomData.indexBuffer));
for (auto j = 0u; j < ICPUMeshBuffer::MAX_ATTR_BUF_BINDING_COUNT; j++)
cpumeshes[lod]->setVertexBufferBinding(asset::SBufferBinding(geomData.bindings[j]), j);
poly <<= 1u;
}
auto gpumeshes = video::CAssetPreservingGPUObjectFromAssetConverter().getGPUObjectsFromAssets(cpumeshes, cpumeshes + LoDLevels, cpu2gpuParams);
core::smart_refctd_ptr<video::IGPUGraphicsPipeline> pipeline;
{
video::IGPUGraphicsPipeline::SCreationParams params;
params.renderpass = renderpass;
params.renderpassIndependent = core::smart_refctd_ptr_dynamic_cast<video::IGPURenderpassIndependentPipeline>(assetManager->findGPUObject(cpupipeline.get()));
params.subpassIx = 0u;
pipeline = cpu2gpuParams.device->createGPUGraphicsPipeline(nullptr, std::move(params));
}
auto drawcallInfosOutIx = drawcallInfos.size();
drawcallInfos.resize(drawcallInfos.size() + gpumeshes->size());
core::aabbox3df aabb(FLT_MAX, FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX);
lod_library_t::LoDInfo prevInfo;
for (auto lod = 0u; lod < gpumeshes->size(); lod++)
{
auto gpumb = gpumeshes->operator[](lod);
auto& di = drawcallInfos[drawcallInfosOutIx++];
memcpy(di.pushConstantData, gpumb->getPushConstantsDataPtr(), video::IGPUMeshBuffer::MAX_PUSH_CONSTANT_BYTESIZE);
di.pipeline = pipeline;
std::fill_n(di.descriptorSets, video::IGPUPipelineLayout::DESCRIPTOR_SET_COUNT, nullptr);
di.descriptorSets[0] = core::smart_refctd_ptr<const video::IGPUDescriptorSet>(transformTreeDS);
di.descriptorSets[1] = perViewDS;
di.indexType = gpumb->getIndexType();
std::copy_n(gpumb->getVertexBufferBindings(), perInstanceRedirectAttrID, di.vertexBufferBindings);
di.vertexBufferBindings[perInstanceRedirectAttrID] = { perInstanceRedirectAttribs.offset,perInstanceRedirectAttribs.buffer };
di.indexBufferBinding = gpumb->getIndexBufferBinding().buffer;
di.drawCommandStride = sizeof(asset::DrawElementsIndirectCommand_t);
di.drawCountOffset = video::IDrawIndirectAllocator::invalid_draw_count_ix;
di.drawCallOffset = video::IDrawIndirectAllocator::invalid_draw_range_begin;
di.drawMaxCount = 0u;
video::IDrawIndirectAllocator::Allocation mdiAlloc;
mdiAlloc.count = 1u;
mdiAlloc.multiDrawCommandRangeByteOffsets = &di.drawCallOffset;
mdiAlloc.multiDrawCommandMaxCounts = &di.drawMaxCount;
mdiAlloc.multiDrawCommandCountOffsets = &di.drawCountOffset;
mdiAlloc.setAllCommandStructSizesConstant(di.drawCommandStride);
// small enough batches that they could use 16-bit indices
// the dispatcher gains above 4k triangles per batch are asymptotic
// we could probably use smaller batches if we implemented drawcall compaction
// (we wouldn't pay for the extra drawcalls generated by batches that have no instances)
// if the culling system was to be used together with occlusion culling, we could use smaller batch sizes
constexpr auto indicesPerBatch = 3u << 12u;
const auto indexCount = gpumb->getIndexCount();
const auto batchCount = di.drawMaxCount = (indexCount - 1u) / indicesPerBatch + 1u;
lodLibraryData.drawCountData.emplace_back(di.drawMaxCount);
const bool success = drawIndirectAllocator->allocateMultiDraws(mdiAlloc);
assert(success);
lodLibraryData.drawCountOffsets.emplace_back(di.drawCountOffset);
di.drawCountOffset *= sizeof(uint32_t);
//
auto& lodInfo = lodLibraryData.lodInfoData.emplace_back(batchCount);
if (lod)
{
lodInfo = lod_library_t::LoDInfo(batchCount, { 129600.f / exp2f(lod << 1) });
if (!lodInfo.isValid(prevInfo))
{
assert(false && "THE LEVEL OF DETAIL CHOICE PARAMS NEED TO BE MONOTONICALLY DECREASING");
exit(0x45u);
}
}
else
lodInfo = lod_library_t::LoDInfo(batchCount, { 2250000.f });
prevInfo = lodInfo;
//
size_t indexSize;
switch (gpumb->getIndexType())
{
case EIT_16BIT:
indexSize = sizeof(uint16_t);
break;
case EIT_32BIT:
indexSize = sizeof(uint32_t);
break;
default:
assert(false);
break;
}
auto batchID = 0u;
for (auto i = 0u; i < indexCount; i += indicesPerBatch, batchID++)
{
auto& drawCallData = lodLibraryData.drawCallData.emplace_back();
drawCallData.count = core::min(indexCount-i,indicesPerBatch);
drawCallData.instanceCount = 0u;
drawCallData.firstIndex = gpumb->getIndexBufferBinding().offset/indexSize+i;
drawCallData.baseVertex = 0u;
drawCallData.baseInstance = 0xdeadbeefu; // set to garbage to test the prefix sum
lodLibraryData.drawCallOffsetsIn20ByteStrides.emplace_back(di.drawCallOffset / di.drawCommandStride + batchID);
core::aabbox3df batchAABB;
{
// temporarily change the base vertex and index count to make AABB computation easier
auto mb = cpumeshes[lod].get();
auto oldBinding = mb->getIndexBufferBinding();
const auto oldIndexCount = mb->getIndexCount();
mb->setIndexBufferBinding({ oldBinding.offset + i * indexSize,oldBinding.buffer });
mb->setIndexCount(drawCallData.count);
batchAABB = IMeshManipulator::calculateBoundingBox(mb);
mb->setIndexCount(oldIndexCount);
mb->setIndexBufferBinding(std::move(oldBinding));
}
aabb.addInternalBox(batchAABB);
const uint32_t drawCallDWORDOffset = (di.drawCallOffset + batchID * di.drawCommandStride) / sizeof(uint32_t);
lodInfo.drawcallInfos[batchID] = scene::ILevelOfDetailLibrary::DrawcallInfo(
drawCallDWORDOffset, batchAABB
);
}
}
auto& lodTable = lodLibraryData.lodTableData.emplace_back(LoDLevels);
lodTable = scene::ILevelOfDetailLibrary::LoDTableInfo(LoDLevels, aabb);
std::fill_n(lodTable.leveInfoUvec2Offsets, LoDLevels, scene::ILevelOfDetailLibrary::invalid);
{
lod_library_t::Allocation::LevelInfoAllocation lodLevelAllocations[1] =
{
lodTable.leveInfoUvec2Offsets,
lodLibraryData.drawCountData.data() + lodLibraryData.drawCountData.size() - LoDLevels
};
uint32_t lodTableOffsets[1u] = { scene::ILevelOfDetailLibrary::invalid };
const uint32_t lodLevelCounts[1u] = { LoDLevels };
//
lod_library_t::Allocation alloc = {};
{
alloc.count = 1u;
alloc.tableUvec4Offsets = lodTableOffsets;
alloc.levelCounts = lodLevelCounts;
alloc.levelAllocations = lodLevelAllocations;
}
const bool success = lodLibrary->allocateLoDs(alloc);
assert(success);
for (auto i = 0u; i < scene::ILevelOfDetailLibrary::LoDTableInfo::getSizeInAlignmentUnits(LoDLevels); i++)
lodLibraryData.lodTableDstUvec4s.push_back(lodTableOffsets[0] + i);
for (auto lod = 0u; lod < LoDLevels; lod++)
{
const auto drawcallCount = lodLevelAllocations[0].drawcallCounts[lod];
const auto offset = lodLevelAllocations[0].levelUvec2Offsets[lod];
for (auto i = 0u; i < lod_library_t::LoDInfo::getSizeInAlignmentUnits(drawcallCount); i++)
lodLibraryData.lodInfoDstUvec2s.push_back(offset + i);
}
}
cpu2gpuParams.waitForCreationToComplete();
}
#include <random>
#include "assets/common.glsl"
class LoDSystemApp : public ApplicationBase
{
_NBL_STATIC_INLINE_CONSTEXPR uint32_t WIN_W = 1600;
_NBL_STATIC_INLINE_CONSTEXPR uint32_t WIN_H = 900;
_NBL_STATIC_INLINE_CONSTEXPR uint32_t FBO_COUNT = 1u;
_NBL_STATIC_INLINE_CONSTEXPR uint32_t FRAMES_IN_FLIGHT = 5u;
static_assert(FRAMES_IN_FLIGHT > FBO_COUNT);
// lod table entries
_NBL_STATIC_INLINE_CONSTEXPR auto MaxDrawables = EGT_COUNT;
// all the lod infos from all lod entries
_NBL_STATIC_INLINE_CONSTEXPR auto MaxTotalLoDs = 8u * MaxDrawables;
// how many contiguous ranges of drawcalls with explicit draw counts
_NBL_STATIC_INLINE_CONSTEXPR auto MaxMDIs = 16u;
// how many drawcalls (meshlets)
_NBL_STATIC_INLINE_CONSTEXPR auto MaxDrawCalls = 256u;
// how many instances
_NBL_STATIC_INLINE_CONSTEXPR auto MaxInstanceCount = 1677721u; // absolute max for Intel HD Graphics on Windows (to keep within 128MB SSBO limit)
// maximum visible instances of a drawcall (should be a sum of MaxLoDDrawcalls[t]*MaxInstances[t] where t iterates over all LoD Tables)
_NBL_STATIC_INLINE_CONSTEXPR auto MaxTotalVisibleDrawcallInstances = MaxInstanceCount + (MaxInstanceCount >> 8u); // This is literally my worst case guess of how many batch-draw-instances there will be on screen at the same time
public:
void setWindow(core::smart_refctd_ptr<nbl::ui::IWindow>&& wnd) override
{
window = std::move(wnd);
}
void setSystem(core::smart_refctd_ptr<nbl::system::ISystem>&& s) override
{
system = std::move(s);
}
nbl::ui::IWindow* getWindow() override
{
return window.get();
}
video::IAPIConnection* getAPIConnection() override
{
return gl.get();
}
video::ILogicalDevice* getLogicalDevice() override
{
return logicalDevice.get();
}
video::IGPURenderpass* getRenderpass() override
{
return renderpass.get();
}
void setSurface(core::smart_refctd_ptr<video::ISurface>&& s) override
{
surface = std::move(s);
}
void setFBOs(std::vector<core::smart_refctd_ptr<video::IGPUFramebuffer>>& f) override
{
for (int i = 0; i < f.size(); i++)
{
fbos[i] = core::smart_refctd_ptr(f[i]);
}
}
void setSwapchain(core::smart_refctd_ptr<video::ISwapchain>&& s) override
{
swapchain = std::move(s);
}
uint32_t getSwapchainImageCount() override
{
return FBO_COUNT;
}
virtual nbl::asset::E_FORMAT getDepthFormat() override
{
return nbl::asset::EF_D32_SFLOAT;
}
APP_CONSTRUCTOR(LoDSystemApp)
void onAppInitialized_impl() override
{
initOutput.window = core::smart_refctd_ptr(window);
initOutput.system = core::smart_refctd_ptr(system);
const auto swapchainImageUsage = static_cast<asset::IImage::E_USAGE_FLAGS>(asset::IImage::EUF_COLOR_ATTACHMENT_BIT | asset::IImage::EUF_TRANSFER_DST_BIT);
const video::ISurface::SFormat surfaceFormat(asset::EF_B8G8R8A8_SRGB, asset::ECP_COUNT, asset::EOTF_UNKNOWN);
CommonAPI::InitWithDefaultExt(initOutput, video::EAT_OPENGL_ES, "Level of Detail System", WIN_W, WIN_H, FBO_COUNT, swapchainImageUsage, surfaceFormat, asset::EF_D32_SFLOAT);
window = std::move(initOutput.window);
gl = std::move(initOutput.apiConnection);
surface = std::move(initOutput.surface);
gpuPhysicalDevice = std::move(initOutput.physicalDevice);
logicalDevice = std::move(initOutput.logicalDevice);
queues = std::move(initOutput.queues);
swapchain = std::move(initOutput.swapchain);
renderpass = std::move(initOutput.renderpass);
fbos = std::move(initOutput.fbo);
commandPools = std::move(initOutput.commandPools);
assetManager = std::move(initOutput.assetManager);
logger = std::move(initOutput.logger);
inputSystem = std::move(initOutput.inputSystem);
system = std::move(initOutput.system);
windowCallback = std::move(initOutput.windowCb);
cpu2gpuParams = std::move(initOutput.cpu2gpuParams);
utilities = std::move(initOutput.utilities);
transferUpQueue = queues[CommonAPI::InitOutput::EQT_TRANSFER_UP];
ttm = scene::ITransformTreeManager::create(utilities.get(),transferUpQueue);
tt = scene::ITransformTreeWithNormalMatrices::create(logicalDevice.get(),MaxInstanceCount);
const auto* ctt = tt.get(); // fight compiler, hard
const video::IPropertyPool* nodePP = ctt->getNodePropertyPool();
asset::SBufferRange<video::IGPUBuffer> nodeList;
// Drawcall Allocator
{
video::IDrawIndirectAllocator::ImplicitBufferCreationParameters drawAllocatorParams;
drawAllocatorParams.device = logicalDevice.get();
drawAllocatorParams.maxDrawCommandStride = sizeof(asset::DrawElementsIndirectCommand_t);
drawAllocatorParams.drawCommandCapacity = MaxDrawCalls;
drawAllocatorParams.drawCountCapacity = MaxMDIs;
drawIndirectAllocator = video::CDrawIndirectAllocator<>::create(std::move(drawAllocatorParams));
}
// LoD Library
lodLibrary = lod_library_t::create({ logicalDevice.get(),MaxDrawables,MaxTotalLoDs,MaxDrawCalls });
// Culling System
core::smart_refctd_ptr<video::IDescriptorPool> cullingDSPool;
cullPushConstants.instanceCount = 0u;
{
constexpr auto LayoutCount = 4u;
core::smart_refctd_ptr<video::IGPUDescriptorSetLayout> layouts[LayoutCount] =
{
scene::ILevelOfDetailLibrary::createDescriptorSetLayout(logicalDevice.get()),
culling_system_t::createInputDescriptorSetLayout(logicalDevice.get()),
culling_system_t::createOutputDescriptorSetLayout(logicalDevice.get()),
[&]() -> core::smart_refctd_ptr<video::IGPUDescriptorSetLayout>
{
// TODO: figure out what should be here
constexpr auto BindingCount = 1u;
video::IGPUDescriptorSetLayout::SBinding bindings[BindingCount];
for (auto i = 0u; i < BindingCount; i++)
{
bindings[i].binding = i;
bindings[i].type = asset::EDT_STORAGE_BUFFER;
bindings[i].count = 1u;
bindings[i].stageFlags = asset::IShader::ESS_COMPUTE;
bindings[i].samplers = nullptr;
}
return logicalDevice->createGPUDescriptorSetLayout(bindings,bindings + BindingCount);
}()
};
cullingDSPool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE, &layouts->get(), &layouts->get() + LayoutCount);
const asset::SPushConstantRange range = { asset::IShader::ESS_COMPUTE,0u,sizeof(CullPushConstants_t) };
cullingSystem = culling_system_t::create(
core::smart_refctd_ptr<video::CScanner>(utilities->getDefaultScanner()), &range, &range + 1u, core::smart_refctd_ptr(layouts[3]),
localInputCWD, "\n#include \"common.glsl\"\n", "\n#include \"cull_overrides.glsl\"\n"
);
cullingParams.indirectDispatchParams = { 0ull,culling_system_t::createDispatchIndirectBuffer(utilities.get(),transferUpQueue) };
{
video::IGPUBuffer::SCreationParams params;
params.usage = asset::IBuffer::EUF_STORAGE_BUFFER_BIT;
nodeList = {0ull,~0ull,logicalDevice->createDeviceLocalGPUBufferOnDedMem(params,sizeof(uint32_t)+sizeof(scene::ITransformTree::node_t)*MaxInstanceCount)};
nodeList.buffer->setObjectDebugName("transformTreeNodeList");
cullingParams.instanceList = {0ull,~0ull,logicalDevice->createDeviceLocalGPUBufferOnDedMem(params,sizeof(culling_system_t::InstanceToCull)*MaxInstanceCount)};
}
cullingParams.scratchBufferRanges = culling_system_t::createScratchBuffer(utilities->getDefaultScanner(), MaxInstanceCount, MaxTotalVisibleDrawcallInstances);
cullingParams.drawCalls = drawIndirectAllocator->getDrawCommandMemoryBlock();
cullingParams.perViewPerInstance = { 0ull,~0ull,culling_system_t::createPerViewPerInstanceDataBuffer<PerViewPerInstance_t>(logicalDevice.get(),MaxInstanceCount) };
cullingParams.perInstanceRedirectAttribs = { 0ul,~0ull,culling_system_t::createInstanceRedirectBuffer(logicalDevice.get(),MaxTotalVisibleDrawcallInstances) };
const auto drawCountsBlock = drawIndirectAllocator->getDrawCountMemoryBlock();
if (drawCountsBlock)
cullingParams.drawCounts = *drawCountsBlock;
cullingParams.lodLibraryDS = core::smart_refctd_ptr<video::IGPUDescriptorSet>(lodLibrary->getDescriptorSet());
cullingParams.transientOutputDS = culling_system_t::createOutputDescriptorSet(
logicalDevice.get(), cullingDSPool.get(), std::move(layouts[2]),
cullingParams.drawCalls,
cullingParams.perViewPerInstance,
cullingParams.perInstanceRedirectAttribs,
cullingParams.drawCounts
);
cullingParams.customDS = logicalDevice->createGPUDescriptorSet(cullingDSPool.get(), std::move(layouts[3]));
{
video::IGPUDescriptorSet::SWriteDescriptorSet write;
video::IGPUDescriptorSet::SDescriptorInfo info(nodePP->getPropertyMemoryBlock(scene::ITransformTree::global_transform_prop_ix));
write.dstSet = cullingParams.customDS.get();
write.binding = 0u;
write.arrayElement = 0u;
write.count = 1u;
write.descriptorType = EDT_STORAGE_BUFFER;
write.info = &info;
logicalDevice->updateDescriptorSets(1u, &write, 0u, nullptr);
}
cullingParams.indirectDispatchParams.buffer->setObjectDebugName("CullingIndirect");
cullingParams.drawCalls.buffer->setObjectDebugName("DrawCallPool");
cullingParams.perInstanceRedirectAttribs.buffer->setObjectDebugName("PerInstanceInputAttribs");
if (cullingParams.drawCounts.buffer)
cullingParams.drawCounts.buffer->setObjectDebugName("DrawCountPool");
cullingParams.perViewPerInstance.buffer->setObjectDebugName("DrawcallInstanceRedirects");
cullingParams.indirectInstanceCull = false;
}
core::smart_refctd_ptr<ICPUSpecializedShader> shaders[2];
{
IAssetLoader::SAssetLoadParams lp;
lp.workingDirectory = localInputCWD;
lp.logger = logger.get();
auto vertexShaderBundle = assetManager->getAsset("mesh.vert", lp);
auto fragShaderBundle = assetManager->getAsset("mesh.frag", lp);
shaders[0] = IAsset::castDown<ICPUSpecializedShader>(*vertexShaderBundle.getContents().begin());
shaders[1] = IAsset::castDown<ICPUSpecializedShader>(*fragShaderBundle.getContents().begin());
}
core::smart_refctd_ptr<video::IGPUDescriptorSet> perViewDS;
core::smart_refctd_ptr<ICPUDescriptorSetLayout> cpuPerViewDSLayout;
{
constexpr auto BindingCount = 1;
ICPUDescriptorSetLayout::SBinding cpuBindings[BindingCount];
for (auto i = 0; i < BindingCount; i++)
{
cpuBindings[i].binding = i;
cpuBindings[i].count = 1u;
cpuBindings[i].stageFlags = IShader::ESS_VERTEX;
cpuBindings[i].samplers = nullptr;
}
cpuBindings[0].type = EDT_STORAGE_BUFFER;
cpuPerViewDSLayout = core::make_smart_refctd_ptr<ICPUDescriptorSetLayout>(cpuBindings, cpuBindings + BindingCount);
auto bindings = reinterpret_cast<video::IGPUDescriptorSetLayout::SBinding*>(cpuBindings);
auto perViewDSLayout = logicalDevice->createGPUDescriptorSetLayout(bindings, bindings + BindingCount);
auto dsPool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE, &perViewDSLayout.get(), &perViewDSLayout.get() + 1u);
perViewDS = logicalDevice->createGPUDescriptorSet(dsPool.get(), std::move(perViewDSLayout));
{
video::IGPUDescriptorSet::SWriteDescriptorSet writes[BindingCount];
video::IGPUDescriptorSet::SDescriptorInfo infos[BindingCount];
for (auto i = 0; i < BindingCount; i++)
{
writes[i].dstSet = perViewDS.get();
writes[i].binding = i;
writes[i].arrayElement = 0u;
writes[i].count = 1u;
writes[i].info = infos + i;
}
writes[0].descriptorType = EDT_STORAGE_BUFFER;
infos[0].desc = cullingParams.perViewPerInstance.buffer;
infos[0].buffer = { 0u,video::IGPUDescriptorSet::SDescriptorInfo::SBufferInfo::WholeBuffer };
logicalDevice->updateDescriptorSets(BindingCount, writes, 0u, nullptr);
}
}
// descset for global tform updates
{
auto layout = ttm->createRecomputeGlobalTransformsDescriptorSetLayout(logicalDevice.get());
auto pool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE,&layout.get(),&layout.get()+1u);
recomputeGlobalTransformsDS = logicalDevice->createGPUDescriptorSet(pool.get(),std::move(layout));
ttm->updateRecomputeGlobalTransformsDescriptorSet(logicalDevice.get(),recomputeGlobalTransformsDS.get(),{0ull,nodeList.buffer});
}
std::mt19937 mt(0x45454545u);
std::uniform_int_distribution<uint32_t> typeDist(0, EGT_COUNT - 1u);
std::uniform_real_distribution<float> rotationDist(0, 2.f * core::PI<float>());
std::uniform_real_distribution<float> posDist(-1200.f, 1200.f);
{
video::CSubpassKiln kiln;
{
LoDLibraryData lodLibraryData;
uint32_t lodTables[EGT_COUNT];
// create all the LoDs of drawables
{
auto* qnc = assetManager->getMeshManipulator()->getQuantNormalCache();
//loading cache from file
const system::path cachePath = sharedOutputCWD / "normalCache101010.sse";
if (!qnc->loadCacheFromFile<asset::EF_A2B10G10R10_SNORM_PACK32>(system.get(), cachePath))
int a = 0;// logger->log("%s", ILogger::ELL_ERROR, "Couldn't load cache.");
//
core::smart_refctd_ptr<asset::ICPUDescriptorSetLayout> cpuTransformTreeDSLayout = scene::ITransformTreeWithNormalMatrices::createRenderDescriptorSetLayout();
// populating `lodTables` is a bit messy, I know
size_t lodTableIx = lodLibraryData.lodTableDstUvec4s.size();
addLoDTable<EGT_CUBE, 1>(
assetManager.get(), cpuTransformTreeDSLayout, cpuPerViewDSLayout, shaders, cpu2gpuParams,
lodLibraryData, drawIndirectAllocator.get(), lodLibrary.get(), kiln.getDrawcallMetadataVector(),
cullingParams.perInstanceRedirectAttribs, renderpass, ctt->getRenderDescriptorSet(), perViewDS
);
lodTables[EGT_CUBE] = lodLibraryData.lodTableDstUvec4s[lodTableIx];
lodTableIx = lodLibraryData.lodTableDstUvec4s.size();
addLoDTable<EGT_SPHERE, 7>(
assetManager.get(), cpuTransformTreeDSLayout, cpuPerViewDSLayout, shaders, cpu2gpuParams,
lodLibraryData, drawIndirectAllocator.get(), lodLibrary.get(), kiln.getDrawcallMetadataVector(),
cullingParams.perInstanceRedirectAttribs, renderpass, ctt->getRenderDescriptorSet(), perViewDS
);
lodTables[EGT_SPHERE] = lodLibraryData.lodTableDstUvec4s[lodTableIx];
lodTableIx = lodLibraryData.lodTableDstUvec4s.size();
addLoDTable<EGT_CYLINDER, 6>(
assetManager.get(), cpuTransformTreeDSLayout, cpuPerViewDSLayout, shaders, cpu2gpuParams,
lodLibraryData, drawIndirectAllocator.get(), lodLibrary.get(), kiln.getDrawcallMetadataVector(),
cullingParams.perInstanceRedirectAttribs, renderpass, ctt->getRenderDescriptorSet(), perViewDS
);
lodTables[EGT_CYLINDER] = lodLibraryData.lodTableDstUvec4s[lodTableIx];
//! cache results -- speeds up mesh generation on second run
qnc->saveCacheToFile<asset::EF_A2B10G10R10_SNORM_PACK32>(system.get(), cachePath);
}
constexpr auto MaxTransfers = 8u;
video::CPropertyPoolHandler::UpStreamingRequest upstreamRequests[MaxTransfers];
// set up the instance list
core::vector<scene::ITransformTree::node_t> instanceGUIDs(
std::uniform_int_distribution<uint32_t>(MaxInstanceCount >> 1u, MaxInstanceCount)(mt), // Instance Count
scene::ITransformTree::invalid_node
);
const uint32_t objectCount = instanceGUIDs.size();
core::vector<core::matrix3x4SIMD> instanceTransforms(objectCount);
for (auto& tform : instanceTransforms)
{
tform.setRotation(core::quaternion(rotationDist(mt), rotationDist(mt), rotationDist(mt)));
tform.setTranslation(core::vectorSIMDf(posDist(mt), posDist(mt), posDist(mt)));
}
{
tt->allocateNodes({instanceGUIDs.data(),instanceGUIDs.data()+objectCount});
utilities->updateBufferRangeViaStagingBuffer(transferUpQueue,{0u,sizeof(uint32_t),nodeList.buffer},&objectCount);
utilities->updateBufferRangeViaStagingBuffer(transferUpQueue,{sizeof(uint32_t),objectCount*sizeof(scene::ITransformTree::node_t),nodeList.buffer},instanceGUIDs.data());
scene::ITransformTreeManager::UpstreamRequest request;
request.tree = tt.get();
request.parents = {}; // no parents
request.relativeTransforms.device2device = false;
request.relativeTransforms.data = instanceTransforms.data();
// TODO: make an `UpstreamRequest` which allows for sourcing the node list from GPUBuffer
request.nodes = {instanceGUIDs.data(),instanceGUIDs.data()+objectCount};
ttm->setupTransfers(request,upstreamRequests);
core::vector<culling_system_t::InstanceToCull> instanceList; instanceList.reserve(objectCount);
for (auto instanceGUID : instanceGUIDs)
{
auto& instance = instanceList.emplace_back();
instance.instanceGUID = instanceGUID;
instance.lodTableUvec4Offset = lodTables[typeDist(mt)];
}
utilities->updateBufferRangeViaStagingBuffer(transferUpQueue, { 0u,instanceList.size()*sizeof(culling_system_t::InstanceToCull),cullingParams.instanceList.buffer }, instanceList.data());
cullPushConstants.instanceCount += instanceList.size();
}
cullingParams.drawcallCount = lodLibraryData.drawCallData.size();
// do the transfer of drawcall and LoD data
{
constexpr auto TTMTransfers = scene::ITransformTreeManager::TransferCount;
for (auto i=TTMTransfers; i<MaxTransfers; i++)
{
upstreamRequests[i].fill = false;
upstreamRequests[i].source.device2device = false;
upstreamRequests[i].srcAddresses = nullptr; // iota 0,1,2,3,4,etc.
}
upstreamRequests[TTMTransfers + 0].destination = drawIndirectAllocator->getDrawCommandMemoryBlock();
upstreamRequests[TTMTransfers + 0].elementSize = sizeof(asset::DrawElementsIndirectCommand_t);
upstreamRequests[TTMTransfers + 0].elementCount = cullingParams.drawcallCount;
upstreamRequests[TTMTransfers + 0].source.data = lodLibraryData.drawCallData.data();
upstreamRequests[TTMTransfers + 0].dstAddresses = lodLibraryData.drawCallOffsetsIn20ByteStrides.data();
upstreamRequests[TTMTransfers + 1].destination = lodLibrary->getLoDInfoBinding();
upstreamRequests[TTMTransfers + 1].elementSize = alignof(lod_library_t::LoDInfo);
upstreamRequests[TTMTransfers + 1].elementCount = lodLibraryData.lodInfoDstUvec2s.size();
upstreamRequests[TTMTransfers + 1].source.data = lodLibraryData.lodInfoData.data();
upstreamRequests[TTMTransfers + 1].dstAddresses = lodLibraryData.lodInfoDstUvec2s.data();
upstreamRequests[TTMTransfers + 2].destination = lodLibrary->getLodTableInfoBinding();
upstreamRequests[TTMTransfers + 2].elementSize = alignof(scene::ILevelOfDetailLibrary::LoDTableInfo);
upstreamRequests[TTMTransfers + 2].elementCount = lodLibraryData.lodTableDstUvec4s.size();
upstreamRequests[TTMTransfers + 2].source.data = lodLibraryData.lodTableData.data();
upstreamRequests[TTMTransfers + 2].dstAddresses = lodLibraryData.lodTableDstUvec4s.data();
auto requestCount = TTMTransfers + 3u;
if (drawIndirectAllocator->getDrawCountMemoryBlock())
{
upstreamRequests[requestCount].destination = *drawIndirectAllocator->getDrawCountMemoryBlock();
upstreamRequests[requestCount].elementSize = sizeof(uint32_t);
upstreamRequests[requestCount].elementCount = lodLibraryData.drawCountOffsets.size();
upstreamRequests[requestCount].source.data = lodLibraryData.drawCountData.data();
upstreamRequests[requestCount].dstAddresses = lodLibraryData.drawCountOffsets.data();
requestCount++;
}
core::smart_refctd_ptr<video::IGPUCommandBuffer> tferCmdBuf;
logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_TRANSFER_UP].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1u, &tferCmdBuf);
auto fence = logicalDevice->createFence(video::IGPUFence::ECF_UNSIGNALED);
tferCmdBuf->begin(0u); // TODO some one time submit bit or something
{
auto ppHandler = utilities->getDefaultPropertyPoolHandler();
asset::SBufferBinding<video::IGPUBuffer> scratch;
{
video::IGPUBuffer::SCreationParams scratchParams = {};
scratchParams.canUpdateSubRange = true;
scratchParams.usage = core::bitflag(video::IGPUBuffer::EUF_TRANSFER_DST_BIT) | video::IGPUBuffer::EUF_STORAGE_BUFFER_BIT;
scratch = { 0ull,logicalDevice->createDeviceLocalGPUBufferOnDedMem(scratchParams,ppHandler->getMaxScratchSize()) };
scratch.buffer->setObjectDebugName("Scratch Buffer");
}
auto* pRequests = upstreamRequests;
uint32_t waitSemaphoreCount = 0u;
video::IGPUSemaphore* const* waitSemaphores = nullptr;
const asset::E_PIPELINE_STAGE_FLAGS* waitStages = nullptr;
ppHandler->transferProperties(
utilities->getDefaultUpStreamingBuffer(), tferCmdBuf.get(), fence.get(), transferUpQueue, scratch,
pRequests, requestCount, waitSemaphoreCount, waitSemaphores, waitStages,
logger.get(), std::chrono::high_resolution_clock::time_point::max() // must finish
);
}
// also clear the scratch
cullingSystem->clearScratch(tferCmdBuf.get(),cullingParams.scratchBufferRanges.lodDrawCallCounts,cullingParams.scratchBufferRanges.prefixSumScratch);
tferCmdBuf->end();
{
video::IGPUQueue::SSubmitInfo submit = {}; // intializes all semaphore stuff to 0 and nullptr
submit.commandBufferCount = 1u;
submit.commandBuffers = &tferCmdBuf.get();
transferUpQueue->submit(1u, &submit, fence.get());
}
logicalDevice->blockForFences(1u, &fence.get());
}
// set up the remaining descriptor sets of the culling system
{
auto& drawCallOffsetsInDWORDs = lodLibraryData.drawCallOffsetsIn20ByteStrides;
for (auto i = 0u; i < cullingParams.drawcallCount; i++)
drawCallOffsetsInDWORDs[i] = lodLibraryData.drawCallOffsetsIn20ByteStrides[i] * sizeof(asset::DrawElementsIndirectCommand_t) / sizeof(uint32_t);
cullingParams.transientInputDS = culling_system_t::createInputDescriptorSet(
logicalDevice.get(), cullingDSPool.get(),
culling_system_t::createInputDescriptorSetLayout(logicalDevice.get()),
cullingParams.indirectDispatchParams,
cullingParams.instanceList,
cullingParams.scratchBufferRanges,
{ 0ull,~0ull,utilities->createFilledDeviceLocalGPUBufferOnDedMem(transferUpQueue,cullingParams.drawcallCount * sizeof(uint32_t),drawCallOffsetsInDWORDs.data()) },
{ 0ull,~0ull,utilities->createFilledDeviceLocalGPUBufferOnDedMem(transferUpQueue,lodLibraryData.drawCountOffsets.size() * sizeof(uint32_t),lodLibraryData.drawCountOffsets.data()) }
);
}
}
// prerecord the secondary cmdbuffer
{
logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_GRAPHICS].get(), video::IGPUCommandBuffer::EL_SECONDARY, 1u, &bakedCommandBuffer);
bakedCommandBuffer->begin(video::IGPUCommandBuffer::EU_RENDER_PASS_CONTINUE_BIT | video::IGPUCommandBuffer::EU_SIMULTANEOUS_USE_BIT);
// TODO: handle teh offsets
auto drawCountBlock = drawIndirectAllocator->getDrawCountMemoryBlock();
kiln.bake(bakedCommandBuffer.get(), renderpass.get(), 0u, drawIndirectAllocator->getDrawCommandMemoryBlock().buffer.get(), drawIndirectAllocator->supportsMultiDrawIndirectCount() ? drawCountBlock->buffer.get():nullptr);
bakedCommandBuffer->end();
}
}
core::vectorSIMDf cameraPosition(0, 5, -10);
matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), float(WIN_W) / WIN_H, 2.f, 4000.f);
{
cullPushConstants.fovDilationFactor = decltype(lod_library_t::LoDInfo::choiceParams)::getFoVDilationFactor(projectionMatrix);
// dilate by resolution as well, because the LoD distances were tweaked @ 720p
cullPushConstants.fovDilationFactor *= float(window->getWidth() * window->getHeight()) / float(1280u * 720u);
}
camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), projectionMatrix, 2.f, 1.f);
oracle.reportBeginFrameRecord();
logicalDevice->createCommandBuffers(commandPools[CommonAPI::InitOutput::EQT_GRAPHICS].get(), video::IGPUCommandBuffer::EL_PRIMARY, FRAMES_IN_FLIGHT, commandBuffers);
for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++)
{
imageAcquire[i] = logicalDevice->createSemaphore();
renderFinished[i] = logicalDevice->createSemaphore();
}
}
void onAppTerminated_impl() override
{
lodLibrary->clear();
drawIndirectAllocator->clear();
const auto& fboCreationParams = fbos[acquiredNextFBO]->getCreationParameters();
auto gpuSourceImageView = fboCreationParams.attachments[0];
bool status = ext::ScreenShot::createScreenShot(
logicalDevice.get(),
queues[CommonAPI::InitOutput::EQT_TRANSFER_DOWN],
renderFinished[resourceIx].get(),
gpuSourceImageView.get(),
assetManager.get(),
"ScreenShot.png",
asset::EIL_PRESENT_SRC,
static_cast<asset::E_ACCESS_FLAGS>(0u));
assert(status);
}
void workLoopBody() override
{
++resourceIx;
if (resourceIx >= FRAMES_IN_FLIGHT)
resourceIx = 0;
auto& commandBuffer = commandBuffers[resourceIx];
auto& fence = frameComplete[resourceIx];
if (fence)
logicalDevice->blockForFences(1u, &fence.get());
else
fence = logicalDevice->createFence(static_cast<video::IGPUFence::E_CREATE_FLAGS>(0));
//
commandBuffer->reset(nbl::video::IGPUCommandBuffer::ERF_RELEASE_RESOURCES_BIT);
commandBuffer->begin(0);
// late latch input
const auto nextPresentationTimestamp = oracle.acquireNextImage(swapchain.get(), imageAcquire[resourceIx].get(), nullptr, &acquiredNextFBO);
// input
{
inputSystem->getDefaultMouse(&mouse);
inputSystem->getDefaultKeyboard(&keyboard);
camera.beginInputProcessing(nextPresentationTimestamp);
mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, logger.get());
keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, logger.get());
camera.endInputProcessing(nextPresentationTimestamp);
}
// update transforms
{
// buffers to barrier
video::IGPUCommandBuffer::SBufferMemoryBarrier barriers[scene::ITransformTreeManager::SBarrierSuggestion::MaxBufferCount];
auto setBufferBarrier = [&barriers,commandBuffer](const uint32_t ix, const asset::SBufferRange<video::IGPUBuffer>& range, const asset::SMemoryBarrier& barrier)
{
barriers[ix].barrier = barrier;
barriers[ix].dstQueueFamilyIndex = barriers[ix].srcQueueFamilyIndex = commandBuffer->getQueueFamilyIndex();
barriers[ix].buffer = range.buffer;
barriers[ix].offset = range.offset;
barriers[ix].size = range.size;
};
// not going to barrier between last frame culling and rendering and TTM recompute, because its not in the same submit
scene::ITransformTreeManager::BaseParams baseParams;
baseParams.cmdbuf = commandBuffer.get();
baseParams.tree = tt.get();
baseParams.logger = logger.get();
scene::ITransformTreeManager::DispatchParams dispatchParams;
dispatchParams.indirect.buffer = nullptr;
dispatchParams.direct.nodeCount = cullPushConstants.instanceCount;
ttm->recomputeGlobalTransforms(baseParams,dispatchParams,recomputeGlobalTransformsDS.get());
// barrier between TTM recompute and TTM recompute+culling system
{
const auto* ctt = tt.get();
auto node_pp = ctt->getNodePropertyPool();
auto sugg = scene::ITransformTreeManager::barrierHelper(scene::ITransformTreeManager::SBarrierSuggestion::EF_POST_GLOBAL_TFORM_RECOMPUTE);
sugg.dstStageMask |= asset::EPSF_VERTEX_SHADER_BIT; // also rendering shader (to read the normal matrix transforms)
uint32_t barrierCount = 0u;
setBufferBarrier(barrierCount++,node_pp->getPropertyMemoryBlock(scene::ITransformTree::global_transform_prop_ix),sugg.globalTransforms);
setBufferBarrier(barrierCount++,node_pp->getPropertyMemoryBlock(scene::ITransformTree::recomputed_stamp_prop_ix),sugg.recomputedTimestamps);
setBufferBarrier(barrierCount++,node_pp->getPropertyMemoryBlock(scene::ITransformTreeWithNormalMatrices::normal_matrix_prop_ix),sugg.normalMatrices);
commandBuffer->pipelineBarrier(sugg.srcStageMask,sugg.dstStageMask,asset::EDF_NONE,0u,nullptr,barrierCount,barriers,0u,nullptr);
}
}
// cull, choose LoDs, and fill our draw indirects
{
const auto* layout = cullingSystem->getInstanceCullAndLoDSelectLayout();
cullPushConstants.viewProjMat = camera.getConcatenatedMatrix();
std::copy_n(camera.getPosition().pointer, 3u, cullPushConstants.camPos.comp);
commandBuffer->pushConstants(layout, asset::IShader::ESS_COMPUTE, 0u, sizeof(cullPushConstants), &cullPushConstants);
cullingParams.cmdbuf = commandBuffer.get();
cullingSystem->processInstancesAndFillIndirectDraws(cullingParams,cullPushConstants.instanceCount);
}
// renderpass
{
asset::SViewport viewport;
viewport.minDepth = 1.f;
viewport.maxDepth = 0.f;
viewport.x = 0u;
viewport.y = 0u;
viewport.width = WIN_W;
viewport.height = WIN_H;
commandBuffer->setViewport(0u, 1u, &viewport);
nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo;
{
VkRect2D area;
area.offset = { 0,0 };
area.extent = { WIN_W, WIN_H };
asset::SClearValue clear[2] = {};
clear[0].color.float32[0] = 1.f;
clear[0].color.float32[1] = 1.f;
clear[0].color.float32[2] = 1.f;
clear[0].color.float32[3] = 1.f;
clear[1].depthStencil.depth = 0.f;
beginInfo.clearValueCount = 2u;
beginInfo.framebuffer = fbos[acquiredNextFBO];
beginInfo.renderpass = renderpass;
beginInfo.renderArea = area;
beginInfo.clearValues = clear;
}
commandBuffer->beginRenderPass(&beginInfo, nbl::asset::ESC_INLINE);
commandBuffer->executeCommands(1u, &bakedCommandBuffer.get());
commandBuffer->endRenderPass();
commandBuffer->end();
}
CommonAPI::Submit(logicalDevice.get(), swapchain.get(), commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], imageAcquire[resourceIx].get(), renderFinished[resourceIx].get(), fence.get());
CommonAPI::Present(logicalDevice.get(), swapchain.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], renderFinished[resourceIx].get(), acquiredNextFBO);
}
bool keepRunning() override
{
return windowCallback->isWindowOpen();
}
private:
CommonAPI::InitOutput initOutput;
nbl::core::smart_refctd_ptr<nbl::ui::IWindow> window;
nbl::core::smart_refctd_ptr<nbl::video::IAPIConnection> gl;
nbl::core::smart_refctd_ptr<nbl::video::ISurface> surface;
nbl::video::IPhysicalDevice* gpuPhysicalDevice;
nbl::core::smart_refctd_ptr<nbl::video::ILogicalDevice> logicalDevice;
std::array<video::IGPUQueue*, CommonAPI::InitOutput::MaxQueuesCount> queues;
nbl::core::smart_refctd_ptr<nbl::video::ISwapchain> swapchain;
nbl::core::smart_refctd_ptr<nbl::video::IGPURenderpass> renderpass;
std::array<nbl::core::smart_refctd_ptr<nbl::video::IGPUFramebuffer>, CommonAPI::InitOutput::MaxSwapChainImageCount> fbos;
std::array<nbl::core::smart_refctd_ptr<nbl::video::IGPUCommandPool>, CommonAPI::InitOutput::MaxQueuesCount> commandPools;
nbl::core::smart_refctd_ptr<nbl::asset::IAssetManager> assetManager;
nbl::core::smart_refctd_ptr<nbl::system::ILogger> logger;
nbl::core::smart_refctd_ptr<CommonAPI::InputSystem> inputSystem;
nbl::core::smart_refctd_ptr<nbl::system::ISystem> system;
nbl::core::smart_refctd_ptr<CommonAPI::CommonAPIEventCallback> windowCallback;
nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams;
nbl::core::smart_refctd_ptr<nbl::video::IUtilities> utilities;
nbl::video::IGPUQueue* transferUpQueue = nullptr;
nbl::core::smart_refctd_ptr<nbl::scene::ITransformTreeManager> ttm;
nbl::core::smart_refctd_ptr<nbl::scene::ITransformTree> tt;
nbl::core::smart_refctd_ptr<nbl::video::IGPUDescriptorSet> recomputeGlobalTransformsDS;
Camera camera = Camera(vectorSIMDf(0, 0, 0), vectorSIMDf(0, 0, 0), matrix4SIMD());
CommonAPI::InputSystem::ChannelReader<IMouseEventChannel> mouse;
CommonAPI::InputSystem::ChannelReader<IKeyboardEventChannel> keyboard;
core::smart_refctd_ptr<lod_library_t> lodLibrary;
core::smart_refctd_ptr<culling_system_t> cullingSystem;
CullPushConstants_t cullPushConstants;
culling_system_t::Params cullingParams;
core::smart_refctd_ptr<video::CDrawIndirectAllocator<>> drawIndirectAllocator;
core::smart_refctd_ptr<video::IGPUCommandBuffer> commandBuffers[FRAMES_IN_FLIGHT];
core::smart_refctd_ptr<video::IGPUCommandBuffer> bakedCommandBuffer;
core::smart_refctd_ptr<video::IGPUFence> frameComplete[FRAMES_IN_FLIGHT] = { nullptr };
core::smart_refctd_ptr<video::IGPUSemaphore> imageAcquire[FRAMES_IN_FLIGHT] = { nullptr };
core::smart_refctd_ptr<video::IGPUSemaphore> renderFinished[FRAMES_IN_FLIGHT] = { nullptr };
video::CDumbPresentationOracle oracle;
uint32_t acquiredNextFBO = {};
int32_t resourceIx = -1;
};
NBL_COMMON_API_MAIN(LoDSystemApp)
| 57.97397
| 239
| 0.627479
|
deprilula28
|
9062ce2842494425e6a4ea1295d791f91160075f
| 7,557
|
cpp
|
C++
|
server/Server/Packets/CGStallRemoveItemHandler.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 3
|
2018-06-19T21:37:38.000Z
|
2021-07-31T21:51:40.000Z
|
server/Server/Packets/CGStallRemoveItemHandler.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | null | null | null |
server/Server/Packets/CGStallRemoveItemHandler.cpp
|
viticm/web-pap
|
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
|
[
"BSD-3-Clause"
] | 13
|
2015-01-30T17:45:06.000Z
|
2022-01-06T02:29:34.000Z
|
#include "stdafx.h"
/*
客户端通知服务器从摊位中拿走此物品
*/
#include "CGStallRemoveItem.h"
#include "GCStallRemoveItem.h"
#include "GamePlayer.h"
#include "Obj_Human.h"
#include "Scene.h"
#include "Log.h"
#include "ItemOperator.h"
#include "HumanItemLogic.h"
UINT CGStallRemoveItemHandler::Execute( CGStallRemoveItem* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
GamePlayer* pGamePlayer = (GamePlayer*)pPlayer ;
Assert( pGamePlayer ) ;
Obj_Human* pHuman = pGamePlayer->GetHuman() ;
Assert( pHuman ) ;
Scene* pScene = pHuman->getScene() ;
if( pScene==NULL )
{
Assert(FALSE) ;
return PACKET_EXE_ERROR ;
}
//检查线程执行资源是否正确
Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
_ITEM_GUID ItemGuid = pPacket->GetObjGUID();
PET_GUID_t PetGuid = pPacket->GetPetGUID();
BYTE ToType = pPacket->GetToType();
UINT Serial = pPacket->GetSerial();
if(pHuman->m_StallBox.GetStallStatus() != ServerStallBox::STALL_OPEN)
{
GCStallError Msg;
Msg.SetID(STALL_MSG::ERR_ILLEGAL);
pGamePlayer->SendPacket(&Msg);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: != ServerStallBox::STALL_OPEN"
,pHuman->GetName()) ;
return PACKET_EXE_CONTINUE;
}
ItemContainer* pStallContainer = pHuman->m_StallBox.GetContainer();
ItemContainer* pStallPetContainer = pHuman->m_StallBox.GetPetContainer();
GCStallError MsgError;
GCStallRemoveItem MsgRemoveItem;
switch(ToType)
{
case STALL_MSG::POS_BAG:
{
INT IndexInStall = pStallContainer->GetIndexByGUID(&ItemGuid);
if(IndexInStall<0)
{
MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY);
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: IndexInStall = %d"
,pHuman->GetName(), IndexInStall) ;
return PACKET_EXE_CONTINUE;
}
if( pHuman->m_StallBox.GetSerialByIndex(IndexInStall) > Serial)
{
MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY);
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: Serial = %d, BoxSerial = %d"
,pHuman->GetName(), Serial, pHuman->m_StallBox.GetSerialByIndex(IndexInStall)) ;
return PACKET_EXE_CONTINUE;
}
Item* pItem = pStallContainer->GetItem(IndexInStall);
ItemContainer* pBagContainer = HumanItemLogic::GetItemContain(pHuman, pItem->GetItemTableIndex());
INT IndexInBag = pBagContainer->GetIndexByGUID(&ItemGuid);
if(IndexInBag<0)
{
MsgError.SetID(STALL_MSG::ERR_ILLEGAL);
pHuman->m_StallBox.CleanUp();
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInBag = %d"
,pHuman->GetName(), IndexInBag) ;
return PACKET_EXE_CONTINUE;
}
//解锁原背包中的物品
g_ItemOperator.UnlockItem( pBagContainer, IndexInBag );
//干掉物品
if(g_ItemOperator.EraseItem(pStallContainer, IndexInStall)>0)
{
pHuman->m_StallBox.IncSerialByIndex(IndexInStall);
pHuman->m_StallBox.SetPriceByIndex(IndexInStall, 0);
}
else
{
MsgError.SetID(STALL_MSG::ERR_ILLEGAL);
pHuman->m_StallBox.CleanUp();
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInStall = %d"
,pHuman->GetName(), IndexInStall) ;
return PACKET_EXE_CONTINUE;
}
//通知客户端
MsgRemoveItem.SetObjGUID( ItemGuid );
MsgRemoveItem.SetSerial( pHuman->m_StallBox.GetSerialByIndex(IndexInStall) );
MsgRemoveItem.SetToType( STALL_MSG::POS_BAG );
pGamePlayer->SendPacket(&MsgRemoveItem);
}
break;
case STALL_MSG::POS_EQUIP:
{
}
break;
case STALL_MSG::POS_PET:
{
INT IndexInStall = pStallPetContainer->GetIndexByGUID(&PetGuid);
if(IndexInStall<0)
{
MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY);
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: IndexInStall = %d"
,pHuman->GetName(), IndexInStall) ;
return PACKET_EXE_CONTINUE;
}
if( pHuman->m_StallBox.GetPetSerialByIndex(IndexInStall) > Serial)
{
MsgError.SetID(STALL_MSG::ERR_NEED_NEW_COPY);
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_NEED_NEW_COPY: Serial = %d, BoxSerial = %d"
,pHuman->GetName(), Serial, pHuman->m_StallBox.GetPetSerialByIndex(IndexInStall)) ;
return PACKET_EXE_CONTINUE;
}
ItemContainer* pPetContainer = pHuman->GetPetContain();
INT IndexInBag = pPetContainer->GetIndexByGUID(&PetGuid);
if(IndexInBag<0)
{
MsgError.SetID(STALL_MSG::ERR_ILLEGAL);
pHuman->m_StallBox.CleanUp();
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInBag = %d"
,pHuman->GetName(), IndexInBag) ;
return PACKET_EXE_CONTINUE;
}
//解锁原背包中的物品
g_ItemOperator.UnlockItem( pPetContainer, IndexInBag );
//干掉物品
if(g_ItemOperator.EraseItem(pStallPetContainer, IndexInStall)>0)
{
pHuman->m_StallBox.IncPetSerialByIndex(IndexInStall);
pHuman->m_StallBox.SetPetPriceByIndex(IndexInStall, 0);
}
else
{
MsgError.SetID(STALL_MSG::ERR_ILLEGAL);
pHuman->m_StallBox.CleanUp();
pGamePlayer->SendPacket(&MsgError);
g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallRemoveItemHandler::ObjName=%s, ERR_ILLEGAL: IndexInStall = %d"
,pHuman->GetName(), IndexInStall) ;
return PACKET_EXE_CONTINUE;
}
//通知客户端
MsgRemoveItem.SetPetGUID( PetGuid );
MsgRemoveItem.SetSerial( pHuman->m_StallBox.GetPetSerialByIndex(IndexInStall) );
MsgRemoveItem.SetToType( STALL_MSG::POS_PET );
pGamePlayer->SendPacket(&MsgRemoveItem);
}
break;
default:
break;
}
g_pLog->FastSaveLog( LOG_FILE_1, "CGStallRemoveItemHandler::ObjName=%s, m_World = %d, m_Server = %d, m_Serial = %d"
,pHuman->GetName(), ItemGuid.m_World, ItemGuid.m_Server, ItemGuid.m_Serial) ;
return PACKET_EXE_CONTINUE ;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR ;
}
| 37.974874
| 142
| 0.592166
|
viticm
|
9066b4d3be7d6c2b62013e62ccef5441636185da
| 1,112
|
cpp
|
C++
|
benchmark_dgemm.cpp
|
seriouslyhypersonic/benchmark_eigen_mkl
|
c2dde3a3ce9c51dd428746400de8e8d2802dc6c0
|
[
"BSL-1.0"
] | null | null | null |
benchmark_dgemm.cpp
|
seriouslyhypersonic/benchmark_eigen_mkl
|
c2dde3a3ce9c51dd428746400de8e8d2802dc6c0
|
[
"BSL-1.0"
] | null | null | null |
benchmark_dgemm.cpp
|
seriouslyhypersonic/benchmark_eigen_mkl
|
c2dde3a3ce9c51dd428746400de8e8d2802dc6c0
|
[
"BSL-1.0"
] | null | null | null |
/*
* Copyright (c) Nuno Alves de Sousa 2019
*
* Use, modification and distribution is subject to 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)
*/
#include <celero/Celero.h>
#include <fixture.hpp>
#include <mkl.h>
CELERO_MAIN
//const int numLinearSamples = 3;
//const int numLinearIterations = 75;
//
//BASELINE_F(Gemm, Baseline, MKLFixture<>, numLinearSamples, numLinearIterations)
//{
// squareDgemm(mA, mA, mC, matrixDim, 1, 1);
//}
//
//BENCHMARK_F(Gemm, Eigen, EigenFixture<>, numLinearSamples, numLinearIterations)
//{
// celero::DoNotOptimizeAway((eA * eA).eval());
//}
const int numSemilogSamples = 5;
const int numSemilogIterations = 0;
BASELINE_F(SemilogGemm, Baseline, MKLFixture<ProgressionPolicy::semilogGemm>
,numSemilogSamples, numSemilogIterations)
{
squareDgemm(mA, mA, mC, matrixDim, 1, 1);
}
BENCHMARK_F(SemilogGemm, Eigen, EigenFixture<ProgressionPolicy::semilogGemm>
,numSemilogSamples, numSemilogIterations)
{
celero::DoNotOptimizeAway((eA * eA).eval());
}
| 26.47619
| 81
| 0.720324
|
seriouslyhypersonic
|
90687b5190c80a3c7c005f5fe2d40921b351cff6
| 11,297
|
cpp
|
C++
|
nvmain/Prefetchers/STeMS/STeMS.cpp
|
code-lamem/lamem
|
c28f72c13a81fbb105c7c83d1b2720a720f3a47f
|
[
"BSD-3-Clause"
] | 1
|
2019-08-27T14:36:00.000Z
|
2019-08-27T14:36:00.000Z
|
nvmain/Prefetchers/STeMS/STeMS.cpp
|
code-lamem/lamem
|
c28f72c13a81fbb105c7c83d1b2720a720f3a47f
|
[
"BSD-3-Clause"
] | null | null | null |
nvmain/Prefetchers/STeMS/STeMS.cpp
|
code-lamem/lamem
|
c28f72c13a81fbb105c7c83d1b2720a720f3a47f
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2012-2014, The Microsystems Design Labratory (MDL)
* Department of Computer Science and Engineering, The Pennsylvania State University
* All rights reserved.
*
* This source code is part of NVMain - A cycle accurate timing, bit accurate
* energy simulator for both volatile (e.g., DRAM) and non-volatile memory
* (e.g., PCRAM). The source code is free and you can redistribute and/or
* modify it by providing 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.
*
* Author list:
* Matt Poremba ( Email: mrp5060 at psu dot edu
* Website: http://www.cse.psu.edu/~poremba/ )
*******************************************************************************/
#include "Prefetchers/STeMS/STeMS.h"
#include <iostream>
using namespace NVM;
void STeMS::FetchNextUnused( PatternSequence *rps, int count,
std::vector<NVMAddress>& prefetchList )
{
uint64_t *lastUnused = new uint64_t[count];
bool *foundUnused = new bool[count];
for( int i = 0; i < count; i++ )
{
lastUnused[i] = 0;
foundUnused[i] = false;
}
/* Find the LAST requests marked as unused. */
for( int i = static_cast<int>(rps->size - 1); i >= 0; i-- )
{
if( !rps->fetched[i] )
{
for( int j = 0; j < count - 1; j++ )
{
lastUnused[j] = lastUnused[j+1];
foundUnused[j] = foundUnused[j+1];
}
lastUnused[count-1] = rps->offset[i];
foundUnused[count-1] = true;
}
else
{
break;
}
}
for( int i = 0; i < count; i++ )
{
if( foundUnused[i] )
{
rps->startedPrefetch = true;
#ifdef DBGPF
std::cout << "Prefetching 0x" << std::hex
<< rps->address + lastUnused[i] << std::dec << std::endl;
#endif
NVMAddress pfAddr;
pfAddr.SetPhysicalAddress( rps->address + lastUnused[i] );
prefetchList.push_back( pfAddr );
/* Mark offset as fetched. */
for( uint64_t j = 0; j < rps->size; j++ )
{
if( rps->offset[j] == lastUnused[i] )
rps->fetched[j] = true;
}
}
}
}
bool STeMS::NotifyAccess( NVMainRequest *accessOp,
std::vector<NVMAddress>& prefetchList )
{
bool rv = false;
/*
* If this access came from a PC that has an allocated reconstruction
* buffer, but it is not the first unused address in the reconstruction
* buffer, deallocate the buffer.
*/
if( ReconBuf.count( accessOp->programCounter ) )
{
PatternSequence *rps = ReconBuf[accessOp->programCounter];
uint64_t address = accessOp->address.GetPhysicalAddress( );
/* Can't evaluate prefetch effectiveness until we've issued some. */
if( !rps->startedPrefetch )
return false;
/*
* If the access was a prefetch we did that was successful, prefetch
* more else if the access is something that was not fetched,
* deallocate the reconstruct buffer.
*/
bool successful = false;
for( uint64_t i = 0; i < rps->size; i++ )
{
if( address == ( rps->address + rps->offset[i] ) )
{
if( rps->fetched[i] && !rps->used[i] )
{
/* Successful prefetch, get more */
successful = true;
#ifdef DBGPF
std::cout << "Successful prefetch ! 0x" << std::hex << address
<< std::dec << std::endl;
#endif
FetchNextUnused( rps, 4, prefetchList );
rv = true;
rps->used[i] = true;
}
}
}
if( !successful )
{
/* Check if the address failed because it's not in the PST. If most
* of the fetches were used, extend the PST.
*/
uint64_t numSuccess = 0;
for( uint64_t i = 0; i < rps->size; i++ )
{
if( rps->used[i] ) numSuccess++;
}
if( ((double)(numSuccess) / (double)(rps->size)) >= 0.6f )
{
PatternSequence *ps = NULL;
std::map<uint64_t, PatternSequence*>::iterator it;
it = PST.find( accessOp->programCounter );
if( it != PST.end( ) )
{
ps = it->second;
if( ps->size < 16 )
{
ps->offset[ps->size] = address - rps->address;
ps->delta[ps->size] = 0;
ps->size++;
}
}
}
std::map<uint64_t, PatternSequence*>::iterator it;
it = ReconBuf.find( accessOp->programCounter );
ReconBuf.erase( it );
}
}
return rv;
}
bool STeMS::DoPrefetch( NVMainRequest *triggerOp,
std::vector<NVMAddress>& prefetchList )
{
NVMAddress pfAddr;
/* If there is an entry in the PST for this PC, build a recon buffer */
if( PST.count( triggerOp->programCounter ) )
{
PatternSequence *ps = PST[triggerOp->programCounter];
uint64_t address = triggerOp->address.GetPhysicalAddress( );
uint64_t pc = triggerOp->programCounter;
/* Check for an RB that is actively being built */
if( ReconBuf.count( pc ) )
{
PatternSequence *rps = ReconBuf[pc];
uint64_t numUsed, numFetched;
numUsed = numFetched = 0;
/* Mark this address as used. */
for( uint64_t i = 0; i < rps->size; i++ )
{
if( ( rps->address + rps->offset[i] ) == address )
{
rps->used[i] = rps->fetched[i] = true;
}
if( rps->used[i] )
numUsed++;
if( rps->fetched[i] )
numFetched++;
}
/*
* If there are enough used out of the fetched values,
* get some more.
*/
if( numUsed >= 2 )
{
FetchNextUnused( rps, 4, prefetchList );
}
}
/* Create new recon buffer by copying the PST entry */
else
{
PatternSequence *rps = new PatternSequence;
uint64_t pc = triggerOp->programCounter;
rps->size = ps->size;
rps->address = triggerOp->address.GetPhysicalAddress( );
for( uint64_t i = 0; i < ps->size; i++ )
{
rps->offset[i] = ps->offset[i];
rps->delta[i] = ps->delta[i];
rps->used[i] = false;
rps->fetched[i] = false;
}
rps->useCount = 1;
rps->startedPrefetch = false;
/*
* Mark the address that triggered reconstruction as
* fetched and used
*/
rps->used[0] = rps->fetched[0] = true;
ReconBuf.insert( std::pair<uint64_t, PatternSequence*>( pc, rps ) );
}
#ifdef DBGPF
std::cout << "Found a PST entry for PC 0x" << std::hex
<< triggerOp->programCounter << std::dec << std::endl;
std::cout << "Triggered by 0x" << std::hex
<< triggerOp->address.GetPhysicalAddress( ) << std::dec
<< std::endl;
std::cout << "Start address 0x" << std::hex << ps->address
<< ": " << std::dec;
for( uint64_t i = 0; i < ps->size; i++ )
{
std::cout << "[" << ps->offset[i] << "," << ps->delta[i] << "], ";
}
std::cout << std::endl;
#endif
}
else
{
/*
* If there is no entry in the PST for this PC, start building an
* AGT entry.
*/
/* Check one of the AGT buffers for misses at this PC */
if( AGT.count( triggerOp->programCounter ) )
{
uint64_t address = triggerOp->address.GetPhysicalAddress( );
uint64_t pc = triggerOp->programCounter;
PatternSequence *ps = AGT[pc];
/*
* If a buffer for this PC exists, append to it. If the buffer size
* exceeds some threshold (say 4) and matches something in the pattern
* table, issue a prefetch for the remaining items in the pattern (up to
* say 8).
*/
uint64_t addressDiff;
addressDiff = ((address > ps->address) ?
(address - ps->address) : (ps->address - address));
if( ( addressDiff / 64 ) < 256 )
{
ps->offset[ps->size] = address - ps->address;
ps->delta[ps->size] = 0;
ps->size++;
/*
* If a buffer exists and the size exceeds some threshold,
* but does not match anything in the pattern table, add this
* buffer to the pattern table
*/
if( ps->size >= 8 )
{
PST.insert( std::pair<uint64_t, PatternSequence*>( pc, ps ) );
std::map<uint64_t, PatternSequence*>::iterator it;
it = AGT.find( pc );
AGT.erase( it );
}
}
}
/* If a buffer does not exist, create one. */
else
{
PatternSequence *ps = new PatternSequence;
uint64_t pc = triggerOp->programCounter;
ps->address = triggerOp->address.GetPhysicalAddress( );
ps->size = 1;
ps->offset[0] = 0;
ps->delta[0] = 0;
AGT.insert( std::pair<uint64_t, PatternSequence*>( pc, ps ) );
}
}
return false;
}
| 33.226471
| 84
| 0.500929
|
code-lamem
|
9068cd65b2531f63fc4eca84dc2e99af5531e3c6
| 4,685
|
cc
|
C++
|
core/Framebuffer.cc
|
pstiasny/derpengine
|
854f6896a6888724cb273c126bf92cc110f3da72
|
[
"MIT"
] | null | null | null |
core/Framebuffer.cc
|
pstiasny/derpengine
|
854f6896a6888724cb273c126bf92cc110f3da72
|
[
"MIT"
] | null | null | null |
core/Framebuffer.cc
|
pstiasny/derpengine
|
854f6896a6888724cb273c126bf92cc110f3da72
|
[
"MIT"
] | 1
|
2019-12-02T22:31:08.000Z
|
2019-12-02T22:31:08.000Z
|
#include "Framebuffer.h"
#include "FramebufferTexture.h"
#include "DepthFramebufferTexture.h"
#include "GraphNode.h"
#include "RenderingContext.h"
GLuint Framebuffer::active_framebuffer_id = 0;
Framebuffer::Framebuffer(unsigned int w, unsigned int h)
: width(w), height(h)
{
color_tex = NULL;
depth_tex = NULL;
color_renderbuffer_id = 0;
depth_renderbuffer_id = 0;
glGenFramebuffers(1, &framebuffer_id);
}
Framebuffer::~Framebuffer()
{
glDeleteFramebuffers(1, &framebuffer_id);
// Delete renderbuffers if any were created
if (color_renderbuffer_id)
glDeleteRenderbuffers(1, &color_renderbuffer_id);
if (depth_renderbuffer_id)
glDeleteRenderbuffers(1, &depth_renderbuffer_id);
}
void Framebuffer::createColorRenderbuffer()
{
if (color_renderbuffer_id)
return;
color_renderbuffer_id = 0;
glGenRenderbuffers(1, &color_renderbuffer_id);
glBindRenderbuffer(GL_RENDERBUFFER, color_renderbuffer_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, color_renderbuffer_id);
}
void Framebuffer::createDepthRenderbuffer()
{
if (depth_renderbuffer_id)
return;
depth_renderbuffer_id = 0;
glGenRenderbuffers(1, &depth_renderbuffer_id);
glBindRenderbuffer(GL_RENDERBUFFER, depth_renderbuffer_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_renderbuffer_id);
}
void Framebuffer::setColorTexture(FramebufferTexture *tex)
{
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id);
color_tex = tex;
if (tex) {
if (color_renderbuffer_id) {
glDeleteRenderbuffers(1, &color_renderbuffer_id);
color_renderbuffer_id = 0;
}
tex->resize(width, height);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex->getId(), 0);
} else {
if (!color_renderbuffer_id)
createColorRenderbuffer();
}
glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id);
}
void Framebuffer::setDepthTexture(DepthFramebufferTexture *tex)
{
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id);
depth_tex = tex;
if (tex) {
if (depth_renderbuffer_id) {
glDeleteRenderbuffers(1, &depth_renderbuffer_id);
depth_renderbuffer_id = 0;
}
tex->resize(width, height);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tex->getId(), 0);
} else {
if (!depth_renderbuffer_id)
createDepthRenderbuffer();
}
glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id);
}
void Framebuffer::resize(unsigned int w, unsigned int h)
{
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id);
width = w;
height = h;
if (color_tex)
color_tex->resize(w, h);
else if (color_renderbuffer_id) {
glBindRenderbuffer(GL_RENDERBUFFER, color_renderbuffer_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);
}
if (depth_tex)
depth_tex->resize(w, h);
else if (depth_renderbuffer_id) {
glBindRenderbuffer(GL_RENDERBUFFER, depth_renderbuffer_id);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height);
}
glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id);
}
bool Framebuffer::isComplete()
{
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id);
switch(glCheckFramebufferStatus(GL_FRAMEBUFFER)) {
case GL_FRAMEBUFFER_COMPLETE:
return true;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
puts("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
puts("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
puts("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
puts("GL_FRAMEBUFFER_UNSUPPORTED");
break;
default:
puts("Unknown framebuffer status");
}
return false;
glBindFramebuffer(GL_FRAMEBUFFER, active_framebuffer_id);
}
void Framebuffer::bindFramebuffer()
{
assert(active_framebuffer_id == 0);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id);
active_framebuffer_id = framebuffer_id;
if (!color_tex && !color_renderbuffer_id)
createColorRenderbuffer();
if (!depth_tex && !depth_renderbuffer_id)
createDepthRenderbuffer();
}
void Framebuffer::unbindFramebuffer()
{
assert(active_framebuffer_id == framebuffer_id);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
active_framebuffer_id = 0;
}
void Framebuffer::renderTo(RenderingContext *rc, GraphNode *scene)
{
GLint prev_draw_buffer;
glGetIntegerv(GL_DRAW_BUFFER, &prev_draw_buffer);
glDrawBuffer(GL_NONE);
bindFramebuffer();
//rc->reshape(w, h);
rc->clear();
scene->render(rc);
unbindFramebuffer();
glDrawBuffer(prev_draw_buffer);
}
| 24.657895
| 78
| 0.785912
|
pstiasny
|
90694f119ea87a46434d16d7c24cf05caf4648df
| 2,075
|
cpp
|
C++
|
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_ordered_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_ordered_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_ordered_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
using stan::math::check_ordered;
TEST(ErrorHandlingMatrix, checkOrdered) {
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
y.resize(3);
y << 0, 1, 2;
EXPECT_NO_THROW(check_ordered("check_ordered", "y", y));
y << 0, 10, std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_ordered("check_ordered", "y", y));
y << -10, 10, std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_ordered("check_ordered", "y", y));
y << -std::numeric_limits<double>::infinity(), 10, std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_ordered("check_ordered", "y", y));
y << 0, 0, 0;
EXPECT_THROW(check_ordered("check_ordered", "y", y),
std::domain_error);
y << 0, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity();
EXPECT_THROW(check_ordered("check_ordered", "y", y),
std::domain_error);
y << -1, 3, 2;
EXPECT_THROW(check_ordered("check_ordered", "y", y),
std::domain_error);
}
TEST(ErrorHandlingMatrix, checkOrdered_one_indexed_message) {
std::string message;
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
y.resize(3);
y << 0, 5, 1;
try {
check_ordered("check_ordered", "y", y);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("element at 3"))
<< message;
}
TEST(ErrorHandlingMatrix, checkOrdered_nan) {
Eigen::Matrix<double, Eigen::Dynamic, 1> y;
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(3);
y << 0, 1, 2;
for (int i = 0; i < y.size(); i++) {
y[i] = nan;
EXPECT_THROW(check_ordered("check_ordered", "y", y),
std::domain_error);
y[i] = i;
}
for (int i = 0; i < y.size(); i++) {
y << 0, 10, std::numeric_limits<double>::infinity();
y[i] = nan;
EXPECT_THROW(check_ordered("check_ordered", "y", y),
std::domain_error);
}
}
| 28.040541
| 93
| 0.615904
|
yizhang-cae
|
906a2524fe426138f4e1108f215ef70d6b50fbb4
| 36,024
|
cpp
|
C++
|
src/main.cpp
|
hdachev/Nimble
|
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
hdachev/Nimble
|
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
hdachev/Nimble
|
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
|
[
"MIT"
] | 1
|
2021-05-10T02:07:12.000Z
|
2021-05-10T02:07:12.000Z
|
#include <iostream>
#include <fstream>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include <memory>
#include "application.h"
#include "camera.h"
#include "utility.h"
#include "material.h"
#include "macros.h"
#include "render_graph.h"
#include "nodes/forward_node.h"
#include "nodes/cubemap_skybox_node.h"
#include "nodes/pcf_point_light_depth_node.h"
#include "nodes/pcf_directional_light_depth_node.h"
#include "nodes/pcss_directional_light_depth_node.h"
#include "nodes/copy_node.h"
#include "nodes/g_buffer_node.h"
#include "nodes/deferred_node.h"
#include "nodes/tone_map_node.h"
#include "nodes/bloom_node.h"
#include "nodes/ssao_node.h"
#include "nodes/hiz_node.h"
#include "nodes/adaptive_exposure_node.h"
#include "nodes/motion_blur_node.h"
#include "nodes/volumetric_light_node.h"
#include "nodes/screen_space_reflection_node.h"
#include "nodes/reflection_node.h"
#include "nodes/fxaa_node.h"
#include "nodes/depth_of_field_node.h"
#include "nodes/vignette_node.h"
#include "nodes/film_grain_node.h"
#include "nodes/chromatic_aberration_node.h"
#include "nodes/color_grade_node.h"
#include "nodes/stop_nans_node.h"
#include "nodes/taa_node.h"
#include "nodes/tiled_forward_node.h"
#include "nodes/tiled_deferred_node.h"
#include "nodes/clustered_forward_node.h"
#include "nodes/clustered_deferred_node.h"
#include "nodes/tiled_light_culling_node.h"
#include "nodes/clustered_light_culling_node.h"
#include "nodes/depth_prepass_node.h"
#include "debug_draw.h"
#include "imgui_helpers.h"
#include "external/nfd/nfd.h"
#include "profiler.h"
#include "probe_renderer/bruneton_probe_renderer.h"
#include "ImGuizmo.h"
#include <random>
#define NIMBLE_EDITOR
namespace nimble
{
#define CAMERA_DEFAULT_FOV 60.0f
#define CAMERA_DEFAULT_NEAR_PLANE 1.0f
#define CAMERA_DEFAULT_FAR_PLANE 3000.0f
class Nimble : public Application
{
protected:
// -----------------------------------------------------------------------------------------------------------------------------------
bool init(int argc, const char* argv[]) override
{
// Attempt to load startup scene.
std::shared_ptr<Scene> scene = m_resource_manager.load_scene("scene/startup.json");
if (scene)
m_scene = scene;
else
{
// If failed, prompt user to select scene to be loaded.
if (!scene && !load_scene_from_dialog())
return false;
}
//create_random_point_lights();
//create_random_spot_lights();
// Create camera.
create_camera();
create_render_graphs();
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void update(double delta) override
{
// Update camera.
update_camera();
if (m_debug_gui)
gui();
#ifdef NIMBLE_EDITOR
if (!m_edit_mode)
{
#endif
if (m_scene)
m_scene->update();
#ifdef NIMBLE_EDITOR
}
#endif
m_renderer.render(delta, &m_viewport_manager);
if (m_scene)
m_debug_draw.render(nullptr, m_width, m_height, m_scene->camera()->m_view_projection);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void shutdown() override
{
m_forward_graph.reset();
m_scene.reset();
}
// -----------------------------------------------------------------------------------------------------------------------------------
AppSettings intial_app_settings() override
{
AppSettings settings;
settings.resizable = true;
settings.width = 1920;
settings.height = 1080;
settings.title = "Nimble - Dihara Wijetunga (c) 2020";
return settings;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void window_resized(int width, int height) override
{
if (m_scene)
{
m_scene->camera()->m_width = m_width;
m_scene->camera()->m_height = m_height;
// Override window resized method to update camera projection.
m_scene->camera()->update_projection(m_scene->camera()->m_fov, m_scene->camera()->m_near, m_scene->camera()->m_far, float(m_width) / float(m_height));
}
m_viewport_manager.on_window_resized(width, height);
m_renderer.on_window_resized(width, height);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void key_pressed(int code) override
{
// Handle forward movement.
if (code == GLFW_KEY_W)
m_heading_speed = m_camera_speed;
else if (code == GLFW_KEY_S)
m_heading_speed = -m_camera_speed;
// Handle sideways movement.
if (code == GLFW_KEY_A)
m_sideways_speed = -m_camera_speed;
else if (code == GLFW_KEY_D)
m_sideways_speed = m_camera_speed;
if (code == GLFW_KEY_G)
m_debug_gui = !m_debug_gui;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void key_released(int code) override
{
// Handle forward movement.
if (code == GLFW_KEY_W || code == GLFW_KEY_S)
m_heading_speed = 0.0f;
// Handle sideways movement.
if (code == GLFW_KEY_A || code == GLFW_KEY_D)
m_sideways_speed = 0.0f;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void mouse_pressed(int code) override
{
// Enable mouse look.
if (code == GLFW_MOUSE_BUTTON_RIGHT)
m_mouse_look = true;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void mouse_released(int code) override
{
// Disable mouse look.
if (code == GLFW_MOUSE_BUTTON_RIGHT)
m_mouse_look = false;
}
// -----------------------------------------------------------------------------------------------------------------------------------
private:
// -----------------------------------------------------------------------------------------------------------------------------------
void create_camera()
{
m_scene->camera()->m_width = m_width;
m_scene->camera()->m_height = m_height;
m_scene->camera()->m_half_pixel_jitter = false;
m_scene->camera()->update_projection(CAMERA_DEFAULT_FOV, CAMERA_DEFAULT_NEAR_PLANE, CAMERA_DEFAULT_FAR_PLANE, float(m_width) / float(m_height));
m_viewport = m_viewport_manager.create_viewport("Main", 0.0f, 0.0f, 1.0f, 1.0f, 0);
m_scene->camera()->m_viewport = m_viewport;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void create_render_graphs()
{
REGISTER_RENDER_NODE(ForwardNode, m_resource_manager);
REGISTER_RENDER_NODE(CubemapSkyboxNode, m_resource_manager);
REGISTER_RENDER_NODE(PCFPointLightDepthNode, m_resource_manager);
REGISTER_RENDER_NODE(PCFDirectionalLightDepthNode, m_resource_manager);
REGISTER_RENDER_NODE(PCFSpotLightDepthNode, m_resource_manager);
REGISTER_RENDER_NODE(PCSSDirectionalLightDepthNode, m_resource_manager);
REGISTER_RENDER_NODE(CopyNode, m_resource_manager);
REGISTER_RENDER_NODE(GBufferNode, m_resource_manager);
REGISTER_RENDER_NODE(DeferredNode, m_resource_manager);
REGISTER_RENDER_NODE(ToneMapNode, m_resource_manager);
REGISTER_RENDER_NODE(BloomNode, m_resource_manager);
REGISTER_RENDER_NODE(SSAONode, m_resource_manager);
REGISTER_RENDER_NODE(HiZNode, m_resource_manager);
REGISTER_RENDER_NODE(AdaptiveExposureNode, m_resource_manager);
REGISTER_RENDER_NODE(MotionBlurNode, m_resource_manager);
REGISTER_RENDER_NODE(VolumetricLightNode, m_resource_manager);
REGISTER_RENDER_NODE(ScreenSpaceReflectionNode, m_resource_manager);
REGISTER_RENDER_NODE(ReflectionNode, m_resource_manager);
REGISTER_RENDER_NODE(FXAANode, m_resource_manager);
REGISTER_RENDER_NODE(DepthOfFieldNode, m_resource_manager);
REGISTER_RENDER_NODE(FilmGrainNode, m_resource_manager);
REGISTER_RENDER_NODE(ChromaticAberrationNode, m_resource_manager);
REGISTER_RENDER_NODE(VignetteNode, m_resource_manager);
REGISTER_RENDER_NODE(ColorGradeNode, m_resource_manager);
REGISTER_RENDER_NODE(StopNaNsNode, m_resource_manager);
REGISTER_RENDER_NODE(TAANode, m_resource_manager);
REGISTER_RENDER_NODE(TiledForwardNode, m_resource_manager);
REGISTER_RENDER_NODE(TiledDeferredNode, m_resource_manager);
REGISTER_RENDER_NODE(ClusteredForwardNode, m_resource_manager);
REGISTER_RENDER_NODE(ClusteredDeferredNode, m_resource_manager);
REGISTER_RENDER_NODE(TiledLightCullingNode, m_resource_manager);
REGISTER_RENDER_NODE(ClusteredLightCullingNode, m_resource_manager);
REGISTER_RENDER_NODE(DepthPrepassNode, m_resource_manager);
// Create Forward render graph
m_forward_graph = m_resource_manager.load_render_graph("graph/clustered_deferred_graph.json", &m_renderer);
// Create Point Light render graph
m_pcf_point_light_graph = m_resource_manager.load_shadow_render_graph("PCFPointLightDepthNode", &m_renderer);
// Create Spot Light render graph
m_pcf_spot_light_graph = m_resource_manager.load_shadow_render_graph("PCFSpotLightDepthNode", &m_renderer);
// Create Directional Light render graph
m_pcf_directional_light_graph = m_resource_manager.load_shadow_render_graph("PCSSDirectionalLightDepthNode", &m_renderer);
m_bruneton_probe_renderer = std::make_shared<BrunetonProbeRenderer>();
// Set the graphs as the active graphs
m_renderer.set_scene(m_scene);
m_renderer.set_point_light_render_graph(m_pcf_point_light_graph);
m_renderer.set_spot_light_render_graph(m_pcf_spot_light_graph);
m_renderer.set_directional_light_render_graph(m_pcf_directional_light_graph);
m_renderer.set_global_probe_renderer(m_bruneton_probe_renderer);
m_renderer.set_scene_render_graph(m_forward_graph);
//create_random_point_lights(4096);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void create_random_spot_lights(uint32_t num_lights)
{
AABB aabb = m_scene->aabb();
const float range = 300.0f;
const float intensity = 10.0f;
const float aabb_scale = 0.6f;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(0.0f, 1.0f);
std::uniform_real_distribution<float> dis_x(aabb.min.x * aabb_scale, aabb.max.x * aabb_scale);
std::uniform_real_distribution<float> dis_y(aabb.min.y * aabb_scale, aabb.max.y * aabb_scale);
std::uniform_real_distribution<float> dis_z(aabb.min.z * aabb_scale, aabb.max.z * aabb_scale);
std::uniform_real_distribution<float> dis_pitch(0.0f, 180.0f);
std::uniform_real_distribution<float> dis_yaw(0.0f, 360.0f);
for (int n = 0; n < num_lights; n++)
m_scene->create_spot_light(glm::vec3(dis_x(rd), dis_y(rd), dis_z(rd)), glm::vec3(dis_pitch(rd), dis_yaw(rd), 0.0f), glm::vec3(dis(rd), dis(rd), dis(rd)), 35.0f, 45.0f, 1000.0f, 10.0f);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void create_random_point_lights(uint32_t num_lights)
{
AABB aabb = m_scene->aabb();
const float range = 100.0f;
const float intensity = 10.0f;
const float aabb_scale = 0.6f;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(0.0f, 1.0f);
std::uniform_real_distribution<float> dis_x(aabb.min.x * aabb_scale, aabb.max.x * aabb_scale);
std::uniform_real_distribution<float> dis_y(aabb.min.y * aabb_scale, aabb.max.y * aabb_scale);
std::uniform_real_distribution<float> dis_z(aabb.min.z * aabb_scale, aabb.max.z * aabb_scale);
for (int n = 0; n < num_lights; n++)
m_scene->create_point_light(glm::vec3(dis_x(rd), dis_y(rd), dis_z(rd)), glm::vec3(dis(rd), dis(rd), dis(rd)), range, intensity, false);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void gui()
{
ImGui::ShowDemoWindow();
ImGuizmo::BeginFrame();
ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f));
ImGui::SetNextWindowSize(ImVec2(m_width, m_height));
int flags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse;
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(m_width, m_height));
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
if (ImGui::Begin("Gizmo", (bool*)0, flags))
ImGuizmo::SetDrawlist();
ImGui::End();
ImGui::PopStyleVar();
if (m_edit_mode)
{
if (ImGui::Begin("Inspector"))
{
Transform* t = nullptr;
if (m_selected_entity != UINT32_MAX)
{
t = &m_scene->lookup_entity(m_selected_entity).transform;
edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t);
}
else if (m_selected_dir_light != UINT32_MAX)
{
DirectionalLight& light = m_scene->lookup_directional_light(m_selected_dir_light);
t = &light.transform;
edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t, false, true, false);
ImGui::Separator();
ImGui::Checkbox("Casts Shadows", &light.casts_shadow);
ImGui::InputFloat("Shadow Map Bias", &light.shadow_map_bias);
ImGui::InputFloat("Intensity", &light.intensity);
ImGui::ColorPicker3("Color", &light.color.x);
}
else if (m_selected_point_light != UINT32_MAX)
{
PointLight& light = m_scene->lookup_point_light(m_selected_point_light);
t = &light.transform;
edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t, true, false, false);
ImGui::Separator();
ImGui::Checkbox("Casts Shadows", &light.casts_shadow);
ImGui::InputFloat("Shadow Map Bias", &light.shadow_map_bias);
ImGui::InputFloat("Intensity", &light.intensity);
ImGui::InputFloat("Range", &light.range);
ImGui::ColorPicker3("Color", &light.color.x);
m_debug_draw.sphere(light.range, light.transform.position, light.color);
}
else if (m_selected_spot_light != UINT32_MAX)
{
SpotLight& light = m_scene->lookup_spot_light(m_selected_spot_light);
t = &light.transform;
edit_transform((float*)&m_scene->camera()->m_view, (float*)&m_scene->camera()->m_projection, t, true, true, false);
ImGui::Separator();
ImGui::Checkbox("Casts Shadows", &light.casts_shadow);
ImGui::InputFloat("Shadow Map Bias", &light.shadow_map_bias);
ImGui::InputFloat("Intensity", &light.intensity);
ImGui::InputFloat("Range", &light.range);
ImGui::InputFloat("Inner Cone Angle", &light.inner_cone_angle);
ImGui::InputFloat("Outer Cone Angle", &light.outer_cone_angle);
ImGui::ColorPicker3("Color", &light.color.x);
}
}
ImGui::End();
}
if (ImGui::Begin("Editor"))
{
ImGui::Checkbox("Edit Mode", &m_edit_mode);
ImGui::Separator();
if (ImGui::CollapsingHeader("Scene"))
{
if (m_scene)
ImGui::Text("Current Scene: %s", m_scene->name().c_str());
else
ImGui::Text("Current Scene: -");
if (ImGui::Button("Load"))
{
if (load_scene_from_dialog())
{
create_camera();
m_renderer.set_scene(m_scene);
}
}
if (m_scene)
{
if (ImGui::Button("Unload"))
{
m_scene = nullptr;
m_resource_manager.shutdown();
}
}
}
if (ImGui::CollapsingHeader("Profiler"))
profiler::ui();
if (ImGui::CollapsingHeader("Render Graph"))
render_node_params();
if (ImGui::CollapsingHeader("Render Target Inspector"))
render_target_inspector();
if (m_renderer.global_probe_renderer())
{
if (ImGui::CollapsingHeader("Global Probe Renderer"))
paramerizable_ui(m_renderer.global_probe_renderer());
}
if (ImGui::CollapsingHeader("Entities"))
{
if (m_scene)
{
Entity* entities = m_scene->entities();
for (uint32_t i = 0; i < m_scene->entity_count(); i++)
{
if (ImGui::Selectable(entities[i].name.c_str(), m_selected_entity == entities[i].id))
{
m_selected_entity = entities[i].id;
m_selected_dir_light = UINT32_MAX;
m_selected_point_light = UINT32_MAX;
m_selected_spot_light = UINT32_MAX;
}
}
}
}
if (ImGui::CollapsingHeader("Camera"))
{
std::shared_ptr<Camera> camera = m_scene->camera();
float near_plane = camera->m_near;
float far_plane = camera->m_far;
float fov = camera->m_fov;
ImGui::InputFloat("Near Plane", &near_plane);
ImGui::InputFloat("Far Plane", &far_plane);
ImGui::SliderFloat("FOV", &fov, 1.0f, 90.0f);
if (near_plane != camera->m_near || far_plane != camera->m_far || fov != camera->m_fov)
camera->update_projection(fov, near_plane, far_plane, float(m_width) / float(m_height));
ImGui::SliderFloat("Near Field Begin", &camera->m_near_begin, camera->m_near, camera->m_far);
ImGui::SliderFloat("Near Field End", &camera->m_near_end, camera->m_near, camera->m_far);
ImGui::SliderFloat("Far Field Begin", &camera->m_far_begin, camera->m_near, camera->m_far);
ImGui::SliderFloat("Far Field End", &camera->m_far_end, camera->m_near, camera->m_far);
}
if (ImGui::CollapsingHeader("Point Lights"))
{
if (m_scene)
{
PointLight* lights = m_scene->point_lights();
for (uint32_t i = 0; i < m_scene->point_light_count(); i++)
{
std::string name = std::to_string(lights[i].id);
if (ImGui::Selectable(name.c_str(), m_selected_point_light == lights[i].id))
{
m_selected_entity = UINT32_MAX;
m_selected_dir_light = UINT32_MAX;
m_selected_point_light = lights[i].id;
m_selected_spot_light = UINT32_MAX;
}
}
ImGui::Separator();
ImGui::PushID(1);
if (ImGui::Button("Create"))
m_scene->create_point_light(glm::vec3(0.0f), glm::vec3(1.0f), 100.0f, 1.0f);
if (m_selected_point_light != UINT32_MAX)
{
ImGui::SameLine();
if (ImGui::Button("Remove"))
{
m_scene->destroy_point_light(m_selected_point_light);
m_selected_point_light = UINT32_MAX;
}
}
ImGui::PopID();
}
}
if (ImGui::CollapsingHeader("Spot Lights"))
{
if (m_scene)
{
SpotLight* lights = m_scene->spot_lights();
for (uint32_t i = 0; i < m_scene->spot_light_count(); i++)
{
std::string name = std::to_string(lights[i].id);
if (ImGui::Selectable(name.c_str(), m_selected_spot_light == lights[i].id))
{
m_selected_entity = UINT32_MAX;
m_selected_dir_light = UINT32_MAX;
m_selected_point_light = UINT32_MAX;
m_selected_spot_light = lights[i].id;
}
}
ImGui::Separator();
ImGui::PushID(2);
if (ImGui::Button("Create"))
m_scene->create_spot_light(glm::vec3(0.0f), glm::vec3(0.0f), glm::vec3(1.0f), 35.0f, 45.0f, 100.0f, 1.0f);
if (m_selected_spot_light != UINT32_MAX)
{
ImGui::SameLine();
if (ImGui::Button("Remove"))
{
m_scene->destroy_spot_light(m_selected_spot_light);
m_selected_spot_light = UINT32_MAX;
}
}
ImGui::PopID();
}
}
if (ImGui::CollapsingHeader("Directional Lights"))
{
if (m_scene)
{
DirectionalLight* lights = m_scene->directional_lights();
for (uint32_t i = 0; i < m_scene->directional_light_count(); i++)
{
std::string name = std::to_string(lights[i].id);
if (ImGui::Selectable(name.c_str(), m_selected_dir_light == lights[i].id))
{
m_selected_entity = UINT32_MAX;
m_selected_dir_light = lights[i].id;
m_selected_point_light = UINT32_MAX;
m_selected_spot_light = UINT32_MAX;
}
}
ImGui::Separator();
ImGui::PushID(3);
if (ImGui::Button("Create"))
m_scene->create_directional_light(glm::vec3(0.0f), glm::vec3(1.0f), 10.0f);
if (m_selected_dir_light != UINT32_MAX)
{
ImGui::SameLine();
if (ImGui::Button("Remove"))
{
m_scene->destroy_directional_light(m_selected_dir_light);
m_selected_dir_light = UINT32_MAX;
}
}
ImGui::PopID();
}
}
}
ImGui::End();
}
// -----------------------------------------------------------------------------------------------------------------------------------
void paramerizable_ui(std::shared_ptr<Parameterizable> paramterizable)
{
int32_t num_bool_params = 0;
int32_t num_int_params = 0;
int32_t num_float_params = 0;
BoolParameter* bool_params = paramterizable->bool_parameters(num_bool_params);
IntParameter* int_params = paramterizable->int_parameters(num_int_params);
FloatParameter* float_params = paramterizable->float_parameters(num_float_params);
for (uint32_t i = 0; i < num_bool_params; i++)
ImGui::Checkbox(bool_params[i].name.c_str(), bool_params[i].ptr);
for (uint32_t i = 0; i < num_int_params; i++)
{
if (int_params[i].min == int_params[i].max)
ImGui::InputInt(int_params[i].name.c_str(), int_params[i].ptr);
else
ImGui::SliderInt(int_params[i].name.c_str(), int_params[i].ptr, int_params[i].min, int_params[i].max);
}
for (uint32_t i = 0; i < num_float_params; i++)
{
if (float_params[i].min == float_params[i].max)
ImGui::InputFloat(float_params[i].name.c_str(), float_params[i].ptr);
else
ImGui::SliderFloat(float_params[i].name.c_str(), float_params[i].ptr, float_params[i].min, float_params[i].max);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void render_node_params()
{
for (uint32_t i = 0; i < m_forward_graph->node_count(); i++)
{
auto node = m_forward_graph->node(i);
if (ImGui::TreeNode(node->name().c_str()))
{
paramerizable_ui(node);
ImGui::TreePop();
}
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void render_target_inspector()
{
bool scaled = m_renderer.scaled_debug_output();
ImGui::Checkbox("Scaled Debug Output", &scaled);
m_renderer.set_scaled_debug_output(scaled);
bool mask_bool[4];
glm::vec4 mask = m_renderer.debug_color_mask();
mask_bool[0] = (bool)mask.x;
mask_bool[1] = (bool)mask.y;
mask_bool[2] = (bool)mask.z;
mask_bool[3] = (bool)mask.w;
ImGui::Checkbox("Red", &mask_bool[0]);
ImGui::Checkbox("Green", &mask_bool[1]);
ImGui::Checkbox("Blue", &mask_bool[2]);
ImGui::Checkbox("Alpha", &mask_bool[3]);
mask.x = (float)mask_bool[0];
mask.y = (float)mask_bool[1];
mask.z = (float)mask_bool[2];
mask.w = (float)mask_bool[3];
m_renderer.set_debug_color_mask(mask);
for (uint32_t i = 0; i < m_forward_graph->node_count(); i++)
{
auto node = m_forward_graph->node(i);
if (ImGui::TreeNode(node->name().c_str()))
{
auto& rts = node->output_render_targets();
for (auto& output : rts)
{
if (ImGui::Selectable(output.slot_name.c_str(), m_renderer.debug_render_target() == output.render_target))
{
if (m_renderer.debug_render_target() == output.render_target)
m_renderer.set_debug_render_target(nullptr);
else
m_renderer.set_debug_render_target(output.render_target);
}
}
for (int j = 0; j < node->intermediate_render_target_count(); j++)
{
std::string name = node->name() + "_intermediate_" + std::to_string(j);
if (ImGui::Selectable(name.c_str(), m_renderer.debug_render_target() == node->intermediate_render_target(j)))
{
if (m_renderer.debug_render_target() == node->intermediate_render_target(j))
m_renderer.set_debug_render_target(nullptr);
else
m_renderer.set_debug_render_target(node->intermediate_render_target(j));
}
}
ImGui::TreePop();
}
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void edit_transform(const float* cameraView, float* cameraProjection, Transform* t, bool show_translate = true, bool show_rotate = true, bool show_scale = true)
{
static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::TRANSLATE);
static ImGuizmo::MODE mCurrentGizmoMode(ImGuizmo::WORLD);
static bool useSnap = false;
static float snap[3] = { 1.f, 1.f, 1.f };
if (show_translate)
{
if (ImGui::RadioButton("Translate", mCurrentGizmoOperation == ImGuizmo::TRANSLATE))
mCurrentGizmoOperation = ImGuizmo::TRANSLATE;
}
if (show_rotate)
{
ImGui::SameLine();
if (ImGui::RadioButton("Rotate", mCurrentGizmoOperation == ImGuizmo::ROTATE))
mCurrentGizmoOperation = ImGuizmo::ROTATE;
}
if (show_scale)
{
ImGui::SameLine();
if (ImGui::RadioButton("Scale", mCurrentGizmoOperation == ImGuizmo::SCALE))
mCurrentGizmoOperation = ImGuizmo::SCALE;
}
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
ImGuizmo::DecomposeMatrixToComponents(&t->model[0][0], &position.x, &rotation.x, &scale.x);
if (show_translate)
ImGui::InputFloat3("Tr", &position.x, 3);
if (show_rotate)
ImGui::InputFloat3("Rt", &rotation.x, 3);
if (show_scale)
ImGui::InputFloat3("Sc", &scale.x, 3);
ImGuizmo::RecomposeMatrixFromComponents(&position.x, &rotation.x, &scale.x, (float*)&t->model);
if (mCurrentGizmoOperation != ImGuizmo::SCALE)
{
if (ImGui::RadioButton("Local", mCurrentGizmoMode == ImGuizmo::LOCAL))
mCurrentGizmoMode = ImGuizmo::LOCAL;
ImGui::SameLine();
if (ImGui::RadioButton("World", mCurrentGizmoMode == ImGuizmo::WORLD))
mCurrentGizmoMode = ImGuizmo::WORLD;
}
ImGui::Checkbox("", &useSnap);
ImGui::SameLine();
switch (mCurrentGizmoOperation)
{
case ImGuizmo::TRANSLATE:
ImGui::InputFloat3("Snap", &snap[0]);
break;
case ImGuizmo::ROTATE:
ImGui::InputFloat("Angle Snap", &snap[0]);
break;
case ImGuizmo::SCALE:
ImGui::InputFloat("Scale Snap", &snap[0]);
break;
}
ImGuiIO& io = ImGui::GetIO();
ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);
ImGuizmo::Manipulate(cameraView, cameraProjection, mCurrentGizmoOperation, mCurrentGizmoMode, (float*)&t->model, NULL, useSnap ? &snap[0] : NULL);
glm::vec3 temp;
ImGuizmo::DecomposeMatrixToComponents((float*)&t->model, &t->position.x, &temp.x, &t->scale.x);
t->prev_model = t->model;
t->orientation = glm::quat(glm::radians(temp));
}
// -----------------------------------------------------------------------------------------------------------------------------------
bool load_scene_from_dialog()
{
std::shared_ptr<Scene> scene = nullptr;
nfdchar_t* scene_path = nullptr;
nfdresult_t result = NFD_OpenDialog("json", nullptr, &scene_path);
if (result == NFD_OKAY)
{
scene = m_resource_manager.load_scene(scene_path, true);
free(scene_path);
if (!scene)
{
NIMBLE_LOG_ERROR("Failed to load scene!");
return false;
}
else
{
if (m_scene)
m_renderer.shader_cache().clear_generated_cache();
m_scene = scene;
}
return true;
}
else if (result == NFD_CANCEL)
return false;
else
{
std::string error = "Scene file read error: ";
error += NFD_GetError();
NIMBLE_LOG_ERROR(error);
return false;
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void update_camera()
{
if (m_scene)
{
auto current = m_scene->camera();
float forward_delta = m_heading_speed * m_delta;
float right_delta = m_sideways_speed * m_delta;
current->set_translation_delta(current->m_forward, forward_delta);
current->set_translation_delta(current->m_right, right_delta);
if (m_mouse_look)
{
// Activate Mouse Look
current->set_rotatation_delta(glm::vec3((float)(m_mouse_delta_y * m_camera_sensitivity),
(float)(m_mouse_delta_x * m_camera_sensitivity),
(float)(0.0f)));
}
else
{
current->set_rotatation_delta(glm::vec3((float)(0),
(float)(0),
(float)(0)));
}
current->update();
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
private:
// Camera controls.
bool m_mouse_look = false;
bool m_edit_mode = true;
bool m_debug_mode = false;
bool m_debug_gui = false;
bool m_move_entities = false;
float m_heading_speed = 0.0f;
float m_sideways_speed = 0.0f;
float m_camera_sensitivity = 0.05f;
float m_camera_speed = 0.1f;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<Viewport> m_viewport;
std::shared_ptr<RenderGraph> m_forward_graph;
std::shared_ptr<RenderGraph> m_pcf_point_light_graph;
std::shared_ptr<RenderGraph> m_pcf_spot_light_graph;
std::shared_ptr<RenderGraph> m_pcf_directional_light_graph;
std::shared_ptr<BrunetonProbeRenderer> m_bruneton_probe_renderer;
Entity::ID m_selected_entity = UINT32_MAX;
PointLight::ID m_selected_point_light = UINT32_MAX;
SpotLight::ID m_selected_spot_light = UINT32_MAX;
DirectionalLight::ID m_selected_dir_light = UINT32_MAX;
};
} // namespace nimble
NIMBLE_DECLARE_MAIN(nimble::Nimble)
| 39.24183
| 273
| 0.515018
|
hdachev
|
906b7416fccae8b3af91851f3b4dcd5301c0c104
| 483
|
cpp
|
C++
|
client/include/game/CTaskSimpleFacial.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 368
|
2015-01-01T21:42:00.000Z
|
2022-03-29T06:22:22.000Z
|
client/include/game/CTaskSimpleFacial.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 92
|
2019-01-23T23:02:31.000Z
|
2022-03-23T19:59:40.000Z
|
client/include/game/CTaskSimpleFacial.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 179
|
2015-02-03T23:41:17.000Z
|
2022-03-26T08:27:16.000Z
|
/*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CTaskSimpleFacial.h"
CTaskSimpleFacial::CTaskSimpleFacial(eFacialExpression nFacialExpress, int nDuration)
: CTaskSimple(plugin::dummy) , m_Timer(plugin::dummy)
{
plugin::CallMethod<0x690C70, CTaskSimpleFacial*, eFacialExpression, int>(this, nFacialExpress, nDuration);
}
| 37.153846
| 110
| 0.780538
|
MayconFelipeA
|
906b770be0557513b38aa2e86e6953ee76de6f45
| 45,893
|
cpp
|
C++
|
aws-cpp-sdk-globalaccelerator/source/GlobalAcceleratorClient.cpp
|
orinem/aws-sdk-cpp
|
f38413cc1f278689ef14e9ebdd74a489a48776be
|
[
"Apache-2.0"
] | 1
|
2020-03-11T05:36:20.000Z
|
2020-03-11T05:36:20.000Z
|
aws-cpp-sdk-globalaccelerator/source/GlobalAcceleratorClient.cpp
|
novaquark/aws-sdk-cpp
|
a0969508545bec9ae2864c9e1e2bb9aff109f90c
|
[
"Apache-2.0"
] | null | null | null |
aws-cpp-sdk-globalaccelerator/source/GlobalAcceleratorClient.cpp
|
novaquark/aws-sdk-cpp
|
a0969508545bec9ae2864c9e1e2bb9aff109f90c
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/core/utils/DNS.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/globalaccelerator/GlobalAcceleratorClient.h>
#include <aws/globalaccelerator/GlobalAcceleratorEndpoint.h>
#include <aws/globalaccelerator/GlobalAcceleratorErrorMarshaller.h>
#include <aws/globalaccelerator/model/AdvertiseByoipCidrRequest.h>
#include <aws/globalaccelerator/model/CreateAcceleratorRequest.h>
#include <aws/globalaccelerator/model/CreateEndpointGroupRequest.h>
#include <aws/globalaccelerator/model/CreateListenerRequest.h>
#include <aws/globalaccelerator/model/DeleteAcceleratorRequest.h>
#include <aws/globalaccelerator/model/DeleteEndpointGroupRequest.h>
#include <aws/globalaccelerator/model/DeleteListenerRequest.h>
#include <aws/globalaccelerator/model/DeprovisionByoipCidrRequest.h>
#include <aws/globalaccelerator/model/DescribeAcceleratorRequest.h>
#include <aws/globalaccelerator/model/DescribeAcceleratorAttributesRequest.h>
#include <aws/globalaccelerator/model/DescribeEndpointGroupRequest.h>
#include <aws/globalaccelerator/model/DescribeListenerRequest.h>
#include <aws/globalaccelerator/model/ListAcceleratorsRequest.h>
#include <aws/globalaccelerator/model/ListByoipCidrsRequest.h>
#include <aws/globalaccelerator/model/ListEndpointGroupsRequest.h>
#include <aws/globalaccelerator/model/ListListenersRequest.h>
#include <aws/globalaccelerator/model/ListTagsForResourceRequest.h>
#include <aws/globalaccelerator/model/ProvisionByoipCidrRequest.h>
#include <aws/globalaccelerator/model/TagResourceRequest.h>
#include <aws/globalaccelerator/model/UntagResourceRequest.h>
#include <aws/globalaccelerator/model/UpdateAcceleratorRequest.h>
#include <aws/globalaccelerator/model/UpdateAcceleratorAttributesRequest.h>
#include <aws/globalaccelerator/model/UpdateEndpointGroupRequest.h>
#include <aws/globalaccelerator/model/UpdateListenerRequest.h>
#include <aws/globalaccelerator/model/WithdrawByoipCidrRequest.h>
using namespace Aws;
using namespace Aws::Auth;
using namespace Aws::Client;
using namespace Aws::GlobalAccelerator;
using namespace Aws::GlobalAccelerator::Model;
using namespace Aws::Http;
using namespace Aws::Utils::Json;
static const char* SERVICE_NAME = "globalaccelerator";
static const char* ALLOCATION_TAG = "GlobalAcceleratorClient";
GlobalAcceleratorClient::GlobalAcceleratorClient(const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<GlobalAcceleratorErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
GlobalAcceleratorClient::GlobalAcceleratorClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<GlobalAcceleratorErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
GlobalAcceleratorClient::GlobalAcceleratorClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider,
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<GlobalAcceleratorErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
GlobalAcceleratorClient::~GlobalAcceleratorClient()
{
}
void GlobalAcceleratorClient::init(const ClientConfiguration& config)
{
m_configScheme = SchemeMapper::ToString(config.scheme);
if (config.endpointOverride.empty())
{
m_uri = m_configScheme + "://" + GlobalAcceleratorEndpoint::ForRegion(config.region, config.useDualStack);
}
else
{
OverrideEndpoint(config.endpointOverride);
}
}
void GlobalAcceleratorClient::OverrideEndpoint(const Aws::String& endpoint)
{
if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0)
{
m_uri = endpoint;
}
else
{
m_uri = m_configScheme + "://" + endpoint;
}
}
AdvertiseByoipCidrOutcome GlobalAcceleratorClient::AdvertiseByoipCidr(const AdvertiseByoipCidrRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return AdvertiseByoipCidrOutcome(AdvertiseByoipCidrResult(outcome.GetResult()));
}
else
{
return AdvertiseByoipCidrOutcome(outcome.GetError());
}
}
AdvertiseByoipCidrOutcomeCallable GlobalAcceleratorClient::AdvertiseByoipCidrCallable(const AdvertiseByoipCidrRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< AdvertiseByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->AdvertiseByoipCidr(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::AdvertiseByoipCidrAsync(const AdvertiseByoipCidrRequest& request, const AdvertiseByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->AdvertiseByoipCidrAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::AdvertiseByoipCidrAsyncHelper(const AdvertiseByoipCidrRequest& request, const AdvertiseByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, AdvertiseByoipCidr(request), context);
}
CreateAcceleratorOutcome GlobalAcceleratorClient::CreateAccelerator(const CreateAcceleratorRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateAcceleratorOutcome(CreateAcceleratorResult(outcome.GetResult()));
}
else
{
return CreateAcceleratorOutcome(outcome.GetError());
}
}
CreateAcceleratorOutcomeCallable GlobalAcceleratorClient::CreateAcceleratorCallable(const CreateAcceleratorRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateAccelerator(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::CreateAcceleratorAsync(const CreateAcceleratorRequest& request, const CreateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateAcceleratorAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::CreateAcceleratorAsyncHelper(const CreateAcceleratorRequest& request, const CreateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateAccelerator(request), context);
}
CreateEndpointGroupOutcome GlobalAcceleratorClient::CreateEndpointGroup(const CreateEndpointGroupRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateEndpointGroupOutcome(CreateEndpointGroupResult(outcome.GetResult()));
}
else
{
return CreateEndpointGroupOutcome(outcome.GetError());
}
}
CreateEndpointGroupOutcomeCallable GlobalAcceleratorClient::CreateEndpointGroupCallable(const CreateEndpointGroupRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateEndpointGroup(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::CreateEndpointGroupAsync(const CreateEndpointGroupRequest& request, const CreateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateEndpointGroupAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::CreateEndpointGroupAsyncHelper(const CreateEndpointGroupRequest& request, const CreateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateEndpointGroup(request), context);
}
CreateListenerOutcome GlobalAcceleratorClient::CreateListener(const CreateListenerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateListenerOutcome(CreateListenerResult(outcome.GetResult()));
}
else
{
return CreateListenerOutcome(outcome.GetError());
}
}
CreateListenerOutcomeCallable GlobalAcceleratorClient::CreateListenerCallable(const CreateListenerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateListener(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::CreateListenerAsync(const CreateListenerRequest& request, const CreateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateListenerAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::CreateListenerAsyncHelper(const CreateListenerRequest& request, const CreateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateListener(request), context);
}
DeleteAcceleratorOutcome GlobalAcceleratorClient::DeleteAccelerator(const DeleteAcceleratorRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteAcceleratorOutcome(NoResult());
}
else
{
return DeleteAcceleratorOutcome(outcome.GetError());
}
}
DeleteAcceleratorOutcomeCallable GlobalAcceleratorClient::DeleteAcceleratorCallable(const DeleteAcceleratorRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteAccelerator(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DeleteAcceleratorAsync(const DeleteAcceleratorRequest& request, const DeleteAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteAcceleratorAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DeleteAcceleratorAsyncHelper(const DeleteAcceleratorRequest& request, const DeleteAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteAccelerator(request), context);
}
DeleteEndpointGroupOutcome GlobalAcceleratorClient::DeleteEndpointGroup(const DeleteEndpointGroupRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteEndpointGroupOutcome(NoResult());
}
else
{
return DeleteEndpointGroupOutcome(outcome.GetError());
}
}
DeleteEndpointGroupOutcomeCallable GlobalAcceleratorClient::DeleteEndpointGroupCallable(const DeleteEndpointGroupRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteEndpointGroup(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DeleteEndpointGroupAsync(const DeleteEndpointGroupRequest& request, const DeleteEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteEndpointGroupAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DeleteEndpointGroupAsyncHelper(const DeleteEndpointGroupRequest& request, const DeleteEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteEndpointGroup(request), context);
}
DeleteListenerOutcome GlobalAcceleratorClient::DeleteListener(const DeleteListenerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteListenerOutcome(NoResult());
}
else
{
return DeleteListenerOutcome(outcome.GetError());
}
}
DeleteListenerOutcomeCallable GlobalAcceleratorClient::DeleteListenerCallable(const DeleteListenerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteListener(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DeleteListenerAsync(const DeleteListenerRequest& request, const DeleteListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteListenerAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DeleteListenerAsyncHelper(const DeleteListenerRequest& request, const DeleteListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteListener(request), context);
}
DeprovisionByoipCidrOutcome GlobalAcceleratorClient::DeprovisionByoipCidr(const DeprovisionByoipCidrRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeprovisionByoipCidrOutcome(DeprovisionByoipCidrResult(outcome.GetResult()));
}
else
{
return DeprovisionByoipCidrOutcome(outcome.GetError());
}
}
DeprovisionByoipCidrOutcomeCallable GlobalAcceleratorClient::DeprovisionByoipCidrCallable(const DeprovisionByoipCidrRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeprovisionByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeprovisionByoipCidr(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DeprovisionByoipCidrAsync(const DeprovisionByoipCidrRequest& request, const DeprovisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeprovisionByoipCidrAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DeprovisionByoipCidrAsyncHelper(const DeprovisionByoipCidrRequest& request, const DeprovisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeprovisionByoipCidr(request), context);
}
DescribeAcceleratorOutcome GlobalAcceleratorClient::DescribeAccelerator(const DescribeAcceleratorRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DescribeAcceleratorOutcome(DescribeAcceleratorResult(outcome.GetResult()));
}
else
{
return DescribeAcceleratorOutcome(outcome.GetError());
}
}
DescribeAcceleratorOutcomeCallable GlobalAcceleratorClient::DescribeAcceleratorCallable(const DescribeAcceleratorRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeAccelerator(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DescribeAcceleratorAsync(const DescribeAcceleratorRequest& request, const DescribeAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeAcceleratorAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DescribeAcceleratorAsyncHelper(const DescribeAcceleratorRequest& request, const DescribeAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeAccelerator(request), context);
}
DescribeAcceleratorAttributesOutcome GlobalAcceleratorClient::DescribeAcceleratorAttributes(const DescribeAcceleratorAttributesRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DescribeAcceleratorAttributesOutcome(DescribeAcceleratorAttributesResult(outcome.GetResult()));
}
else
{
return DescribeAcceleratorAttributesOutcome(outcome.GetError());
}
}
DescribeAcceleratorAttributesOutcomeCallable GlobalAcceleratorClient::DescribeAcceleratorAttributesCallable(const DescribeAcceleratorAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeAcceleratorAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeAcceleratorAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DescribeAcceleratorAttributesAsync(const DescribeAcceleratorAttributesRequest& request, const DescribeAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeAcceleratorAttributesAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DescribeAcceleratorAttributesAsyncHelper(const DescribeAcceleratorAttributesRequest& request, const DescribeAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeAcceleratorAttributes(request), context);
}
DescribeEndpointGroupOutcome GlobalAcceleratorClient::DescribeEndpointGroup(const DescribeEndpointGroupRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DescribeEndpointGroupOutcome(DescribeEndpointGroupResult(outcome.GetResult()));
}
else
{
return DescribeEndpointGroupOutcome(outcome.GetError());
}
}
DescribeEndpointGroupOutcomeCallable GlobalAcceleratorClient::DescribeEndpointGroupCallable(const DescribeEndpointGroupRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeEndpointGroup(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DescribeEndpointGroupAsync(const DescribeEndpointGroupRequest& request, const DescribeEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeEndpointGroupAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DescribeEndpointGroupAsyncHelper(const DescribeEndpointGroupRequest& request, const DescribeEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeEndpointGroup(request), context);
}
DescribeListenerOutcome GlobalAcceleratorClient::DescribeListener(const DescribeListenerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DescribeListenerOutcome(DescribeListenerResult(outcome.GetResult()));
}
else
{
return DescribeListenerOutcome(outcome.GetError());
}
}
DescribeListenerOutcomeCallable GlobalAcceleratorClient::DescribeListenerCallable(const DescribeListenerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeListener(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::DescribeListenerAsync(const DescribeListenerRequest& request, const DescribeListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeListenerAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::DescribeListenerAsyncHelper(const DescribeListenerRequest& request, const DescribeListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeListener(request), context);
}
ListAcceleratorsOutcome GlobalAcceleratorClient::ListAccelerators(const ListAcceleratorsRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListAcceleratorsOutcome(ListAcceleratorsResult(outcome.GetResult()));
}
else
{
return ListAcceleratorsOutcome(outcome.GetError());
}
}
ListAcceleratorsOutcomeCallable GlobalAcceleratorClient::ListAcceleratorsCallable(const ListAcceleratorsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListAcceleratorsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAccelerators(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::ListAcceleratorsAsync(const ListAcceleratorsRequest& request, const ListAcceleratorsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListAcceleratorsAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::ListAcceleratorsAsyncHelper(const ListAcceleratorsRequest& request, const ListAcceleratorsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListAccelerators(request), context);
}
ListByoipCidrsOutcome GlobalAcceleratorClient::ListByoipCidrs(const ListByoipCidrsRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListByoipCidrsOutcome(ListByoipCidrsResult(outcome.GetResult()));
}
else
{
return ListByoipCidrsOutcome(outcome.GetError());
}
}
ListByoipCidrsOutcomeCallable GlobalAcceleratorClient::ListByoipCidrsCallable(const ListByoipCidrsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListByoipCidrsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListByoipCidrs(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::ListByoipCidrsAsync(const ListByoipCidrsRequest& request, const ListByoipCidrsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListByoipCidrsAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::ListByoipCidrsAsyncHelper(const ListByoipCidrsRequest& request, const ListByoipCidrsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListByoipCidrs(request), context);
}
ListEndpointGroupsOutcome GlobalAcceleratorClient::ListEndpointGroups(const ListEndpointGroupsRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListEndpointGroupsOutcome(ListEndpointGroupsResult(outcome.GetResult()));
}
else
{
return ListEndpointGroupsOutcome(outcome.GetError());
}
}
ListEndpointGroupsOutcomeCallable GlobalAcceleratorClient::ListEndpointGroupsCallable(const ListEndpointGroupsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListEndpointGroupsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListEndpointGroups(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::ListEndpointGroupsAsync(const ListEndpointGroupsRequest& request, const ListEndpointGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListEndpointGroupsAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::ListEndpointGroupsAsyncHelper(const ListEndpointGroupsRequest& request, const ListEndpointGroupsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListEndpointGroups(request), context);
}
ListListenersOutcome GlobalAcceleratorClient::ListListeners(const ListListenersRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListListenersOutcome(ListListenersResult(outcome.GetResult()));
}
else
{
return ListListenersOutcome(outcome.GetError());
}
}
ListListenersOutcomeCallable GlobalAcceleratorClient::ListListenersCallable(const ListListenersRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListListenersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListListeners(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::ListListenersAsync(const ListListenersRequest& request, const ListListenersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListListenersAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::ListListenersAsyncHelper(const ListListenersRequest& request, const ListListenersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListListeners(request), context);
}
ListTagsForResourceOutcome GlobalAcceleratorClient::ListTagsForResource(const ListTagsForResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListTagsForResourceOutcome(ListTagsForResourceResult(outcome.GetResult()));
}
else
{
return ListTagsForResourceOutcome(outcome.GetError());
}
}
ListTagsForResourceOutcomeCallable GlobalAcceleratorClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListTagsForResource(request), context);
}
ProvisionByoipCidrOutcome GlobalAcceleratorClient::ProvisionByoipCidr(const ProvisionByoipCidrRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ProvisionByoipCidrOutcome(ProvisionByoipCidrResult(outcome.GetResult()));
}
else
{
return ProvisionByoipCidrOutcome(outcome.GetError());
}
}
ProvisionByoipCidrOutcomeCallable GlobalAcceleratorClient::ProvisionByoipCidrCallable(const ProvisionByoipCidrRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ProvisionByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ProvisionByoipCidr(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::ProvisionByoipCidrAsync(const ProvisionByoipCidrRequest& request, const ProvisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ProvisionByoipCidrAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::ProvisionByoipCidrAsyncHelper(const ProvisionByoipCidrRequest& request, const ProvisionByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ProvisionByoipCidr(request), context);
}
TagResourceOutcome GlobalAcceleratorClient::TagResource(const TagResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return TagResourceOutcome(TagResourceResult(outcome.GetResult()));
}
else
{
return TagResourceOutcome(outcome.GetError());
}
}
TagResourceOutcomeCallable GlobalAcceleratorClient::TagResourceCallable(const TagResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, TagResource(request), context);
}
UntagResourceOutcome GlobalAcceleratorClient::UntagResource(const UntagResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UntagResourceOutcome(UntagResourceResult(outcome.GetResult()));
}
else
{
return UntagResourceOutcome(outcome.GetError());
}
}
UntagResourceOutcomeCallable GlobalAcceleratorClient::UntagResourceCallable(const UntagResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UntagResource(request), context);
}
UpdateAcceleratorOutcome GlobalAcceleratorClient::UpdateAccelerator(const UpdateAcceleratorRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateAcceleratorOutcome(UpdateAcceleratorResult(outcome.GetResult()));
}
else
{
return UpdateAcceleratorOutcome(outcome.GetError());
}
}
UpdateAcceleratorOutcomeCallable GlobalAcceleratorClient::UpdateAcceleratorCallable(const UpdateAcceleratorRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateAcceleratorOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateAccelerator(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::UpdateAcceleratorAsync(const UpdateAcceleratorRequest& request, const UpdateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateAcceleratorAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::UpdateAcceleratorAsyncHelper(const UpdateAcceleratorRequest& request, const UpdateAcceleratorResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateAccelerator(request), context);
}
UpdateAcceleratorAttributesOutcome GlobalAcceleratorClient::UpdateAcceleratorAttributes(const UpdateAcceleratorAttributesRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateAcceleratorAttributesOutcome(UpdateAcceleratorAttributesResult(outcome.GetResult()));
}
else
{
return UpdateAcceleratorAttributesOutcome(outcome.GetError());
}
}
UpdateAcceleratorAttributesOutcomeCallable GlobalAcceleratorClient::UpdateAcceleratorAttributesCallable(const UpdateAcceleratorAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateAcceleratorAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateAcceleratorAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::UpdateAcceleratorAttributesAsync(const UpdateAcceleratorAttributesRequest& request, const UpdateAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateAcceleratorAttributesAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::UpdateAcceleratorAttributesAsyncHelper(const UpdateAcceleratorAttributesRequest& request, const UpdateAcceleratorAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateAcceleratorAttributes(request), context);
}
UpdateEndpointGroupOutcome GlobalAcceleratorClient::UpdateEndpointGroup(const UpdateEndpointGroupRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateEndpointGroupOutcome(UpdateEndpointGroupResult(outcome.GetResult()));
}
else
{
return UpdateEndpointGroupOutcome(outcome.GetError());
}
}
UpdateEndpointGroupOutcomeCallable GlobalAcceleratorClient::UpdateEndpointGroupCallable(const UpdateEndpointGroupRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateEndpointGroupOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateEndpointGroup(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::UpdateEndpointGroupAsync(const UpdateEndpointGroupRequest& request, const UpdateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateEndpointGroupAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::UpdateEndpointGroupAsyncHelper(const UpdateEndpointGroupRequest& request, const UpdateEndpointGroupResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateEndpointGroup(request), context);
}
UpdateListenerOutcome GlobalAcceleratorClient::UpdateListener(const UpdateListenerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateListenerOutcome(UpdateListenerResult(outcome.GetResult()));
}
else
{
return UpdateListenerOutcome(outcome.GetError());
}
}
UpdateListenerOutcomeCallable GlobalAcceleratorClient::UpdateListenerCallable(const UpdateListenerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateListenerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateListener(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::UpdateListenerAsync(const UpdateListenerRequest& request, const UpdateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateListenerAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::UpdateListenerAsyncHelper(const UpdateListenerRequest& request, const UpdateListenerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateListener(request), context);
}
WithdrawByoipCidrOutcome GlobalAcceleratorClient::WithdrawByoipCidr(const WithdrawByoipCidrRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return WithdrawByoipCidrOutcome(WithdrawByoipCidrResult(outcome.GetResult()));
}
else
{
return WithdrawByoipCidrOutcome(outcome.GetError());
}
}
WithdrawByoipCidrOutcomeCallable GlobalAcceleratorClient::WithdrawByoipCidrCallable(const WithdrawByoipCidrRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< WithdrawByoipCidrOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->WithdrawByoipCidr(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void GlobalAcceleratorClient::WithdrawByoipCidrAsync(const WithdrawByoipCidrRequest& request, const WithdrawByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->WithdrawByoipCidrAsyncHelper( request, handler, context ); } );
}
void GlobalAcceleratorClient::WithdrawByoipCidrAsyncHelper(const WithdrawByoipCidrRequest& request, const WithdrawByoipCidrResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, WithdrawByoipCidr(request), context);
}
| 45.619284
| 269
| 0.783627
|
orinem
|
906c27d56bc24a4ac2a48fa53fdd7821d5e5f405
| 3,313
|
cpp
|
C++
|
modules/cpplocate/source/cpplocate/source/cpplocate.cpp
|
helmesjo/minesweeper-sweeper
|
06e269e8a7342d343c6f145af9ac43a52dfc2239
|
[
"MIT"
] | null | null | null |
modules/cpplocate/source/cpplocate/source/cpplocate.cpp
|
helmesjo/minesweeper-sweeper
|
06e269e8a7342d343c6f145af9ac43a52dfc2239
|
[
"MIT"
] | null | null | null |
modules/cpplocate/source/cpplocate/source/cpplocate.cpp
|
helmesjo/minesweeper-sweeper
|
06e269e8a7342d343c6f145af9ac43a52dfc2239
|
[
"MIT"
] | null | null | null |
#include <cpplocate/cpplocate.h>
#if defined SYSTEM_LINUX
#include <unistd.h>
#include <limits.h>
#elif defined SYSTEM_WINDOWS
#include <stdlib.h>
#elif defined SYSTEM_SOLARIS
#include <stdlib.h>
#include <limits.h>
#elif defined SYSTEM_DARWIN
#include <mach-o/dyld.h>
#elif defined SYSTEM_FREEBSD
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#include <cstdlib>
#include <vector>
#include <string>
#include <cpplocate/utils.h>
namespace
{
#ifdef SYSTEM_WINDOWS
const char pathDelim = '\\';
#else
const char pathDelim = '/';
#endif
} // namespace
namespace cpplocate
{
std::string getExecutablePath()
{
#if defined SYSTEM_LINUX
char exePath[PATH_MAX];
ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath));
if (len == -1 || len == sizeof(exePath)) {
len = 0;
}
exePath[len] = '\0';
#elif defined SYSTEM_WINDOWS
char * exePath;
if (_get_pgmptr(&exePath) != 0) {
exePath = "";
}
#elif defined SYSTEM_SOLARIS
char exePath[PATH_MAX];
if (realpath(getexecname(), exePath) == nullptr) {
exePath[0] = '\0';
}
#elif defined SYSTEM_DARWIN
char exePath[PATH_MAX];
uint32_t len = sizeof(exePath);
if (_NSGetExecutablePath(exePath, &len) == 0) {
char * realPath = realpath(exePath, nullptr);
if (realPath) {
strncpy(exePath, realPath, len);
free(realPath);
}
} else {
exePath[0] = '\0';
}
#elif defined SYSTEM_FREEBSD
char exePath[2048];
size_t len = sizeof(exePath);
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
if (sysctl(mib, 4, exePath, &len, nullptr, 0) != 0) {
exePath[0] = '\0';
}
#else
char * exePath = "";
#endif
return std::string(exePath);
}
std::string getModulePath()
{
return utils::getDirectoryPath(getExecutablePath());
}
ModuleInfo findModule(const std::string & name)
{
ModuleInfo info;
// Search at current module location
if (utils::loadModule(getModulePath(), name, info))
{
return info;
}
// Search all paths in CPPLOCATE_PATH
std::vector<std::string> paths;
std::string cppLocatePath = utils::getEnv("CPPLOCATE_PATH");
utils::getPaths(cppLocatePath, paths);
for (std::string path : paths)
{
if (utils::loadModule(path, name, info))
{
return info;
}
if (utils::loadModule(utils::trimPath(path) + pathDelim + name, name, info))
{
return info;
}
}
// Search in standard locations
#if defined SYSTEM_WINDOWS
std::string programFiles64 = utils::getEnv("programfiles");
std::string programFiles32 = utils::getEnv("programfiles(x86)");
if (utils::loadModule(programFiles64 + "\\" + name, name, info))
{
return info;
}
if (utils::loadModule(programFiles32 + "\\" + name, name, info))
{
return info;
}
#else
if (utils::loadModule("/usr/share/" + name, name, info))
{
return info;
}
if (utils::loadModule("/usr/local/share/" + name, name, info))
{
return info;
}
#endif
// Not found
return ModuleInfo();
}
} // namespace cpplocate
| 18.931429
| 84
| 0.598853
|
helmesjo
|
906cf38280a216b2fac548bef4a0f9d47b36abbc
| 1,394
|
cc
|
C++
|
src/rocksdb2/util/hash.cc
|
yinchengtsinghua/RippleCPPChinese
|
a32a38a374547bdc5eb0fddcd657f45048aaad6a
|
[
"BSL-1.0"
] | 5
|
2019-01-23T04:36:03.000Z
|
2020-02-04T07:10:39.000Z
|
src/rocksdb2/util/hash.cc
|
yinchengtsinghua/RippleCPPChinese
|
a32a38a374547bdc5eb0fddcd657f45048aaad6a
|
[
"BSL-1.0"
] | null | null | null |
src/rocksdb2/util/hash.cc
|
yinchengtsinghua/RippleCPPChinese
|
a32a38a374547bdc5eb0fddcd657f45048aaad6a
|
[
"BSL-1.0"
] | 2
|
2019-05-14T07:26:59.000Z
|
2020-06-15T07:25:01.000Z
|
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2011至今,Facebook,Inc.保留所有权利。
//此源代码在两个gplv2下都获得了许可(在
//复制根目录中的文件)和Apache2.0许可证
//(在根目录的license.apache文件中找到)。
//
//版权所有(c)2011 LevelDB作者。版权所有。
//此源代码的使用受可以
//在许可证文件中找到。有关参与者的名称,请参阅作者文件。
#include <string.h>
#include "util/coding.h"
#include "util/hash.h"
namespace rocksdb {
uint32_t Hash(const char* data, size_t n, uint32_t seed) {
//类似于杂音杂音杂音
const uint32_t m = 0xc6a4a793;
const uint32_t r = 24;
const char* limit = data + n;
uint32_t h = static_cast<uint32_t>(seed ^ (n * m));
//一次接收四个字节
while (data + 4 <= limit) {
uint32_t w = DecodeFixed32(data);
data += 4;
h += w;
h *= m;
h ^= (h >> 16);
}
//提取剩余字节
switch (limit - data) {
//注意:最初的哈希实现使用了数据[i]<<shift,其中
//将char提升为int,然后执行移位。如果字符是
//否定,移位是C++中未定义的行为。哈希算法是
//格式定义的一部分,因此我们不能更改它;以获取相同的
//在法律上的行为,我们只是投给uint32,这会
//延长签名。确保与chars架构的兼容性
//是无符号的,我们首先将字符转换为int8_t。
case 3:
h += static_cast<uint32_t>(static_cast<int8_t>(data[2])) << 16;
//跌倒
case 2:
h += static_cast<uint32_t>(static_cast<int8_t>(data[1])) << 8;
//跌倒
case 1:
h += static_cast<uint32_t>(static_cast<int8_t>(data[0]));
h *= m;
h ^= (h >> r);
break;
}
return h;
}
} //命名空间rocksdb
| 21.446154
| 69
| 0.662123
|
yinchengtsinghua
|
906d57444875fde21714cb5e41b17f06969ab1d2
| 97
|
cpp
|
C++
|
elements/behavior/movebehavior.cpp
|
zenitaeglos/AsteroidsGame
|
7456d29f5edee3089fd15d51e2247c8b4f351cdf
|
[
"CC-BY-3.0"
] | null | null | null |
elements/behavior/movebehavior.cpp
|
zenitaeglos/AsteroidsGame
|
7456d29f5edee3089fd15d51e2247c8b4f351cdf
|
[
"CC-BY-3.0"
] | null | null | null |
elements/behavior/movebehavior.cpp
|
zenitaeglos/AsteroidsGame
|
7456d29f5edee3089fd15d51e2247c8b4f351cdf
|
[
"CC-BY-3.0"
] | null | null | null |
#include "movebehavior.h"
MoveBehavior::MoveBehavior()
{
}
MoveBehavior::~MoveBehavior()
{
}
| 8.083333
| 29
| 0.701031
|
zenitaeglos
|
9070c486a2eccf11ce71491643e47edb3543c1e2
| 806
|
cpp
|
C++
|
codeforces/914E.cpp
|
Victoralin10/ACMSolutions
|
6d6e50da87b2bc455e953629737215b74b10269c
|
[
"MIT"
] | null | null | null |
codeforces/914E.cpp
|
Victoralin10/ACMSolutions
|
6d6e50da87b2bc455e953629737215b74b10269c
|
[
"MIT"
] | null | null | null |
codeforces/914E.cpp
|
Victoralin10/ACMSolutions
|
6d6e50da87b2bc455e953629737215b74b10269c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define pii pair <int, int>
#define all(v) (v).begin() (v).end()
#define fi first
#define se second
#define ll long long
#define ull long long
#define ld long double
#define MOD 1000000007
#define MAXN 200005
using namespace std;
map <int, int> DP[MAXN];
vector <int> G[MAXN];
int n;
char label[MAXN];
void dfs1(int nd, int parent) {
for (int i = 0, h; i < G[nd].size(); i++) {
h = G[nd][i];
if (h == parent) continue;
dfs1(h, nd);
}
DP[nd][1<<(label[nd-1] - 'a')] = 1;
}
int main(int nargs, char **args) {
scanf("%d", &n);
for (int i = 1, u, v; i < n; i++) {
scanf("%d%d", &u, &v);
G[u].pb(v);
G[v].pb(u);
}
scanf("%s", label);
return 0;
}
| 17.521739
| 47
| 0.532258
|
Victoralin10
|
907319f2232ab9f64e20be32d130956246853a4c
| 4,607
|
cpp
|
C++
|
source/tests/external/gotcha_tests_lib.cpp
|
dalg24/timemory
|
8cbbf89a25d8d460382664baeec0b13d5d4e2d38
|
[
"MIT"
] | null | null | null |
source/tests/external/gotcha_tests_lib.cpp
|
dalg24/timemory
|
8cbbf89a25d8d460382664baeec0b13d5d4e2d38
|
[
"MIT"
] | null | null | null |
source/tests/external/gotcha_tests_lib.cpp
|
dalg24/timemory
|
8cbbf89a25d8d460382664baeec0b13d5d4e2d38
|
[
"MIT"
] | null | null | null |
// MIT License
//
// Copyright (c) 2019, The Regents of the University of California,
// through Lawrence Berkeley National Laboratory (subject to receipt of any
// required approvals from the U.S. Dept. of Energy). All rights reserved.
//
// 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 "gotcha_tests_lib.hpp"
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <string>
#include <thread>
extern "C"
{
double test_exp(double val) { return exp(val); }
}
//
namespace ext
{
//--------------------------------------------------------------------------------------//
void
do_puts(const char* msg)
{
puts(msg);
}
//--------------------------------------------------------------------------------------//
template <typename _Tp, typename _Func, typename _Incr>
_Tp
work(int64_t nitr, _Func&& func, _Incr&& incr)
{
_Tp val = 2.0;
_Tp sum = 0.0;
for(int64_t i = 0; i < nitr; ++i)
{
sum += func(val);
val = incr(val, i + 1);
}
return sum;
}
//--------------------------------------------------------------------------------------//
std::tuple<float, double>
do_work(int64_t nitr, const std::pair<float, double>& p)
{
auto fsum =
work<float>(nitr, [](float val) -> float { return cosf(val); },
[&](float val, int64_t i) -> float { return val + p.first * i; });
auto dsum =
work<double>(nitr, [](double val) -> double { return cos(val); },
[&](double val, int64_t i) -> double { return val + p.second * i; });
return std::tuple<float, double>(fsum, dsum);
}
//--------------------------------------------------------------------------------------//
} // namespace ext
//--------------------------------------------------------------------------------------//
DoWork::DoWork(const std::pair<float, double>& pair)
: m_pair(pair)
, m_tuple{ 0.0f, 0.0 }
{}
//--------------------------------------------------------------------------------------//
void
DoWork::execute_fp4(int64_t nitr)
{
std::get<0>(m_tuple) = ext::work<float>(
nitr, [](float val) -> float { return cosf(val); },
[&](float val, int64_t i) -> float { return val + m_pair.first * i; });
}
//--------------------------------------------------------------------------------------//
void
DoWork::execute_fp8(int64_t nitr)
{
std::get<1>(m_tuple) = ext::work<double>(
nitr, [](double val) -> double { return cos(val); },
[&](double val, int64_t i) -> double { return val + m_pair.second * i; });
}
//--------------------------------------------------------------------------------------//
void
DoWork::execute_fp(int64_t nitr, std::vector<float> fvals,
const std::deque<double>& dvals)
{
float fret = 0.0;
for(const auto& itr : fvals)
{
fret += ext::work<float>(
nitr, [](float val) -> float { return cosf(val); },
[&](float val, int64_t i) -> float { return val + itr * i; });
}
std::get<0>(m_tuple) = fret;
double dret = 0.0;
for(const auto& itr : dvals)
{
dret += ext::work<double>(
nitr, [](double val) -> double { return cos(val); },
[&](double val, int64_t i) -> double { return val + itr * i; });
}
std::get<1>(m_tuple) = dret;
}
//--------------------------------------------------------------------------------------//
std::tuple<float, double>
DoWork::get() const
{
return m_tuple;
}
//--------------------------------------------------------------------------------------//
| 31.128378
| 90
| 0.504884
|
dalg24
|
90797082a0f4ca7439543035bd08f5a61b201d42
| 2,236
|
cpp
|
C++
|
Light.cpp
|
catinapoke/opengl-1-intermediate-mode
|
9562f258024408625688c52d349738ba9dfb83e4
|
[
"Unlicense"
] | 4
|
2019-10-19T18:30:26.000Z
|
2019-12-15T17:54:27.000Z
|
Light.cpp
|
catinapoke/opengl-1-intermediate-mode
|
9562f258024408625688c52d349738ba9dfb83e4
|
[
"Unlicense"
] | null | null | null |
Light.cpp
|
catinapoke/opengl-1-intermediate-mode
|
9562f258024408625688c52d349738ba9dfb83e4
|
[
"Unlicense"
] | null | null | null |
#include "Light.h"
Light::Light() :Light(vec3(0, 0, 0))
{
}
Light::Light(vec3 position)
{
setPosition(vec4(position.x, position.y, position.z, 1.0));
setAmbient(vec4(1.0, 1.0, 1.0, 1.0));
setDiffuse(vec4(0.0, 0.0, 0.0, 1.0));
setSpecular(vec4(0.0, 0.0, 0.0, 1.0));
}
Light::Light(float x, float y, float z) :Light(vec3(x, y, z))
{
}
Light::Light(const char* filename)
{
load(filename);
}
void Light::setAmbient(vec4 color)
{
ambient = color;
}
void Light::setDiffuse(vec4 color)
{
diffuse = color;
}
void Light::setSpecular(vec4 color)
{
ambient = color;
}
void Light::setPosition(vec4 pos)
{
position = pos;
}
void Light::setPosition(glm::vec3 pos)
{
position.x = pos.x;
position.y = pos.y;
position.z = pos.z;
position.w = 1;
}
void Light::load(const char* jsonfile)
{
std::ifstream ifs(jsonfile);
if (!ifs.is_open())
{
std::cerr << "Couldn't open file " << jsonfile << "for reading \n";
return;
}
//Read from file
rapidjson::IStreamWrapper isw(ifs);
rapidjson::Document doc;
doc.ParseStream(isw);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
if (doc.HasParseError())
{
std::cerr << "Parse error: " << doc.GetParseError() << "\n Offset: " << doc.GetErrorOffset() << "\n";
return;
}
ambient = vec4(
doc["ambient"][0].GetDouble(),
doc["ambient"][1].GetDouble(),
doc["ambient"][2].GetDouble(),
doc["ambient"][3].GetDouble()
);
diffuse = vec4(
doc["diffuse"][0].GetDouble(),
doc["diffuse"][1].GetDouble(),
doc["diffuse"][2].GetDouble(),
doc["diffuse"][3].GetDouble()
);
specular = vec4(
doc["specular"][0].GetDouble(),
doc["specular"][1].GetDouble(),
doc["specular"][2].GetDouble(),
doc["specular"][3].GetDouble()
);
position = vec4(
doc["position"][0].GetDouble(),
doc["position"][1].GetDouble(),
doc["position"][2].GetDouble(),
doc["position"][3].GetDouble()
);
//Close the file
ifs.close();
}
void Light::apply(GLenum light)
{
glEnable(light);
glLightfv(light, GL_AMBIENT, glm::value_ptr(ambient));
glLightfv(light, GL_DIFFUSE, glm::value_ptr(diffuse));
glLightfv(light, GL_SPECULAR, glm::value_ptr(specular));
glLightfv(light, GL_POSITION, glm::value_ptr(position));
}
| 19.614035
| 103
| 0.650268
|
catinapoke
|
908026e9f741b99671f70fd49c30840c0c3ad925
| 170
|
cpp
|
C++
|
src/Hooks.cpp
|
Exit-9B/Enemy-Health-HUD
|
e209582a0430673dafce5a550be85eb8b80b4222
|
[
"MIT"
] | 1
|
2021-03-19T14:32:16.000Z
|
2021-03-19T14:32:16.000Z
|
src/Hooks.cpp
|
Exit-9B/Enemy-Health-HUD
|
e209582a0430673dafce5a550be85eb8b80b4222
|
[
"MIT"
] | null | null | null |
src/Hooks.cpp
|
Exit-9B/Enemy-Health-HUD
|
e209582a0430673dafce5a550be85eb8b80b4222
|
[
"MIT"
] | 1
|
2021-03-19T14:32:18.000Z
|
2021-03-19T14:32:18.000Z
|
#include "Hooks.h"
#include "EnemyHealthManager.h"
namespace Hooks
{
void Install()
{
EnemyHealthManager::InstallHooks();
logger::info("Installed all hooks");
}
}
| 15.454545
| 38
| 0.711765
|
Exit-9B
|
9083c828bb3a94f8f3618f072dff28ba8df65ea1
| 2,952
|
cc
|
C++
|
src/externalized/content/Dialogs.cc
|
oldlaptop/ja2-stracciatella
|
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
|
[
"BSD-Source-Code"
] | null | null | null |
src/externalized/content/Dialogs.cc
|
oldlaptop/ja2-stracciatella
|
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
|
[
"BSD-Source-Code"
] | null | null | null |
src/externalized/content/Dialogs.cc
|
oldlaptop/ja2-stracciatella
|
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
|
[
"BSD-Source-Code"
] | null | null | null |
#include "Dialogs.h"
#include <stdio.h>
#include "game/Directories.h"
#include "game/Tactical/Soldier_Profile.h"
#include "game/Tactical/Soldier_Profile_Type.h"
#include "MercProfile.h"
const char* Content::GetDialogueTextFilename(const MercProfile &profile,
bool useAlternateDialogueFile,
bool isCurrentlyTalking)
{
static char zFileName[164];
uint8_t ubFileNumID;
// Are we an NPC OR an RPC that has not been recruited?
// ATE: Did the || clause here to allow ANY RPC that talks while the talking menu is up to use an npc quote file
if ( useAlternateDialogueFile )
{
{
// assume EDT files are in EDT directory on HARD DRIVE
sprintf(zFileName, NPCDATADIR "/d_%03d.edt", profile.getNum());
}
}
else if ( profile.getNum() >= FIRST_RPC
&& ( !profile.isRecruited()
|| isCurrentlyTalking
|| profile.isForcedNPCQuote()))
{
ubFileNumID = profile.getNum();
// ATE: If we are merc profile ID #151-154, all use 151's data....
if (profile.getNum() >= HERVE && profile.getNum() <= CARLO)
{
ubFileNumID = HERVE;
}
{
// assume EDT files are in EDT directory on HARD DRIVE
sprintf(zFileName, NPCDATADIR "/%03d.edt", ubFileNumID);
}
}
else
{
{
// assume EDT files are in EDT directory on HARD DRIVE
sprintf(zFileName, MERCEDTDIR "/%03d.edt", profile.getNum());
}
}
return( zFileName );
}
const char* Content::GetDialogueVoiceFilename(const MercProfile &profile, uint16_t usQuoteNum,
bool useAlternateDialogueFile,
bool isCurrentlyTalking,
bool isRussianVersion)
{
static char zFileName[164];
uint8_t ubFileNumID;
// Are we an NPC OR an RPC that has not been recruited?
// ATE: Did the || clause here to allow ANY RPC that talks while the talking menu is up to use an npc quote file
if ( useAlternateDialogueFile )
{
{
// build name of wav file (characternum + quotenum)
sprintf(zFileName, NPC_SPEECHDIR "/d_%03d_%03d.wav", profile.getNum(), usQuoteNum);
}
}
else if ( profile.getNum() >= FIRST_RPC
&& ( !profile.isRecruited()
|| isCurrentlyTalking
|| profile.isForcedNPCQuote()))
{
ubFileNumID = profile.getNum();
// ATE: If we are merc profile ID #151-154, all use 151's data....
if (profile.getNum() >= HERVE && profile.getNum() <= CARLO)
{
ubFileNumID = HERVE;
}
{
sprintf(zFileName, NPC_SPEECHDIR "/%03d_%03d.wav", ubFileNumID, usQuoteNum);
}
}
else
{
{
if(isRussianVersion)
{
if (profile.getNum() >= FIRST_RPC && profile.isRecruited())
{
sprintf(zFileName, SPEECHDIR "/r_%03d_%03d.wav", profile.getNum(), usQuoteNum);
}
else
{
// build name of wav file (characternum + quotenum)
sprintf(zFileName, SPEECHDIR "/%03d_%03d.wav", profile.getNum(), usQuoteNum);
}
}
else
{
// build name of wav file (characternum + quotenum)
sprintf(zFileName, SPEECHDIR "/%03d_%03d.wav", profile.getNum(), usQuoteNum);
}
}
}
return( zFileName );
}
| 25.894737
| 113
| 0.671748
|
oldlaptop
|
90846bb77f329996dc9479a922ccfff66d831ae4
| 3,703
|
cpp
|
C++
|
samples/ScenegraphTestApp.cpp
|
calebjohnston/Cinder-scenegraph
|
590b9e12966c5ca25fbccaf69b3199dfeebfb777
|
[
"BSD-2-Clause"
] | null | null | null |
samples/ScenegraphTestApp.cpp
|
calebjohnston/Cinder-scenegraph
|
590b9e12966c5ca25fbccaf69b3199dfeebfb777
|
[
"BSD-2-Clause"
] | null | null | null |
samples/ScenegraphTestApp.cpp
|
calebjohnston/Cinder-scenegraph
|
590b9e12966c5ca25fbccaf69b3199dfeebfb777
|
[
"BSD-2-Clause"
] | null | null | null |
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "NodeBase.h"
#include "Node2d.h"
#include "Node3d.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ScenegraphTestApp : public App {
public:
void mouseMove( MouseEvent event );
void mouseDown( MouseEvent event );
void mouseDrag( MouseEvent event );
void mouseUp( MouseEvent event );
void keyDown( KeyEvent event );
void keyUp( KeyEvent event );
void resize();
void setup();
void update();
void draw();
protected:
//! Keeps track of current game time, used to calculate elapsed time in seconds.
double mTime;
scene::Node2dRef mRoot;
};
void ScenegraphTestApp::setup()
{
// Initialize game time
mTime = getElapsedSeconds();
// create the root node: a large rectangle
mRoot = scene::Node2d::create();
// specify the position of the anchor point on our canvas
mRoot->setPosition(320, 240);
// set the size of the node
mRoot->setSize(600, 450);
// we can easily set the anchor point to its center:
mRoot->setPivotPercentage(0.5f, 0.5f);
// add smaller rectangles to the root node
Node2dRef child1 = scene::Node2d::create();
child1->setPosition(0, 0);
child1->setSize(240, 200);
mRoot->addChild(child1);
Node2dRef child2 = scene::Node2d::create();
child2->setPosition(260, 0);
child2->setSize(240, 200);
mRoot->addChild(child2);
// add even smaller rectangles to the child rectangles
Node2dRef child = scene::Node2d::create();
child->setPosition(5, 5);
child->setSize(100, 100);
child1->addChild(child);
//child.reset( new NodeRectangle() );
child->setPosition(5, 5);
child->setSize(100, 100);
child2->addChild(child);
}
void ScenegraphTestApp::mouseMove( MouseEvent event )
{
// pass the mouseMove event to all nodes. Important: this can easily bring your
// frame rate down if you have a lot of nodes and none of them does anything with
// this event. Only use it if you must! Needs optimization.
// mRoot->deepMouseMove(event);
}
void ScenegraphTestApp::mouseDown( MouseEvent event )
{
// pass the mouseDown event to all nodes. This is usually very quick because
// it starts at the top nodes and they often catch the event.
// mRoot->deepMouseDown(event);
}
void ScenegraphTestApp::mouseDrag( MouseEvent event )
{
// pass the mouseDrag event to all nodes. This is usually very quick.
// mRoot->deepMouseDrag(event);
}
void ScenegraphTestApp::mouseUp( MouseEvent event )
{
// pass the mouseUp event to all nodes. This is usually very quick.
// mRoot->deepMouseUp(event);
}
void ScenegraphTestApp::keyDown( KeyEvent event )
{
// let nodes handle keys first
/*
if (!mRoot->deepKeyDown(event)) {
switch(event.getCode()) {
case KeyEvent::KEY_ESCAPE:
quit();
break;
case KeyEvent::KEY_f:
setFullScreen(!isFullScreen());
break;
}
}
*/
}
void ScenegraphTestApp::keyUp( KeyEvent event )
{
// mRoot->deepKeyUp(event);
}
void ScenegraphTestApp::update()
{
// calculate elapsed time since last frame
double elapsed = getElapsedSeconds() - mTime;
mTime = getElapsedSeconds();
// rotate the root node around its anchor point
mRoot->setRotation( 0.1 * mTime );
// update all nodes
mRoot->deepUpdate( elapsed );
// important and easy to forget: calculate transformations of all nodes
// after they have been updated, so the transformation matrices reflect
// any animation done on the nodes
mRoot->deepTransform( gl::getModelView() );
}
void ScenegraphTestApp::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
// draw all nodes, starting with the root node
mRoot->deepDraw();
}
CINDER_APP_BASIC( ScenegraphTestApp, RendererGl )
| 24.361842
| 82
| 0.712935
|
calebjohnston
|
90849e310a69a084de74906cbf8f6c09f67e143d
| 61,373
|
inl
|
C++
|
ijk/include/ijk/ijk-math/ijk-real/_util/_inl/ijkVectorSwizzle.inl
|
dbuckstein/ijk
|
959f7292d6465e9d2c888ea94bc724c8ee03597e
|
[
"Apache-2.0"
] | 1
|
2020-05-31T21:14:49.000Z
|
2020-05-31T21:14:49.000Z
|
ijk/include/ijk/ijk-math/ijk-real/_util/_inl/ijkVectorSwizzle.inl
|
dbuckstein/ijk
|
959f7292d6465e9d2c888ea94bc724c8ee03597e
|
[
"Apache-2.0"
] | null | null | null |
ijk/include/ijk/ijk-math/ijk-real/_util/_inl/ijkVectorSwizzle.inl
|
dbuckstein/ijk
|
959f7292d6465e9d2c888ea94bc724c8ee03597e
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2020-2021 Daniel S. Buckstein
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.
*/
/*
ijk: an open-source, cross-platform, light-weight,
c-based rendering framework
By Daniel S. Buckstein
ijkVectorSwizzle.inl
Inline definitions for vector swizzling types (C++).
*/
#ifdef _IJK_VECTORSWIZZLE_H_
#ifndef _IJK_VECTORSWIZZLE_INL_
#define _IJK_VECTORSWIZZLE_INL_
#ifdef __cplusplus
//-----------------------------------------------------------------------------
/*
ttvec1 const operator +() const;
ttvec1 const operator -() const;
ttvec1 const operator ~() const;
ttvec1 const operator +(ttvec1 const& v_rh) const;
ttvec1 const operator -(ttvec1 const& v_rh) const;
ttvec1 const operator *(ttvec1 const& v_rh) const;
ttvec1 const operator /(ttvec1 const& v_rh) const;
ttvec1 const operator %(ttvec1 const& v_rh) const;
ttvec1 const operator &(ttvec1 const& v_rh) const;
ttvec1 const operator |(ttvec1 const& v_rh) const;
ttvec1 const operator ^(ttvec1 const& v_rh) const;
ttvec1 const operator <<(ttvec1 const& v_rh) const;
ttvec1 const operator >>(ttvec1 const& v_rh) const;
ttvec1 const operator +(type const& s_rh) const;
ttvec1 const operator -(type const& s_rh) const;
ttvec1 const operator *(type const& s_rh) const;
ttvec1 const operator /(type const& s_rh) const;
ttvec1 const operator %(type const& s_rh) const;
ttvec1 const operator &(type const& s_rh) const;
ttvec1 const operator |(type const& s_rh) const;
ttvec1 const operator ^(type const& s_rh) const;
ttvec1 const operator <<(type const& s_rh) const;
ttvec1 const operator >>(type const& s_rh) const;
ttvec1<bool> const operator !() const;
ttvec1<bool> const operator ==(ttvec1 const& v_rh) const;
ttvec1<bool> const operator !=(ttvec1 const& v_rh) const;
ttvec1<bool> const operator <=(ttvec1 const& v_rh) const;
ttvec1<bool> const operator >=(ttvec1 const& v_rh) const;
ttvec1<bool> const operator <(ttvec1 const& v_rh) const;
ttvec1<bool> const operator >(ttvec1 const& v_rh) const;
ttvec1<bool> const operator ==(type const& s_rh) const;
ttvec1<bool> const operator !=(type const& s_rh) const;
ttvec1<bool> const operator <=(type const& s_rh) const;
ttvec1<bool> const operator >=(type const& s_rh) const;
ttvec1<bool> const operator <(type const& s_rh) const;
ttvec1<bool> const operator >(type const& s_rh) const;
ttvec1& operator +=(ttvec1 const& v_rh);
ttvec1& operator -=(ttvec1 const& v_rh);
ttvec1& operator *=(ttvec1 const& v_rh);
ttvec1& operator /=(ttvec1 const& v_rh);
ttvec1& operator %=(ttvec1 const& v_rh);
ttvec1& operator &=(ttvec1 const& v_rh);
ttvec1& operator |=(ttvec1 const& v_rh);
ttvec1& operator ^=(ttvec1 const& v_rh);
ttvec1& operator <<=(ttvec1 const& v_rh);
ttvec1& operator >>=(ttvec1 const& v_rh);
ttvec1& operator +=(type const& s_rh);
ttvec1& operator -=(type const& s_rh);
ttvec1& operator *=(type const& s_rh);
ttvec1& operator /=(type const& s_rh);
ttvec1& operator %=(type const& s_rh);
ttvec1& operator &=(type const& s_rh);
ttvec1& operator |=(type const& s_rh);
ttvec1& operator ^=(type const& s_rh);
ttvec1& operator <<=(type const& s_rh);
ttvec1& operator >>=(type const& s_rh);
*/
/*
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator +() const
{
return *this;
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator -() const
{
return ttvec1<type>(-x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator ~() const
{
return ttvec1<type>(~x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator +(ttvec1 const& v_rh) const
{
return ttvec1<type>(x + v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator -(ttvec1 const& v_rh) const
{
return ttvec1<type>(x - v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator *(ttvec1 const& v_rh) const
{
return ttvec1<type>(x * v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator /(ttvec1 const& v_rh) const
{
return ttvec1<type>(x / v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator %(ttvec1 const& v_rh) const
{
return ttvec1<type>(x % v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator &(ttvec1 const& v_rh) const
{
return ttvec1<type>(x & v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator |(ttvec1 const& v_rh) const
{
return ttvec1<type>(x | v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator ^(ttvec1 const& v_rh) const
{
return ttvec1<type>(x ^ v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator <<(ttvec1 const& v_rh) const
{
return ttvec1<type>(x << v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator >>(ttvec1 const& v_rh) const
{
return ttvec1<type>(x >> v_rh.x);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator +(type const& s_rh) const
{
return ttvec1<type>(x + s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator -(type const& s_rh) const
{
return ttvec1<type>(x - s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator *(type const& s_rh) const
{
return ttvec1<type>(x * s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator /(type const& s_rh) const
{
return ttvec1<type>(x / s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator %(type const& s_rh) const
{
return ttvec1<type>(x % s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator &(type const& s_rh) const
{
return ttvec1<type>(x & s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator |(type const& s_rh) const
{
return ttvec1<type>(x | s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator ^(type const& s_rh) const
{
return ttvec1<type>(x ^ s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator <<(type const& s_rh) const
{
return ttvec1<type>(x << s_rh);
}
template<typename type>
inline ttvec1<type> const ttvec1<type>::operator >>(type const& s_rh) const
{
return ttvec1<type>(x >> s_rh);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator !() const
{
return ttvec1<bool>(!x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator ==(ttvec1 const& v_rh) const
{
return ttvec1<bool>(x == v_rh.x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator !=(ttvec1 const& v_rh) const
{
return ttvec1<bool>(x != v_rh.x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator <=(ttvec1 const& v_rh) const
{
return ttvec1<bool>(x <= v_rh.x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator >=(ttvec1 const& v_rh) const
{
return ttvec1<bool>(x >= v_rh.x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator <(ttvec1 const& v_rh) const
{
return ttvec1<bool>(x < v_rh.x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator >(ttvec1 const& v_rh) const
{
return ttvec1<bool>(x > v_rh.x);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator ==(type const& s_rh) const
{
return ttvec1<bool>(x == s_rh);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator !=(type const& s_rh) const
{
return ttvec1<bool>(x != s_rh);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator <=(type const& s_rh) const
{
return ttvec1<bool>(x <= s_rh);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator >=(type const& s_rh) const
{
return ttvec1<bool>(x >= s_rh);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator <(type const& s_rh) const
{
return ttvec1<bool>(x < s_rh);
}
template<typename type>
inline ttvec1<bool> const ttvec1<type>::operator >(type const& s_rh) const
{
return ttvec1<bool>(x > s_rh);
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator +=(ttvec1 const& v_rh)
{
x += v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator -=(ttvec1 const& v_rh)
{
x -= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator *=(ttvec1 const& v_rh)
{
x *= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator /=(ttvec1 const& v_rh)
{
x /= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator %=(ttvec1 const& v_rh)
{
x %= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator &=(ttvec1 const& v_rh)
{
x &= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator |=(ttvec1 const& v_rh)
{
x |= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator ^=(ttvec1 const& v_rh)
{
x ^= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator <<=(ttvec1 const& v_rh)
{
x <<= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator >>=(ttvec1 const& v_rh)
{
x >>= v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator +=(type const& s_rh)
{
x += s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator -=(type const& s_rh)
{
x -= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator *=(type const& s_rh)
{
x *= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator /=(type const& s_rh)
{
x /= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator %=(type const& s_rh)
{
x %= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator &=(type const& s_rh)
{
x &= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator |=(type const& s_rh)
{
x |= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator ^=(type const& s_rh)
{
x ^= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator <<=(type const& s_rh)
{
x <<= s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator >>=(type const& s_rh)
{
x >>= s_rh;
return *this;
}
*/
//-----------------------------------------------------------------------------
template<typename type>
inline ttvec1<type>::ttvec1(type const& xc)
: x(xc)
{
}
template<typename type>
inline ttvec1<type>::ttvec1(ttvec1 const& xc)
: x(xc.x)
{
}
template<typename type>
inline ttvec1<type>::ttvec1(stvec1<type> const& xc)
: x(xc.x)
{
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator =(ttvec1 const& v_rh)
{
x = v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator =(stvec1<type> const& v_rh)
{
x = v_rh.x;
return *this;
}
template<typename type>
inline ttvec1<type>& ttvec1<type>::operator =(type const& s_rh)
{
x = s_rh;
return *this;
}
template<typename type>
inline ttvec1<type>::operator type const () const
{
return x;
}
template<typename type>
inline ttvec1<type>::operator type& ()
{
return x;
}
//-----------------------------------------------------------------------------
template <typename type>
inline ttvec2<type>::ttvec2(type const& xy)
: x(xy), y(xy)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(type const& xc, type const& yc)
: x(xc), y(yc)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec2 const& xy)
: x(xy.x), y(xy.y)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec3<type> const& xy)
: x(xy.x), y(xy.y)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec4<type> const& xy)
: x(xy.x), y(xy.y)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(stvec2<type> const& xy)
: x(xy.x), y(xy.y)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(stvec3<type> const& xy)
: x(xy.x), y(xy.y)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(stvec4<type> const& xy)
: x(xy.x), y(xy.y)
{
}
template <typename type>
inline ttvec2<type>::ttvec2(bool2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(int2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(intl2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(uint2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(uintl2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(float2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(double2 const xy)
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<bool> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<i32> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<i64> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<ui32> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<ui64> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<f32> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type>::ttvec2(ttvec1<f64> const xy[2])
: x((type)xy[0]), y((type)xy[1])
{
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator +() const
{
return *this;
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator -() const
{
return ttvec2(-x, -y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator ~() const
{
return ttvec2(~x, ~y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator !() const
{
return ttvec2<bool>(!x, !y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator +(ttvec2 const& v_rh) const
{
return ttvec2(x + v_rh.x, y + v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator -(ttvec2 const& v_rh) const
{
return ttvec2(x - v_rh.x, y - v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator *(ttvec2 const& v_rh) const
{
return ttvec2(x * v_rh.x, y * v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator /(ttvec2 const& v_rh) const
{
return ttvec2(x / v_rh.x, y / v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator %(ttvec2 const& v_rh) const
{
return ttvec2(x % v_rh.x, y % v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator &(ttvec2 const& v_rh) const
{
return ttvec2(x & v_rh.x, y & v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator |(ttvec2 const& v_rh) const
{
return ttvec2(x | v_rh.x, y | v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator ^(ttvec2 const& v_rh) const
{
return ttvec2(x ^ v_rh.x, y ^ v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator <<(ttvec2 const& v_rh) const
{
return ttvec2(x << v_rh.x, y << v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator >>(ttvec2 const& v_rh) const
{
return ttvec2(x >> v_rh.x, y >> v_rh.y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator ==(ttvec2 const& v_rh) const
{
return ttvec2<bool>(x == v_rh.x, y == v_rh.y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator !=(ttvec2 const& v_rh) const
{
return ttvec2<bool>(x != v_rh.x, y != v_rh.y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator <=(ttvec2 const& v_rh) const
{
return ttvec2<bool>(x <= v_rh.x, y <= v_rh.y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator >=(ttvec2 const& v_rh) const
{
return ttvec2<bool>(x >= v_rh.x, y >= v_rh.y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator <(ttvec2 const& v_rh) const
{
return ttvec2<bool>(x < v_rh.x, y < v_rh.y);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator >(ttvec2 const& v_rh) const
{
return ttvec2<bool>(x > v_rh.x, y > v_rh.y);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator +(type const& s_rh) const
{
return ttvec2(x + s_rh, y + s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator -(type const& s_rh) const
{
return ttvec2(x - s_rh, y - s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator *(type const& s_rh) const
{
return ttvec2(x * s_rh, y * s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator /(type const& s_rh) const
{
return ttvec2(x / s_rh, y / s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator %(type const& s_rh) const
{
return ttvec2(x % s_rh, y % s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator &(type const& s_rh) const
{
return ttvec2(x & s_rh, y & s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator |(type const& s_rh) const
{
return ttvec2(x | s_rh, y | s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator ^(type const& s_rh) const
{
return ttvec2(x ^ s_rh, y ^ s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator <<(type const& s_rh) const
{
return ttvec2(x << s_rh, y << s_rh);
}
template <typename type>
inline ttvec2<type> const ttvec2<type>::operator >>(type const& s_rh) const
{
return ttvec2(x >> s_rh, y >> s_rh);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator ==(type const& s_rh) const
{
return ttvec2<bool>(x == s_rh, y == s_rh);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator !=(type const& s_rh) const
{
return ttvec2<bool>(x != s_rh, y != s_rh);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator <=(type const& s_rh) const
{
return ttvec2<bool>(x <= s_rh, y <= s_rh);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator >=(type const& s_rh) const
{
return ttvec2<bool>(x >= s_rh, y >= s_rh);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator <(type const& s_rh) const
{
return ttvec2<bool>(x < s_rh, y < s_rh);
}
template <typename type>
inline ttvec2<bool> const ttvec2<type>::operator >(type const& s_rh) const
{
return ttvec2<bool>(x > s_rh, y > s_rh);
}
template <typename type>
inline type const ttvec2<type>::operator [](index const i) const
{
return xy[i];
}
template <typename type>
inline ttvec2<type>::operator type const* () const
{
return xy;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator =(ttvec2 const& v_rh)
{
x = v_rh.x;
y = v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator =(stvec2<type> const& v_rh)
{
x = v_rh.x;
y = v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator +=(ttvec2 const& v_rh)
{
x += v_rh.x;
y += v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator -=(ttvec2 const& v_rh)
{
x -= v_rh.x;
y -= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator *=(ttvec2 const& v_rh)
{
x *= v_rh.x;
y *= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator /=(ttvec2 const& v_rh)
{
x /= v_rh.x;
y /= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator %=(ttvec2 const& v_rh)
{
x %= v_rh.x;
y %= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator &=(ttvec2 const& v_rh)
{
x &= v_rh.x;
y &= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator |=(ttvec2 const& v_rh)
{
x |= v_rh.x;
y |= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator ^=(ttvec2 const& v_rh)
{
x ^= v_rh.x;
y ^= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator <<=(ttvec2 const& v_rh)
{
x <<= v_rh.x;
y <<= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator >>=(ttvec2 const& v_rh)
{
x >>= v_rh.x;
y >>= v_rh.y;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator =(type const& s_rh)
{
x = y = s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator +=(type const& s_rh)
{
x += s_rh;
y += s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator -=(type const& s_rh)
{
x -= s_rh;
y -= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator *=(type const& s_rh)
{
x *= s_rh;
y *= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator /=(type const& s_rh)
{
x /= s_rh;
y /= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator %=(type const& s_rh)
{
x %= s_rh;
y %= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator &=(type const& s_rh)
{
x &= s_rh;
y &= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator |=(type const& s_rh)
{
x |= s_rh;
y |= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator ^=(type const& s_rh)
{
x ^= s_rh;
y ^= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator <<=(type const& s_rh)
{
x <<= s_rh;
y <<= s_rh;
return *this;
}
template <typename type>
inline ttvec2<type>& ttvec2<type>::operator >>=(type const& s_rh)
{
x >>= s_rh;
y >>= s_rh;
return *this;
}
template <typename type>
inline type& ttvec2<type>::operator [](index const i)
{
return xy[i];
}
template <typename type>
inline ttvec2<type>::operator type* ()
{
return xy;
}
template<typename type>
inline ttvec2<type> const operator +(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh + s_lh);
}
template<typename type>
inline ttvec2<type> const operator -(type const& s_lh, ttvec2<type> const& v_rh)
{
return ttvec2<type>(s_lh - v_rh.x, s_lh - v_rh.y);
}
template<typename type>
inline ttvec2<type> const operator *(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh * s_lh);
}
template<typename type>
inline ttvec2<type> const operator /(type const& s_lh, ttvec2<type> const& v_rh)
{
return ttvec2<type>(s_lh / v_rh.x, s_lh / v_rh.y);
}
template<typename type>
inline ttvec2<type> const operator %(type const& s_lh, ttvec2<type> const& v_rh)
{
return ttvec2<type>(s_lh % v_rh.x, s_lh % v_rh.y);
}
template<typename type>
inline ttvec2<type> const operator &(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh & s_lh);
}
template<typename type>
inline ttvec2<type> const operator |(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh | s_lh);
}
template<typename type>
inline ttvec2<type> const operator ^(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh ^ s_lh);
}
template<typename type>
inline ttvec2<type> const operator <<(type const& s_lh, ttvec2<type> const& v_rh)
{
return ttvec2<type>(s_lh << v_rh.x, s_lh << v_rh.y);
}
template<typename type>
inline ttvec2<type> const operator >>(type const& s_lh, ttvec2<type> const& v_rh)
{
return ttvec2<type>(s_lh >> v_rh.x, s_lh >> v_rh.y);
}
template<typename type>
inline ttvec2<bool> const operator ==(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh == s_lh);
}
template<typename type>
inline ttvec2<bool> const operator !=(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh != s_lh);
}
template<typename type>
inline ttvec2<bool> const operator <=(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh <= s_lh);
}
template<typename type>
inline ttvec2<bool> const operator >=(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh >= s_lh);
}
template<typename type>
inline ttvec2<bool> const operator <(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh < s_lh);
}
template<typename type>
inline ttvec2<bool> const operator >(type const& s_lh, ttvec2<type> const& v_rh)
{
return (v_rh > s_lh);
}
//-----------------------------------------------------------------------------
template <typename type>
inline ttvec3<type>::ttvec3(type const& xyz)
: x(xyz), y(xyz), z(xyz)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(type const& xc, type const& yc, type const& zc)
: x(xc), y(yc), z(zc)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec2<type> const& xy, type const& zc)
: x(xy.x), y(xy.y), z(zc)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(type const& xc, ttvec2<type> const& yz)
: x(xc), y(yz.x), z(yz.y)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec3 const& xyz)
: x(xyz.x), y(xyz.y), z(xyz.z)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec4<type> const& xyz)
: x(xyz.x), y(xyz.y), z(xyz.z)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(stvec2<type> const& xy, type const& zc)
: x(xy.x), y(xy.y), z(zc)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(type const& xc, stvec2<type> const& yz)
: x(xc), y(yz.x), z(yz.y)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(stvec3<type> const& xyz)
: x(xyz.x), y(xyz.y), z(xyz.z)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(stvec4<type> const& xyz)
: x(xyz.x), y(xyz.y), z(xyz.z)
{
}
template <typename type>
inline ttvec3<type>::ttvec3(bool3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(int3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(intl3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(uint3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(uintl3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(float3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(double3 const xyz)
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<bool> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<i32> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<i64> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<ui32> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<ui64> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<f32> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type>::ttvec3(ttvec1<f64> const xyz[3])
: x((type)xyz[0]), y((type)xyz[1]), z((type)xyz[2])
{
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator +() const
{
return *this;
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator -() const
{
return ttvec3(-x, -y, -z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator ~() const
{
return ttvec3(~x, ~y, ~z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator !() const
{
return ttvec3<bool>(!x, !y, !z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator +(ttvec3 const& v_rh) const
{
return ttvec3(x + v_rh.x, y + v_rh.y, z + v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator -(ttvec3 const& v_rh) const
{
return ttvec3(x - v_rh.x, y - v_rh.y, z - v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator *(ttvec3 const& v_rh) const
{
return ttvec3(x * v_rh.x, y * v_rh.y, z * v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator /(ttvec3 const& v_rh) const
{
return ttvec3(x / v_rh.x, y / v_rh.y, z / v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator %(ttvec3 const& v_rh) const
{
return ttvec3(x % v_rh.x, y % v_rh.y, z % v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator &(ttvec3 const& v_rh) const
{
return ttvec3(x & v_rh.x, y & v_rh.y, z & v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator |(ttvec3 const& v_rh) const
{
return ttvec3(x | v_rh.x, y | v_rh.y, z | v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator ^(ttvec3 const& v_rh) const
{
return ttvec3(x ^ v_rh.x, y ^ v_rh.y, z ^ v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator <<(ttvec3 const& v_rh) const
{
return ttvec3(x << v_rh.x, y << v_rh.y, z << v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator >>(ttvec3 const& v_rh) const
{
return ttvec3(x >> v_rh.x, y >> v_rh.y, z >> v_rh.z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator ==(ttvec3 const& v_rh) const
{
return ttvec3<bool>(x == v_rh.x, y == v_rh.y, z == v_rh.z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator !=(ttvec3 const& v_rh) const
{
return ttvec3<bool>(x != v_rh.x, y != v_rh.y, z != v_rh.z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator <=(ttvec3 const& v_rh) const
{
return ttvec3<bool>(x <= v_rh.x, y <= v_rh.y, z <= v_rh.z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator >=(ttvec3 const& v_rh) const
{
return ttvec3<bool>(x >= v_rh.x, y >= v_rh.y, z >= v_rh.z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator <(ttvec3 const& v_rh) const
{
return ttvec3<bool>(x < v_rh.x, y < v_rh.y, z < v_rh.z);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator >(ttvec3 const& v_rh) const
{
return ttvec3<bool>(x > v_rh.x, y > v_rh.y, z > v_rh.z);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator +(type const& s_rh) const
{
return ttvec3(x + s_rh, y + s_rh, z + s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator -(type const& s_rh) const
{
return ttvec3(x - s_rh, y - s_rh, z - s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator *(type const& s_rh) const
{
return ttvec3(x * s_rh, y * s_rh, z * s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator /(type const& s_rh) const
{
return ttvec3(x / s_rh, y / s_rh, z / s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator %(type const& s_rh) const
{
return ttvec3(x % s_rh, y % s_rh, z % s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator &(type const& s_rh) const
{
return ttvec3(x & s_rh, y & s_rh, z & s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator |(type const& s_rh) const
{
return ttvec3(x | s_rh, y | s_rh, z | s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator ^(type const& s_rh) const
{
return ttvec3(x ^ s_rh, y ^ s_rh, z ^ s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator <<(type const& s_rh) const
{
return ttvec3(x << s_rh, y << s_rh, z << s_rh);
}
template <typename type>
inline ttvec3<type> const ttvec3<type>::operator >>(type const& s_rh) const
{
return ttvec3(x >> s_rh, y >> s_rh, z >> s_rh);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator ==(type const& s_rh) const
{
return ttvec3<bool>(x == s_rh, y == s_rh, z == s_rh);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator !=(type const& s_rh) const
{
return ttvec3<bool>(x != s_rh, y != s_rh, z != s_rh);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator <=(type const& s_rh) const
{
return ttvec3<bool>(x <= s_rh, y <= s_rh, z <= s_rh);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator >=(type const& s_rh) const
{
return ttvec3<bool>(x >= s_rh, y >= s_rh, z >= s_rh);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator <(type const& s_rh) const
{
return ttvec3<bool>(x < s_rh, y < s_rh, z < s_rh);
}
template <typename type>
inline ttvec3<bool> const ttvec3<type>::operator >(type const& s_rh) const
{
return ttvec3<bool>(x > s_rh, y > s_rh, z > s_rh);
}
template <typename type>
inline type const ttvec3<type>::operator [](index const i) const
{
return xyz[i];
}
template <typename type>
inline ttvec3<type>::operator type const* () const
{
return xyz;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator =(ttvec3 const& v_rh)
{
x = v_rh.x;
y = v_rh.y;
z = v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator =(stvec3<type> const& v_rh)
{
x = v_rh.x;
y = v_rh.y;
z = v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator +=(ttvec3 const& v_rh)
{
x += v_rh.x;
y += v_rh.y;
z += v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator -=(ttvec3 const& v_rh)
{
x -= v_rh.x;
y -= v_rh.y;
z -= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator *=(ttvec3 const& v_rh)
{
x *= v_rh.x;
y *= v_rh.y;
z *= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator /=(ttvec3 const& v_rh)
{
x /= v_rh.x;
y /= v_rh.y;
z /= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator %=(ttvec3 const& v_rh)
{
x %= v_rh.x;
y %= v_rh.y;
z %= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator &=(ttvec3 const& v_rh)
{
x &= v_rh.x;
y &= v_rh.y;
z &= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator |=(ttvec3 const& v_rh)
{
x |= v_rh.x;
y |= v_rh.y;
z |= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator ^=(ttvec3 const& v_rh)
{
x ^= v_rh.x;
y ^= v_rh.y;
z ^= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator <<=(ttvec3 const& v_rh)
{
x <<= v_rh.x;
y <<= v_rh.y;
z <<= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator >>=(ttvec3 const& v_rh)
{
x >>= v_rh.x;
y >>= v_rh.y;
z >>= v_rh.z;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator =(type const& s_rh)
{
x = y = z = s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator +=(type const& s_rh)
{
x += s_rh;
y += s_rh;
z += s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator -=(type const& s_rh)
{
x -= s_rh;
y -= s_rh;
z -= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator *=(type const& s_rh)
{
x *= s_rh;
y *= s_rh;
z *= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator /=(type const& s_rh)
{
x /= s_rh;
y /= s_rh;
z /= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator %=(type const& s_rh)
{
x %= s_rh;
y %= s_rh;
z %= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator &=(type const& s_rh)
{
x &= s_rh;
y &= s_rh;
z &= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator |=(type const& s_rh)
{
x |= s_rh;
y |= s_rh;
z |= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator ^=(type const& s_rh)
{
x ^= s_rh;
y ^= s_rh;
z ^= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator <<=(type const& s_rh)
{
x <<= s_rh;
y <<= s_rh;
z <<= s_rh;
return *this;
}
template <typename type>
inline ttvec3<type>& ttvec3<type>::operator >>=(type const& s_rh)
{
x >>= s_rh;
y >>= s_rh;
z >>= s_rh;
return *this;
}
template <typename type>
inline type& ttvec3<type>::operator [](index const i)
{
return xyz[i];
}
template <typename type>
inline ttvec3<type>::operator type* ()
{
return xyz;
}
template<typename type>
inline ttvec3<type> const operator +(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh + s_lh);
}
template<typename type>
inline ttvec3<type> const operator -(type const& s_lh, ttvec3<type> const& v_rh)
{
return ttvec3<type>(s_lh - v_rh.x, s_lh - v_rh.y, s_lh - v_rh.z);
}
template<typename type>
inline ttvec3<type> const operator *(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh * s_lh);
}
template<typename type>
inline ttvec3<type> const operator /(type const& s_lh, ttvec3<type> const& v_rh)
{
return ttvec3<type>(s_lh / v_rh.x, s_lh / v_rh.y, s_lh / v_rh.z);
}
template<typename type>
inline ttvec3<type> const operator %(type const& s_lh, ttvec3<type> const& v_rh)
{
return ttvec3<type>(s_lh % v_rh.x, s_lh % v_rh.y, s_lh % v_rh.z);
}
template<typename type>
inline ttvec3<type> const operator &(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh & s_lh);
}
template<typename type>
inline ttvec3<type> const operator |(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh | s_lh);
}
template<typename type>
inline ttvec3<type> const operator ^(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh ^ s_lh);
}
template<typename type>
inline ttvec3<type> const operator <<(type const& s_lh, ttvec3<type> const& v_rh)
{
return ttvec3<type>(s_lh << v_rh.x, s_lh << v_rh.y, s_lh << v_rh.z);
}
template<typename type>
inline ttvec3<type> const operator >>(type const& s_lh, ttvec3<type> const& v_rh)
{
return ttvec3<type>(s_lh >> v_rh.x, s_lh >> v_rh.y, s_lh >> v_rh.z);
}
template<typename type>
inline ttvec3<bool> const operator ==(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh == s_lh);
}
template<typename type>
inline ttvec3<bool> const operator !=(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh != s_lh);
}
template<typename type>
inline ttvec3<bool> const operator <=(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh <= s_lh);
}
template<typename type>
inline ttvec3<bool> const operator >=(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh >= s_lh);
}
template<typename type>
inline ttvec3<bool> const operator <(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh < s_lh);
}
template<typename type>
inline ttvec3<bool> const operator >(type const& s_lh, ttvec3<type> const& v_rh)
{
return (v_rh > s_lh);
}
//-----------------------------------------------------------------------------
template <typename type>
inline ttvec4<type>::ttvec4(type const& xyzw)
: x(xyzw), y(xyzw), z(xyzw), w(xyzw)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, type const& yc, type const& zc, type const& wc)
: x(xc), y(yc), z(zc), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec2<type> const& xy, type const& zc, type const& wc)
: x(xy.x), y(xy.y), z(zc), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, ttvec2<type> const& yz, type const& wc)
: x(xc), y(yz.x), z(yz.y), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, type const& yc, ttvec2<type> const& zw)
: x(xc), y(yc), z(zw.x), w(zw.y)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec2<type> const& xy, ttvec2<type> const& zw)
: x(xy.x), y(xy.y), z(zw.x), w(zw.y)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec3<type> const& xyz, type const& wc)
: x(xyz.x), y(xyz.y), z(xyz.z), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, ttvec3<type> const& yzw)
: x(xc), y(yzw.x), z(yzw.y), w(yzw.z)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec4 const& xyzw)
: x(xyzw.x), y(xyzw.y), z(xyzw.z), w(xyzw.w)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(stvec2<type> const& xy, type const& zc, type const& wc)
: x(xy.x), y(xy.y), z(zc), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, stvec2<type> const& yz, type const& wc)
: x(xc), y(yz.x), z(yz.y), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, type const& yc, stvec2<type> const& zw)
: x(xc), y(yc), z(zw.x), w(zw.y)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(stvec2<type> const& xy, stvec2<type> const& zw)
: x(xy.x), y(xy.y), z(zw.x), w(zw.y)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(stvec3<type> const& xyz, type const& wc)
: x(xyz.x), y(xyz.y), z(xyz.z), w(wc)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(type const& xc, stvec3<type> const& yzw)
: x(xc), y(yzw.x), z(yzw.y), w(yzw.z)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(stvec4<type> const& xyzw)
: x(xyzw.x), y(xyzw.y), z(xyzw.z), w(xyzw.w)
{
}
template <typename type>
inline ttvec4<type>::ttvec4(bool4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(int4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(intl4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(uint4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(uintl4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(float4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(double4 const xyzw)
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<bool> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<i32> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<i64> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<ui32> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<ui64> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<f32> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type>::ttvec4(ttvec1<f64> const xyzw[4])
: x((type)xyzw[0]), y((type)xyzw[1]), z((type)xyzw[2]), w((type)xyzw[3])
{
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator +() const
{
return *this;
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator -() const
{
return ttvec4(-x, -y, -z, -w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator ~() const
{
return ttvec4(~x, ~y, ~z, ~w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator !() const
{
return ttvec4<bool>(!x, !y, !z, !w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator +(ttvec4 const& v_rh) const
{
return ttvec4(x + v_rh.x, y + v_rh.y, z + v_rh.z, w + v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator -(ttvec4 const& v_rh) const
{
return ttvec4(x - v_rh.x, y - v_rh.y, z - v_rh.z, w - v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator *(ttvec4 const& v_rh) const
{
return ttvec4(x * v_rh.x, y * v_rh.y, z * v_rh.z, w * v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator /(ttvec4 const& v_rh) const
{
return ttvec4(x / v_rh.x, y / v_rh.y, z / v_rh.z, w / v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator %(ttvec4 const& v_rh) const
{
return ttvec4(x % v_rh.x, y % v_rh.y, z % v_rh.z, w % v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator &(ttvec4 const& v_rh) const
{
return ttvec4(x & v_rh.x, y & v_rh.y, z & v_rh.z, w & v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator |(ttvec4 const& v_rh) const
{
return ttvec4(x | v_rh.x, y | v_rh.y, z | v_rh.z, w | v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator ^(ttvec4 const& v_rh) const
{
return ttvec4(x ^ v_rh.x, y ^ v_rh.y, z ^ v_rh.z, w ^ v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator <<(ttvec4 const& v_rh) const
{
return ttvec4(x << v_rh.x, y << v_rh.y, z << v_rh.z, w << v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator >>(ttvec4 const& v_rh) const
{
return ttvec4(x >> v_rh.x, y >> v_rh.y, z >> v_rh.z, w >> v_rh.w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator ==(ttvec4 const& v_rh) const
{
return ttvec4<bool>(x == v_rh.x, y == v_rh.y, z == v_rh.z, w == v_rh.w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator !=(ttvec4 const& v_rh) const
{
return ttvec4<bool>(x != v_rh.x, y != v_rh.y, z != v_rh.z, w != v_rh.w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator <=(ttvec4 const& v_rh) const
{
return ttvec4<bool>(x <= v_rh.x, y <= v_rh.y, z <= v_rh.z, w <= v_rh.w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator >=(ttvec4 const& v_rh) const
{
return ttvec4<bool>(x >= v_rh.x, y >= v_rh.y, z >= v_rh.z, w >= v_rh.w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator <(ttvec4 const& v_rh) const
{
return ttvec4<bool>(x < v_rh.x, y < v_rh.y, z < v_rh.z, w < v_rh.w);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator >(ttvec4 const& v_rh) const
{
return ttvec4<bool>(x > v_rh.x, y > v_rh.y, z > v_rh.z, w > v_rh.w);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator +(type const& s_rh) const
{
return ttvec4(x + s_rh, y + s_rh, z + s_rh, w + s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator -(type const& s_rh) const
{
return ttvec4(x - s_rh, y - s_rh, z - s_rh, w - s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator *(type const& s_rh) const
{
return ttvec4(x * s_rh, y * s_rh, z * s_rh, w * s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator /(type const& s_rh) const
{
return ttvec4(x / s_rh, y / s_rh, z / s_rh, w / s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator %(type const& s_rh) const
{
return ttvec4(x % s_rh, y % s_rh, z % s_rh, w % s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator &(type const& s_rh) const
{
return ttvec4(x & s_rh, y & s_rh, z & s_rh, w & s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator |(type const& s_rh) const
{
return ttvec4(x | s_rh, y | s_rh, z | s_rh, w | s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator ^(type const& s_rh) const
{
return ttvec4(x ^ s_rh, y ^ s_rh, z ^ s_rh, w ^ s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator <<(type const& s_rh) const
{
return ttvec4(x << s_rh, y << s_rh, z << s_rh, w << s_rh);
}
template <typename type>
inline ttvec4<type> const ttvec4<type>::operator >>(type const& s_rh) const
{
return ttvec4(x >> s_rh, y >> s_rh, z >> s_rh, w >> s_rh);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator ==(type const& s_rh) const
{
return ttvec4<bool>(x == s_rh, y == s_rh, z == s_rh, w == s_rh);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator !=(type const& s_rh) const
{
return ttvec4<bool>(x != s_rh, y != s_rh, z != s_rh, w != s_rh);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator <=(type const& s_rh) const
{
return ttvec4<bool>(x <= s_rh, y <= s_rh, z <= s_rh, w <= s_rh);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator >=(type const& s_rh) const
{
return ttvec4<bool>(x >= s_rh, y >= s_rh, z >= s_rh, w >= s_rh);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator <(type const& s_rh) const
{
return ttvec4<bool>(x < s_rh, y < s_rh, z < s_rh, w < s_rh);
}
template <typename type>
inline ttvec4<bool> const ttvec4<type>::operator >(type const& s_rh) const
{
return ttvec4<bool>(x > s_rh, y > s_rh, z > s_rh, w > s_rh);
}
template <typename type>
inline type const ttvec4<type>::operator [](index const i) const
{
return xyzw[i];
}
template <typename type>
inline ttvec4<type>::operator type const* () const
{
return xyzw;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator =(ttvec4 const& v_rh)
{
x = v_rh.x;
y = v_rh.y;
z = v_rh.z;
w = v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator =(stvec4<type> const& v_rh)
{
x = v_rh.x;
y = v_rh.y;
z = v_rh.z;
w = v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator +=(ttvec4 const& v_rh)
{
x += v_rh.x;
y += v_rh.y;
z += v_rh.z;
w += v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator -=(ttvec4 const& v_rh)
{
x -= v_rh.x;
y -= v_rh.y;
z -= v_rh.z;
w -= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator *=(ttvec4 const& v_rh)
{
x *= v_rh.x;
y *= v_rh.y;
z *= v_rh.z;
w *= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator /=(ttvec4 const& v_rh)
{
x /= v_rh.x;
y /= v_rh.y;
z /= v_rh.z;
w /= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator %=(ttvec4 const& v_rh)
{
x %= v_rh.x;
y %= v_rh.y;
z %= v_rh.z;
w %= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator &=(ttvec4 const& v_rh)
{
x &= v_rh.x;
y &= v_rh.y;
z &= v_rh.z;
w &= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator |=(ttvec4 const& v_rh)
{
x |= v_rh.x;
y |= v_rh.y;
z |= v_rh.z;
w |= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator ^=(ttvec4 const& v_rh)
{
x ^= v_rh.x;
y ^= v_rh.y;
z ^= v_rh.z;
w ^= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator <<=(ttvec4 const& v_rh)
{
x <<= v_rh.x;
y <<= v_rh.y;
z <<= v_rh.z;
w <<= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator >>=(ttvec4 const& v_rh)
{
x >>= v_rh.x;
y >>= v_rh.y;
z >>= v_rh.z;
w >>= v_rh.w;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator =(type const& s_rh)
{
x = y = z = w = s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator +=(type const& s_rh)
{
x += s_rh;
y += s_rh;
z += s_rh;
w += s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator -=(type const& s_rh)
{
x -= s_rh;
y -= s_rh;
z -= s_rh;
w -= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator *=(type const& s_rh)
{
x *= s_rh;
y *= s_rh;
z *= s_rh;
w *= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator /=(type const& s_rh)
{
x /= s_rh;
y /= s_rh;
z /= s_rh;
w /= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator %=(type const& s_rh)
{
x %= s_rh;
y %= s_rh;
z %= s_rh;
w %= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator &=(type const& s_rh)
{
x &= s_rh;
y &= s_rh;
z &= s_rh;
w &= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator |=(type const& s_rh)
{
x |= s_rh;
y |= s_rh;
z |= s_rh;
w |= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator ^=(type const& s_rh)
{
x ^= s_rh;
y ^= s_rh;
z ^= s_rh;
w ^= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator <<=(type const& s_rh)
{
x <<= s_rh;
y <<= s_rh;
z <<= s_rh;
w <<= s_rh;
return *this;
}
template <typename type>
inline ttvec4<type>& ttvec4<type>::operator >>=(type const& s_rh)
{
x >>= s_rh;
y >>= s_rh;
z >>= s_rh;
w >>= s_rh;
return *this;
}
template <typename type>
inline type& ttvec4<type>::operator [](index const i)
{
return xyzw[i];
}
template <typename type>
inline ttvec4<type>::operator type* ()
{
return xyzw;
}
template<typename type>
inline ttvec4<type> const operator +(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh + s_lh);
}
template<typename type>
inline ttvec4<type> const operator -(type const& s_lh, ttvec4<type> const& v_rh)
{
return ttvec4<type>(s_lh - v_rh.x, s_lh - v_rh.y, s_lh - v_rh.z, s_lh - v_rh.w);
}
template<typename type>
inline ttvec4<type> const operator *(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh * s_lh);
}
template<typename type>
inline ttvec4<type> const operator /(type const& s_lh, ttvec4<type> const& v_rh)
{
return ttvec4<type>(s_lh / v_rh.x, s_lh / v_rh.y, s_lh / v_rh.z, s_lh / v_rh.w);
}
template<typename type>
inline ttvec4<type> const operator %(type const& s_lh, ttvec4<type> const& v_rh)
{
return ttvec4<type>(s_lh % v_rh.x, s_lh % v_rh.y, s_lh % v_rh.z, s_lh % v_rh.w);
}
template<typename type>
inline ttvec4<type> const operator &(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh & s_lh);
}
template<typename type>
inline ttvec4<type> const operator |(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh | s_lh);
}
template<typename type>
inline ttvec4<type> const operator ^(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh ^ s_lh);
}
template<typename type>
inline ttvec4<type> const operator <<(type const& s_lh, ttvec4<type> const& v_rh)
{
return ttvec4<type>(s_lh << v_rh.x, s_lh << v_rh.y, s_lh << v_rh.z, s_lh << v_rh.w);
}
template<typename type>
inline ttvec4<type> const operator >>(type const& s_lh, ttvec4<type> const& v_rh)
{
return ttvec4<type>(s_lh >> v_rh.x, s_lh >> v_rh.y, s_lh >> v_rh.z, s_lh >> v_rh.w);
}
template<typename type>
inline ttvec4<bool> const operator ==(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh == s_lh);
}
template<typename type>
inline ttvec4<bool> const operator !=(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh != s_lh);
}
template<typename type>
inline ttvec4<bool> const operator <=(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh <= s_lh);
}
template<typename type>
inline ttvec4<bool> const operator >=(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh >= s_lh);
}
template<typename type>
inline ttvec4<bool> const operator <(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh < s_lh);
}
template<typename type>
inline ttvec4<bool> const operator >(type const& s_lh, ttvec4<type> const& v_rh)
{
return (v_rh > s_lh);
}
//-----------------------------------------------------------------------------
template<typename type>
inline ttvec1<type> const stvec1<type>::operator =(ttvec1<type> const v)
{
// pass-by-value is deliberate; need copy in case 'v' is the swizzle target
this->x = v.x;
return ttvec1<type>(*this);
}
template<typename type>
inline ttvec1<type> const stvec1<type>::operator =(stvec1 const& v)
{
return (*this = ttvec1<type>(v));
}
template<typename type>
inline ttvec1<type> const stvec1<type>::operator =(type const& xc)
{
return (*this = ttvec1<type>(xc));
}
template<typename type>
inline stvec1<type>::stvec1(type& xr)
: ttvec1<type>(xr), xr(xr)
{
}
template<typename type>
inline stvec1<type>::~stvec1()
{
// assign final state
xr = this->x;
}
template<typename type>
inline ttvec2<type> const stvec2<type>::operator =(ttvec2<type> const v)
{
// pass-by-value is deliberate; need copy in case 'v' is the swizzle target
this->x = v.x;
this->y = v.y;
return ttvec2<type>(*this);
}
template<typename type>
inline ttvec2<type> const stvec2<type>::operator =(stvec2 const& v)
{
return (*this = ttvec2<type>(v));
}
template<typename type>
inline ttvec2<type> const stvec2<type>::operator =(type const& xy)
{
return (*this = ttvec2<type>(xy));
}
template<typename type>
inline stvec2<type>::stvec2(type& xr, type& yr)
: ttvec2<type>(xr, yr), xr(xr), yr(yr)
{
}
template<typename type>
inline stvec2<type>::~stvec2()
{
// assign final state
xr = this->x;
yr = this->y;
}
template<typename type>
inline ttvec3<type> const stvec3<type>::operator =(ttvec3<type> const v)
{
// pass-by-value is deliberate; need copy in case 'v' is the swizzle target
this->x = v.x;
this->y = v.y;
this->z = v.z;
return ttvec3<type>(*this);
}
template<typename type>
inline ttvec3<type> const stvec3<type>::operator =(stvec3 const& v)
{
return (*this = ttvec3<type>(v));
}
template<typename type>
inline ttvec3<type> const stvec3<type>::operator =(type const& xyz)
{
return (*this = ttvec3<type>(xyz));
}
template<typename type>
inline stvec3<type>::stvec3(type& xr, type& yr, type& zr)
: ttvec3<type>(xr, yr, zr), xr(xr), yr(yr), zr(zr)
{
}
template<typename type>
inline stvec3<type>::~stvec3()
{
// assign final state
xr = this->x;
yr = this->y;
zr = this->z;
}
template<typename type>
inline ttvec4<type> const stvec4<type>::operator =(ttvec4<type> const v)
{
// pass-by-value is deliberate; need copy in case 'v' is the swizzle target
this->x = v.x;
this->y = v.y;
this->z = v.z;
this->w = v.w;
return ttvec4<type>(*this);
}
template<typename type>
inline ttvec4<type> const stvec4<type>::operator =(stvec4 const& v)
{
return (*this = ttvec4<type>(v));
}
template<typename type>
inline ttvec4<type> const stvec4<type>::operator =(type const& xyzw)
{
return (*this = ttvec4<type>(xyzw));
}
template<typename type>
inline stvec4<type>::stvec4(type& xr, type& yr, type& zr, type& wr)
: ttvec4<type>(xr, yr, zr, wr), xr(xr), yr(yr), zr(zr), wr(wr)
{
}
template<typename type>
inline stvec4<type>::~stvec4()
{
// assign final state
xr = this->x;
yr = this->y;
zr = this->z;
wr = this->w;
}
//-----------------------------------------------------------------------------
#ifdef IJK_VECTOR_SWIZZLE
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 1, inline);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 2, inline);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 3, inline);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, ttvec, 4, inline);
/*
IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 1);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 1, inline);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 2);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 2, inline);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 3);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 3, inline);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_DECL_RTEMP, IJK_SWIZZLE_DECL_RTEMP, ttvec, stvec, stvec, 4);
IJK_SWIZZLE_ALL(IJK_SWIZZLE_IMPL_RTEMP, IJK_SWIZZLE_IMPL_RTEMP, ttvec, stvec, stvec, 4, inline);
*/
#endif // IJK_VECTOR_SWIZZLE
//-----------------------------------------------------------------------------
#endif // __cplusplus
#endif // !_IJK_VECTORSWIZZLE_INL_
#endif // _IJK_VECTORSWIZZLE_H_
| 25.604088
| 96
| 0.675053
|
dbuckstein
|
908711a2194f5d82a80a46a8537ec2f653d75e7d
| 2,541
|
cpp
|
C++
|
LeetCode-Weekly-Contest/weekly-contest-224/1727.cpp
|
sptuan/PAT-Practice
|
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
|
[
"MIT"
] | null | null | null |
LeetCode-Weekly-Contest/weekly-contest-224/1727.cpp
|
sptuan/PAT-Practice
|
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
|
[
"MIT"
] | null | null | null |
LeetCode-Weekly-Contest/weekly-contest-224/1727.cpp
|
sptuan/PAT-Practice
|
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int largestSubmatrix(vector<vector<int>>& matrix) {
vector<int> conti_seg_left,conti_seg_right;
// speical for line
int line_counter = 0;
int total_counter = 0;
if(matrix.size() == 1){
for(int i=0; i<matrix[0].size(); i++){
if(matrix[0][i] == 1){
line_counter++;
}
//cout<<line_counter<<endl;
}
return line_counter;
}
if(matrix[0].size() == 1){
for(int i=0; i<matrix.size(); i++){
if(matrix[i][0] == 1){
line_counter++;
}
//cout<<line_counter<<endl;
}
return line_counter;
}
// common
else{
for(int i=0; i<matrix[0].size(); i++){
int temp_l = 0;
int temp_r = 0;
if(matrix[0][i] == 1){
conti_seg_left.push_back(0);
//total
total_counter++;
}
for(int j=1; j<matrix.size(); j++){
if(matrix[j][i] == 0 && matrix[j-1][i] == 1){
conti_seg_right.push_back(j-1);
}
if(matrix[j][i] == 1 && matrix[j-1][i] == 0){
conti_seg_left.push_back(j);
}
//total
if(matrix[j][i] == 1){
total_counter++;
}
}
if(matrix[matrix.size()-1][i] == 1){
conti_seg_right.push_back(matrix.size()-1);
}
}
}
int max_size = 0;
if(total_counter == (matrix.size() * matrix[0].size()))
return total_counter;
for(int L=0; L<matrix.size(); L++){
for(int R=L; R<matrix.size(); R++){
int temp_counter = 0;
for(int s=0; s<conti_seg_left.size(); s++){
if(conti_seg_left[s]<=L && conti_seg_right[s]>=R)
temp_counter++;
}
int temp_size = (R-L+1) * temp_counter;
if(temp_size > max_size){
max_size = temp_size;
}
}
}
return max_size;
}
};
| 33
| 70
| 0.358127
|
sptuan
|
908ce98a98ca51186e12f3042435ce3af8a27cba
| 810
|
cpp
|
C++
|
src/HAL/InputPin.cpp
|
SqLemon/Robotics_HAL
|
3364ef3a41345b9551a19554015b9582b7258fc6
|
[
"MIT"
] | null | null | null |
src/HAL/InputPin.cpp
|
SqLemon/Robotics_HAL
|
3364ef3a41345b9551a19554015b9582b7258fc6
|
[
"MIT"
] | null | null | null |
src/HAL/InputPin.cpp
|
SqLemon/Robotics_HAL
|
3364ef3a41345b9551a19554015b9582b7258fc6
|
[
"MIT"
] | null | null | null |
/*
* Pin.h
*
* Created on: Jan 2, 2021
* Author: ianicknoejovich
*/
#include <HAL/InputPin.h>
InputPin::InputPin(uint8_t port, uint8_t pin, Mode mode) : Pin(port, pin) {
_mode = mode;
}
void InputPin::init(void){
GPIO_setDir(_port, _pin, INPUT);
if(_mode == PULLDOWN) GPIO_setInputMode(_port, _pin, _mode-1);
else GPIO_setInputMode(_port, _pin, _mode);
if(_mode == PULLUP) GPIO_setPull(_port, _pin, HIGH);
else GPIO_setPull(_port, _pin, LOW);
}
void InputPin::paramInit(uint8_t port, uint8_t pin, Mode mode){
GPIO_setDir(port, pin, INPUT);
if(mode == PULLDOWN) GPIO_setInputMode(port, pin, PULLUP); //form input mode pullup and pullfown share "code"
else GPIO_setInputMode(port, pin, mode);
if(mode == PULLUP) GPIO_setPull(port, pin, HIGH);
else GPIO_setPull(port, pin, LOW);
}
| 25.3125
| 110
| 0.7
|
SqLemon
|
908f67e681541d578b4cd466bda4805f73cce902
| 1,765
|
cpp
|
C++
|
server/main.cpp
|
ReddyArunreddy/BeastLounge
|
ae848cb604d1cac785d6345252de5007377f2ee1
|
[
"BSL-1.0"
] | null | null | null |
server/main.cpp
|
ReddyArunreddy/BeastLounge
|
ae848cb604d1cac785d6345252de5007377f2ee1
|
[
"BSL-1.0"
] | null | null | null |
server/main.cpp
|
ReddyArunreddy/BeastLounge
|
ae848cb604d1cac785d6345252de5007377f2ee1
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2018-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/vinniefalco/BeastLounge
//
#include "logger.hpp"
#include "server.hpp"
#include <boost/config.hpp>
#include <boost/beast/src.hpp>
#include <iostream>
#ifdef BOOST_MSVC
# ifndef WIN32_LEAN_AND_MEAN // VC_EXTRALEAN
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# undef WIN32_LEAN_AND_MEAN
# else
# include <windows.h>
# endif
#endif
//------------------------------------------------------------------------------
extern
std::unique_ptr<logger>
make_logger();
/** Create a server.
The configuration file is loaded,
and all child objects are created.
*/
extern
std::unique_ptr<server>
make_server(
char const* config_path,
std::unique_ptr<logger> log);
//------------------------------------------------------------------------------
int
main(int argc, char* argv[])
{
#if BOOST_MSVC
{
int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
flags |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(flags);
}
#endif
// Create the logger
auto log = make_logger();
if(! log)
return EXIT_FAILURE;
// Check command line arguments.
if(argc != 2)
{
log->cerr() <<
"Usage: lounge-server <config-path>\n";
return EXIT_FAILURE;
}
auto const config_path = argv[1];
// Create the server
beast::error_code ec;
auto srv = make_server(
config_path,
std::move(log));
if(! srv)
return EXIT_FAILURE;
srv->run();
return EXIT_SUCCESS;
}
| 21.52439
| 80
| 0.5983
|
ReddyArunreddy
|
9093b2b88c85bb24c49e59169ca9c1a7ccc7eb9d
| 4,475
|
cpp
|
C++
|
src/shared/tests/diagnostics/counter_set.cpp
|
snowmeltarcade/projectbirdracing
|
55cd479c81979de535b0cf496e91dd8d48b99fa8
|
[
"MIT"
] | null | null | null |
src/shared/tests/diagnostics/counter_set.cpp
|
snowmeltarcade/projectbirdracing
|
55cd479c81979de535b0cf496e91dd8d48b99fa8
|
[
"MIT"
] | 3
|
2021-11-13T02:18:59.000Z
|
2021-12-04T18:16:01.000Z
|
src/shared/tests/diagnostics/counter_set.cpp
|
snowmeltarcade/projectbirdracing
|
55cd479c81979de535b0cf496e91dd8d48b99fa8
|
[
"MIT"
] | null | null | null |
#include <thread>
#include "catch2/catch.hpp"
#include "shared/diagnostics/counter_set.h"
using namespace pbr::shared::diagnostics;
//////////
/// increment
//////////
TEST_CASE("increment - valid amount - increments counter", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
c.increment_counter(key, value);
c.increment_counter(key, value);
auto result = c.get_counter(key);
REQUIRE(result == value * 2);
}
//////////
/// decrement
//////////
TEST_CASE("decrement - valid amount - decrements counter", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
c.decrement_counter(key, value);
c.decrement_counter(key, value);
auto result = c.get_counter(key);
REQUIRE(result == -value * 2);
}
//////////
/// add_value_to_list
//////////
TEST_CASE("add_value_to_list - valid value - adds value to list", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
auto value2 = 20;
c.add_value_to_list(key, value);
c.add_value_to_list(key, value2);
auto result = c.get_values_for_counter_list(key);
REQUIRE(result.size() == 2);
REQUIRE(result[0] == value);
REQUIRE(result[1] == value2);
}
//////////
/// get_counter
//////////
TEST_CASE("get_counter - returns counter", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
c.increment_counter(key, value);
auto result = c.get_counter(key);
REQUIRE(result == value);
c.increment_counter(key, value);
result = c.get_counter(key);
REQUIRE(result == value * 2);
}
//////////
/// get_values_for_counter_list
//////////
TEST_CASE("get_values_for_counter_list - returns values", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
auto value2 = 20;
c.add_value_to_list(key, value);
auto result = c.get_values_for_counter_list(key);
REQUIRE(result.size() == 1);
REQUIRE(result[0] == value);
c.add_value_to_list(key, value2);
result = c.get_values_for_counter_list(key);
REQUIRE(result.size() == 2);
REQUIRE(result[0] == value);
REQUIRE(result[1] == value2);
}
//////////
/// get_counter_for_duration
//////////
TEST_CASE("get_counter_for_duration - returns values", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
auto now = std::chrono::system_clock::now();
auto duration = std::chrono::milliseconds(500);
auto expected {0};
auto result_on_duration {0};
// ensure the last update time is set up correctly
c.get_counter_for_duration(key, duration, result_on_duration);
result_on_duration = 0;
while (std::chrono::system_clock::now() - now < duration) {
expected += value;
c.increment_counter(key, value);
auto result = c.get_counter_for_duration(key, duration, result_on_duration);
REQUIRE(result == expected);
REQUIRE(result_on_duration == 0);
}
std::this_thread::sleep_for(duration / 2);
// the duration has now passed
auto passed_result = c.get_counter_for_duration(key, duration, result_on_duration);
REQUIRE(passed_result >= 0);
REQUIRE(passed_result < expected);
REQUIRE(expected == result_on_duration);
}
//////////
/// get_average_for_duration
//////////
TEST_CASE("get_average_for_duration - returns values", "[shared/diagnostics]") {
counter_set c;
auto key = "key";
auto value = 10;
auto now = std::chrono::system_clock::now();
auto duration = std::chrono::milliseconds(500);
auto number_of_additions {0};
auto total {0};
auto result_on_duration {0.0f};
// ensure the last update time is set up correctly
c.get_average_for_duration(key, duration, result_on_duration);
result_on_duration = 0.0f;
while (std::chrono::system_clock::now() - now <= duration) {
total += value;
++number_of_additions;
c.add_value_to_list(key, value);
c.get_average_for_duration(key, duration, result_on_duration);
REQUIRE(result_on_duration == 0.0f);
}
std::this_thread::sleep_for(duration / 2);
auto expected = static_cast<float>(total) / number_of_additions;
// the duration has now passed
auto result = c.get_average_for_duration(key, duration, result_on_duration);
REQUIRE(result == expected);
REQUIRE(result_on_duration == expected);
}
| 23.677249
| 91
| 0.642458
|
snowmeltarcade
|
90959b3dd90afb9a9bb2734d16fef8bdfda59684
| 18,918
|
cc
|
C++
|
mediapipe/python/pybind/packet_creator.cc
|
Yuuraa/mediapipe-gesture-recognition
|
e2444cedbfcedf2b242ad025ceac39359c945db2
|
[
"Apache-2.0"
] | 47
|
2019-12-29T02:52:48.000Z
|
2022-02-21T08:39:14.000Z
|
mediapipe/python/pybind/packet_creator.cc
|
Yuuraa/mediapipe-gesture-recognition
|
e2444cedbfcedf2b242ad025ceac39359c945db2
|
[
"Apache-2.0"
] | null | null | null |
mediapipe/python/pybind/packet_creator.cc
|
Yuuraa/mediapipe-gesture-recognition
|
e2444cedbfcedf2b242ad025ceac39359c945db2
|
[
"Apache-2.0"
] | 16
|
2020-07-21T06:28:25.000Z
|
2022-02-02T13:40:36.000Z
|
// Copyright 2020 The MediaPipe Authors.
//
// 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 "mediapipe/python/pybind/packet_creator.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "mediapipe/framework/formats/matrix.h"
#include "mediapipe/framework/packet.h"
#include "mediapipe/framework/port/integral_types.h"
#include "mediapipe/framework/timestamp.h"
#include "mediapipe/python/pybind/image_frame_util.h"
#include "mediapipe/python/pybind/util.h"
#include "pybind11/eigen.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
namespace mediapipe {
namespace python {
namespace {
Packet CreateImageFramePacket(mediapipe::ImageFormat::Format format,
const py::array& data) {
if (format == mediapipe::ImageFormat::SRGB ||
format == mediapipe::ImageFormat::SRGBA ||
format == mediapipe::ImageFormat::GRAY8) {
return Adopt(CreateImageFrame<uint8>(format, data).release());
} else if (format == mediapipe::ImageFormat::GRAY16 ||
format == mediapipe::ImageFormat::SRGB48 ||
format == mediapipe::ImageFormat::SRGBA64) {
return Adopt(CreateImageFrame<uint16>(format, data).release());
} else if (format == mediapipe::ImageFormat::VEC32F1 ||
format == mediapipe::ImageFormat::VEC32F2) {
return Adopt(CreateImageFrame<float>(format, data).release());
}
throw RaisePyError(PyExc_RuntimeError,
absl::StrCat("Unsupported ImageFormat: ", format).c_str());
return Packet();
}
} // namespace
namespace py = pybind11;
void PublicPacketCreators(pybind11::module* m) {
m->def(
"create_string",
[](const std::string& data) { return MakePacket<std::string>(data); },
R"doc(Create a MediaPipe std::string Packet from a str.
Args:
data: A str.
Returns:
A MediaPipe std::string Packet.
Raises:
TypeError: If the input is not a str.
Examples:
packet = mp.packet_creator.create_string('abc')
data = mp.packet_getter.get_string(packet)
)doc",
py::return_value_policy::move);
m->def(
"create_string",
[](const py::bytes& data) { return MakePacket<std::string>(data); },
R"doc(Create a MediaPipe std::string Packet from a bytes object.
Args:
data: A bytes object.
Returns:
A MediaPipe std::string Packet.
Raises:
TypeError: If the input is not a bytes object.
Examples:
packet = mp.packet_creator.create_string(b'\xd0\xd0\xd0')
data = mp.packet_getter.get_bytes(packet)
)doc",
py::return_value_policy::move);
m->def(
"create_bool", [](bool data) { return MakePacket<bool>(data); },
R"doc(Create a MediaPipe bool Packet from a boolean object.
Args:
data: A boolean object.
Returns:
A MediaPipe bool Packet.
Raises:
TypeError: If the input is not a boolean object.
Examples:
packet = mp.packet_creator.create_bool(True)
data = mp.packet_getter.get_bool(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int",
[](int64 data) {
RaisePyErrorIfOverflow(data, INT_MIN, INT_MAX);
return MakePacket<int>(data);
},
R"doc(Create a MediaPipe int Packet from an integer.
Args:
data: An integer or a np.intc.
Returns:
A MediaPipe int Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is not an integer.
Examples:
packet = mp.packet_creator.create_int(0)
data = mp.packet_getter.get_int(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int8",
[](int64 data) {
RaisePyErrorIfOverflow(data, INT8_MIN, INT8_MAX);
return MakePacket<int8>(data);
},
R"doc(Create a MediaPipe int8 Packet from an integer.
Args:
data: An integer or a np.int8.
Returns:
A MediaPipe int8 Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is neither an integer nor a np.int8.
Examples:
packet = mp.packet_creator.create_int8(2**7 - 1)
data = mp.packet_getter.get_int(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int16",
[](int64 data) {
RaisePyErrorIfOverflow(data, INT16_MIN, INT16_MAX);
return MakePacket<int16>(data);
},
R"doc(Create a MediaPipe int16 Packet from an integer.
Args:
data: An integer or a np.int16.
Returns:
A MediaPipe int16 Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is neither an integer nor a np.int16.
Examples:
packet = mp.packet_creator.create_int16(2**15 - 1)
data = mp.packet_getter.get_int(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int32",
[](int64 data) {
RaisePyErrorIfOverflow(data, INT32_MIN, INT32_MAX);
return MakePacket<int32>(data);
},
R"doc(Create a MediaPipe int32 Packet from an integer.
Args:
data: An integer or a np.int32.
Returns:
A MediaPipe int32 Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is neither an integer nor a np.int32.
Examples:
packet = mp.packet_creator.create_int32(2**31 - 1)
data = mp.packet_getter.get_int(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int64", [](int64 data) { return MakePacket<int64>(data); },
R"doc(Create a MediaPipe int64 Packet from an integer.
Args:
data: An integer or a np.int64.
Returns:
A MediaPipe int64 Packet.
Raises:
TypeError: If the input is neither an integer nor a np.int64.
Examples:
packet = mp.packet_creator.create_int64(2**63 - 1)
data = mp.packet_getter.get_int(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_uint8",
[](int64 data) {
RaisePyErrorIfOverflow(data, 0, UINT8_MAX);
return MakePacket<uint8>(data);
},
R"doc(Create a MediaPipe uint8 Packet from an integer.
Args:
data: An integer or a np.uint8.
Returns:
A MediaPipe uint8 Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is neither an integer nor a np.uint8.
Examples:
packet = mp.packet_creator.create_uint8(2**8 - 1)
data = mp.packet_getter.get_uint(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_uint16",
[](int64 data) {
RaisePyErrorIfOverflow(data, 0, UINT16_MAX);
return MakePacket<uint16>(data);
},
R"doc(Create a MediaPipe uint16 Packet from an integer.
Args:
data: An integer or a np.uint16.
Returns:
A MediaPipe uint16 Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is neither an integer nor a np.uint16.
Examples:
packet = mp.packet_creator.create_uint16(2**16 - 1)
data = mp.packet_getter.get_uint(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_uint32",
[](int64 data) {
RaisePyErrorIfOverflow(data, 0, UINT32_MAX);
return MakePacket<uint32>(data);
},
R"doc(Create a MediaPipe uint32 Packet from an integer.
Args:
data: An integer or a np.uint32.
Returns:
A MediaPipe uint32 Packet.
Raises:
OverflowError: If the input integer overflows.
TypeError: If the input is neither an integer nor a np.uint32.
Examples:
packet = mp.packet_creator.create_uint32(2**32 - 1)
data = mp.packet_getter.get_uint(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_uint64", [](uint64 data) { return MakePacket<uint64>(data); },
R"doc(Create a MediaPipe uint64 Packet from an integer.
Args:
data: An integer or a np.uint64.
Returns:
A MediaPipe uint64 Packet.
Raises:
TypeError: If the input is neither an integer nor a np.uint64.
Examples:
packet = mp.packet_creator.create_uint64(2**64 - 1)
data = mp.packet_getter.get_uint(packet)
)doc",
// py::arg().noconvert() won't allow this to accept np.uint64 data type.
py::arg(), py::return_value_policy::move);
m->def(
"create_float", [](float data) { return MakePacket<float>(data); },
R"doc(Create a MediaPipe float Packet from a float.
Args:
data: A float or a np.float.
Returns:
A MediaPipe float Packet.
Raises:
TypeError: If the input is neither a float nor a np.float.
Examples:
packet = mp.packet_creator.create_float(0.1)
data = mp.packet_getter.get_float(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_double", [](double data) { return MakePacket<double>(data); },
R"doc(Create a MediaPipe double Packet from a float.
Args:
data: A float or a np.double.
Returns:
A MediaPipe double Packet.
Raises:
TypeError: If the input is neither a float nore a np.double.
Examples:
packet = mp.packet_creator.create_double(0.1)
data = mp.packet_getter.get_float(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int_array",
[](const std::vector<int>& data) {
int* ints = new int[data.size()];
std::copy(data.begin(), data.end(), ints);
return Adopt(reinterpret_cast<int(*)[]>(ints));
},
R"doc(Create a MediaPipe int array Packet from a list of integers.
Args:
data: A list of integers.
Returns:
A MediaPipe int array Packet.
Raises:
TypeError: If the input is not a list of integers.
Examples:
packet = mp.packet_creator.create_int_array([1, 2, 3])
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_float_array",
[](const std::vector<float>& data) {
float* floats = new float[data.size()];
std::copy(data.begin(), data.end(), floats);
return Adopt(reinterpret_cast<float(*)[]>(floats));
},
R"doc(Create a MediaPipe float array Packet from a list of floats.
Args:
data: A list of floats.
Returns:
A MediaPipe float array Packet.
Raises:
TypeError: If the input is not a list of floats.
Examples:
packet = mp.packet_creator.create_float_array([0.1, 0.2, 0.3])
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_int_vector",
[](const std::vector<int>& data) {
return MakePacket<std::vector<int>>(data);
},
R"doc(Create a MediaPipe int vector Packet from a list of integers.
Args:
data: A list of integers.
Returns:
A MediaPipe int vector Packet.
Raises:
TypeError: If the input is not a list of integers.
Examples:
packet = mp.packet_creator.create_int_vector([1, 2, 3])
data = mp.packet_getter.get_int_vector(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_float_vector",
[](const std::vector<float>& data) {
return MakePacket<std::vector<float>>(data);
},
R"doc(Create a MediaPipe float vector Packet from a list of floats.
Args:
data: A list of floats
Returns:
A MediaPipe float vector Packet.
Raises:
TypeError: If the input is not a list of floats.
Examples:
packet = mp.packet_creator.create_float_vector([0.1, 0.2, 0.3])
data = mp.packet_getter.get_float_list(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_string_vector",
[](const std::vector<std::string>& data) {
return MakePacket<std::vector<std::string>>(data);
},
R"doc(Create a MediaPipe std::string vector Packet from a list of str.
Args:
data: A list of str.
Returns:
A MediaPipe std::string vector Packet.
Raises:
TypeError: If the input is not a list of str.
Examples:
packet = mp.packet_creator.create_string_vector(['a', 'b', 'c'])
data = mp.packet_getter.get_str_list(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_packet_vector",
[](const std::vector<Packet>& data) {
return MakePacket<std::vector<Packet>>(data);
},
R"doc(Create a MediaPipe Packet holds a vector of packets.
Args:
data: A list of packets.
Returns:
A MediaPipe Packet holds a vector of packets.
Raises:
TypeError: If the input is not a list of packets.
Examples:
packet = mp.packet_creator.create_packet_vector([
mp.packet_creator.create_float(0.1),
mp.packet_creator.create_int(1),
mp.packet_creator.create_string('1')
])
data = mp.packet_getter.get_packet_vector(packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_string_to_packet_map",
[](const std::map<std::string, Packet>& data) {
return MakePacket<std::map<std::string, Packet>>(data);
},
R"doc(Create a MediaPipe std::string to packet map Packet from a dictionary.
Args:
data: A dictionary that has (str, Packet) pairs.
Returns:
A MediaPipe Packet holds std::map<std::string, Packet>.
Raises:
TypeError: If the input is not a dictionary from str to packet.
Examples:
dict_packet = mp.packet_creator.create_string_to_packet_map({
'float': mp.packet_creator.create_float(0.1),
'int': mp.packet_creator.create_int(1),
'std::string': mp.packet_creator.create_string('1')
data = mp.packet_getter.get_str_to_packet_dict(dict_packet)
)doc",
py::arg().noconvert(), py::return_value_policy::move);
m->def(
"create_matrix",
// Eigen Map class
// (https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html) is the
// way to reuse the external memory as an Eigen type. However, when
// creating an Eigen::MatrixXf from an Eigen Map object, the data copy
// still happens. We can make a packet of an Eigen Map type for reusing
// external memory. However,the packet data type is no longer
// Eigen::MatrixXf.
// TODO: Should take "const Eigen::Ref<const Eigen::MatrixXf>&"
// as the input argument. Investigate why bazel non-optimized mode
// triggers a memory allocation bug in Eigen::internal::aligned_free().
[](const Eigen::MatrixXf& matrix) {
// MakePacket copies the data.
return MakePacket<Matrix>(matrix);
},
R"doc(Create a MediaPipe Matrix Packet from a 2d numpy float ndarray.
The method copies data from the input MatrixXf and the returned packet owns
a MatrixXf object.
Args:
matrix: A 2d numpy float ndarray.
Returns:
A MediaPipe Matrix Packet.
Raises:
TypeError: If the input is not a 2d numpy float ndarray.
Examples:
packet = mp.packet_creator.create_matrix(
np.array([[.1, .2, .3], [.4, .5, .6]])
matrix = mp.packet_getter.get_matrix(packet)
)doc",
py::return_value_policy::move);
}
void InternalPacketCreators(pybind11::module* m) {
m->def(
"_create_image_frame_with_copy",
[](mediapipe::ImageFormat::Format format, const py::array& data) {
return CreateImageFramePacket(format, data);
},
py::arg("format"), py::arg("data").noconvert(),
py::return_value_policy::move);
m->def(
"_create_image_frame_with_reference",
[](mediapipe::ImageFormat::Format format, const py::array& data) {
throw RaisePyError(
PyExc_NotImplementedError,
"Creating image frame packet with reference is not supproted yet.");
},
py::arg("format"), py::arg("data").noconvert(),
py::return_value_policy::move);
m->def(
"_create_image_frame_with_copy",
[](ImageFrame& image_frame) {
auto image_frame_copy = absl::make_unique<ImageFrame>();
// Set alignment_boundary to kGlDefaultAlignmentBoundary so that
// both GPU and CPU can process it.
image_frame_copy->CopyFrom(image_frame,
ImageFrame::kGlDefaultAlignmentBoundary);
return Adopt(image_frame_copy.release());
},
py::arg("image_frame").noconvert(), py::return_value_policy::move);
m->def(
"_create_image_frame_with_reference",
[](ImageFrame& image_frame) {
throw RaisePyError(
PyExc_NotImplementedError,
"Creating image frame packet with reference is not supproted yet.");
},
py::arg("image_frame").noconvert(), py::return_value_policy::move);
m->def(
"_create_proto",
[](const std::string& type_name, const py::bytes& serialized_proto) {
using packet_internal::HolderBase;
mediapipe::StatusOr<std::unique_ptr<HolderBase>> maybe_holder =
packet_internal::MessageHolderRegistry::CreateByName(type_name);
if (!maybe_holder.ok()) {
throw RaisePyError(
PyExc_RuntimeError,
absl::StrCat("Unregistered proto message type: ", type_name)
.c_str());
}
// Creates a Packet with the concrete C++ payload type.
std::unique_ptr<HolderBase> message_holder =
std::move(maybe_holder).ValueOrDie();
auto* copy = const_cast<proto_ns::MessageLite*>(
message_holder->GetProtoMessageLite());
copy->ParseFromString(serialized_proto);
return packet_internal::Create(message_holder.release());
},
py::return_value_policy::move);
m->def(
"_create_proto_vector",
[](const std::string& type_name,
const std::vector<py::bytes>& serialized_proto_vector) {
// TODO: Implement this.
throw RaisePyError(PyExc_NotImplementedError,
"Creating a packet from a vector of proto messages "
"is not supproted yet.");
return Packet();
},
py::return_value_policy::move);
}
void PacketCreatorSubmodule(pybind11::module* module) {
py::module m = module->def_submodule(
"_packet_creator", "MediaPipe internal packet creator module.");
PublicPacketCreators(&m);
InternalPacketCreators(&m);
}
} // namespace python
} // namespace mediapipe
| 29.28483
| 82
| 0.654773
|
Yuuraa
|
90983beec8f4579019604a4f5fe12d342d12cab7
| 11,829
|
cpp
|
C++
|
common/jpeg/ImgHWEncoder.cpp
|
rockchip-toybrick/hardware_rockchip_camera
|
18ff40c3b502c65b9cbb35902b3419ebae60726b
|
[
"Apache-2.0"
] | null | null | null |
common/jpeg/ImgHWEncoder.cpp
|
rockchip-toybrick/hardware_rockchip_camera
|
18ff40c3b502c65b9cbb35902b3419ebae60726b
|
[
"Apache-2.0"
] | null | null | null |
common/jpeg/ImgHWEncoder.cpp
|
rockchip-toybrick/hardware_rockchip_camera
|
18ff40c3b502c65b9cbb35902b3419ebae60726b
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2014-2017 Intel Corporation
* Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd
*
* 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.
*/
#define LOG_TAG "ImgHWEncoder"
#include "ImgHWEncoder.h"
#include "LogHelper.h"
#include "PerformanceTraces.h"
#include "CameraMetadataHelper.h"
#include "PlatformData.h"
#include <cutils/properties.h>
namespace android {
namespace camera2 {
#define ALIGN(value, x) ((value + (x-1)) & (~(x-1)))
ImgHWEncoder::ImgHWEncoder(int cameraid) :
mCameraId(cameraid),
mPool(NULL)
{
memset(sMaker, 0, sizeof(sMaker));
memset(sModel, 0, sizeof(sModel));
LOGI("@%s enter", __FUNCTION__);
}
ImgHWEncoder::~ImgHWEncoder()
{
LOGI("@%s enter", __FUNCTION__);
deInit();
}
status_t ImgHWEncoder::init()
{
status_t status = NO_ERROR;
LOGI("@%s enter", __FUNCTION__);
memset(&mExifInfo, 0, sizeof(RkExifInfo));
memset(&mGpsInfo, 0, sizeof(RkGPSInfo));
if (create_vpu_memory_pool_allocator(&mPool, 1, 320*240*2) < 0) {
LOGE("@%s %d: create vpu memory failed ", __FUNCTION__, __LINE__);
return UNKNOWN_ERROR;
}
return status;
}
void ImgHWEncoder::deInit()
{
LOGI("@%s enter", __FUNCTION__);
if (mPool) {
release_vpu_memory_pool_allocator(mPool);
mPool = NULL;
}
}
void ImgHWEncoder::fillRkExifInfo(RkExifInfo &exifInfo, exif_attribute_t* exifAttrs)
{
char maker_value[PROPERTY_VALUE_MAX] = {0};
char model_value[PROPERTY_VALUE_MAX] = {0};
property_get("ro.product.manufacturer", maker_value, "rockchip");
property_get("ro.product.model", model_value, "rockchip_mid");
memcpy(sMaker, maker_value, strlen(maker_value));
memcpy(sModel, model_value, strlen(model_value));
exifInfo.maker = sMaker;
exifInfo.makerchars = ALIGN(strlen(sMaker),4); //gallery can't get the maker if maker value longer than 4byte
exifInfo.modelstr = sModel;
exifInfo.modelchars = ALIGN(strlen(sModel),4); //gallery can't get the tag if the value longer than 4byte, need fix
exifInfo.Orientation = exifAttrs->orientation;
memcpy(exifInfo.DateTime, exifAttrs->date_time, 20);
exifInfo.ExposureTime.num = exifAttrs->exposure_time.num;
exifInfo.ExposureTime.denom = exifAttrs->exposure_time.den;
exifInfo.ApertureFNumber.num = exifAttrs->fnumber.num;
exifInfo.ApertureFNumber.denom = exifAttrs->fnumber.den;
exifInfo.ISOSpeedRatings = exifAttrs->iso_speed_rating;
exifInfo.CompressedBitsPerPixel.num = 0x4;
exifInfo.CompressedBitsPerPixel.denom = 0x1;
exifInfo.ShutterSpeedValue.num = exifAttrs->shutter_speed.num;
exifInfo.ShutterSpeedValue.denom = exifAttrs->shutter_speed.den;
exifInfo.ApertureValue.num = exifAttrs->aperture.num;
exifInfo.ApertureValue.denom = exifAttrs->aperture.den;
exifInfo.ExposureBiasValue.num = exifAttrs->exposure_bias.num;
exifInfo.ExposureBiasValue.denom = exifAttrs->exposure_bias.den;
exifInfo.MaxApertureValue.num = exifAttrs->max_aperture.num;
exifInfo.MaxApertureValue.denom = exifAttrs->max_aperture.den;
exifInfo.MeteringMode = exifAttrs->metering_mode;
exifInfo.Flash = exifAttrs->flash;
exifInfo.FocalLength.num = exifAttrs->focal_length.num;
exifInfo.FocalLength.denom = exifAttrs->focal_length.den;
exifInfo.FocalPlaneXResolution.num = exifAttrs->x_resolution.num;
exifInfo.FocalPlaneXResolution.denom = exifAttrs->x_resolution.den;
exifInfo.FocalPlaneYResolution.num = exifAttrs->y_resolution.num;
exifInfo.FocalPlaneYResolution.denom = exifAttrs->y_resolution.den;
exifInfo.SensingMethod = 2;//2 means 1 chip color area sensor
exifInfo.FileSource = 3;//3 means the image source is digital still camera
exifInfo.CustomRendered = exifAttrs->custom_rendered;
exifInfo.ExposureMode = exifAttrs->exposure_mode;
exifInfo.WhiteBalance = exifAttrs->white_balance;
exifInfo.DigitalZoomRatio.num = exifAttrs->zoom_ratio.num;
exifInfo.DigitalZoomRatio.denom = exifAttrs->zoom_ratio.den;
exifInfo.SceneCaptureType = exifAttrs->scene_capture_type;
exifInfo.makernote = NULL;
exifInfo.makernotechars = 0;
memcpy(exifInfo.subsectime, exifAttrs->subsec_time, 8);
}
void ImgHWEncoder::fillGpsInfo(RkGPSInfo &gpsInfo, exif_attribute_t* exifAttrs)
{
gpsInfo.GPSLatitudeRef[0] = exifAttrs->gps_latitude_ref[0];
gpsInfo.GPSLatitudeRef[1] = exifAttrs->gps_latitude_ref[1];
gpsInfo.GPSLatitude[0].num = exifAttrs->gps_latitude[0].num;
gpsInfo.GPSLatitude[0].denom = exifAttrs->gps_latitude[0].den;
gpsInfo.GPSLatitude[1].num = exifAttrs->gps_latitude[1].num;
gpsInfo.GPSLatitude[1].denom = exifAttrs->gps_latitude[1].den;
gpsInfo.GPSLatitude[2].num = exifAttrs->gps_latitude[2].num;
gpsInfo.GPSLatitude[2].denom = exifAttrs->gps_latitude[2].den;
gpsInfo.GPSLongitudeRef[0] = exifAttrs->gps_longitude_ref[0];
gpsInfo.GPSLongitudeRef[1] = exifAttrs->gps_longitude_ref[1];
gpsInfo.GPSLongitude[0].num = exifAttrs->gps_longitude[0].num;
gpsInfo.GPSLongitude[0].denom = exifAttrs->gps_longitude[0].den;
gpsInfo.GPSLongitude[1].num = exifAttrs->gps_longitude[1].num;
gpsInfo.GPSLongitude[1].denom = exifAttrs->gps_longitude[1].den;
gpsInfo.GPSLongitude[2].num = exifAttrs->gps_longitude[2].num;
gpsInfo.GPSLongitude[2].denom = exifAttrs->gps_longitude[2].den;
gpsInfo.GPSAltitudeRef = exifAttrs->gps_altitude_ref;
gpsInfo.GPSAltitude.num = exifAttrs->gps_altitude.num;
gpsInfo.GPSAltitude.denom = exifAttrs->gps_altitude.den;
gpsInfo.GpsTimeStamp[0].num = exifAttrs->gps_timestamp[0].num;
gpsInfo.GpsTimeStamp[0].denom = exifAttrs->gps_timestamp[0].den;
gpsInfo.GpsTimeStamp[1].num = exifAttrs->gps_timestamp[1].num;
gpsInfo.GpsTimeStamp[1].denom = exifAttrs->gps_timestamp[1].den;
gpsInfo.GpsTimeStamp[2].num = exifAttrs->gps_timestamp[2].num;
gpsInfo.GpsTimeStamp[2].denom = exifAttrs->gps_timestamp[2].den;
memcpy(gpsInfo.GpsDateStamp, exifAttrs->gps_datestamp, 11);//"YYYY:MM:DD\0"
gpsInfo.GPSProcessingMethod = (char *)exifAttrs->gps_processing_method;
gpsInfo.GpsProcessingMethodchars = 100;//length of GpsProcessingMethod
}
bool
ImgHWEncoder::checkInputBuffer(CameraBuffer* buf) {
// just for YUV420 format buffer
int Ysize = ALIGN(buf->width(), 16) * ALIGN(buf->height(), 16);
int UVsize = ALIGN(buf->width(), 16) * ALIGN(buf->height() / 2, 16);
if(buf->size() >= Ysize + UVsize) {
return true;
} else {
LOGE("@%s : Input buffer (%dx%d) size(%d) can't meet the HwJpeg input condition",
__FUNCTION__, buf->width(), buf->height(), buf->size());
return false;
}
}
/**
* encodeSync
*
*/
status_t ImgHWEncoder::encodeSync(EncodePackage & package)
{
PERFORMANCE_ATRACE_CALL();
status_t status = NO_ERROR;
JpegEncInInfo JpegInInfo;
JpegEncOutInfo JpegOutInfo;
std::shared_ptr<CameraBuffer> srcBuf = package.main;
std::shared_ptr<CameraBuffer> destBuf = package.jpegOut;
ExifMetaData *exifMeta = package.exifMeta;
exif_attribute_t *exifAttrs = package.exifAttrs;
int width = srcBuf->width();
int height = srcBuf->height();
int stride = srcBuf->stride();
void* srcY = srcBuf->data();
int jpegw = width;
int jpegh = height;
int outJPEGSize = destBuf->size();
int quality = exifMeta->mJpegSetting.jpegQuality;
int thumbquality = exifMeta->mJpegSetting.jpegThumbnailQuality;
LOGI("@%s %d: in buffer fd:%d, vir_addr:%p, out buffer fd:%d, vir_addr:%p", __FUNCTION__, __LINE__,
srcBuf->dmaBufFd(), srcBuf->data(),
destBuf->dmaBufFd(), destBuf->data());
// HwJpeg encode require buffer width and height align to 16 or large enough.
if(!checkInputBuffer(srcBuf.get()))
return UNKNOWN_ERROR;
JpegInInfo.pool = mPool;
JpegInInfo.frameHeader = 1;
// TODO: we only support DEGREE_0 now
JpegInInfo.rotateDegree = DEGREE_0;
// After Android7.1, HW jpeg encoder just supports fd, and
// no longer supports virtual address.
JpegInInfo.y_rgb_addr = srcBuf->dmaBufFd();
// virtual address is just used for thumbnail
JpegInInfo.y_vir_addr = (unsigned char*)srcBuf->data();
JpegInInfo.uv_vir_addr = ((unsigned char*)srcBuf->data() + jpegw*jpegh);
JpegInInfo.inputW = jpegw;
JpegInInfo.inputH = jpegh;
if(srcBuf->v4l2Fmt() != V4L2_PIX_FMT_NV12) {
LOGE("@%s %d: srcBuffer format(%s) is not NV12", __FUNCTION__, __LINE__, v4l2Fmt2Str(srcBuf->v4l2Fmt()));
return UNKNOWN_ERROR;
}
JpegInInfo.type = JPEGENC_YUV420_SP;//HWJPEGENC_RGB888//HWJPEGENC_RGB565
JpegInInfo.qLvl = quality/10;
if (JpegInInfo.qLvl < 5)
JpegInInfo.qLvl = 5;
if(JpegInInfo.qLvl > 10)
JpegInInfo.qLvl = 9;
//if not doThumb,please set doThumbNail,thumbW and thumbH to zero;
if (exifMeta->mJpegSetting.thumbWidth && exifMeta->mJpegSetting.thumbHeight)
JpegInInfo.doThumbNail = 1;
else
JpegInInfo.doThumbNail = 0;
LOGD("@%s : exifAttrs->enableThumb = %d doThumbNail=%d", __FUNCTION__,
exifAttrs->enableThumb, JpegInInfo.doThumbNail);
JpegInInfo.thumbW = exifMeta->mJpegSetting.thumbWidth;
JpegInInfo.thumbH = exifMeta->mJpegSetting.thumbHeight;
//if thumbData is NULL, do scale, the type above can not be 420_P or 422_UYVY
JpegInInfo.thumbData = NULL;
JpegInInfo.thumbDataLen = 0; //don't care when thumbData is Null
JpegInInfo.thumbqLvl = thumbquality /10;
if (JpegInInfo.thumbqLvl < 5)
JpegInInfo.thumbqLvl = 5;
if(JpegInInfo.thumbqLvl > 10)
JpegInInfo.thumbqLvl = 9;
fillRkExifInfo(mExifInfo, exifAttrs);
JpegInInfo.exifInfo = &mExifInfo;
if (exifAttrs->enableGps) {
fillGpsInfo(mGpsInfo, exifAttrs);
JpegInInfo.gpsInfo = &mGpsInfo;
} else {
JpegInInfo.gpsInfo = NULL;
}
JpegOutInfo.outBufPhyAddr = destBuf->dmaBufFd();
JpegOutInfo.outBufVirAddr = (unsigned char*)destBuf->data();
JpegOutInfo.outBuflen = outJPEGSize;
JpegOutInfo.jpegFileLen = 0;
JpegOutInfo.cacheflush = NULL;
LOGI("@%s %d: JpegInInfo thumbW:%d, thumbH:%d, thumbqLvl:%d, inputW:%d, inputH:%d, qLvl:%d", __FUNCTION__, __LINE__,
JpegInInfo.thumbW, JpegInInfo.thumbH, JpegInInfo.thumbqLvl,
JpegInInfo.inputW, JpegInInfo.inputH, JpegInInfo.qLvl);
if(hw_jpeg_encode(&JpegInInfo, &JpegOutInfo) < 0 || JpegOutInfo.jpegFileLen <= 0){
LOGE("@%s %d: hw jpeg encode fail.", __FUNCTION__, __LINE__);
return UNKNOWN_ERROR;
}
LOGI("@%s %d: actual jpeg offset: %d, size: %d, destBuf size: %d ", __FUNCTION__, __LINE__, JpegOutInfo.finalOffset, JpegOutInfo.jpegFileLen, destBuf->size());
// save jpeg size at the end of file, App will detect this header for the
// jpeg actual size
if (destBuf->size()) {
char *pCur = (char*)(destBuf->data()) + destBuf->size()
- sizeof(struct camera_jpeg_blob);
struct camera_jpeg_blob *blob = new struct camera_jpeg_blob;
blob->jpeg_blob_id = CAMERA_JPEG_BLOB_ID;
blob->jpeg_size = JpegOutInfo.jpegFileLen;
STDCOPY(pCur, (int8_t *)blob, sizeof(struct camera_jpeg_blob));
delete blob;
} else {
LOGE("ERROR: JPEG_MAX_SIZE is 0 !");
}
return status;
}
}
}
| 40.789655
| 163
| 0.704793
|
rockchip-toybrick
|
909e3d56baefe70e1e3c4fc6048bb0bcdcdd240a
| 393
|
cpp
|
C++
|
engine/runtime/ecs/constructs/scene.cpp
|
ValtoForks/EtherealEngine
|
ab769803dcd71a61c2805afd259959b62fcdc1ff
|
[
"BSD-2-Clause"
] | 791
|
2016-11-04T14:13:41.000Z
|
2022-03-20T20:47:31.000Z
|
engine/runtime/ecs/constructs/scene.cpp
|
ValtoForks/EtherealEngine
|
ab769803dcd71a61c2805afd259959b62fcdc1ff
|
[
"BSD-2-Clause"
] | 28
|
2016-12-01T05:59:30.000Z
|
2021-03-20T09:49:26.000Z
|
engine/runtime/ecs/constructs/scene.cpp
|
ValtoForks/EtherealEngine
|
ab769803dcd71a61c2805afd259959b62fcdc1ff
|
[
"BSD-2-Clause"
] | 151
|
2016-12-21T09:44:43.000Z
|
2022-03-31T13:42:18.000Z
|
#include "scene.h"
#include "utils.h"
#include <core/system/subsystem.h>
std::vector<runtime::entity> scene::instantiate(mode mod)
{
if(mod == mode::standard)
{
auto& ecs = core::get_subsystem<runtime::entity_component_system>();
ecs.dispose();
}
std::vector<runtime::entity> out_vec;
if(!data)
return out_vec;
ecs::utils::deserialize_data(*data, out_vec);
return out_vec;
}
| 17.863636
| 70
| 0.699746
|
ValtoForks
|
90a5bfac2a60f91735e7509413cb52df81968193
| 1,061
|
cpp
|
C++
|
src/engine/lua_bind/lua_env.cpp
|
LunarGameTeam/Lunar-GameEngine
|
b387d7008525681fe06db8811f4f7ee95aa7aaf1
|
[
"MIT"
] | 4
|
2020-08-07T02:18:13.000Z
|
2021-07-08T09:46:11.000Z
|
src/engine/lua_bind/lua_env.cpp
|
LunarGameTeam/Lunar-GameEngine
|
b387d7008525681fe06db8811f4f7ee95aa7aaf1
|
[
"MIT"
] | null | null | null |
src/engine/lua_bind/lua_env.cpp
|
LunarGameTeam/Lunar-GameEngine
|
b387d7008525681fe06db8811f4f7ee95aa7aaf1
|
[
"MIT"
] | null | null | null |
#include "lua_env.h"
#include "core/object/entity.h"
#include "core/object/component.h"
#include "world/scene.h"
namespace luna
{
void luna::LuaEnv::Init()
{
// m_state = luaL_newstate();
// const luaL_Reg lualibs[] = {
// { LUA_COLIBNAME, luaopen_base },
// { LUA_LOADLIBNAME, luaopen_package },
// { LUA_TABLIBNAME, luaopen_table },
// { LUA_IOLIBNAME, luaopen_io },
// { LUA_OSLIBNAME, luaopen_os },
// { LUA_STRLIBNAME, luaopen_string },
// { LUA_MATHLIBNAME, luaopen_math },
// { LUA_DBLIBNAME, luaopen_debug },
// { NULL, NULL }
// };
// if (m_state != NULL)
// {
// const luaL_Reg* lib = lualibs;
// for (; lib->func; lib++) {
// lua_pushcfunction(m_state, lib->func);
// lua_pushstring(m_state, lib->name);
// lua_call(m_state, 1, 0);
// }
// }
}
void luna::LuaEnv::RunScript(const LString &str)
{
//
// int err = luaL_loadbuffer(m_state, str.c_str(), str.Length(), "console");
// if (err == 0)
// {
// err = lua_pcall(m_state, 0, 0, 0);
// }
// if (err)
// {
// lua_pop(m_state, 1);
// }
}
}
| 20.803922
| 77
| 0.598492
|
LunarGameTeam
|
90a98e4cd7a03185d19e2b699f3ce8272de4b9d7
| 3,761
|
hpp
|
C++
|
include/tiny/basic.hpp
|
yell0w4x/tiny-arduino-serial-port
|
af4318e1c210e80d31be3d4993c8124dd4e2c8c0
|
[
"MIT"
] | null | null | null |
include/tiny/basic.hpp
|
yell0w4x/tiny-arduino-serial-port
|
af4318e1c210e80d31be3d4993c8124dd4e2c8c0
|
[
"MIT"
] | null | null | null |
include/tiny/basic.hpp
|
yell0w4x/tiny-arduino-serial-port
|
af4318e1c210e80d31be3d4993c8124dd4e2c8c0
|
[
"MIT"
] | null | null | null |
// Arduino async serial port library with nine data bits support.
//
// 2015, (c) Gk Ltd.
// MIT License
#ifndef TINY_BASIC_HPP_
#define TINY_BASIC_HPP_
#include <tiny/detail/auto_sense.hpp>
#include <iterator>
#include <bitset>
#include <stdint.h>
namespace tiny
{
#ifdef bit
# undef bit
#endif // bit
#ifdef TINY_ARDUINO_MEGA
//# include <avr/io.h>
typedef uint8_t reg_type;
#elif defined(TINY_ARDUINO_DUE)
//# include <chip.h>
typedef uint32_t reg_type;
#endif // TINY_ARDUINO_MEGA
/** Control and status register type. */
typedef volatile reg_type register_type;
/** Pointer to control and status register type. */
typedef register_type* /*const*/ register_ptr;
/** The size of the register in bits. */
enum { register_width = sizeof(register_type) * 8 };
/** The type representing register bits. */
typedef std::bitset<register_width> register_bits_type;
/** Returns the mask for the given bit no. */
template <typename ResultT>
inline ResultT mask(size_t pos) { return static_cast<ResultT>(1 << pos); }
/** Returns the mask for the given bit no. */
inline register_type mask(size_t pos) { return mask<register_type>(pos); }
#ifdef TINY_ARDUINO_MEGA
/** Reads the register bit.
*
* @param r Register address.
* @param pos Position of the bit where 0 is lsb.
* @return r & (1 << bit_pos)
*/
inline size_t bit(register_ptr r, size_t pos)
{
return *r & (1 << pos);
}
/** Reads the register bit.
*
* @param r Register address.
* @param pos Position of the bit where 0 is lsb.
* @return r & (1 << bit_pos)
*/
inline size_t bit(register_type r, size_t pos)
{
return r & (1 << pos);
}
/** Tests whether bit is set or clear.
*
* @param r Register address.
* @param pos Position of the bit where 0 is lsb.
* @return True if set, false if clear.
*/
template <typename T>
inline bool is_bit(T r, size_t pos)
{
return bit(r, pos) != 0;
}
/** Sets the register bit. */
inline void set_bit(register_ptr r, size_t pos)
{
*r |= mask(pos);
}
/** Sets the register bit. */
inline void set_bit(register_type& r, size_t pos)
{
r |= mask(pos);
}
/** Clears the register bit. */
inline void clear_bit(register_ptr r, size_t pos)
{
*r &= ~mask(pos);
}
/** Clears the register bit. */
inline void clear_bit(register_type& r, size_t pos)
{
r &= ~mask(pos);
}
/** Sets the register bit. */
template <typename T>
inline void set_bit(T& r, size_t pos, bool value)
{
if (value) { set_bit(r, pos); } else { clear_bit(r, pos); }
}
/** Returns the value of bits specified. */
inline size_t bits_value(register_ptr r, const register_bits_type& mask)
{
register_type msk = static_cast<register_type>(mask.to_ulong());
size_t v = *r & msk;
for (; msk && (msk & 1) == 0; msk >>= 1) { v >>= 1; }
return v;
}
/** Returns the value of bits specified. */
inline size_t bits_value(register_type r, const register_bits_type& mask)
{
register_type msk = static_cast<register_type>(mask.to_ulong());
size_t v = r & msk;
for (; msk && (msk & 1) == 0; msk >>= 1) { v >>= 1; }
return v;
}
#elif defined(TINY_ARDUINO_DUE)
/** Reads the register bit.
*
* @param r Register address.
* @param pos Position of the bit where 0 is lsb.
* @return r & (1 << bit_pos)
*/
inline size_t bit(register_type r, register_type mask)
{
return r & mask;
}
/** Tests whether bit is set or clear.
*
* @param r Register address.
* @param pos Position of the bit where 0 is lsb.
* @return True if set, false if clear.
*/
template <typename T>
inline bool is_bit(T r, register_type mask)
{
return bit(r, mask) != 0;
}
/** Sets the register bit. */
inline void set_bit(register_type& r, register_type mask)
{
r |= mask;
}
#endif // TINY_ARDUINO_MEGA
} // namespace tiny
#endif // TINY_BASIC_HPP_
| 21.369318
| 74
| 0.670035
|
yell0w4x
|
90ab42f31a104a3e7ed5de92918fefab26330e23
| 214
|
cpp
|
C++
|
VertexBuffer.cpp
|
rabinadk1/learnopengl
|
66e5a26af5e63aebc7274efc051f05a99211f5a9
|
[
"MIT"
] | 5
|
2020-03-06T10:01:28.000Z
|
2020-05-06T07:57:20.000Z
|
VertexBuffer.cpp
|
rabinadk1/learnopengl
|
66e5a26af5e63aebc7274efc051f05a99211f5a9
|
[
"MIT"
] | 1
|
2020-03-06T02:51:50.000Z
|
2020-03-06T04:33:30.000Z
|
VertexBuffer.cpp
|
rabinadk1/learnopengl
|
66e5a26af5e63aebc7274efc051f05a99211f5a9
|
[
"MIT"
] | 29
|
2020-03-05T15:15:24.000Z
|
2021-07-21T07:05:00.000Z
|
#include "VertexBuffer.hpp"
VertexBuffer::VertexBuffer(const void *data, const unsigned int size)
{
glGenBuffers(1, &m_RendererID);
Bind();
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
}
| 23.777778
| 69
| 0.733645
|
rabinadk1
|
90ab57fa83b576215082827427467f947a158eb3
| 675
|
cc
|
C++
|
modules/ugdk-core/src/time/manager.cc
|
uspgamedev/ugdk
|
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
|
[
"Zlib"
] | 11
|
2015-03-06T13:14:32.000Z
|
2020-06-09T23:34:28.000Z
|
modules/ugdk-core/src/time/manager.cc
|
uspgamedev/ugdk
|
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
|
[
"Zlib"
] | 62
|
2015-01-04T05:47:40.000Z
|
2018-06-15T17:00:25.000Z
|
modules/ugdk-core/src/time/manager.cc
|
uspgamedev/ugdk
|
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
|
[
"Zlib"
] | 2
|
2017-04-05T20:35:49.000Z
|
2017-07-30T03:44:02.000Z
|
#include <ugdk/time/manager.h>
#include "SDL_timer.h"
namespace ugdk {
namespace time {
Manager::Manager() {
last_update_ = current_time_ = initial_time_ = SDL_GetTicks();
}
void Manager::Update() {
last_update_ = current_time_;
current_time_ = SDL_GetTicks();
}
uint32 Manager::TimeElapsed() const {
return current_time_ - initial_time_;
}
uint32 Manager::TimeElapsedInFrame() const{
return SDL_GetTicks() - current_time_;
}
uint32 Manager::TimeDifference() const {
return current_time_ - last_update_;
}
uint32 Manager::TimeSince(uint32 t0) const {
return current_time_ - t0 - initial_time_;
}
} // namespace time
} // namespace ugdk
| 19.285714
| 66
| 0.715556
|
uspgamedev
|
90aead07e280f730ea042b4a74cb137141dbcc46
| 5,421
|
hpp
|
C++
|
include/codegen/include/HMUI/ColorGradientSlider.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/HMUI/ColorGradientSlider.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/HMUI/ColorGradientSlider.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:21 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: HMUI.TextSlider
#include "HMUI/TextSlider.hpp"
// Including type: ColorChangeUIEventType
#include "GlobalNamespace/ColorChangeUIEventType.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: GradientImage
class GradientImage;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`3<T1, T2, T3>
template<typename T1, typename T2, typename T3>
class Action_3;
}
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: StringBuilder
class StringBuilder;
}
// Forward declaring namespace: UnityEngine::EventSystems
namespace UnityEngine::EventSystems {
// Forward declaring type: PointerEventData
class PointerEventData;
}
// Completed forward declares
// Type namespace: HMUI
namespace HMUI {
// Autogenerated type: HMUI.ColorGradientSlider
class ColorGradientSlider : public HMUI::TextSlider, public UnityEngine::EventSystems::IPointerUpHandler, public UnityEngine::EventSystems::IEventSystemHandler {
public:
// private System.String _textPrefix
// Offset: 0x138
::Il2CppString* textPrefix;
// private UnityEngine.Color _color0
// Offset: 0x140
UnityEngine::Color color0;
// private UnityEngine.Color _color1
// Offset: 0x150
UnityEngine::Color color1;
// private HMUI.GradientImage[] _gradientImages
// Offset: 0x160
::Array<HMUI::GradientImage*>* gradientImages;
// private UnityEngine.Color _darkColor
// Offset: 0x168
UnityEngine::Color darkColor;
// private UnityEngine.Color _lightColor
// Offset: 0x178
UnityEngine::Color lightColor;
// private System.Action`3<HMUI.ColorGradientSlider,UnityEngine.Color,ColorChangeUIEventType> colorDidChangeEvent
// Offset: 0x188
System::Action_3<HMUI::ColorGradientSlider*, UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* colorDidChangeEvent;
// private System.Text.StringBuilder _stringBuilder
// Offset: 0x190
System::Text::StringBuilder* stringBuilder;
// public System.Void add_colorDidChangeEvent(System.Action`3<HMUI.ColorGradientSlider,UnityEngine.Color,ColorChangeUIEventType> value)
// Offset: 0xEC1524
void add_colorDidChangeEvent(System::Action_3<HMUI::ColorGradientSlider*, UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* value);
// public System.Void remove_colorDidChangeEvent(System.Action`3<HMUI.ColorGradientSlider,UnityEngine.Color,ColorChangeUIEventType> value)
// Offset: 0xEC15CC
void remove_colorDidChangeEvent(System::Action_3<HMUI::ColorGradientSlider*, UnityEngine::Color, GlobalNamespace::ColorChangeUIEventType>* value);
// public System.Void SetColors(UnityEngine.Color color0, UnityEngine.Color color1)
// Offset: 0xEC179C
void SetColors(UnityEngine::Color color0, UnityEngine::Color color1);
// private System.Void HandleNormalizedValueDidChange(HMUI.TextSlider slider, System.Single normalizedValue)
// Offset: 0xEC1B18
void HandleNormalizedValueDidChange(HMUI::TextSlider* slider, float normalizedValue);
// protected override System.Void Awake()
// Offset: 0xEC1674
// Implemented from: UnityEngine.UI.Selectable
// Base method: System.Void Selectable::Awake()
void Awake();
// protected override System.Void OnDestroy()
// Offset: 0xEC1710
// Implemented from: UnityEngine.EventSystems.UIBehaviour
// Base method: System.Void UIBehaviour::OnDestroy()
void OnDestroy();
// protected override System.Void UpdateVisuals()
// Offset: 0xEC17CC
// Implemented from: HMUI.TextSlider
// Base method: System.Void TextSlider::UpdateVisuals()
void UpdateVisuals();
// protected override System.String TextForNormalizedValue(System.Single normalizedValue)
// Offset: 0xEC1A48
// Implemented from: HMUI.TextSlider
// Base method: System.String TextSlider::TextForNormalizedValue(System.Single normalizedValue)
::Il2CppString* TextForNormalizedValue(float normalizedValue);
// public override System.Void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData)
// Offset: 0xEC1BCC
// Implemented from: UnityEngine.UI.Selectable
// Base method: System.Void Selectable::OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData)
void OnPointerUp(UnityEngine::EventSystems::PointerEventData* eventData);
// public System.Void .ctor()
// Offset: 0xEC1CEC
// Implemented from: HMUI.TextSlider
// Base method: System.Void TextSlider::.ctor()
// Base method: System.Void Selectable::.ctor()
// Base method: System.Void UIBehaviour::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static ColorGradientSlider* New_ctor();
}; // HMUI.ColorGradientSlider
}
DEFINE_IL2CPP_ARG_TYPE(HMUI::ColorGradientSlider*, "HMUI", "ColorGradientSlider");
#pragma pack(pop)
| 45.554622
| 163
| 0.740638
|
Futuremappermydud
|
90b0960d974ad6a84c89a3d7ea0498d656a6482c
| 566
|
cpp
|
C++
|
lowercase.cpp
|
AyushVerma-code/databinarytextfiles
|
f404bfb07d1854e9e4f8f6edbb32268d39aed908
|
[
"MIT"
] | 1
|
2021-02-12T08:24:17.000Z
|
2021-02-12T08:24:17.000Z
|
lowercase.cpp
|
AyushVerma-code/databinarytextfiles
|
f404bfb07d1854e9e4f8f6edbb32268d39aed908
|
[
"MIT"
] | null | null | null |
lowercase.cpp
|
AyushVerma-code/databinarytextfiles
|
f404bfb07d1854e9e4f8f6edbb32268d39aed908
|
[
"MIT"
] | null | null | null |
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<ctype.h>
void alphacount()
{
fstream f;
f.open("notes3.txt",ios::in|ios::out);
char ch;
int count=0;
char ans='y';
while(ans=='y')
{
cout<<"\nEnter a character ";
cin>>ch;
f<<ch;
cout<<"\nDo you want to continue ";
cin>>ans;
}
f.seekg(0);
while(!f.eof())
{
f.get(ch);
if(islower(ch))
{
count++;
}
}
cout<<"\nLowercase alphabets are "<<count;
f.close();
}
void main()
{
clrscr();
alphacount();
getch();
}
| 11.32
| 47
| 0.526502
|
AyushVerma-code
|
90b32d3646f414cd94bd41b90a51ca6072a5bc3a
| 3,594
|
cpp
|
C++
|
src/BoundaryConditions/FixedCellBoundaryCondition.cpp
|
clairemiller/2018_MaintainingStemCellNiche
|
2999a37169ac0db78ebf9ac57b36153a0a149eb3
|
[
"BSD-4-Clause-UC"
] | null | null | null |
src/BoundaryConditions/FixedCellBoundaryCondition.cpp
|
clairemiller/2018_MaintainingStemCellNiche
|
2999a37169ac0db78ebf9ac57b36153a0a149eb3
|
[
"BSD-4-Clause-UC"
] | null | null | null |
src/BoundaryConditions/FixedCellBoundaryCondition.cpp
|
clairemiller/2018_MaintainingStemCellNiche
|
2999a37169ac0db78ebf9ac57b36153a0a149eb3
|
[
"BSD-4-Clause-UC"
] | null | null | null |
/*
Copyright (c) 2005-2016, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "FixedCellBoundaryCondition.hpp"
#include "Debug.hpp"
template<unsigned DIM>
FixedCellBoundaryCondition<DIM>::FixedCellBoundaryCondition(AbstractCellPopulation<DIM>* pCellPopulation)
: AbstractCellPopulationBoundaryCondition<DIM>(pCellPopulation)
{
}
template<unsigned DIM>
void FixedCellBoundaryCondition<DIM>::ImposeBoundaryCondition(const std::map<Node<DIM>*, c_vector<double, DIM> >& rOldLocations)
{
// Iterate over all nodes associated with real cells to update their positions
for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->mpCellPopulation->Begin();
cell_iter != this->mpCellPopulation->End();
++cell_iter)
{
if ( (*cell_iter)->GetCellProliferativeType()->template IsType<StemCellProliferativeType>() )
{
// Get the node
unsigned node_index = this->mpCellPopulation->GetLocationIndexUsingCell(*cell_iter);
Node<DIM>* p_node = this->mpCellPopulation->GetNode(node_index);
// Get old node location
c_vector<double, DIM> old_node_location = rOldLocations.find(p_node)->second;
// Return node to old location
p_node->rGetModifiableLocation() = old_node_location;
}
}
}
template<unsigned DIM>
void FixedCellBoundaryCondition<DIM>::OutputCellPopulationBoundaryConditionParameters(out_stream& rParamsFile)
{
// Call method on direct parent class
AbstractCellPopulationBoundaryCondition<DIM>::OutputCellPopulationBoundaryConditionParameters(rParamsFile);
}
// Explicit instantiation
template class FixedCellBoundaryCondition<1>;
template class FixedCellBoundaryCondition<2>;
template class FixedCellBoundaryCondition<3>;
// Serialization for Boost >= 1.36
#include "SerializationExportWrapperForCpp.hpp"
EXPORT_TEMPLATE_CLASS_SAME_DIMS(FixedCellBoundaryCondition)
| 43.829268
| 128
| 0.772955
|
clairemiller
|
ff9b1c0934cc08187bc8bd8b0e814679b27b59bc
| 4,247
|
cpp
|
C++
|
kernel/src/sound/sound-blaster16/sb16.cpp
|
pradosh-arduino/pradoshOS
|
b7c2a8b238261fc61460e609fd8352aa62b5f32e
|
[
"MIT"
] | 9
|
2021-11-17T10:27:18.000Z
|
2022-03-16T09:43:24.000Z
|
kernel/src/sound/sound-blaster16/sb16.cpp
|
pradosh-arduino/pradoshOS
|
b7c2a8b238261fc61460e609fd8352aa62b5f32e
|
[
"MIT"
] | 1
|
2022-03-17T08:31:05.000Z
|
2022-03-28T02:50:59.000Z
|
kernel/src/sound/sound-blaster16/sb16.cpp
|
pradosh-arduino/pradoshOS
|
b7c2a8b238261fc61460e609fd8352aa62b5f32e
|
[
"MIT"
] | 1
|
2021-12-21T09:49:02.000Z
|
2021-12-21T09:49:02.000Z
|
#include "sb16.h"
const uint32_t PCI_Enable_Bit = 0x80000000;
const uint32_t PCI_Config_Address = 0xCF8;
const uint32_t PCI_Config_Data = 0xCFC;
unsigned char pci_bus_sb16 = 0;
unsigned char pci_device_sb16 = 0;
unsigned char pci_device_fn_sb16 = 0;
SoundBlaster16* SB16;
uint32_t sb16_ioaddr;
DSP* dspPort;
DSP_Write* dspPortw;
MixerPort* Mixer;
SoundBlaster16::SoundBlaster16(DSP* dspPort, DSP_Write* dspPortw){
ResetDSP(dspPort);
TurnSpeakerOn(dspPortw);
DMAChannel1();
Program(dspPort);
SetIRQ(dspPort);
GlobalRenderer->Print("Sound Blaster 16 - sound card Initialized!");
GlobalRenderer->Next();
}
SoundBlaster16::~SoundBlaster16(){
GlobalRenderer->Print("Sound Blaster 16 - Exited");
}
uint16_t getDeviceAddr;
void SoundBlaster16::PCI(){
for (uint8_t bus = 0; bus != 0xff; bus++) {
// per bus there can be at most 32 devices
for (int device = 0; device < 32; device++) {
// every device can be multi function device of up to 8 functions
for (int func = 0; func < 8; func++) {
// read the first dword (index 0) from the PCI configuration space
// dword 0 contains the vendor and device values from the PCI configuration space
int data = r_pci_32(pci_bus_sb16, pci_bus_sb16, func, 0);
if (data != 0xffffffff) {
// parse the values
uint16_t device_value = (data >> 16);
uint16_t vendor = data & 0xFFFF;
pci_bus_sb16 = bus;
pci_device_sb16 = device;
pci_device_fn_sb16 = func;
}
}
}
}
for(getDeviceAddr = getDeviceAddr; getDeviceAddr < 0xFFFF; getDeviceAddr++){
sb16_ioaddr = r_pci_32(pci_bus_sb16, getDeviceAddr, pci_device_fn_sb16, 4);
GlobalRenderer->Print(" Device ID 0x");
GlobalRenderer->Print(to_hstring((uint16_t)getDeviceAddr));
GlobalRenderer->Next();
exit();
//if(r_pci_32(pci_bus_sb16, pci_device_sb16, pci_device_fn_sb16, 4) <= 0){
//
//}else{
// //GlobalRenderer->Print("Found SB16! BUS: 0x");
// //GlobalRenderer->Print(to_hstring((uint16_t)pci_bus_sb16));
// //GlobalRenderer->Print(" Device: 0x");
// //GlobalRenderer->Print(to_hstring((uint16_t)pci_device_sb16));
// ////GlobalRenderer->Print(" Function: 0x");
// ////GlobalRenderer->Print(to_hstring((uint16_t)func));
// //GlobalRenderer->Print(" Device ID 0x");
// //GlobalRenderer->Print(to_hstring((uint16_t)getDeviceAddr));
// //GlobalRenderer->Next();
// exit();
//}
}
}
void exit(){
for(int i=0;i<100;i++){
}
GlobalRenderer->Clear();
GlobalRenderer->CursorPosition = {0, 0};
}
void SoundBlaster16::ResetDSP(DSP* dspPort){
outb(dspPort->DSPReset, 0x01);
outb(dspPort->DSPReset, 0x00);
dspPort->DSPReadPort = 0xAA;
}
void SoundBlaster16::SetIRQ(DSP* dspPort){
outb(dspPort->DSPMixerPort, 0x80);
uint16_t GetIRQ = inb(dspPort->DSPMixerPort);
outb(dspPort->DSPMixerDataPort, GetIRQ);
}
void SoundBlaster16::TurnSpeakerOn(DSP_Write* dspPortw){
outb(dspPortw->SpeakerAddr, dspPortw->SpeakerOn);
}
void SoundBlaster16::TurnSpeakerOff(DSP_Write* dspPortw){
outb(dspPortw->SpeakerAddr, dspPortw->SpeakerOff);
}
void SoundBlaster16::DMAChannel1(){
outb(0x0A, 5); // disable channel 1
outb(0x0C, 1); // filp flop
outb(0x0B, 0x49); // transfer mode
outb(0x83, 0x01); // Page Transfer
outb(0x02, 0x04); // Position Low Bit
outb(0x02, 0x0F); // Position High Bit
outb(0x03, 0xFF); // Count Low Bit
outb(0x03, 0x0F); // Count High Bit
outb(0x0A, 1); // enable channel 1
}
void SoundBlaster16::Program(DSP* dspPort){
outb(dspPort->DSPWrite, 0x40);
outb(dspPort->DSPWrite, 165);
outb(dspPort->DSPWrite, 0xC0);
outb(dspPort->DSPWrite, 0x00);
outb(dspPort->DSPWrite, 0xFE);
outb(dspPort->DSPWrite, 0x0F);
}
void SoundBlaster16::SetVolume(MixerPort* mixer, uint8_t volume){
outb(mixer->MasterVolume, volume);
}
uint32_t SoundBlaster16::r_pci_32(uint8_t bus, uint8_t device, uint8_t func, uint8_t pcireg) {
uint32_t index = PCI_Enable_Bit | (bus << 16) | (device << 11) | (func << 8) | (pcireg << 2);
outl(index, PCI_Config_Address);
return inl(PCI_Config_Data);
}
| 30.120567
| 95
| 0.662821
|
pradosh-arduino
|
ff9c16a85d3df00ea4a530f703ce464ba1714c7c
| 1,854
|
cpp
|
C++
|
Iron/strategy/locutus.cpp
|
biug/titan
|
aacb4e2dc4d55601abd45cb8321d8e5160851eec
|
[
"MIT"
] | null | null | null |
Iron/strategy/locutus.cpp
|
biug/titan
|
aacb4e2dc4d55601abd45cb8321d8e5160851eec
|
[
"MIT"
] | null | null | null |
Iron/strategy/locutus.cpp
|
biug/titan
|
aacb4e2dc4d55601abd45cb8321d8e5160851eec
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////
//
// This file is part of Iron's source files.
// Iron is free software, licensed under the MIT/X11 License.
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2016, 2017, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////
#include "locutus.h"
#include "strategy.h"
#include "zerglingRush.h"
#include "expand.h"
#include "../units/army.h"
#include "../units/his.h"
#include "../Iron.h"
namespace { auto & bw = Broodwar; }
namespace iron
{
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// class Locutus
// //
//////////////////////////////////////////////////////////////////////////////////////////////
Locutus::Locutus()
{
std::string enemyName = him().Player()->getName();
if (enemyName == "Locutus" || enemyName == "locutus")
{
me().SetOpening("SKT");
m_detected = true;
}
}
Locutus::~Locutus()
{
ai()->GetStrategy()->SetMinScoutingSCVs(1);
}
string Locutus::StateDescription() const
{
if (!m_detected) return "-";
if (m_detected) return "detected";
return "-";
}
void Locutus::OnFrame_v()
{
if (him().LostUnits(Protoss_Shuttle) == 1 && him().Units(Protoss_Dark_Templar).size() == 0)
{
m_detected = false;
Discard();
return;
}
if (him().LostUnits(Protoss_Dark_Templar) >= 4)
{
m_detected = false;
Discard();
return;
}
if (bw->getFrameCount() > 13000)
{
m_detected = false;
Discard();
return;
}
}
} // namespace iron
| 21.310345
| 95
| 0.434736
|
biug
|
ff9c196469416f6b335467100b9fa172436555b0
| 868
|
cpp
|
C++
|
CO1028/LAB2/Ex4/main.cpp
|
Smithienious/hcmut-192
|
4f1dfa322321fc18d151835213a5b544c9d764f2
|
[
"MIT"
] | null | null | null |
CO1028/LAB2/Ex4/main.cpp
|
Smithienious/hcmut-192
|
4f1dfa322321fc18d151835213a5b544c9d764f2
|
[
"MIT"
] | null | null | null |
CO1028/LAB2/Ex4/main.cpp
|
Smithienious/hcmut-192
|
4f1dfa322321fc18d151835213a5b544c9d764f2
|
[
"MIT"
] | 1
|
2020-04-26T10:28:41.000Z
|
2020-04-26T10:28:41.000Z
|
#include <iostream>
#include <fstream>
using namespace std;
// matrix is two dimensional array. You should transposition matrix
void transposition(int rows, int cols, int **matrix) {
for (int i = 0; i < cols; i++) {
cout << matrix[0][i];
for (int j = 1; j < rows; j++) {
cout << " " << matrix[j][i];
}
cout << endl;
}
}
int main(int argc, char** argv)
{
ifstream ifs;
ifs.open("test02.txt");
int rows;
int cols;
ifs >> rows;
ifs >> cols;
int** matrix = new int*[rows];
try
{
int i = 0;
int j = 0;
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
for (int j = 0; j < cols; j++) {
ifs >> matrix[i][j];
}
}
transposition(rows, cols, matrix);
}
catch (char const* s)
{
printf("An exception occurred. Exception type: %s\n", s);
}
ifs.close();
return 0;
}
| 18.083333
| 68
| 0.534562
|
Smithienious
|
ff9ee956272ccb07a5a4f771657487b2715743cb
| 5,718
|
cc
|
C++
|
source/extensions/filters/http/gfunction/gfunction_filter.cc
|
adesaegher/envoy-gloo
|
92d59246ff30199523603d18a969ac9ae5d6e4d3
|
[
"Apache-2.0"
] | null | null | null |
source/extensions/filters/http/gfunction/gfunction_filter.cc
|
adesaegher/envoy-gloo
|
92d59246ff30199523603d18a969ac9ae5d6e4d3
|
[
"Apache-2.0"
] | null | null | null |
source/extensions/filters/http/gfunction/gfunction_filter.cc
|
adesaegher/envoy-gloo
|
92d59246ff30199523603d18a969ac9ae5d6e4d3
|
[
"Apache-2.0"
] | null | null | null |
#include "extensions/filters/http/gfunction/gfunction_filter.h"
#include <algorithm>
#include <list>
#include <string>
#include <vector>
#include "envoy/http/header_map.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/empty_string.h"
#include "common/common/hex.h"
#include "common/common/utility.h"
#include "common/http/headers.h"
#include "common/http/solo_filter_utility.h"
#include "common/http/utility.h"
#include "common/singleton/const_singleton.h"
#include "extensions/filters/http/solo_well_known_names.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace GcloudGfunc {
struct RcDetailsValues {
// The jwt_authn filter rejected the request
const std::string FunctionNotFound = "gfunction_function_not_found";
};
typedef ConstSingleton<RcDetailsValues> RcDetails;
class GcloudGfuncHeaderValues {
public:
const Http::LowerCaseString InvocationType{"x-amz-invocation-type"};
const std::string InvocationTypeEvent{"Event"};
const std::string InvocationTypeRequestResponse{"RequestResponse"};
const Http::LowerCaseString LogType{"x-amz-log-type"};
const std::string LogNone{"None"};
const Http::LowerCaseString HostHead{"x-amz-log-type"};
};
typedef ConstSingleton<GcloudGfuncHeaderValues> GcloudGfuncHeaderNames;
//const HeaderList GcloudGfuncFilter::HeadersToSign =
// GcloudAuthenticator::createHeaderToSign(
// {GcloudGfuncHeaderNames::get().InvocationType,
// GcloudGfuncHeaderNames::get().LogType, Http::Headers::get().HostLegacy,
// Http::Headers::get().ContentType});
GcloudGfuncFilter::GcloudGfuncFilter(Upstream::ClusterManager &cluster_manager
)
// TimeSource &time_source)
// : gcloud_authenticator_(time_source), cluster_manager_(cluster_manager) {}
: cluster_manager_(cluster_manager) {}
GcloudGfuncFilter::~GcloudGfuncFilter() {}
std::string GcloudGfuncFilter::functionUrlPath(const std::string &url) {
std::stringstream val;
absl::string_view host;
absl::string_view path;
Http::Utility::extractHostPathFromUri(url, host, path);
val << path;
return val.str();
}
std::string GcloudGfuncFilter::functionUrlHost(const std::string &url) {
std::stringstream val;
absl::string_view host;
absl::string_view path;
Http::Utility::extractHostPathFromUri(url, host, path);
val << host;
return val.str();
}
Http::FilterHeadersStatus
GcloudGfuncFilter::decodeHeaders(Http::HeaderMap &headers, bool end_stream) {
protocol_options_ = Http::SoloFilterUtility::resolveProtocolOptions<
const GcloudGfuncProtocolExtensionConfig>(
SoloHttpFilterNames::get().GcloudGfunc, decoder_callbacks_,
cluster_manager_);
if (!protocol_options_) {
return Http::FilterHeadersStatus::Continue;
}
route_ = decoder_callbacks_->route();
// great! this is an gcloud cluster. get the function information:
function_on_route_ =
Http::SoloFilterUtility::resolvePerFilterConfig<GcloudGfuncRouteConfig>(
SoloHttpFilterNames::get().GcloudGfunc, route_);
if (!function_on_route_) {
decoder_callbacks_->sendLocalReply(Http::Code::NotFound,
"no function present for Gcloud upstream",
nullptr, absl::nullopt, RcDetails::get().FunctionNotFound);
return Http::FilterHeadersStatus::StopIteration;
}
// gcloud_authenticator_.init(&protocol_options_->accessKey(),
// &protocol_options_->secretKey());
request_headers_ = &headers;
request_headers_->insertMethod().value().setReference(
Http::Headers::get().MethodValues.Post);
request_headers_->insertPath().value(functionUrlPath(
function_on_route_->url()));
if (end_stream) {
gfuncfy();
return Http::FilterHeadersStatus::Continue;
}
return Http::FilterHeadersStatus::StopIteration;
}
Http::FilterDataStatus GcloudGfuncFilter::decodeData(Buffer::Instance &data,
bool end_stream) {
if (!function_on_route_) {
return Http::FilterDataStatus::Continue;
}
if (data.length() != 0) {
has_body_ = true;
}
// gcloud_authenticator_.updatePayloadHash(data);
if (end_stream) {
gfuncfy();
return Http::FilterDataStatus::Continue;
}
return Http::FilterDataStatus::StopIterationAndBuffer;
}
Http::FilterTrailersStatus GcloudGfuncFilter::decodeTrailers(Http::HeaderMap &) {
if (function_on_route_ != nullptr) {
gfuncfy();
}
return Http::FilterTrailersStatus::Continue;
}
void GcloudGfuncFilter::gfuncfy() {
handleDefaultBody();
request_headers_->addReference(GcloudGfuncHeaderNames::get().LogType,
GcloudGfuncHeaderNames::get().LogNone);
request_headers_->insertHost().value(functionUrlHost(
function_on_route_->url()));
// gcloud_authenticator_.sign(request_headers_, HeadersToSign,
// protocol_options_->region());
cleanup();
}
void GcloudGfuncFilter::handleDefaultBody() {
if ((!has_body_) && function_on_route_->defaultBody()) {
Buffer::OwnedImpl data(function_on_route_->defaultBody().value());
request_headers_->insertContentType().value().setReference(
Http::Headers::get().ContentTypeValues.Json);
request_headers_->insertContentLength().value(data.length());
// gcloud_authenticator_.updatePayloadHash(data);
decoder_callbacks_->addDecodedData(data, false);
}
}
void GcloudGfuncFilter::cleanup() {
request_headers_ = nullptr;
function_on_route_ = nullptr;
protocol_options_.reset();
}
} // namespace GcloudGfunc
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
| 30.741935
| 98
| 0.714236
|
adesaegher
|
ffa582936f230158ae857b11dd54dac8f154b20c
| 547
|
cpp
|
C++
|
src/wavetable.cpp
|
stephanepericat/sb-StochKit
|
767383b9eda7b61ea5c8187296c676dd4fcf94fa
|
[
"CC0-1.0"
] | 16
|
2019-05-02T09:42:38.000Z
|
2022-01-28T02:08:44.000Z
|
src/wavetable.cpp
|
stephanepericat/sb-StochKit
|
767383b9eda7b61ea5c8187296c676dd4fcf94fa
|
[
"CC0-1.0"
] | 4
|
2019-07-06T13:27:24.000Z
|
2022-01-27T19:11:10.000Z
|
src/wavetable.cpp
|
stephanepericat/sb-StochKit
|
767383b9eda7b61ea5c8187296c676dd4fcf94fa
|
[
"CC0-1.0"
] | 2
|
2019-05-23T08:33:52.000Z
|
2019-07-07T16:56:02.000Z
|
/*
* wavetable.cpp
* Samuel Laing - 2019
*
* just a few utility functions to be used by the GendyOscillator
*/
#include "wavetable.hpp"
namespace rack {
float wrap(float in, float lb, float ub) {
float out = in;
if (in > ub) out = lb;
else if (in < lb) out = ub;
return out;
}
float mirror(float in, float lb, float ub) {
float out = in;
if (in > ub) {
out = out - (in - ub);
}
else if (in < lb) {
out = out - (in - lb);
}
return out;
}
}
| 17.645161
| 65
| 0.499086
|
stephanepericat
|
ffa5f26ab8bc81d742f1f150d8e1b06714137991
| 3,019
|
cpp
|
C++
|
Codeforces/CF - 716E - Centeroid Decomposition.cpp
|
bishoy-magdy/Competitive-Programming
|
689daac9aeb475da3c28aba4a69df394c68a9a34
|
[
"MIT"
] | null | null | null |
Codeforces/CF - 716E - Centeroid Decomposition.cpp
|
bishoy-magdy/Competitive-Programming
|
689daac9aeb475da3c28aba4a69df394c68a9a34
|
[
"MIT"
] | null | null | null |
Codeforces/CF - 716E - Centeroid Decomposition.cpp
|
bishoy-magdy/Competitive-Programming
|
689daac9aeb475da3c28aba4a69df394c68a9a34
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#include "ext/numeric"
using namespace __gnu_cxx;
using namespace std;
typedef long long ll;
const int N = 1e5 + 10, M = 2 * N;
int tenInvPW[N];
int n,m;
int phi(int x){//complexity sqrt(x)
int res=x;
for(int i=2;i<=x/i;i++) {
if (x % i) continue;
res -= res / i;
while (!(x % i)) {
x /= i;
}
}
if(x>1) res-=res/x;
return res;
}
struct Mul{
int m;
Mul(int m):m(m){}
int operator()(int a,int b){
return (a*1ll*b)%m;
}
};
int identity_element(const Mul&){
return 1;
}
int mod_inverse(int x,int m){//x base , m power
return power(x,phi(m)-1,Mul(m));
}
Mul mul(0);
struct ADJ {
int head[N], nxt[M],cost[M], to[M], ne, n;
void addEdge(int u, int v,int c) {
nxt[ne] = head[u];
to[ne] = v;
cost[ne]=c;
head[u] = ne++;
}
void addBiEdge(int u, int v,int c) {
addEdge(u, v,c);
addEdge(v, u,c);
}
void init(int n) {
this->n = n;
ne = 0;
memset(head, -1, n * sizeof head[0]);
}
} adj;
#define neig(u, v, e, a) for(int e=a.head[u],v;~e and (v=a.to[e],1);e=a.nxt[e])
int treeCentroid,sz[N],treeSz,minChild,deleted[N],delId;
void calc_SZ(int u,int p){
sz[u]=1;
int mx=0;
neig(u,v,e,adj){
if(v==p or deleted[v]==delId) continue;
calc_SZ(v,u);
sz[u]+=sz[v];
mx=max(mx,sz[v]);
}
mx=max(mx,treeSz-sz[u]);
if(mx<minChild) {
minChild=mx;
treeCentroid=u;
}
}
int pre[N],Sz,suf[N],len[N];
void calc_paths(int u,int p,int prefix,int suffix,int len,int pw){
pre[Sz]=prefix,suf[Sz]=suffix;
::len[Sz++]=len;
neig(u,v,e,adj){
if(v==p or deleted[v]==delId) continue;
calc_paths(v,u,(prefix+mul(adj.cost[e],pw))%m,(mul(suffix,10)+adj.cost[e])%m,len+1,mul(pw,10));
}
}
ll solve(int u,int digit){
Sz=0;
calc_paths(u,-1,digit%m,digit%m,digit!=0,(digit!=0)?10:1);
unordered_map<int,int > mp;
for (int i = 0; i < Sz; ++i) {
mp[pre[i]]++;
}
ll ret=0;
for (int i = 0; i < Sz; ++i) {
ret+= mp[ mul(m-suf[i],tenInvPW[len[i]]) ];
}
return ret;
}
ll decompose(int u){
ll ret=solve(u,0)-1;
deleted[u]=delId;
neig(u,v,e,adj) {
if (deleted[v] == delId) continue;
ret -= solve(v, adj.cost[e]);
treeSz = minChild = sz[v];
calc_SZ(v,-1);
calc_SZ(treeCentroid,-1);
ret+=decompose(treeCentroid);
}
return ret;
}
ll centroid(){
treeSz=minChild=adj.n;
delId++;
calc_SZ(0,-1);
calc_SZ(treeCentroid,-1);
return decompose(treeCentroid);
}
int main(){
// freopen("in.txt","r",stdin);
scanf("%d%d",&n,&m);
int u,v,c;
int tenInverse=mod_inverse(10,m);
mul=Mul(m);
adj.init(n);
tenInvPW[0]=1;
for (int i = 1; i < n; ++i) {
tenInvPW[i]=mul(tenInvPW[i-1],tenInverse);
scanf("%d%d%d",&u,&v,&c);
adj.addBiEdge(u,v,c);
}
printf("%lld\n",centroid());
}
| 22.871212
| 103
| 0.516396
|
bishoy-magdy
|
ffac724073668a2c90de89fb7ec654900e698e06
| 147,237
|
cpp
|
C++
|
src/runtime/objmodel.cpp
|
amyvmiwei/pyston
|
f074ed04f8f680316971513f5c42e9cf7d992e06
|
[
"Apache-2.0"
] | 1
|
2015-11-06T03:39:51.000Z
|
2015-11-06T03:39:51.000Z
|
src/runtime/objmodel.cpp
|
amyvmiwei/pyston
|
f074ed04f8f680316971513f5c42e9cf7d992e06
|
[
"Apache-2.0"
] | null | null | null |
src/runtime/objmodel.cpp
|
amyvmiwei/pyston
|
f074ed04f8f680316971513f5c42e9cf7d992e06
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2014 Dropbox, 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 "runtime/objmodel.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <stdint.h>
#include "asm_writing/icinfo.h"
#include "asm_writing/rewriter.h"
#include "codegen/codegen.h"
#include "codegen/compvars.h"
#include "codegen/irgen/hooks.h"
#include "codegen/llvm_interpreter.h"
#include "codegen/parser.h"
#include "codegen/type_recording.h"
#include "core/ast.h"
#include "core/options.h"
#include "core/stats.h"
#include "core/types.h"
#include "gc/collector.h"
#include "gc/heap.h"
#include "runtime/capi.h"
#include "runtime/classobj.h"
#include "runtime/float.h"
#include "runtime/generator.h"
#include "runtime/iterobject.h"
#include "runtime/types.h"
#include "runtime/util.h"
#define BOX_CLS_OFFSET ((char*)&(((Box*)0x01)->cls) - (char*)0x1)
#define HCATTRS_HCLS_OFFSET ((char*)&(((HCAttrs*)0x01)->hcls) - (char*)0x1)
#define HCATTRS_ATTRS_OFFSET ((char*)&(((HCAttrs*)0x01)->attr_list) - (char*)0x1)
#define ATTRLIST_ATTRS_OFFSET ((char*)&(((HCAttrs::AttrList*)0x01)->attrs) - (char*)0x1)
#define ATTRLIST_KIND_OFFSET ((char*)&(((HCAttrs::AttrList*)0x01)->gc_header.kind_id) - (char*)0x1)
#define INSTANCEMETHOD_FUNC_OFFSET ((char*)&(((BoxedInstanceMethod*)0x01)->func) - (char*)0x1)
#define INSTANCEMETHOD_OBJ_OFFSET ((char*)&(((BoxedInstanceMethod*)0x01)->obj) - (char*)0x1)
#define BOOL_B_OFFSET ((char*)&(((BoxedBool*)0x01)->b) - (char*)0x1)
#define INT_N_OFFSET ((char*)&(((BoxedInt*)0x01)->n) - (char*)0x1)
namespace pyston {
// TODO should centralize all of these:
static const std::string _call_str("__call__"), _new_str("__new__"), _init_str("__init__"), _get_str("__get__");
static const std::string _getattr_str("__getattr__");
static const std::string _getattribute_str("__getattribute__");
struct GetattrRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage obj;
Location destination;
bool call_done_guarding;
bool out_success;
RewriterVarUsage out_rtn;
bool obj_hcls_guarded;
GetattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding)
: rewriter(rewriter), obj(std::move(obj)), destination(destination), call_done_guarding(call_done_guarding),
out_success(false), out_rtn(RewriterVarUsage::empty()), obj_hcls_guarded(false) {}
~GetattrRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() { obj.ensureDoneUsing(); }
};
struct SetattrRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage obj, attrval;
bool call_done_guarding;
bool out_success;
SetattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, RewriterVarUsage&& attrval, bool call_done_guarding)
: rewriter(rewriter), obj(std::move(obj)), attrval(std::move(attrval)), call_done_guarding(call_done_guarding),
out_success(false) {}
~SetattrRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() { obj.ensureDoneUsing(); }
};
struct DelattrRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage obj;
bool call_done_guarding;
bool out_success;
DelattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, bool call_done_guarding)
: rewriter(rewriter), obj(std::move(obj)), call_done_guarding(call_done_guarding), out_success(false) {}
~DelattrRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() { obj.ensureDoneUsing(); }
};
struct LenRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage obj;
Location destination;
bool call_done_guarding;
bool out_success;
RewriterVarUsage out_rtn;
LenRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding)
: rewriter(rewriter), obj(std::move(obj)), destination(destination), call_done_guarding(call_done_guarding),
out_success(false), out_rtn(RewriterVarUsage::empty()) {}
~LenRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() { obj.ensureDoneUsing(); }
};
struct CallRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage obj;
RewriterVarUsage arg1, arg2, arg3, args;
bool func_guarded;
bool args_guarded;
Location destination;
bool call_done_guarding;
bool out_success;
RewriterVarUsage out_rtn;
CallRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding)
: rewriter(rewriter), obj(std::move(obj)), arg1(RewriterVarUsage::empty()), arg2(RewriterVarUsage::empty()),
arg3(RewriterVarUsage::empty()), args(RewriterVarUsage::empty()), func_guarded(false), args_guarded(false),
destination(destination), call_done_guarding(call_done_guarding), out_success(false),
out_rtn(RewriterVarUsage::empty()) {}
~CallRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() {
obj.ensureDoneUsing();
arg1.ensureDoneUsing();
arg2.ensureDoneUsing();
arg3.ensureDoneUsing();
args.ensureDoneUsing();
}
};
struct BinopRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage lhs, rhs;
Location destination;
bool call_done_guarding;
bool out_success;
RewriterVarUsage out_rtn;
BinopRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& lhs, RewriterVarUsage&& rhs, Location destination,
bool call_done_guarding)
: rewriter(rewriter), lhs(std::move(lhs)), rhs(std::move(rhs)), destination(destination),
call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {}
~BinopRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() {
lhs.ensureDoneUsing();
rhs.ensureDoneUsing();
}
};
struct CompareRewriteArgs {
Rewriter* rewriter;
RewriterVarUsage lhs, rhs;
Location destination;
bool call_done_guarding;
bool out_success;
RewriterVarUsage out_rtn;
CompareRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& lhs, RewriterVarUsage&& rhs, Location destination,
bool call_done_guarding)
: rewriter(rewriter), lhs(std::move(lhs)), rhs(std::move(rhs)), destination(destination),
call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {}
~CompareRewriteArgs() {
if (!out_success) {
ensureAllDone();
}
}
void ensureAllDone() {
lhs.ensureDoneUsing();
rhs.ensureDoneUsing();
}
};
Box* runtimeCallInternal(Box* obj, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3,
Box** args, const std::vector<const std::string*>* keyword_names);
static Box* (*runtimeCallInternal0)(Box*, CallRewriteArgs*, ArgPassSpec)
= (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec))runtimeCallInternal;
static Box* (*runtimeCallInternal1)(Box*, CallRewriteArgs*, ArgPassSpec, Box*)
= (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*))runtimeCallInternal;
static Box* (*runtimeCallInternal2)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*)
= (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*))runtimeCallInternal;
static Box* (*runtimeCallInternal3)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*)
= (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))runtimeCallInternal;
static Box* (*typeCallInternal1)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*)
= (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*))typeCallInternal;
static Box* (*typeCallInternal2)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*, Box*)
= (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*, Box*))typeCallInternal;
static Box* (*typeCallInternal3)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*, Box*, Box*)
= (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))typeCallInternal;
bool checkClass(LookupScope scope) {
return (scope & CLASS_ONLY) != 0;
}
bool checkInst(LookupScope scope) {
return (scope & INST_ONLY) != 0;
}
static Box* (*callattrInternal0)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec)
= (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec))callattrInternal;
static Box* (*callattrInternal1)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*)
= (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*))callattrInternal;
static Box* (*callattrInternal2)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*)
= (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*))callattrInternal;
static Box* (*callattrInternal3)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*)
= (Box
* (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))callattrInternal;
size_t PyHasher::operator()(Box* b) const {
if (b->cls == str_cls) {
std::hash<std::string> H;
return H(static_cast<BoxedString*>(b)->s);
}
BoxedInt* i = hash(b);
assert(sizeof(size_t) == sizeof(i->n));
size_t rtn = i->n;
return rtn;
}
bool PyEq::operator()(Box* lhs, Box* rhs) const {
if (lhs->cls == rhs->cls) {
if (lhs->cls == str_cls) {
return static_cast<BoxedString*>(lhs)->s == static_cast<BoxedString*>(rhs)->s;
}
}
// TODO fix this
Box* cmp = compareInternal(lhs, rhs, AST_TYPE::Eq, NULL);
assert(cmp->cls == bool_cls);
BoxedBool* b = static_cast<BoxedBool*>(cmp);
bool rtn = b->b;
return rtn;
}
bool PyLt::operator()(Box* lhs, Box* rhs) const {
// TODO fix this
Box* cmp = compareInternal(lhs, rhs, AST_TYPE::Lt, NULL);
assert(cmp->cls == bool_cls);
BoxedBool* b = static_cast<BoxedBool*>(cmp);
bool rtn = b->b;
return rtn;
}
extern "C" bool softspace(Box* b, bool newval) {
assert(b);
if (isSubclass(b->cls, file_cls)) {
bool& ss = static_cast<BoxedFile*>(b)->softspace;
bool r = ss;
ss = newval;
return r;
}
bool r;
Box* gotten = b->getattr("softspace");
if (!gotten) {
r = 0;
} else {
r = nonzero(gotten);
}
b->setattr("softspace", boxInt(newval), NULL);
return r;
}
extern "C" void my_assert(bool b) {
assert(b);
}
extern "C" bool isSubclass(BoxedClass* child, BoxedClass* parent) {
// TODO the class is allowed to override this using __subclasscheck__
while (child) {
if (child == parent)
return true;
child = child->base;
}
return false;
}
extern "C" void assertFail(BoxedModule* inModule, Box* msg) {
if (msg) {
BoxedString* tostr = str(msg);
raiseExcHelper(AssertionError, "%s", tostr->s.c_str());
} else {
raiseExcHelper(AssertionError, NULL);
}
}
extern "C" void assertNameDefined(bool b, const char* name, BoxedClass* exc_cls, bool local_var_msg) {
if (!b) {
if (local_var_msg)
raiseExcHelper(exc_cls, "local variable '%s' referenced before assignment", name);
else
raiseExcHelper(exc_cls, "name '%s' is not defined", name);
}
}
extern "C" void raiseAttributeErrorStr(const char* typeName, const char* attr) {
raiseExcHelper(AttributeError, "'%s' object has no attribute '%s'", typeName, attr);
}
extern "C" void raiseAttributeError(Box* obj, const char* attr) {
if (obj->cls == type_cls) {
// Slightly different error message:
raiseExcHelper(AttributeError, "type object '%s' has no attribute '%s'",
getNameOfClass(static_cast<BoxedClass*>(obj))->c_str(), attr);
} else {
raiseAttributeErrorStr(getTypeName(obj)->c_str(), attr);
}
}
extern "C" void raiseNotIterableError(const char* typeName) {
raiseExcHelper(TypeError, "'%s' object is not iterable", typeName);
}
static void _checkUnpackingLength(i64 expected, i64 given) {
if (given == expected)
return;
if (given > expected)
raiseExcHelper(ValueError, "too many values to unpack");
else {
if (given == 1)
raiseExcHelper(ValueError, "need more than %ld value to unpack", given);
else
raiseExcHelper(ValueError, "need more than %ld values to unpack", given);
}
}
extern "C" Box** unpackIntoArray(Box* obj, int64_t expected_size) {
assert(expected_size > 0);
if (obj->cls == tuple_cls) {
BoxedTuple* t = static_cast<BoxedTuple*>(obj);
_checkUnpackingLength(expected_size, t->elts.size());
return &t->elts[0];
}
if (obj->cls == list_cls) {
BoxedList* l = static_cast<BoxedList*>(obj);
_checkUnpackingLength(expected_size, l->size);
return &l->elts->elts[0];
}
BoxedTuple::GCVector elts;
for (auto e : obj->pyElements()) {
elts.push_back(e);
if (elts.size() > expected_size)
break;
}
_checkUnpackingLength(expected_size, elts.size());
return &elts[0];
}
PyObject* Py_CallPythonNew(PyTypeObject* self, PyObject* args, PyObject* kwds) {
try {
Py_FatalError("this function is untested");
Box* new_attr = typeLookup(self, _new_str, NULL);
assert(new_attr);
new_attr = processDescriptor(new_attr, None, self);
return runtimeCallInternal(new_attr, NULL, ArgPassSpec(1, 0, true, true), self, args, kwds, NULL, NULL);
} catch (Box* e) {
abort();
}
}
PyObject* Py_CallPythonCall(PyObject* self, PyObject* args, PyObject* kwds) {
try {
Py_FatalError("this function is untested");
return runtimeCallInternal(self, NULL, ArgPassSpec(0, 0, true, true), args, kwds, NULL, NULL, NULL);
} catch (Box* e) {
abort();
}
}
void BoxedClass::freeze() {
assert(!is_constant);
assert(getattr("__name__")); // otherwise debugging will be very hard
// This will probably share a lot in common with Py_TypeReady:
if (!tp_new) {
this->tp_new = &Py_CallPythonNew;
} else if (tp_new != Py_CallPythonNew) {
ASSERT(0, "need to set __new__?");
}
if (!tp_call) {
this->tp_call = &Py_CallPythonCall;
} else if (tp_call != Py_CallPythonCall) {
ASSERT(0, "need to set __call__?");
}
is_constant = true;
}
BoxedClass::BoxedClass(BoxedClass* metaclass, BoxedClass* base, gcvisit_func gc_visit, int attrs_offset,
int instance_size, bool is_user_defined)
: BoxVar(metaclass, 0), base(base), gc_visit(gc_visit), attrs_offset(attrs_offset), is_constant(false),
is_user_defined(is_user_defined) {
// Zero out the CPython tp_* slots:
memset(&tp_name, 0, (char*)(&tp_version_tag + 1) - (char*)(&tp_name));
tp_basicsize = instance_size;
if (metaclass == NULL) {
assert(type_cls == NULL);
} else {
assert(isSubclass(metaclass, type_cls));
}
assert(tp_dealloc == NULL);
if (gc_visit == NULL) {
assert(base);
this->gc_visit = base->gc_visit;
}
assert(this->gc_visit);
if (!base) {
assert(object_cls == nullptr);
// we're constructing 'object'
// Will have to add __base__ = None later
} else {
assert(object_cls);
if (base->attrs_offset)
RELEASE_ASSERT(attrs_offset == base->attrs_offset, "");
assert(tp_basicsize >= base->tp_basicsize);
}
if (base && cls && str_cls)
giveAttr("__base__", base);
assert(tp_basicsize % sizeof(void*) == 0); // Not critical I suppose, but probably signals a bug
if (attrs_offset) {
assert(tp_basicsize >= attrs_offset + sizeof(HCAttrs));
assert(attrs_offset % sizeof(void*) == 0); // Not critical I suppose, but probably signals a bug
}
if (!is_user_defined)
gc::registerPermanentRoot(this);
}
std::string getFullNameOfClass(BoxedClass* cls) {
Box* b = cls->getattr("__name__");
assert(b);
ASSERT(b->cls == str_cls, "%p", b->cls);
BoxedString* name = static_cast<BoxedString*>(b);
b = cls->getattr("__module__");
if (!b)
return name->s;
assert(b);
if (b->cls != str_cls)
return name->s;
BoxedString* module = static_cast<BoxedString*>(b);
return module->s + "." + name->s;
}
std::string getFullTypeName(Box* o) {
return getFullNameOfClass(o->cls);
}
extern "C" const std::string* getNameOfClass(BoxedClass* cls) {
Box* b = cls->getattr("__name__");
assert(b);
ASSERT(b->cls == str_cls, "%p", b->cls);
BoxedString* sb = static_cast<BoxedString*>(b);
return &sb->s;
}
extern "C" const std::string* getTypeName(Box* o) {
return getNameOfClass(o->cls);
}
HiddenClass* HiddenClass::getOrMakeChild(const std::string& attr) {
std::unordered_map<std::string, HiddenClass*>::iterator it = children.find(attr);
if (it != children.end())
return it->second;
static StatCounter num_hclses("num_hidden_classes");
num_hclses.log();
HiddenClass* rtn = new HiddenClass(this);
this->children[attr] = rtn;
rtn->attr_offsets[attr] = attr_offsets.size();
return rtn;
}
/**
* del attr from current HiddenClass, pertain the orders of remaining attrs
*/
HiddenClass* HiddenClass::delAttrToMakeHC(const std::string& attr) {
int idx = getOffset(attr);
assert(idx >= 0);
std::vector<std::string> new_attrs(attr_offsets.size() - 1);
for (auto it = attr_offsets.begin(); it != attr_offsets.end(); ++it) {
if (it->second < idx)
new_attrs[it->second] = it->first;
else if (it->second > idx) {
new_attrs[it->second - 1] = it->first;
}
}
// TODO we can first locate the parent HiddenClass of the deleted
// attribute and hence avoid creation of its ancestors.
HiddenClass* cur = root_hcls;
for (const auto& attr : new_attrs) {
cur = cur->getOrMakeChild(attr);
}
return cur;
}
Box::Box(BoxedClass* cls) : cls(cls) {
// if (TRACK_ALLOCATIONS) {
// int id = Stats::getStatId("allocated_" + *getNameOfClass(c));
// Stats::log(id);
//}
// the only way cls should be NULL is if we're creating the type_cls
// object itself:
if (cls == NULL) {
ASSERT(type_cls == NULL, "should pass a non-null cls here");
} else {
}
}
HCAttrs* Box::getAttrsPtr() {
assert(cls->instancesHaveAttrs());
char* p = reinterpret_cast<char*>(this);
p += cls->attrs_offset;
return reinterpret_cast<HCAttrs*>(p);
}
Box* Box::getattr(const std::string& attr, GetattrRewriteArgs* rewrite_args) {
// Have to guard on the memory layout of this object.
// Right now, guard on the specific Python-class, which in turn
// specifies the C structure.
// In the future, we could create another field (the flavor?)
// that also specifies the structure and can include multiple
// classes.
// Only matters if we end up getting multiple classes with the same
// structure (ex user class) and the same hidden classes, because
// otherwise the guard will fail anyway.;
if (rewrite_args) {
rewrite_args->obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)cls);
rewrite_args->out_success = true;
}
if (!cls->instancesHaveAttrs()) {
if (rewrite_args) {
rewrite_args->obj.setDoneUsing();
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
}
return NULL;
}
HCAttrs* attrs = getAttrsPtr();
HiddenClass* hcls = attrs->hcls;
if (rewrite_args) {
if (!rewrite_args->obj_hcls_guarded)
rewrite_args->obj.addAttrGuard(cls->attrs_offset + HCATTRS_HCLS_OFFSET, (intptr_t)hcls);
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
}
int offset = hcls->getOffset(attr);
if (offset == -1) {
if (rewrite_args) {
rewrite_args->obj.setDoneUsing();
}
return NULL;
}
if (rewrite_args) {
// TODO using the output register as the temporary makes register allocation easier
// since we don't need to clobber a register, but does it make the code slower?
RewriterVarUsage attrs = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET,
RewriterVarUsage::Kill, Location::any());
rewrite_args->out_rtn
= attrs.getAttr(offset * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any());
}
Box* rtn = attrs->attr_list->attrs[offset];
return rtn;
}
void Box::setattr(const std::string& attr, Box* val, SetattrRewriteArgs* rewrite_args) {
assert(cls->instancesHaveAttrs());
assert(gc::isValidGCObject(val));
// Have to guard on the memory layout of this object.
// Right now, guard on the specific Python-class, which in turn
// specifies the C structure.
// In the future, we could create another field (the flavor?)
// that also specifies the structure and can include multiple
// classes.
// Only matters if we end up getting multiple classes with the same
// structure (ex user class) and the same hidden classes, because
// otherwise the guard will fail anyway.;
if (rewrite_args)
rewrite_args->obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)cls);
static const std::string none_str("None");
RELEASE_ASSERT(attr != none_str || this == builtins_module, "can't assign to None");
HCAttrs* attrs = getAttrsPtr();
HiddenClass* hcls = attrs->hcls;
int numattrs = hcls->attr_offsets.size();
int offset = hcls->getOffset(attr);
if (rewrite_args) {
rewrite_args->obj.addAttrGuard(cls->attrs_offset + HCATTRS_HCLS_OFFSET, (intptr_t)hcls);
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
// rewrite_args->rewriter->addDecision(offset == -1 ? 1 : 0);
}
if (offset >= 0) {
assert(offset < numattrs);
Box* prev = attrs->attr_list->attrs[offset];
attrs->attr_list->attrs[offset] = val;
if (rewrite_args) {
RewriterVarUsage r_hattrs = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET,
RewriterVarUsage::Kill, Location::any());
r_hattrs.setAttr(offset * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, std::move(rewrite_args->attrval));
r_hattrs.setDoneUsing();
rewrite_args->out_success = true;
}
return;
}
assert(offset == -1);
HiddenClass* new_hcls = hcls->getOrMakeChild(attr);
// TODO need to make sure we don't need to rearrange the attributes
assert(new_hcls->attr_offsets[attr] == numattrs);
#ifndef NDEBUG
for (const auto& p : hcls->attr_offsets) {
assert(new_hcls->attr_offsets[p.first] == p.second);
}
#endif
RewriterVarUsage r_new_array2(RewriterVarUsage::empty());
int new_size = sizeof(HCAttrs::AttrList) + sizeof(Box*) * (numattrs + 1);
if (numattrs == 0) {
attrs->attr_list = (HCAttrs::AttrList*)gc_alloc(new_size, gc::GCKind::UNTRACKED);
if (rewrite_args) {
RewriterVarUsage r_newsize = rewrite_args->rewriter->loadConst(new_size, Location::forArg(0));
RewriterVarUsage r_kind
= rewrite_args->rewriter->loadConst((int)gc::GCKind::UNTRACKED, Location::forArg(1));
r_new_array2
= rewrite_args->rewriter->call(false, (void*)gc::gc_alloc, std::move(r_newsize), std::move(r_kind));
}
} else {
attrs->attr_list = (HCAttrs::AttrList*)gc::gc_realloc(attrs->attr_list, new_size);
if (rewrite_args) {
RewriterVarUsage r_oldarray = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET,
RewriterVarUsage::NoKill, Location::forArg(0));
RewriterVarUsage r_newsize = rewrite_args->rewriter->loadConst(new_size, Location::forArg(1));
r_new_array2 = rewrite_args->rewriter->call(false, (void*)gc::gc_realloc, std::move(r_oldarray),
std::move(r_newsize));
}
}
// Don't set the new hcls until after we do the allocation for the new attr_list;
// that allocation can cause a collection, and we want the collector to always
// see a consistent state between the hcls and the attr_list
attrs->hcls = new_hcls;
if (rewrite_args) {
r_new_array2.setAttr(numattrs * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, std::move(rewrite_args->attrval));
rewrite_args->obj.setAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, std::move(r_new_array2));
RewriterVarUsage r_hcls = rewrite_args->rewriter->loadConst((intptr_t)new_hcls);
rewrite_args->obj.setAttr(cls->attrs_offset + HCATTRS_HCLS_OFFSET, std::move(r_hcls));
rewrite_args->obj.setDoneUsing();
rewrite_args->out_success = true;
}
attrs->attr_list->attrs[numattrs] = val;
}
Box* typeLookup(BoxedClass* cls, const std::string& attr, GetattrRewriteArgs* rewrite_args) {
Box* val;
if (rewrite_args) {
assert(!rewrite_args->out_success);
RewriterVarUsage obj_saved = rewrite_args->obj.addUse();
bool call_done_guarding = rewrite_args->call_done_guarding;
rewrite_args->call_done_guarding = false;
val = cls->getattr(attr, rewrite_args);
assert(rewrite_args->out_success);
if (!val and cls->base) {
rewrite_args->out_success = false;
rewrite_args->obj = obj_saved.getAttr(offsetof(BoxedClass, base), RewriterVarUsage::Kill);
val = typeLookup(cls->base, attr, rewrite_args);
} else {
obj_saved.setDoneUsing();
}
if (call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
return val;
} else {
val = cls->getattr(attr, NULL);
if (!val and cls->base)
return typeLookup(cls->base, attr, NULL);
return val;
}
}
bool isNondataDescriptorInstanceSpecialCase(Box* descr) {
return descr->cls == function_cls || descr->cls == method_cls;
}
Box* nondataDescriptorInstanceSpecialCases(GetattrRewriteArgs* rewrite_args, Box* obj, Box* descr,
RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) {
// Special case: non-data descriptor: function
if (descr->cls == function_cls || descr->cls == method_cls) {
if (!for_call) {
if (rewrite_args) {
// can't guard after because we make this call... the call is trivial enough
// that we can probably work around it if it's important, but otherwise, if
// this triggers, just abort rewriting, I guess
assert(rewrite_args->call_done_guarding);
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxInstanceMethod,
std::move(rewrite_args->obj), std::move(r_descr));
rewrite_args->out_success = true;
}
return boxInstanceMethod(obj, descr);
} else {
if (rewrite_args) {
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->obj.setDoneUsing();
rewrite_args->out_rtn = std::move(r_descr);
rewrite_args->out_success = true;
}
*should_bind_out = true;
return descr;
}
}
return NULL;
}
Box* descriptorClsSpecialCases(GetattrRewriteArgs* rewrite_args, BoxedClass* cls, Box* descr, RewriterVarUsage& r_descr,
bool for_call, bool* should_bind_out) {
// Special case: functions
if (descr->cls == function_cls || descr->cls == method_cls) {
if (rewrite_args)
r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls);
if (!for_call && descr->cls == function_cls) {
if (rewrite_args) {
assert(rewrite_args->call_done_guarding);
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->obj.setDoneUsing();
// return an unbound instancemethod
rewrite_args->out_rtn
= rewrite_args->rewriter->call(false, (void*)boxUnboundInstanceMethod, std::move(r_descr));
rewrite_args->out_success = true;
}
return boxUnboundInstanceMethod(descr);
}
if (rewrite_args) {
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->obj.setDoneUsing();
rewrite_args->out_success = true;
rewrite_args->out_rtn = std::move(r_descr);
}
// leave should_bind_out set to false
return descr;
}
// Special case: member descriptor
if (descr->cls == member_cls) {
if (rewrite_args)
r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls);
if (rewrite_args) {
assert(rewrite_args->call_done_guarding);
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->obj.setDoneUsing();
// Actually just return val (it's a descriptor but only
// has special behaviour for instance lookups - see below)
rewrite_args->out_rtn = std::move(r_descr);
rewrite_args->out_success = true;
}
return descr;
}
return NULL;
}
Box* dataDescriptorInstanceSpecialCases(GetattrRewriteArgs* rewrite_args, Box* obj, Box* descr,
RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) {
// Special case: data descriptor: member descriptor
if (descr->cls == member_cls) {
BoxedMemberDescriptor* member_desc = static_cast<BoxedMemberDescriptor*>(descr);
// TODO should also have logic to raise a type error if type of obj is wrong
if (rewrite_args) {
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
r_descr.setDoneUsing();
}
switch (member_desc->type) {
case BoxedMemberDescriptor::OBJECT: {
assert(member_desc->offset % sizeof(Box*) == 0);
Box* rtn = reinterpret_cast<Box**>(obj)[member_desc->offset / sizeof(Box*)];
RELEASE_ASSERT(rtn, "");
if (rewrite_args) {
rewrite_args->out_rtn = rewrite_args->obj.getAttr(
member_desc->offset, RewriterVarUsage::KillFlag::Kill, rewrite_args->destination);
rewrite_args->out_success = true;
}
return rtn;
}
case BoxedMemberDescriptor::BYTE: {
// TODO rewriter stuff for these other cases as well
rewrite_args = NULL;
int8_t rtn = reinterpret_cast<int8_t*>(obj)[member_desc->offset];
return boxInt(rtn);
}
case BoxedMemberDescriptor::BOOL: {
rewrite_args = NULL;
bool rtn = reinterpret_cast<bool*>(obj)[member_desc->offset];
return boxBool(rtn);
}
case BoxedMemberDescriptor::INT: {
rewrite_args = NULL;
int rtn = reinterpret_cast<int*>(obj)[member_desc->offset / sizeof(int)];
return boxInt(rtn);
}
case BoxedMemberDescriptor::FLOAT: {
rewrite_args = NULL;
double rtn = reinterpret_cast<double*>(obj)[member_desc->offset / sizeof(double)];
return boxFloat(rtn);
}
default:
RELEASE_ASSERT(0, "%d", member_desc->type);
}
}
return NULL;
}
inline Box* getclsattr_internal(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args) {
return getattrInternalGeneral(obj, attr, rewrite_args,
/* cls_only */ true,
/* for_call */ false, NULL);
}
extern "C" Box* getclsattr(Box* obj, const char* attr) {
static StatCounter slowpath_getclsattr("slowpath_getclsattr");
slowpath_getclsattr.log();
Box* gotten;
#if 0
std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, 1, "getclsattr"));
if (rewriter.get()) {
//rewriter->trap();
GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0));
gotten = getclsattr_internal(obj, attr, &rewrite_args, NULL);
if (rewrite_args.out_success && gotten) {
rewrite_args.out_rtn.move(-1);
rewriter->commit();
}
#else
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getclsattr"));
if (rewriter.get()) {
// rewriter->trap();
GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true);
gotten = getclsattr_internal(obj, attr, &rewrite_args);
if (rewrite_args.out_success && gotten) {
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
}
#endif
}
else {
gotten = getclsattr_internal(obj, attr, NULL);
}
RELEASE_ASSERT(gotten, "%s:%s", getTypeName(obj)->c_str(), attr);
return gotten;
}
// Does a simple call of the descriptor's __get__ if it exists;
// this function is useful for custom getattribute implementations that already know whether the descriptor
// came from the class or not.
Box* processDescriptorOrNull(Box* obj, Box* inst, Box* owner) {
Box* descr_r = callattrInternal(obj, &_get_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(2), inst, owner, NULL,
NULL, NULL);
return descr_r;
}
Box* processDescriptor(Box* obj, Box* inst, Box* owner) {
Box* descr_r = processDescriptorOrNull(obj, inst, owner);
if (descr_r)
return descr_r;
return obj;
}
static Box* (*runtimeCall0)(Box*, ArgPassSpec) = (Box * (*)(Box*, ArgPassSpec))runtimeCall;
static Box* (*runtimeCall1)(Box*, ArgPassSpec, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*))runtimeCall;
static Box* (*runtimeCall2)(Box*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*, Box*))runtimeCall;
static Box* (*runtimeCall3)(Box*, ArgPassSpec, Box*, Box*, Box*)
= (Box * (*)(Box*, ArgPassSpec, Box*, Box*, Box*))runtimeCall;
Box* getattrInternalGeneral(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args, bool cls_only,
bool for_call, bool* should_bind_out) {
if (for_call) {
*should_bind_out = false;
}
if (obj->cls == closure_cls) {
Box* val = NULL;
if (rewrite_args) {
GetattrRewriteArgs hrewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(),
rewrite_args->destination, false);
val = obj->getattr(attr, &hrewrite_args);
if (!hrewrite_args.out_success) {
rewrite_args = NULL;
} else if (val) {
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->out_rtn = std::move(hrewrite_args.out_rtn);
rewrite_args->out_success = true;
rewrite_args->obj.setDoneUsing();
return val;
}
} else {
val = obj->getattr(attr, NULL);
if (val) {
return val;
}
}
// If val doesn't exist, then we move up to the parent closure
// TODO closures should get their own treatment, but now just piggy-back on the
// normal hidden-class IC logic.
// Can do better since we don't need to guard on the cls (always going to be closure)
BoxedClosure* closure = static_cast<BoxedClosure*>(obj);
if (closure->parent) {
if (rewrite_args) {
rewrite_args->obj = rewrite_args->obj.getAttr(offsetof(BoxedClosure, parent), RewriterVarUsage::NoKill);
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
}
return getattrInternal(closure->parent, attr, rewrite_args);
}
raiseExcHelper(NameError, "free variable '%s' referenced before assignment in enclosing scope", attr.c_str());
}
if (!cls_only) {
// Don't need to pass icentry args, since we special-case __getattribtue__ and __getattr__ to use
// invalidation rather than guards
// TODO since you changed this to typeLookup you need to guard
Box* getattribute = typeLookup(obj->cls, "__getattribute__", NULL);
if (getattribute) {
// TODO this is a good candidate for interning?
Box* boxstr = boxString(attr);
Box* rtn = runtimeCall2(getattribute, ArgPassSpec(2), obj, boxstr);
return rtn;
}
if (rewrite_args) {
rewrite_args->rewriter->addDependenceOn(obj->cls->dependent_icgetattrs);
}
}
// Handle descriptor logic here.
// A descriptor is either a data descriptor or a non-data descriptor.
// data descriptors define both __get__ and __set__. non-data descriptors
// only define __get__. Rules are different for the two types, which means
// that even though __get__ is the one we might call, we still have to check
// if __set__ exists.
// If __set__ exists, it's a data descriptor, and it takes precedence over
// the instance attribute.
// Otherwise, it's non-data, and we only call __get__ if the instance
// attribute doesn't exist.
// In the cls_only case, we ignore the instance attribute
// (so we don't have to check if __set__ exists at all)
// Look up the class attribute (called `descr` here because it might
// be a descriptor).
Box* descr = NULL;
RewriterVarUsage r_descr(RewriterVarUsage::empty());
if (rewrite_args) {
RewriterVarUsage r_obj_cls
= rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any());
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_obj_cls), rewrite_args->destination,
false);
descr = typeLookup(obj->cls, attr, &grewrite_args);
if (!grewrite_args.out_success) {
rewrite_args = NULL;
} else if (descr) {
r_descr = std::move(grewrite_args.out_rtn);
}
} else {
descr = typeLookup(obj->cls, attr, NULL);
}
// Check if it's a data descriptor
Box* _get_ = NULL;
RewriterVarUsage r_get(RewriterVarUsage::empty());
if (descr) {
if (rewrite_args)
r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls);
// Special-case data descriptors (e.g., member descriptors)
Box* res = dataDescriptorInstanceSpecialCases(rewrite_args, obj, descr, r_descr, for_call, should_bind_out);
if (res) {
return res;
}
// Let's only check if __get__ exists if it's not a special case
// nondata descriptor. The nondata case is handled below, but
// we can immediately know to skip this part if it's one of the
// special case nondata descriptors.
if (!isNondataDescriptorInstanceSpecialCase(descr)) {
// Check if __get__ exists
if (rewrite_args) {
RewriterVarUsage r_descr_cls
= r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any());
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_descr_cls), Location::any(),
false);
_get_ = typeLookup(descr->cls, _get_str, &grewrite_args);
if (!grewrite_args.out_success) {
rewrite_args = NULL;
} else if (_get_) {
r_get = std::move(grewrite_args.out_rtn);
}
} else {
_get_ = typeLookup(descr->cls, _get_str, NULL);
}
// As an optimization, don't check for __set__ if we're in cls_only mode, since it won't matter.
if (_get_ && !cls_only) {
// Check if __set__ exists
Box* _set_ = NULL;
if (rewrite_args) {
RewriterVarUsage r_descr_cls
= r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any());
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_descr_cls), Location::any(),
false);
_set_ = typeLookup(descr->cls, "__set__", &grewrite_args);
if (!grewrite_args.out_success) {
rewrite_args = NULL;
} else if (_set_) {
grewrite_args.out_rtn.setDoneUsing();
}
} else {
_set_ = typeLookup(descr->cls, "__set__", NULL);
}
// Call __get__(descr, obj, obj->cls)
if (_set_) {
// this could happen for the callattr path...
if (rewrite_args && !rewrite_args->call_done_guarding)
rewrite_args = NULL;
Box* res;
if (rewrite_args) {
CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get),
rewrite_args->destination, rewrite_args->call_done_guarding);
crewrite_args.arg1 = std::move(r_descr);
crewrite_args.arg2 = rewrite_args->obj.addUse();
crewrite_args.arg3
= rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::Kill, Location::any());
res = runtimeCallInternal(_get_, &crewrite_args, ArgPassSpec(3), descr, obj, obj->cls, NULL,
NULL);
if (!crewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_success = true;
rewrite_args->out_rtn = std::move(crewrite_args.out_rtn);
}
} else {
r_descr.ensureDoneUsing();
r_get.ensureDoneUsing();
res = runtimeCallInternal(_get_, NULL, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL);
}
return res;
}
}
}
}
if (!cls_only) {
if (obj->cls != type_cls) {
// Look up the val in the object's dictionary and if you find it, return it.
Box* val;
RewriterVarUsage r_val(RewriterVarUsage::empty());
if (rewrite_args) {
GetattrRewriteArgs hrewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(),
rewrite_args->destination, false);
val = obj->getattr(attr, &hrewrite_args);
if (!hrewrite_args.out_success) {
rewrite_args = NULL;
} else if (val) {
r_val = std::move(hrewrite_args.out_rtn);
}
} else {
val = obj->getattr(attr, NULL);
}
if (val) {
if (rewrite_args) {
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->obj.setDoneUsing();
rewrite_args->out_rtn = std::move(r_val);
rewrite_args->out_success = true;
}
r_descr.ensureDoneUsing();
r_get.ensureDoneUsing();
return val;
}
} else {
// More complicated when obj is a type
// We have to look up the attr in the entire
// class hierarchy, and we also have to check if it is a descriptor,
// in addition to the data/nondata descriptor logic.
// (in CPython, see type_getattro in typeobject.c)
Box* val;
RewriterVarUsage r_val(RewriterVarUsage::empty());
if (rewrite_args) {
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(),
rewrite_args->destination, false);
val = typeLookup(static_cast<BoxedClass*>(obj), attr, &grewrite_args);
if (!grewrite_args.out_success) {
rewrite_args = NULL;
} else if (val) {
r_val = std::move(grewrite_args.out_rtn);
}
} else {
val = typeLookup(static_cast<BoxedClass*>(obj), attr, NULL);
}
if (val) {
r_get.ensureDoneUsing();
r_descr.ensureDoneUsing();
Box* res = descriptorClsSpecialCases(rewrite_args, static_cast<BoxedClass*>(obj), val, r_val, for_call,
should_bind_out);
if (res) {
return res;
}
// Lookup __get__
RewriterVarUsage r_get(RewriterVarUsage::empty());
Box* local_get;
if (rewrite_args) {
RewriterVarUsage r_val_cls
= r_val.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any());
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_val_cls), Location::any(),
false);
local_get = typeLookup(val->cls, _get_str, &grewrite_args);
if (!grewrite_args.out_success) {
rewrite_args = NULL;
} else if (local_get) {
r_get = std::move(grewrite_args.out_rtn);
}
} else {
local_get = typeLookup(val->cls, _get_str, NULL);
}
// Call __get__(val, None, obj)
if (local_get) {
Box* res;
// this could happen for the callattr path...
if (rewrite_args && !rewrite_args->call_done_guarding)
rewrite_args = NULL;
if (rewrite_args) {
CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get),
rewrite_args->destination, rewrite_args->call_done_guarding);
crewrite_args.arg1 = std::move(r_val);
crewrite_args.arg2 = rewrite_args->rewriter->loadConst((intptr_t)None, Location::any());
crewrite_args.arg3 = std::move(rewrite_args->obj);
res = runtimeCallInternal(local_get, &crewrite_args, ArgPassSpec(3), val, None, obj, NULL,
NULL);
if (!crewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_success = true;
rewrite_args->out_rtn = std::move(crewrite_args.out_rtn);
}
} else {
r_val.ensureDoneUsing();
r_get.ensureDoneUsing();
res = runtimeCallInternal(local_get, NULL, ArgPassSpec(3), val, None, obj, NULL, NULL);
}
return res;
}
// If there was no local __get__, just return val
if (rewrite_args) {
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->obj.setDoneUsing();
rewrite_args->out_rtn = std::move(r_val);
rewrite_args->out_success = true;
} else {
r_val.ensureDoneUsing();
}
return val;
}
}
}
// If descr and __get__ exist, then call __get__
if (descr) {
// Special cases first
Box* res = nondataDescriptorInstanceSpecialCases(rewrite_args, obj, descr, r_descr, for_call, should_bind_out);
if (res) {
return res;
}
// We looked up __get__ above. If we found it, call it and return
// the result.
if (_get_) {
// this could happen for the callattr path...
if (rewrite_args && !rewrite_args->call_done_guarding)
rewrite_args = NULL;
Box* res;
if (rewrite_args) {
CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination,
rewrite_args->call_done_guarding);
crewrite_args.arg1 = std::move(r_descr);
crewrite_args.arg2 = rewrite_args->obj.addUse();
crewrite_args.arg3 = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::Kill, Location::any());
res = runtimeCallInternal(_get_, &crewrite_args, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL);
if (!crewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_success = true;
rewrite_args->out_rtn = std::move(crewrite_args.out_rtn);
}
} else {
r_descr.ensureDoneUsing();
r_get.ensureDoneUsing();
res = runtimeCallInternal(_get_, NULL, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL);
}
return res;
}
// Otherwise, just return descr.
if (rewrite_args) {
rewrite_args->obj.setDoneUsing();
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
rewrite_args->out_rtn = std::move(r_descr);
rewrite_args->out_success = true;
}
return descr;
}
// Finally, check __getattr__
if (!cls_only) {
// Don't need to pass icentry args, since we special-case __getattribute__ and __getattr__ to use
// invalidation rather than guards
rewrite_args = NULL;
Box* getattr = typeLookup(obj->cls, "__getattr__", NULL);
if (getattr) {
Box* boxstr = boxString(attr);
Box* rtn = runtimeCall2(getattr, ArgPassSpec(2), obj, boxstr);
if (rewrite_args)
rewrite_args->out_rtn.ensureDoneUsing();
return rtn;
}
if (rewrite_args) {
rewrite_args->rewriter->addDependenceOn(obj->cls->dependent_icgetattrs);
}
}
if (rewrite_args) {
rewrite_args->obj.ensureDoneUsing();
rewrite_args->out_success = true;
}
return NULL;
}
Box* getattrInternal(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args) {
return getattrInternalGeneral(obj, attr, rewrite_args,
/* cls_only */ false,
/* for_call */ false, NULL);
}
extern "C" Box* getattr(Box* obj, const char* attr) {
static StatCounter slowpath_getattr("slowpath_getattr");
slowpath_getattr.log();
if (VERBOSITY() >= 2) {
#if !DISABLE_STATS
std::string per_name_stat_name = "getattr__" + std::string(attr);
int id = Stats::getStatId(per_name_stat_name);
Stats::log(id);
#endif
}
if (strcmp(attr, "__dict__") == 0) {
if (obj->cls->instancesHaveAttrs())
return makeAttrWrapper(obj);
}
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getattr"));
Box* val;
if (rewriter.get()) {
Location dest;
TypeRecorder* recorder = rewriter->getTypeRecorder();
if (recorder)
dest = Location::forArg(1);
else
dest = rewriter->getReturnDestination();
GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), dest, true);
val = getattrInternal(obj, attr, &rewrite_args);
// should make sure getattrInternal calls finishes using obj itself
// if it is successful
if (!rewrite_args.out_success)
rewrite_args.obj.ensureDoneUsing();
if (rewrite_args.out_success && val) {
if (recorder) {
RewriterVarUsage record_rtn = rewriter->call(
false, (void*)recordType, rewriter->loadConst((intptr_t)recorder, Location::forArg(0)),
std::move(rewrite_args.out_rtn));
rewriter->commitReturning(std::move(record_rtn));
recordType(recorder, val);
} else {
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
}
}
} else {
val = getattrInternal(obj, attr, NULL);
}
if (val) {
return val;
}
raiseAttributeError(obj, attr);
}
void setattrInternal(Box* obj, const std::string& attr, Box* val, SetattrRewriteArgs* rewrite_args) {
assert(gc::isValidGCObject(val));
// Lookup a descriptor
Box* descr = NULL;
RewriterVarUsage r_descr(RewriterVarUsage::empty());
// TODO probably check that the cls is user-defined or something like that
// (figure out exactly what)
// (otherwise no need to check descriptor logic)
if (rewrite_args) {
RewriterVarUsage r_cls
= rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::KillFlag::NoKill, Location::any());
GetattrRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_cls),
rewrite_args->rewriter->getReturnDestination(), false);
descr = typeLookup(obj->cls, attr, &crewrite_args);
if (!crewrite_args.out_success) {
rewrite_args = NULL;
} else if (descr) {
r_descr = std::move(crewrite_args.out_rtn);
}
} else {
descr = typeLookup(obj->cls, attr, NULL);
}
if (isSubclass(obj->cls, type_cls)) {
BoxedClass* self = static_cast<BoxedClass*>(obj);
if (attr == _getattr_str || attr == _getattribute_str) {
// Will have to embed the clear in the IC, so just disable the patching for now:
rewrite_args = NULL;
// TODO should put this clearing behavior somewhere else, since there are probably more
// cases in which we want to do it.
self->dependent_icgetattrs.invalidateAll();
}
if (attr == "__base__" && self->getattr("__base__"))
raiseExcHelper(TypeError, "readonly attribute");
if (attr == "__new__") {
self->tp_new = &Py_CallPythonNew;
// TODO update subclasses
rewrite_args = NULL;
}
if (attr == "__call__") {
self->tp_call = &Py_CallPythonCall;
// TODO update subclasses
rewrite_args = NULL;
}
}
Box* _set_ = NULL;
RewriterVarUsage r_set(RewriterVarUsage::empty());
if (descr) {
if (rewrite_args) {
RewriterVarUsage r_cls
= r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::KillFlag::NoKill, Location::any());
GetattrRewriteArgs trewrite_args(rewrite_args->rewriter, std::move(r_cls), Location::any(), false);
_set_ = typeLookup(descr->cls, "__set__", &trewrite_args);
if (!trewrite_args.out_success) {
rewrite_args = NULL;
} else if (_set_) {
r_set = std::move(trewrite_args.out_rtn);
}
} else {
_set_ = typeLookup(descr->cls, "__set__", NULL);
}
}
// If `descr` has __set__ (thus making it a descriptor) we should call
// __set__ with `val` rather than directly calling setattr
if (descr && _set_) {
if (rewrite_args) {
CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_set), Location::any(),
rewrite_args->call_done_guarding);
crewrite_args.arg1 = std::move(r_descr);
crewrite_args.arg2 = std::move(rewrite_args->obj);
crewrite_args.arg3 = std::move(rewrite_args->attrval);
runtimeCallInternal(_set_, &crewrite_args, ArgPassSpec(3), descr, obj, val, NULL, NULL);
if (crewrite_args.out_success) {
crewrite_args.out_rtn.setDoneUsing();
rewrite_args->out_success = true;
}
} else {
runtimeCallInternal(_set_, NULL, ArgPassSpec(3), descr, obj, val, NULL, NULL);
}
} else {
r_descr.ensureDoneUsing();
r_set.ensureDoneUsing();
obj->setattr(attr, val, rewrite_args);
}
}
extern "C" void setattr(Box* obj, const char* attr, Box* attr_val) {
assert(strcmp(attr, "__class__") != 0);
static StatCounter slowpath_setattr("slowpath_setattr");
slowpath_setattr.log();
if (!obj->cls->instancesHaveAttrs()) {
raiseAttributeError(obj, attr);
}
if (obj->cls == type_cls) {
BoxedClass* cobj = static_cast<BoxedClass*>(obj);
if (!isUserDefined(cobj)) {
raiseExcHelper(TypeError, "can't set attributes of built-in/extension type '%s'",
getNameOfClass(cobj)->c_str());
}
}
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "setattr"));
if (rewriter.get()) {
// rewriter->trap();
SetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(2), true);
setattrInternal(obj, attr, attr_val, &rewrite_args);
if (rewrite_args.out_success) {
rewriter->commit();
} else {
rewrite_args.obj.ensureDoneUsing();
rewrite_args.attrval.ensureDoneUsing();
}
} else {
setattrInternal(obj, attr, attr_val, NULL);
}
}
bool isUserDefined(BoxedClass* cls) {
return cls->is_user_defined;
// return cls->hasattrs && (cls != function_cls && cls != type_cls) && !cls->is_constant;
}
extern "C" bool nonzero(Box* obj) {
static StatCounter slowpath_nonzero("slowpath_nonzero");
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 1, "nonzero"));
RewriterVarUsage r_obj(RewriterVarUsage::empty());
if (rewriter.get()) {
r_obj = std::move(rewriter->getArg(0));
// rewriter->trap();
r_obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)obj->cls);
rewriter->setDoneGuarding();
}
if (obj->cls == bool_cls) {
if (rewriter.get()) {
RewriterVarUsage b
= r_obj.getAttr(BOOL_B_OFFSET, RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination());
rewriter->commitReturning(std::move(b));
}
BoxedBool* bool_obj = static_cast<BoxedBool*>(obj);
return bool_obj->b;
} else if (obj->cls == int_cls) {
if (rewriter.get()) {
// TODO should do:
// test %rsi, %rsi
// setne %al
RewriterVarUsage n
= r_obj.getAttr(INT_N_OFFSET, RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination());
RewriterVarUsage b = n.toBool(RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination());
rewriter->commitReturning(std::move(b));
}
BoxedInt* int_obj = static_cast<BoxedInt*>(obj);
return int_obj->n != 0;
} else if (obj->cls == float_cls) {
if (rewriter.get()) {
RewriterVarUsage b = rewriter->call(false, (void*)floatNonzeroUnboxed, std::move(r_obj));
rewriter->commitReturning(std::move(b));
}
return static_cast<BoxedFloat*>(obj)->d != 0;
} else if (obj->cls == none_cls) {
if (rewriter.get()) {
r_obj.setDoneUsing();
RewriterVarUsage b = rewriter->loadConst(0, rewriter->getReturnDestination());
rewriter->commitReturning(std::move(b));
}
return false;
}
if (rewriter.get()) {
r_obj.setDoneUsing();
}
// FIXME we have internal functions calling this method;
// instead, we should break this out into an external and internal function.
// slowpath_* counters are supposed to count external calls; putting it down
// here gets a better representation of that.
// TODO move internal callers to nonzeroInternal, and log *all* calls to nonzero
slowpath_nonzero.log();
// int id = Stats::getStatId("slowpath_nonzero_" + *getTypeName(obj));
// Stats::log(id);
// go through descriptor logic
Box* func = getclsattr_internal(obj, "__nonzero__", NULL);
if (func == NULL) {
ASSERT(isUserDefined(obj->cls) || obj->cls == classobj_cls, "%s.__nonzero__",
getTypeName(obj)->c_str()); // TODO
return true;
}
Box* r = runtimeCall0(func, ArgPassSpec(0));
if (r->cls == bool_cls) {
BoxedBool* b = static_cast<BoxedBool*>(r);
bool rtn = b->b;
return rtn;
} else if (r->cls == int_cls) {
BoxedInt* b = static_cast<BoxedInt*>(r);
bool rtn = b->n != 0;
return rtn;
} else {
raiseExcHelper(TypeError, "__nonzero__ should return bool or int, returned %s", getTypeName(r)->c_str());
}
}
extern "C" BoxedString* str(Box* obj) {
static StatCounter slowpath_str("slowpath_str");
slowpath_str.log();
if (obj->cls != str_cls) {
static const std::string str_str("__str__");
obj = callattrInternal(obj, &str_str, CLASS_ONLY, NULL, ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL);
}
if (obj->cls != str_cls) {
raiseExcHelper(TypeError, "__str__ did not return a string!");
}
return static_cast<BoxedString*>(obj);
}
extern "C" BoxedString* repr(Box* obj) {
static StatCounter slowpath_repr("slowpath_repr");
slowpath_repr.log();
static const std::string repr_str("__repr__");
obj = callattrInternal(obj, &repr_str, CLASS_ONLY, NULL, ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL);
if (obj->cls != str_cls) {
raiseExcHelper(TypeError, "__repr__ did not return a string!");
}
return static_cast<BoxedString*>(obj);
}
extern "C" BoxedString* reprOrNull(Box* obj) {
try {
Box* r = repr(obj);
assert(r->cls == str_cls); // this should be checked by repr()
return static_cast<BoxedString*>(r);
} catch (Box* b) {
return nullptr;
}
}
extern "C" BoxedString* strOrNull(Box* obj) {
try {
BoxedString* r = str(obj);
return static_cast<BoxedString*>(r);
} catch (Box* b) {
return nullptr;
}
}
extern "C" bool isinstance(Box* obj, Box* cls, int64_t flags) {
bool false_on_noncls = (flags & 0x1);
if (cls->cls == tuple_cls) {
auto t = static_cast<BoxedTuple*>(cls);
for (auto c : t->elts) {
if (isinstance(obj, c, flags))
return true;
}
return false;
}
if (cls->cls == classobj_cls) {
if (!isSubclass(obj->cls, instance_cls))
return false;
return instanceIsinstance(static_cast<BoxedInstance*>(obj), static_cast<BoxedClassobj*>(cls));
}
if (!false_on_noncls) {
assert(cls->cls == type_cls);
} else {
if (cls->cls != type_cls)
return false;
}
BoxedClass* ccls = static_cast<BoxedClass*>(cls);
// TODO the class is allowed to override this using __instancecheck__
return isSubclass(obj->cls, ccls);
}
extern "C" BoxedInt* hash(Box* obj) {
static StatCounter slowpath_hash("slowpath_hash");
slowpath_hash.log();
// goes through descriptor logic
Box* hash = getclsattr_internal(obj, "__hash__", NULL);
if (hash == NULL) {
ASSERT(isUserDefined(obj->cls), "%s.__hash__", getTypeName(obj)->c_str());
// TODO not the best way to handle this...
return static_cast<BoxedInt*>(boxInt((i64)obj));
}
Box* rtn = runtimeCall0(hash, ArgPassSpec(0));
if (rtn->cls != int_cls) {
raiseExcHelper(TypeError, "an integer is required");
}
return static_cast<BoxedInt*>(rtn);
}
extern "C" BoxedInt* lenInternal(Box* obj, LenRewriteArgs* rewrite_args) {
Box* rtn;
static std::string attr_str("__len__");
if (rewrite_args) {
CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(rewrite_args->obj), rewrite_args->destination,
rewrite_args->call_done_guarding);
rtn = callattrInternal0(obj, &attr_str, CLASS_ONLY, &crewrite_args, ArgPassSpec(0));
if (!crewrite_args.out_success)
rewrite_args = NULL;
else if (rtn)
rewrite_args->out_rtn = std::move(crewrite_args.out_rtn);
} else {
rtn = callattrInternal0(obj, &attr_str, CLASS_ONLY, NULL, ArgPassSpec(0));
}
if (rtn == NULL) {
raiseExcHelper(TypeError, "object of type '%s' has no len()", getTypeName(obj)->c_str());
}
if (rtn->cls != int_cls) {
raiseExcHelper(TypeError, "an integer is required");
}
if (rewrite_args)
rewrite_args->out_success = true;
return static_cast<BoxedInt*>(rtn);
}
extern "C" BoxedInt* len(Box* obj) {
static StatCounter slowpath_len("slowpath_len");
slowpath_len.log();
return lenInternal(obj, NULL);
}
extern "C" i64 unboxedLen(Box* obj) {
static StatCounter slowpath_unboxedlen("slowpath_unboxedlen");
slowpath_unboxedlen.log();
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 1, "unboxedLen"));
BoxedInt* lobj;
RewriterVarUsage r_boxed(RewriterVarUsage::empty());
if (rewriter.get()) {
// rewriter->trap();
LenRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true);
lobj = lenInternal(obj, &rewrite_args);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else
r_boxed = std::move(rewrite_args.out_rtn);
} else {
lobj = lenInternal(obj, NULL);
}
assert(lobj->cls == int_cls);
i64 rtn = lobj->n;
if (rewriter.get()) {
RewriterVarUsage rtn
= std::move(r_boxed.getAttr(INT_N_OFFSET, RewriterVarUsage::KillFlag::Kill, Location(assembler::RAX)));
rewriter->commitReturning(std::move(rtn));
}
return rtn;
}
extern "C" void dump(void* p) {
printf("\n");
bool is_gc = (gc::global_heap.getAllocationFromInteriorPointer(p) != NULL);
if (!is_gc) {
printf("non-gc memory\n");
return;
}
gc::GCAllocation* al = gc::GCAllocation::fromUserData(p);
if (al->kind_id == gc::GCKind::UNTRACKED) {
printf("gc-untracked object\n");
return;
}
if (al->kind_id == gc::GCKind::CONSERVATIVE) {
printf("conservatively-scanned object object\n");
return;
}
if (al->kind_id == gc::GCKind::PYTHON) {
printf("Python object\n");
Box* b = (Box*)p;
printf("Class: %s\n", getFullTypeName(b).c_str());
if (isSubclass(b->cls, type_cls)) {
printf("Type name: %s\n", getFullNameOfClass(static_cast<BoxedClass*>(b)).c_str());
}
if (isSubclass(b->cls, str_cls)) {
printf("String value: %s\n", static_cast<BoxedString*>(b)->s.c_str());
}
if (isSubclass(b->cls, tuple_cls)) {
printf("%ld elements\n", static_cast<BoxedTuple*>(b)->elts.size());
}
return;
}
RELEASE_ASSERT(0, "%d", (int)al->kind_id);
}
// For rewriting purposes, this function assumes that nargs will be constant.
// That's probably fine for some uses (ex binops), but otherwise it should be guarded on beforehand.
extern "C" Box* callattrInternal(Box* obj, const std::string* attr, LookupScope scope, CallRewriteArgs* rewrite_args,
ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args,
const std::vector<const std::string*>* keyword_names) {
int npassed_args = argspec.totalPassed();
if (rewrite_args && !rewrite_args->args_guarded) {
// TODO duplication with runtime_call
// TODO should know which args don't need to be guarded, ex if we're guaranteed that they
// already fit, either since the type inferencer could determine that,
// or because they only need to fit into an UNKNOWN slot.
if (npassed_args >= 1)
rewrite_args->arg1.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg1->cls);
if (npassed_args >= 2)
rewrite_args->arg2.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg2->cls);
if (npassed_args >= 3)
rewrite_args->arg3.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg3->cls);
if (npassed_args > 3) {
for (int i = 3; i < npassed_args; i++) {
// TODO if there are a lot of args (>16), might be better to increment a pointer
// rather index them directly?
RewriterVarUsage v = rewrite_args->args.getAttr((i - 3) * sizeof(Box*),
RewriterVarUsage::KillFlag::NoKill, Location::any());
v.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)args[i - 3]->cls);
v.setDoneUsing();
}
}
}
// right now I don't think this is ever called with INST_ONLY?
assert(scope != INST_ONLY);
// Look up the argument. Pass in the arguments to getattrInternalGeneral or getclsattr_general
// that will shortcut functions by not putting them into instancemethods
bool should_bind;
Box* val;
RewriterVarUsage r_val(RewriterVarUsage::empty());
if (rewrite_args) {
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), Location::any(), false);
val = getattrInternalGeneral(obj, *attr, &grewrite_args, scope == CLASS_ONLY, true, &should_bind);
if (!grewrite_args.out_success) {
rewrite_args = NULL;
} else if (val) {
r_val = std::move(grewrite_args.out_rtn);
}
} else {
val = getattrInternalGeneral(obj, *attr, NULL, scope == CLASS_ONLY, true, &should_bind);
}
if (val == NULL) {
if (rewrite_args) {
rewrite_args->arg1.ensureDoneUsing();
rewrite_args->arg2.ensureDoneUsing();
rewrite_args->arg3.ensureDoneUsing();
rewrite_args->args.ensureDoneUsing();
rewrite_args->out_success = true;
rewrite_args->obj.setDoneUsing();
}
return val;
}
if (should_bind) {
if (rewrite_args) {
r_val.addGuard((int64_t)val);
}
// TODO copy from runtimeCall
// TODO these two branches could probably be folded together (the first one is becoming
// a subset of the second)
if (npassed_args <= 2) {
Box* rtn;
if (rewrite_args) {
CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination,
rewrite_args->call_done_guarding);
srewrite_args.arg1 = std::move(rewrite_args->obj);
// should be no-ops:
if (npassed_args >= 1)
srewrite_args.arg2 = std::move(rewrite_args->arg1);
if (npassed_args >= 2)
srewrite_args.arg3 = std::move(rewrite_args->arg2);
srewrite_args.func_guarded = true;
srewrite_args.args_guarded = true;
rtn = runtimeCallInternal(val, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords,
argspec.has_starargs, argspec.has_kwargs),
obj, arg1, arg2, NULL, keyword_names);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_rtn = std::move(srewrite_args.out_rtn);
}
} else {
rtn = runtimeCallInternal(val, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords,
argspec.has_starargs, argspec.has_kwargs),
obj, arg1, arg2, NULL, keyword_names);
}
if (rewrite_args)
rewrite_args->out_success = true;
return rtn;
} else {
int alloca_size = sizeof(Box*) * (npassed_args + 1 - 3);
Box** new_args = (Box**)alloca(alloca_size);
new_args[0] = arg3;
memcpy(new_args + 1, args, (npassed_args - 3) * sizeof(Box*));
Box* rtn;
if (rewrite_args) {
CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination,
rewrite_args->call_done_guarding);
srewrite_args.arg1 = std::move(rewrite_args->obj);
srewrite_args.arg2 = std::move(rewrite_args->arg1);
srewrite_args.arg3 = std::move(rewrite_args->arg2);
srewrite_args.args = rewrite_args->rewriter->allocateAndCopyPlus1(
std::move(rewrite_args->arg3),
npassed_args == 3 ? RewriterVarUsage::empty() : std::move(rewrite_args->args), npassed_args - 3);
srewrite_args.args_guarded = true;
srewrite_args.func_guarded = true;
rtn = runtimeCallInternal(val, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords,
argspec.has_starargs, argspec.has_kwargs),
obj, arg1, arg2, new_args, keyword_names);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_rtn = std::move(srewrite_args.out_rtn);
rewrite_args->out_success = true;
}
} else {
rtn = runtimeCallInternal(val, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords,
argspec.has_starargs, argspec.has_kwargs),
obj, arg1, arg2, new_args, keyword_names);
}
return rtn;
}
} else {
if (rewrite_args) {
rewrite_args->obj.setDoneUsing();
}
Box* rtn;
if (val->cls != function_cls && val->cls != instancemethod_cls) {
rewrite_args = NULL;
r_val.ensureDoneUsing();
}
if (rewrite_args) {
CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination,
rewrite_args->call_done_guarding);
if (npassed_args >= 1)
srewrite_args.arg1 = std::move(rewrite_args->arg1);
if (npassed_args >= 2)
srewrite_args.arg2 = std::move(rewrite_args->arg2);
if (npassed_args >= 3)
srewrite_args.arg3 = std::move(rewrite_args->arg3);
if (npassed_args >= 4)
srewrite_args.args = std::move(rewrite_args->args);
srewrite_args.args_guarded = true;
rtn = runtimeCallInternal(val, &srewrite_args, argspec, arg1, arg2, arg3, args, keyword_names);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_rtn = std::move(srewrite_args.out_rtn);
}
} else {
rtn = runtimeCallInternal(val, NULL, argspec, arg1, arg2, arg3, args, keyword_names);
}
if (!rtn) {
raiseExcHelper(TypeError, "'%s' object is not callable", getTypeName(val)->c_str());
}
if (rewrite_args)
rewrite_args->out_success = true;
return rtn;
}
}
extern "C" Box* callattr(Box* obj, const std::string* attr, bool clsonly, ArgPassSpec argspec, Box* arg1, Box* arg2,
Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) {
int npassed_args = argspec.totalPassed();
static StatCounter slowpath_callattr("slowpath_callattr");
slowpath_callattr.log();
assert(attr);
int num_orig_args = 4 + std::min(4, npassed_args);
if (argspec.num_keywords)
num_orig_args++;
std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter(
__builtin_extract_return_addr(__builtin_return_address(0)), num_orig_args, "callattr"));
Box* rtn;
LookupScope scope = clsonly ? CLASS_ONLY : CLASS_OR_INST;
if (rewriter.get()) {
// TODO feel weird about doing this; it either isn't necessary
// or this kind of thing is necessary in a lot more places
// rewriter->getArg(3).addGuard(npassed_args);
CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(),
true);
if (npassed_args >= 1)
rewrite_args.arg1 = std::move(rewriter->getArg(4));
if (npassed_args >= 2)
rewrite_args.arg2 = std::move(rewriter->getArg(5));
if (npassed_args >= 3)
rewrite_args.arg3 = std::move(rewriter->getArg(6));
if (npassed_args >= 4)
rewrite_args.args = std::move(rewriter->getArg(7));
rtn = callattrInternal(obj, attr, scope, &rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else if (rtn) {
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
}
} else {
rtn = callattrInternal(obj, attr, scope, NULL, argspec, arg1, arg2, arg3, args, keyword_names);
}
if (rtn == NULL) {
raiseAttributeError(obj, attr->c_str());
}
return rtn;
}
static inline Box*& getArg(int idx, Box*& arg1, Box*& arg2, Box*& arg3, Box** args) {
if (idx == 0)
return arg1;
if (idx == 1)
return arg2;
if (idx == 2)
return arg3;
return args[idx - 3];
}
static CompiledFunction* pickVersion(CLFunction* f, int num_output_args, Box* oarg1, Box* oarg2, Box* oarg3,
Box** oargs) {
LOCK_REGION(codegen_rwlock.asWrite());
CompiledFunction* chosen_cf = NULL;
for (CompiledFunction* cf : f->versions) {
assert(cf->spec->arg_types.size() == num_output_args);
if (cf->spec->rtn_type->llvmType() != UNKNOWN->llvmType())
continue;
bool works = true;
for (int i = 0; i < num_output_args; i++) {
Box* arg = getArg(i, oarg1, oarg2, oarg3, oargs);
ConcreteCompilerType* t = cf->spec->arg_types[i];
if ((arg && !t->isFitBy(arg->cls)) || (!arg && t != UNKNOWN)) {
works = false;
break;
}
}
if (!works)
continue;
chosen_cf = cf;
break;
}
if (chosen_cf == NULL) {
if (f->source == NULL) {
// TODO I don't think this should be happening any more?
printf("Error: couldn't find suitable function version and no source to recompile!\n");
abort();
}
std::vector<ConcreteCompilerType*> arg_types;
for (int i = 0; i < num_output_args; i++) {
Box* arg = getArg(i, oarg1, oarg2, oarg3, oargs);
assert(arg); // only builtin functions can pass NULL args
arg_types.push_back(typeFromClass(arg->cls));
}
FunctionSpecialization* spec = new FunctionSpecialization(UNKNOWN, arg_types);
EffortLevel::EffortLevel new_effort = initialEffort();
// this also pushes the new CompiledVersion to the back of the version list:
chosen_cf = compileFunction(f, spec, new_effort, NULL);
}
return chosen_cf;
}
static void placeKeyword(const std::vector<AST_expr*>& arg_names, std::vector<bool>& params_filled,
const std::string& kw_name, Box* kw_val, Box*& oarg1, Box*& oarg2, Box*& oarg3, Box** oargs,
BoxedDict* okwargs) {
assert(kw_val);
bool found = false;
for (int j = 0; j < arg_names.size(); j++) {
AST_expr* e = arg_names[j];
if (e->type != AST_TYPE::Name)
continue;
AST_Name* n = ast_cast<AST_Name>(e);
if (n->id == kw_name) {
if (params_filled[j]) {
raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'",
kw_name.c_str());
}
getArg(j, oarg1, oarg2, oarg3, oargs) = kw_val;
params_filled[j] = true;
found = true;
break;
}
}
if (!found) {
if (okwargs) {
Box*& v = okwargs->d[boxString(kw_name)];
if (v) {
raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'",
kw_name.c_str());
}
v = kw_val;
} else {
raiseExcHelper(TypeError, "<function>() got an unexpected keyword argument '%s'", kw_name.c_str());
}
}
}
Box* callFunc(BoxedFunction* func, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3,
Box** args, const std::vector<const std::string*>* keyword_names) {
/*
* Procedure:
* - First match up positional arguments; any extra go to varargs. error if too many.
* - Then apply keywords; any extra go to kwargs. error if too many.
* - Use defaults to fill in any missing
* - error about missing parameters
*/
static StatCounter slowpath_resolveclfunc("slowpath_callfunc");
slowpath_resolveclfunc.log();
CLFunction* f = func->f;
FunctionList& versions = f->versions;
int num_output_args = f->numReceivedArgs();
int num_passed_args = argspec.totalPassed();
BoxedClosure* closure = func->closure;
if (argspec.has_starargs || argspec.has_kwargs || f->takes_kwargs || func->isGenerator) {
rewrite_args = NULL;
}
// These could be handled:
if (argspec.num_keywords) {
rewrite_args = NULL;
}
// TODO Should we guard on the CLFunction or the BoxedFunction?
// A single CLFunction could end up forming multiple BoxedFunctions, and we
// could emit assembly that handles any of them. But doing this involves some
// extra indirection, and it's not clear if that's worth it, since it seems like
// the common case will be functions only ever getting a single set of default arguments.
bool guard_clfunc = false;
assert(!guard_clfunc && "I think there are users that expect the boxedfunction to be guarded");
if (rewrite_args) {
assert(rewrite_args->args_guarded && "need to guard args here");
if (!rewrite_args->func_guarded) {
if (guard_clfunc) {
rewrite_args->obj.addAttrGuard(offsetof(BoxedFunction, f), (intptr_t)f);
} else {
rewrite_args->obj.addGuard((intptr_t)func);
rewrite_args->obj.setDoneUsing();
}
} else {
rewrite_args->obj.setDoneUsing();
}
if (rewrite_args->call_done_guarding)
rewrite_args->rewriter->setDoneGuarding();
assert(rewrite_args->rewriter->isDoneGuarding());
// if (guard_clfunc) {
// Have to save the defaults array since the object itself will probably get overwritten:
// rewrite_args->obj = rewrite_args->obj.move(-2);
// r_defaults_array = rewrite_args->obj.getAttr(offsetof(BoxedFunction, defaults), -2);
//}
}
if (rewrite_args) {
// We might have trouble if we have more output args than input args,
// such as if we need more space to pass defaults.
if (num_output_args > 3 && num_output_args > argspec.totalPassed()) {
int arg_bytes_required = (num_output_args - 3) * sizeof(Box*);
RewriterVarUsage new_args(RewriterVarUsage::empty());
if (rewrite_args->args.isDoneUsing()) {
// rewrite_args->args could be empty if there are not more than
// 3 input args.
new_args = rewrite_args->rewriter->allocate(num_output_args - 3);
} else {
new_args = rewrite_args->rewriter->allocateAndCopy(std::move(rewrite_args->args), num_output_args - 3);
}
rewrite_args->args = std::move(new_args);
}
}
std::vector<Box*> varargs;
if (argspec.has_starargs) {
Box* given_varargs = getArg(argspec.num_args + argspec.num_keywords, arg1, arg2, arg3, args);
for (Box* e : given_varargs->pyElements()) {
varargs.push_back(e);
}
}
// The "output" args that we will pass to the called function:
Box* oarg1 = NULL, * oarg2 = NULL, * oarg3 = NULL;
Box** oargs = NULL;
if (num_output_args > 3) {
int size = (num_output_args - 3) * sizeof(Box*);
oargs = (Box**)alloca(size);
#ifndef NDEBUG
memset(&oargs[0], 0, size);
#endif
}
////
// First, match up positional parameters to positional/varargs:
int positional_to_positional = std::min((int)argspec.num_args, f->num_args);
for (int i = 0; i < positional_to_positional; i++) {
getArg(i, oarg1, oarg2, oarg3, oargs) = getArg(i, arg1, arg2, arg3, args);
// we already moved the positional args into position
}
int varargs_to_positional = std::min((int)varargs.size(), f->num_args - positional_to_positional);
for (int i = 0; i < varargs_to_positional; i++) {
assert(!rewrite_args && "would need to be handled here");
getArg(i + positional_to_positional, oarg1, oarg2, oarg3, oargs) = varargs[i];
}
std::vector<bool> params_filled(num_output_args, false);
for (int i = 0; i < positional_to_positional + varargs_to_positional; i++) {
params_filled[i] = true;
}
std::vector<Box*, StlCompatAllocator<Box*> > unused_positional;
for (int i = positional_to_positional; i < argspec.num_args; i++) {
rewrite_args = NULL;
unused_positional.push_back(getArg(i, arg1, arg2, arg3, args));
}
for (int i = varargs_to_positional; i < varargs.size(); i++) {
rewrite_args = NULL;
unused_positional.push_back(varargs[i]);
}
if (f->takes_varargs) {
int varargs_idx = f->num_args;
if (rewrite_args) {
assert(!unused_positional.size());
// rewrite_args->rewriter->loadConst((intptr_t)EmptyTuple, Location::forArg(varargs_idx));
RewriterVarUsage emptyTupleConst = rewrite_args->rewriter->loadConst(
(intptr_t)EmptyTuple, varargs_idx < 3 ? Location::forArg(varargs_idx) : Location::any());
if (varargs_idx == 0)
rewrite_args->arg1 = std::move(emptyTupleConst);
if (varargs_idx == 1)
rewrite_args->arg2 = std::move(emptyTupleConst);
if (varargs_idx == 2)
rewrite_args->arg3 = std::move(emptyTupleConst);
if (varargs_idx >= 3)
rewrite_args->args.setAttr((varargs_idx - 3) * sizeof(Box*), std::move(emptyTupleConst));
}
Box* ovarargs = new BoxedTuple(std::move(unused_positional));
getArg(varargs_idx, oarg1, oarg2, oarg3, oargs) = ovarargs;
} else if (unused_positional.size()) {
raiseExcHelper(TypeError, "<function>() takes at most %d argument%s (%d given)", f->num_args,
(f->num_args == 1 ? "" : "s"), argspec.num_args + argspec.num_keywords + varargs.size());
}
////
// Second, apply any keywords:
BoxedDict* okwargs = NULL;
if (f->takes_kwargs) {
assert(!rewrite_args && "would need to be handled here");
okwargs = new BoxedDict();
getArg(f->num_args + (f->takes_varargs ? 1 : 0), oarg1, oarg2, oarg3, oargs) = okwargs;
}
const std::vector<AST_expr*>* arg_names = f->source ? f->source->arg_names.args : NULL;
if (arg_names == nullptr && argspec.num_keywords && !f->takes_kwargs) {
raiseExcHelper(TypeError, "<function @%p>() doesn't take keyword arguments", f->versions[0]->code);
}
if (argspec.num_keywords)
assert(argspec.num_keywords == keyword_names->size());
for (int i = 0; i < argspec.num_keywords; i++) {
assert(!rewrite_args && "would need to be handled here");
int arg_idx = i + argspec.num_args;
Box* kw_val = getArg(arg_idx, arg1, arg2, arg3, args);
if (!arg_names) {
assert(okwargs);
okwargs->d[boxStringPtr((*keyword_names)[i])] = kw_val;
continue;
}
assert(arg_names);
placeKeyword(*arg_names, params_filled, *(*keyword_names)[i], kw_val, oarg1, oarg2, oarg3, oargs, okwargs);
}
if (argspec.has_kwargs) {
assert(!rewrite_args && "would need to be handled here");
Box* kwargs
= getArg(argspec.num_args + argspec.num_keywords + (argspec.has_starargs ? 1 : 0), arg1, arg2, arg3, args);
RELEASE_ASSERT(kwargs->cls == dict_cls, "haven't implemented this for non-dicts");
BoxedDict* d_kwargs = static_cast<BoxedDict*>(kwargs);
for (auto& p : d_kwargs->d) {
if (p.first->cls != str_cls)
raiseExcHelper(TypeError, "<function>() keywords must be strings");
BoxedString* s = static_cast<BoxedString*>(p.first);
if (arg_names) {
placeKeyword(*arg_names, params_filled, s->s, p.second, oarg1, oarg2, oarg3, oargs, okwargs);
} else {
assert(okwargs);
Box*& v = okwargs->d[p.first];
if (v) {
raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'",
s->s.c_str());
}
v = p.second;
}
}
}
// Fill with defaults:
for (int i = 0; i < f->num_args - f->num_defaults; i++) {
if (params_filled[i])
continue;
// TODO not right error message
raiseExcHelper(TypeError, "<function>() did not get a value for positional argument %d", i);
}
RewriterVarUsage r_defaults_array(RewriterVarUsage::empty());
if (guard_clfunc) {
r_defaults_array = rewrite_args->obj.getAttr(offsetof(BoxedFunction, defaults),
RewriterVarUsage::KillFlag::Kill, Location::any());
}
for (int i = f->num_args - f->num_defaults; i < f->num_args; i++) {
if (params_filled[i])
continue;
int default_idx = i + f->num_defaults - f->num_args;
Box* default_obj = func->defaults->elts[default_idx];
if (rewrite_args) {
int offset = offsetof(std::remove_pointer<decltype(BoxedFunction::defaults)>::type, elts)
+ sizeof(Box*) * default_idx;
if (guard_clfunc) {
// If we just guarded on the CLFunction, then we have to emit assembly
// to fetch the values from the defaults array:
if (i < 3) {
RewriterVarUsage r_default
= r_defaults_array.getAttr(offset, RewriterVarUsage::KillFlag::NoKill, Location::forArg(i));
if (i == 0)
rewrite_args->arg1 = std::move(r_default);
if (i == 1)
rewrite_args->arg2 = std::move(r_default);
if (i == 2)
rewrite_args->arg3 = std::move(r_default);
} else {
RewriterVarUsage r_default
= r_defaults_array.getAttr(offset, RewriterVarUsage::KillFlag::Kill, Location::any());
rewrite_args->args.setAttr((i - 3) * sizeof(Box*), std::move(r_default));
}
} else {
// If we guarded on the BoxedFunction, which has a constant set of defaults,
// we can embed the default arguments directly into the instructions.
if (i < 3) {
RewriterVarUsage r_default
= rewrite_args->rewriter->loadConst((intptr_t)default_obj, Location::any());
if (i == 0)
rewrite_args->arg1 = std::move(r_default);
if (i == 1)
rewrite_args->arg2 = std::move(r_default);
if (i == 2)
rewrite_args->arg3 = std::move(r_default);
} else {
RewriterVarUsage r_default
= rewrite_args->rewriter->loadConst((intptr_t)default_obj, Location::any());
rewrite_args->args.setAttr((i - 3) * sizeof(Box*), std::move(r_default));
}
}
}
getArg(i, oarg1, oarg2, oarg3, oargs) = default_obj;
}
// special handling for generators:
// the call to function containing a yield should just create a new generator object.
Box* res;
if (func->isGenerator) {
res = createGenerator(func, oarg1, oarg2, oarg3, oargs);
} else {
res = callCLFunc(f, rewrite_args, num_output_args, closure, NULL, oarg1, oarg2, oarg3, oargs);
}
return res;
}
Box* callCLFunc(CLFunction* f, CallRewriteArgs* rewrite_args, int num_output_args, BoxedClosure* closure,
BoxedGenerator* generator, Box* oarg1, Box* oarg2, Box* oarg3, Box** oargs) {
CompiledFunction* chosen_cf = pickVersion(f, num_output_args, oarg1, oarg2, oarg3, oargs);
assert(chosen_cf->is_interpreted == (chosen_cf->code == NULL));
if (chosen_cf->is_interpreted) {
return interpretFunction(chosen_cf->func, num_output_args, closure, generator, oarg1, oarg2, oarg3, oargs);
}
if (rewrite_args) {
rewrite_args->rewriter->addDependenceOn(chosen_cf->dependent_callsites);
std::vector<RewriterVarUsage> arg_vec;
// TODO this kind of embedded reference needs to be tracked by the GC somehow?
// Or maybe it's ok, since we've guarded on the function object?
if (closure)
arg_vec.push_back(std::move(rewrite_args->rewriter->loadConst((intptr_t)closure, Location::forArg(0))));
if (num_output_args >= 1)
arg_vec.push_back(std::move(rewrite_args->arg1));
if (num_output_args >= 2)
arg_vec.push_back(std::move(rewrite_args->arg2));
if (num_output_args >= 3)
arg_vec.push_back(std::move(rewrite_args->arg3));
if (num_output_args >= 4)
arg_vec.push_back(std::move(rewrite_args->args));
rewrite_args->out_rtn = rewrite_args->rewriter->call(true, (void*)chosen_cf->call, std::move(arg_vec));
rewrite_args->out_success = true;
}
if (closure && generator)
return chosen_cf->closure_generator_call(closure, generator, oarg1, oarg2, oarg3, oargs);
else if (closure)
return chosen_cf->closure_call(closure, oarg1, oarg2, oarg3, oargs);
else if (generator)
return chosen_cf->generator_call(generator, oarg1, oarg2, oarg3, oargs);
else
return chosen_cf->call(oarg1, oarg2, oarg3, oargs);
}
Box* runtimeCallInternal(Box* obj, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3,
Box** args, const std::vector<const std::string*>* keyword_names) {
int npassed_args = argspec.totalPassed();
if (obj->cls != function_cls && obj->cls != instancemethod_cls) {
Box* rtn;
if (rewrite_args) {
// TODO is this ok?
// rewrite_args->rewriter->trap();
rtn = callattrInternal(obj, &_call_str, CLASS_ONLY, rewrite_args, argspec, arg1, arg2, arg3, args,
keyword_names);
} else {
rtn = callattrInternal(obj, &_call_str, CLASS_ONLY, NULL, argspec, arg1, arg2, arg3, args, keyword_names);
}
if (!rtn)
raiseExcHelper(TypeError, "'%s' object is not callable", getTypeName(obj)->c_str());
return rtn;
}
if (rewrite_args) {
if (!rewrite_args->args_guarded) {
// TODO should know which args don't need to be guarded, ex if we're guaranteed that they
// already fit, either since the type inferencer could determine that,
// or because they only need to fit into an UNKNOWN slot.
if (npassed_args >= 1)
rewrite_args->arg1.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg1->cls);
if (npassed_args >= 2)
rewrite_args->arg2.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg2->cls);
if (npassed_args >= 3)
rewrite_args->arg3.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg3->cls);
for (int i = 3; i < npassed_args; i++) {
RewriterVarUsage v = rewrite_args->args.getAttr((i - 3) * sizeof(Box*),
RewriterVarUsage::KillFlag::NoKill, Location::any());
v.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)args[i - 3]->cls);
v.setDoneUsing();
}
rewrite_args->args_guarded = true;
}
rewrite_args->rewriter->addDecision(obj->cls == function_cls ? 1 : 0);
}
if (obj->cls == function_cls) {
BoxedFunction* f = static_cast<BoxedFunction*>(obj);
// Some functions are sufficiently important that we want them to be able to patchpoint themselves;
// they can do this by setting the "internal_callable" field:
CLFunction::InternalCallable callable = f->f->internal_callable;
if (callable == NULL) {
callable = callFunc;
}
Box* res = callable(f, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names);
return res;
} else if (obj->cls == instancemethod_cls) {
// TODO it's dumb but I should implement patchpoints here as well
// duplicated with callattr
BoxedInstanceMethod* im = static_cast<BoxedInstanceMethod*>(obj);
if (rewrite_args && !rewrite_args->func_guarded) {
rewrite_args->obj.addAttrGuard(INSTANCEMETHOD_FUNC_OFFSET, (intptr_t)im->func);
}
// Guard on which type of instancemethod (bound or unbound)
// That is, if im->obj is NULL, guard on it being NULL
// otherwise, guard on it being non-NULL
if (rewrite_args) {
rewrite_args->obj.addAttrGuard(INSTANCEMETHOD_OBJ_OFFSET, 0, im->obj != NULL);
}
// TODO guard on im->obj being NULL or not
if (im->obj == NULL) {
Box* f = im->func;
if (rewrite_args) {
rewrite_args->func_guarded = true;
rewrite_args->args_guarded = true;
rewrite_args->obj
= rewrite_args->obj.getAttr(INSTANCEMETHOD_FUNC_OFFSET, RewriterVarUsage::Kill, Location::any());
}
Box* res = runtimeCallInternal(f, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names);
return res;
}
if (npassed_args <= 2) {
Box* rtn;
if (rewrite_args) {
// Kind of weird that we don't need to give this a valid RewriterVar, but it shouldn't need to access it
// (since we've already guarded on the function).
// rewriter enforce that we give it one, though
CallRewriteArgs srewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(),
rewrite_args->destination, rewrite_args->call_done_guarding);
srewrite_args.arg1 = rewrite_args->obj.getAttr(INSTANCEMETHOD_OBJ_OFFSET,
RewriterVarUsage::KillFlag::Kill, Location::any());
srewrite_args.func_guarded = true;
srewrite_args.args_guarded = true;
if (npassed_args >= 1)
srewrite_args.arg2 = std::move(rewrite_args->arg1);
if (npassed_args >= 2)
srewrite_args.arg3 = std::move(rewrite_args->arg2);
rtn = runtimeCallInternal(
im->func, &srewrite_args,
ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs),
im->obj, arg1, arg2, NULL, keyword_names);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->out_rtn = std::move(srewrite_args.out_rtn);
}
} else {
rtn = runtimeCallInternal(im->func, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords,
argspec.has_starargs, argspec.has_kwargs),
im->obj, arg1, arg2, NULL, keyword_names);
}
if (rewrite_args)
rewrite_args->out_success = true;
return rtn;
} else {
Box** new_args = (Box**)alloca(sizeof(Box*) * (npassed_args + 1 - 3));
new_args[0] = arg3;
memcpy(new_args + 1, args, (npassed_args - 3) * sizeof(Box*));
Box* rtn = runtimeCall(im->func, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords,
argspec.has_starargs, argspec.has_kwargs),
im->obj, arg1, arg2, new_args, keyword_names);
return rtn;
}
}
assert(0);
abort();
}
extern "C" Box* runtimeCall(Box* obj, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args,
const std::vector<const std::string*>* keyword_names) {
int npassed_args = argspec.totalPassed();
static StatCounter slowpath_runtimecall("slowpath_runtimecall");
slowpath_runtimecall.log();
int num_orig_args = 2 + std::min(4, npassed_args);
if (argspec.num_keywords > 0) {
assert(argspec.num_keywords == keyword_names->size());
num_orig_args++;
}
std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter(
__builtin_extract_return_addr(__builtin_return_address(0)), num_orig_args, "runtimeCall"));
Box* rtn;
if (rewriter.get()) {
// TODO feel weird about doing this; it either isn't necessary
// or this kind of thing is necessary in a lot more places
// rewriter->getArg(1).addGuard(npassed_args);
CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(),
true);
if (npassed_args >= 1)
rewrite_args.arg1 = std::move(rewriter->getArg(2));
if (npassed_args >= 2)
rewrite_args.arg2 = std::move(rewriter->getArg(3));
if (npassed_args >= 3)
rewrite_args.arg3 = std::move(rewriter->getArg(4));
if (npassed_args >= 4)
rewrite_args.args = std::move(rewriter->getArg(5));
rtn = runtimeCallInternal(obj, &rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else if (rtn) {
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
}
} else {
rtn = runtimeCallInternal(obj, NULL, argspec, arg1, arg2, arg3, args, keyword_names);
}
assert(rtn);
return rtn;
}
extern "C" Box* binopInternal(Box* lhs, Box* rhs, int op_type, bool inplace, BinopRewriteArgs* rewrite_args) {
// TODO handle the case of the rhs being a subclass of the lhs
// this could get really annoying because you can dynamically make one type a subclass
// of the other!
if (rewrite_args) {
// TODO probably don't need to guard on the lhs_cls since it
// will get checked no matter what, but the check that should be
// removed is probably the later one.
// ie we should have some way of specifying what we know about the values
// of objects and their attributes, and the attributes' attributes.
rewrite_args->lhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)lhs->cls);
rewrite_args->rhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)rhs->cls);
}
Box* irtn = NULL;
if (inplace) {
std::string iop_name = getInplaceOpName(op_type);
if (rewrite_args) {
CallRewriteArgs srewrite_args(rewrite_args->rewriter, rewrite_args->lhs.addUse(), rewrite_args->destination,
rewrite_args->call_done_guarding);
srewrite_args.arg1 = rewrite_args->rhs.addUse();
srewrite_args.args_guarded = true;
irtn = callattrInternal1(lhs, &iop_name, CLASS_ONLY, &srewrite_args, ArgPassSpec(1), rhs);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else if (irtn) {
if (irtn == NotImplemented)
srewrite_args.out_rtn.ensureDoneUsing();
else
rewrite_args->out_rtn = std::move(srewrite_args.out_rtn);
}
} else {
irtn = callattrInternal1(lhs, &iop_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs);
}
if (irtn) {
if (irtn != NotImplemented) {
if (rewrite_args) {
rewrite_args->lhs.setDoneUsing();
rewrite_args->rhs.setDoneUsing();
rewrite_args->out_success = true;
}
return irtn;
}
}
}
const std::string& op_name = getOpName(op_type);
Box* lrtn;
if (rewrite_args) {
CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(rewrite_args->lhs), rewrite_args->destination,
rewrite_args->call_done_guarding);
srewrite_args.arg1 = std::move(rewrite_args->rhs);
lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, &srewrite_args, ArgPassSpec(1), rhs);
if (!srewrite_args.out_success)
rewrite_args = NULL;
else if (lrtn) {
if (lrtn == NotImplemented)
srewrite_args.out_rtn.ensureDoneUsing();
else
rewrite_args->out_rtn = std::move(srewrite_args.out_rtn);
}
} else {
lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs);
}
if (lrtn) {
if (lrtn != NotImplemented) {
if (rewrite_args) {
rewrite_args->out_success = true;
}
return lrtn;
}
}
// TODO patch these cases
if (rewrite_args) {
assert(rewrite_args->out_success == false);
rewrite_args = NULL;
}
std::string rop_name = getReverseOpName(op_type);
Box* rrtn = callattrInternal1(rhs, &rop_name, CLASS_ONLY, NULL, ArgPassSpec(1), lhs);
if (rrtn != NULL && rrtn != NotImplemented)
return rrtn;
llvm::StringRef op_sym = getOpSymbol(op_type);
const char* op_sym_suffix = "";
if (inplace) {
op_sym_suffix = "=";
}
if (VERBOSITY()) {
if (inplace) {
std::string iop_name = getInplaceOpName(op_type);
if (irtn)
fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(lhs)->c_str(),
iop_name.c_str());
else
fprintf(stderr, "%s does not have %s\n", getTypeName(lhs)->c_str(), iop_name.c_str());
}
if (lrtn)
fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(lhs)->c_str(), op_name.c_str());
else
fprintf(stderr, "%s does not have %s\n", getTypeName(lhs)->c_str(), op_name.c_str());
if (rrtn)
fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(rhs)->c_str(), rop_name.c_str());
else
fprintf(stderr, "%s does not have %s\n", getTypeName(rhs)->c_str(), rop_name.c_str());
}
raiseExcHelper(TypeError, "unsupported operand type(s) for %s%s: '%s' and '%s'", op_sym.data(), op_sym_suffix,
getTypeName(lhs)->c_str(), getTypeName(rhs)->c_str());
}
extern "C" Box* binop(Box* lhs, Box* rhs, int op_type) {
static StatCounter slowpath_binop("slowpath_binop");
slowpath_binop.log();
// static StatCounter nopatch_binop("nopatch_binop");
// int id = Stats::getStatId("slowpath_binop_" + *getTypeName(lhs) + op_name + *getTypeName(rhs));
// Stats::log(id);
std::unique_ptr<Rewriter> rewriter((Rewriter*)NULL);
// Currently can't patchpoint user-defined binops since we can't assume that just because
// resolving it one way right now (ex, using the value from lhs.__add__) means that later
// we'll resolve it the same way, even for the same argument types.
// TODO implement full resolving semantics inside the rewrite?
bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls);
if (can_patchpoint)
rewriter.reset(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "binop"));
Box* rtn;
if (rewriter.get()) {
// rewriter->trap();
BinopRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(1),
rewriter->getReturnDestination(), true);
rtn = binopInternal(lhs, rhs, op_type, false, &rewrite_args);
assert(rtn);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
} else {
rtn = binopInternal(lhs, rhs, op_type, false, NULL);
}
return rtn;
}
extern "C" Box* augbinop(Box* lhs, Box* rhs, int op_type) {
static StatCounter slowpath_binop("slowpath_binop");
slowpath_binop.log();
// static StatCounter nopatch_binop("nopatch_binop");
// int id = Stats::getStatId("slowpath_binop_" + *getTypeName(lhs) + op_name + *getTypeName(rhs));
// Stats::log(id);
std::unique_ptr<Rewriter> rewriter((Rewriter*)NULL);
// Currently can't patchpoint user-defined binops since we can't assume that just because
// resolving it one way right now (ex, using the value from lhs.__add__) means that later
// we'll resolve it the same way, even for the same argument types.
// TODO implement full resolving semantics inside the rewrite?
bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls);
if (can_patchpoint)
rewriter.reset(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "binop"));
Box* rtn;
if (rewriter.get()) {
BinopRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(1),
rewriter->getReturnDestination(), true);
rtn = binopInternal(lhs, rhs, op_type, true, &rewrite_args);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else {
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
}
} else {
rtn = binopInternal(lhs, rhs, op_type, true, NULL);
}
return rtn;
}
Box* compareInternal(Box* lhs, Box* rhs, int op_type, CompareRewriteArgs* rewrite_args) {
if (op_type == AST_TYPE::Is || op_type == AST_TYPE::IsNot) {
bool neg = (op_type == AST_TYPE::IsNot);
if (rewrite_args) {
rewrite_args->rewriter->setDoneGuarding();
RewriterVarUsage cmpres = rewrite_args->lhs.cmp(neg ? AST_TYPE::NotEq : AST_TYPE::Eq,
std::move(rewrite_args->rhs), rewrite_args->destination);
rewrite_args->lhs.setDoneUsing();
rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxBool, std::move(cmpres));
rewrite_args->out_success = true;
}
return boxBool((lhs == rhs) ^ neg);
}
if (op_type == AST_TYPE::In || op_type == AST_TYPE::NotIn) {
// TODO do rewrite
static const std::string str_contains("__contains__");
Box* contained = callattrInternal1(rhs, &str_contains, CLASS_ONLY, NULL, ArgPassSpec(1), lhs);
if (contained == NULL) {
static const std::string str_iter("__iter__");
Box* iter = callattrInternal0(rhs, &str_iter, CLASS_ONLY, NULL, ArgPassSpec(0));
if (iter)
ASSERT(isUserDefined(rhs->cls), "%s should probably have a __contains__", getTypeName(rhs)->c_str());
RELEASE_ASSERT(iter == NULL, "need to try iterating");
Box* getitem = typeLookup(rhs->cls, "__getitem__", NULL);
if (getitem)
ASSERT(isUserDefined(rhs->cls), "%s should probably have a __contains__", getTypeName(rhs)->c_str());
RELEASE_ASSERT(getitem == NULL, "need to try old iteration protocol");
raiseExcHelper(TypeError, "argument of type '%s' is not iterable", getTypeName(rhs)->c_str());
}
bool b = nonzero(contained);
if (op_type == AST_TYPE::NotIn)
return boxBool(!b);
return boxBool(b);
}
// Can do the guard checks after the Is/IsNot handling, since that is
// irrespective of the object classes
if (rewrite_args) {
// TODO probably don't need to guard on the lhs_cls since it
// will get checked no matter what, but the check that should be
// removed is probably the later one.
// ie we should have some way of specifying what we know about the values
// of objects and their attributes, and the attributes' attributes.
rewrite_args->lhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)lhs->cls);
rewrite_args->rhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)rhs->cls);
}
const std::string& op_name = getOpName(op_type);
Box* lrtn;
if (rewrite_args) {
CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(rewrite_args->lhs), rewrite_args->destination,
rewrite_args->call_done_guarding);
crewrite_args.arg1 = std::move(rewrite_args->rhs);
lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, &crewrite_args, ArgPassSpec(1), rhs);
if (!crewrite_args.out_success)
rewrite_args = NULL;
else if (lrtn)
rewrite_args->out_rtn = std::move(crewrite_args.out_rtn);
} else {
lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs);
}
if (lrtn) {
if (lrtn != NotImplemented) {
bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls);
if (rewrite_args) {
if (can_patchpoint) {
rewrite_args->out_success = true;
} else {
rewrite_args->out_rtn.ensureDoneUsing();
}
}
return lrtn;
}
}
// TODO patch these cases
if (rewrite_args) {
rewrite_args->out_rtn.ensureDoneUsing();
assert(rewrite_args->out_success == false);
rewrite_args = NULL;
}
std::string rop_name = getReverseOpName(op_type);
Box* rrtn = callattrInternal1(rhs, &rop_name, CLASS_ONLY, NULL, ArgPassSpec(1), lhs);
if (rrtn != NULL && rrtn != NotImplemented)
return rrtn;
if (op_type == AST_TYPE::Eq)
return boxBool(lhs == rhs);
if (op_type == AST_TYPE::NotEq)
return boxBool(lhs != rhs);
#ifndef NDEBUG
if ((lhs->cls == int_cls || lhs->cls == float_cls || lhs->cls == long_cls)
&& (rhs->cls == int_cls || rhs->cls == float_cls || rhs->cls == long_cls)) {
Py_FatalError("missing comparison between these classes");
}
#endif
// TODO
// According to http://docs.python.org/2/library/stdtypes.html#comparisons
// CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects
// of the same types that don’t support proper comparison are ordered by their address.
if (op_type == AST_TYPE::Gt || op_type == AST_TYPE::GtE || op_type == AST_TYPE::Lt || op_type == AST_TYPE::LtE) {
intptr_t cmp1, cmp2;
if (lhs->cls == rhs->cls) {
cmp1 = (intptr_t)lhs;
cmp2 = (intptr_t)rhs;
} else {
// This isn't really necessary, but try to make sure that numbers get sorted first
if (lhs->cls == int_cls || lhs->cls == float_cls)
cmp1 = 0;
else
cmp1 = (intptr_t)lhs->cls;
if (rhs->cls == int_cls || rhs->cls == float_cls)
cmp2 = 0;
else
cmp2 = (intptr_t)rhs->cls;
}
if (op_type == AST_TYPE::Gt)
return boxBool(cmp1 > cmp2);
if (op_type == AST_TYPE::GtE)
return boxBool(cmp1 >= cmp2);
if (op_type == AST_TYPE::Lt)
return boxBool(cmp1 < cmp2);
if (op_type == AST_TYPE::LtE)
return boxBool(cmp1 <= cmp2);
}
RELEASE_ASSERT(0, "%d", op_type);
}
extern "C" Box* compare(Box* lhs, Box* rhs, int op_type) {
static StatCounter slowpath_compare("slowpath_compare");
slowpath_compare.log();
static StatCounter nopatch_compare("nopatch_compare");
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "compare"));
Box* rtn;
if (rewriter.get()) {
// rewriter->trap();
CompareRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), std::move(rewriter->getArg(1)),
rewriter->getReturnDestination(), true);
rtn = compareInternal(lhs, rhs, op_type, &rewrite_args);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
} else {
rtn = compareInternal(lhs, rhs, op_type, NULL);
}
return rtn;
}
extern "C" Box* unaryop(Box* operand, int op_type) {
static StatCounter slowpath_unaryop("slowpath_unaryop");
slowpath_unaryop.log();
const std::string& op_name = getOpName(op_type);
Box* attr_func = getclsattr_internal(operand, op_name, NULL);
ASSERT(attr_func, "%s.%s", getTypeName(operand)->c_str(), op_name.c_str());
Box* rtn = runtimeCall0(attr_func, ArgPassSpec(0));
return rtn;
}
extern "C" Box* getitem(Box* value, Box* slice) {
// This possibly could just be represented as a single callattr; the only tricky part
// are the error messages.
// Ex "(1)[1]" and "(1).__getitem__(1)" give different error messages.
static StatCounter slowpath_getitem("slowpath_getitem");
slowpath_getitem.log();
static std::string str_getitem("__getitem__");
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getitem"));
Box* rtn;
if (rewriter.get()) {
CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(),
true);
rewrite_args.arg1 = std::move(rewriter->getArg(1));
rtn = callattrInternal1(value, &str_getitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(1), slice);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else if (rtn)
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
} else {
rtn = callattrInternal1(value, &str_getitem, CLASS_ONLY, NULL, ArgPassSpec(1), slice);
}
if (rtn == NULL) {
// different versions of python give different error messages for this:
if (PYTHON_VERSION_MAJOR == 2 && PYTHON_VERSION_MINOR < 7) {
raiseExcHelper(TypeError, "'%s' object is unsubscriptable", getTypeName(value)->c_str()); // tested on 2.6.6
} else if (PYTHON_VERSION_MAJOR == 2 && PYTHON_VERSION_MINOR == 7 && PYTHON_VERSION_MICRO < 3) {
raiseExcHelper(TypeError, "'%s' object is not subscriptable",
getTypeName(value)->c_str()); // tested on 2.7.1
} else {
// Changed to this in 2.7.3:
raiseExcHelper(TypeError, "'%s' object has no attribute '__getitem__'",
getTypeName(value)->c_str()); // tested on 2.7.3
}
}
return rtn;
}
// target[slice] = value
extern "C" void setitem(Box* target, Box* slice, Box* value) {
static StatCounter slowpath_setitem("slowpath_setitem");
slowpath_setitem.log();
static std::string str_setitem("__setitem__");
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "setitem"));
Box* rtn;
if (rewriter.get()) {
CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(),
true);
rewrite_args.arg1 = std::move(rewriter->getArg(1));
rewrite_args.arg2 = std::move(rewriter->getArg(2));
rtn = callattrInternal2(target, &str_setitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(2), slice, value);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else if (rtn)
rewrite_args.out_rtn.setDoneUsing();
} else {
rtn = callattrInternal2(target, &str_setitem, CLASS_ONLY, NULL, ArgPassSpec(2), slice, value);
}
if (rtn == NULL) {
raiseExcHelper(TypeError, "'%s' object does not support item assignment", getTypeName(target)->c_str());
}
if (rewriter.get()) {
rewriter->commit();
}
}
// del target[start:end:step]
extern "C" void delitem(Box* target, Box* slice) {
static StatCounter slowpath_delitem("slowpath_delitem");
slowpath_delitem.log();
static std::string str_delitem("__delitem__");
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "delitem"));
Box* rtn;
if (rewriter.get()) {
CallRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true);
rewrite_args.arg1 = std::move(rewriter->getArg(1));
rtn = callattrInternal1(target, &str_delitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(1), slice);
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
} else if (rtn != NULL) {
rewrite_args.out_rtn.setDoneUsing();
}
} else {
rtn = callattrInternal1(target, &str_delitem, CLASS_ONLY, NULL, ArgPassSpec(1), slice);
}
if (rtn == NULL) {
raiseExcHelper(TypeError, "'%s' object does not support item deletion", getTypeName(target)->c_str());
}
if (rewriter.get()) {
rewriter->commit();
}
}
void Box::delattr(const std::string& attr, DelattrRewriteArgs* rewrite_args) {
// as soon as the hcls changes, the guard on hidden class won't pass.
HCAttrs* attrs = getAttrsPtr();
HiddenClass* hcls = attrs->hcls;
HiddenClass* new_hcls = hcls->delAttrToMakeHC(attr);
// The order of attributes is pertained as delAttrToMakeHC constructs
// the new HiddenClass by invoking getOrMakeChild in the prevous order
// of remaining attributes
int num_attrs = hcls->attr_offsets.size();
int offset = hcls->getOffset(attr);
assert(offset >= 0);
Box** start = attrs->attr_list->attrs;
memmove(start + offset, start + offset + 1, (num_attrs - offset - 1) * sizeof(Box*));
attrs->hcls = new_hcls;
// guarantee the size of the attr_list equals the number of attrs
int new_size = sizeof(HCAttrs::AttrList) + sizeof(Box*) * (num_attrs - 1);
attrs->attr_list = (HCAttrs::AttrList*)gc::gc_realloc(attrs->attr_list, new_size);
}
extern "C" void delattr_internal(Box* obj, const std::string& attr, bool allow_custom,
DelattrRewriteArgs* rewrite_args) {
static const std::string delattr_str("__delattr__");
static const std::string delete_str("__delete__");
// custom __delattr__
if (allow_custom) {
Box* delAttr = typeLookup(obj->cls, delattr_str, NULL);
if (delAttr != NULL) {
Box* boxstr = boxString(attr);
Box* rtn = runtimeCall2(delAttr, ArgPassSpec(2), obj, boxstr);
return;
}
}
// first check whether the deleting attribute is a descriptor
Box* clsAttr = typeLookup(obj->cls, attr, NULL);
if (clsAttr != NULL) {
Box* delAttr = typeLookup(static_cast<BoxedClass*>(clsAttr->cls), delete_str, NULL);
if (delAttr != NULL) {
Box* boxstr = boxString(attr);
Box* rtn = runtimeCall2(delAttr, ArgPassSpec(2), clsAttr, obj);
return;
}
}
// check if the attribute is in the instance's __dict__
Box* attrVal = obj->getattr(attr, NULL);
if (attrVal != NULL) {
obj->delattr(attr, NULL);
} else {
// the exception cpthon throws is different when the class contains the attribute
if (clsAttr != NULL) {
raiseExcHelper(AttributeError, "'%s' object attribute '%s' is read-only", getTypeName(obj)->c_str(),
attr.c_str());
} else {
raiseAttributeError(obj, attr.c_str());
}
}
}
// del target.attr
extern "C" void delattr(Box* obj, const char* attr) {
static StatCounter slowpath_delattr("slowpath_delattr");
slowpath_delattr.log();
if (obj->cls == type_cls) {
BoxedClass* cobj = static_cast<BoxedClass*>(obj);
if (!isUserDefined(cobj)) {
raiseExcHelper(TypeError, "can't set attributes of built-in/extension type '%s'\n",
getNameOfClass(cobj)->c_str());
}
}
delattr_internal(obj, attr, true, NULL);
}
extern "C" Box* getiter(Box* o) {
// TODO add rewriting to this? probably want to try to avoid this path though
static const std::string iter_str("__iter__");
Box* r = callattrInternal0(o, &iter_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(0));
if (r)
return r;
static const std::string getitem_str("__getitem__");
if (typeLookup(o->cls, getitem_str, NULL)) {
return new BoxedSeqIter(o);
}
raiseExcHelper(TypeError, "'%s' object is not iterable", getTypeName(o)->c_str());
}
llvm::iterator_range<BoxIterator> Box::pyElements() {
Box* iter = getiter(this);
assert(iter);
return llvm::iterator_range<BoxIterator>(++BoxIterator(iter), BoxIterator(nullptr));
}
// For use on __init__ return values
static void assertInitNone(Box* obj) {
if (obj != None) {
raiseExcHelper(TypeError, "__init__() should return None, not '%s'", getTypeName(obj)->c_str());
}
}
Box* typeNew(Box* _cls, Box* arg1, Box* arg2, Box** _args) {
Box* arg3 = _args[0];
if (!isSubclass(_cls->cls, type_cls))
raiseExcHelper(TypeError, "type.__new__(X): X is not a type object (%s)", getTypeName(_cls)->c_str());
BoxedClass* cls = static_cast<BoxedClass*>(_cls);
if (!isSubclass(cls, type_cls))
raiseExcHelper(TypeError, "type.__new__(%s): %s is not a subtype of type", getNameOfClass(cls)->c_str(),
getNameOfClass(cls)->c_str());
if (arg2 == NULL) {
assert(arg3 == NULL);
BoxedClass* rtn = arg1->cls;
return rtn;
}
RELEASE_ASSERT(arg3->cls == dict_cls, "%s", getTypeName(arg3)->c_str());
BoxedDict* attr_dict = static_cast<BoxedDict*>(arg3);
RELEASE_ASSERT(arg2->cls == tuple_cls, "");
BoxedTuple* bases = static_cast<BoxedTuple*>(arg2);
RELEASE_ASSERT(arg1->cls == str_cls, "");
BoxedString* name = static_cast<BoxedString*>(arg1);
BoxedClass* base;
if (bases->elts.size() == 0) {
bases = new BoxedTuple({ object_cls });
}
RELEASE_ASSERT(bases->elts.size() == 1, "");
Box* _base = bases->elts[0];
RELEASE_ASSERT(_base->cls == type_cls, "");
base = static_cast<BoxedClass*>(_base);
BoxedClass* made;
if (base->instancesHaveAttrs()) {
made = new BoxedClass(cls, base, NULL, base->attrs_offset, base->tp_basicsize, true);
} else {
assert(base->tp_basicsize % sizeof(void*) == 0);
made = new BoxedClass(cls, base, NULL, base->tp_basicsize, base->tp_basicsize + sizeof(HCAttrs), true);
}
made->giveAttr("__module__", boxString(getCurrentModule()->name()));
made->giveAttr("__doc__", None);
for (const auto& p : attr_dict->d) {
assert(p.first->cls == str_cls);
made->setattr(static_cast<BoxedString*>(p.first)->s, p.second, NULL);
}
// Note: make sure to do this after assigning the attrs, since it will overwrite any defined __name__
made->setattr("__name__", name, NULL);
// TODO this function (typeNew) should probably call PyType_Ready
made->tp_new = base->tp_new;
made->tp_alloc = reinterpret_cast<decltype(cls->tp_alloc)>(PyType_GenericAlloc);
return made;
}
Box* typeCallInternal(BoxedFunction* f, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2,
Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) {
int npassed_args = argspec.totalPassed();
static StatCounter slowpath_typecall("slowpath_typecall");
slowpath_typecall.log();
// TODO shouldn't have to redo this argument handling here...
if (argspec.has_starargs) {
rewrite_args = NULL;
assert(argspec.num_args == 0); // doesn't need to be true, but assumed here
Box* starargs = arg1;
assert(starargs->cls == tuple_cls);
BoxedTuple* targs = static_cast<BoxedTuple*>(starargs);
int n = targs->elts.size();
if (n >= 1)
arg1 = targs->elts[0];
if (n >= 2)
arg2 = targs->elts[1];
if (n >= 3)
arg3 = targs->elts[2];
if (n >= 4)
args = &targs->elts[3];
argspec = ArgPassSpec(n);
}
Box* _cls = arg1;
RewriterVarUsage r_ccls(RewriterVarUsage::empty());
RewriterVarUsage r_new(RewriterVarUsage::empty());
RewriterVarUsage r_init(RewriterVarUsage::empty());
Box* new_attr, *init_attr;
if (rewrite_args) {
assert(!argspec.has_starargs);
assert(argspec.num_args > 0);
rewrite_args->obj.setDoneUsing();
// rewrite_args->rewriter->annotate(0);
// rewrite_args->rewriter->trap();
r_ccls = std::move(rewrite_args->arg1);
// This is probably a duplicate, but it's hard to really convince myself of that.
// Need to create a clear contract of who guards on what
r_ccls.addGuard((intptr_t)arg1);
}
if (!isSubclass(_cls->cls, type_cls)) {
raiseExcHelper(TypeError, "descriptor '__call__' requires a 'type' object but received an '%s'",
getTypeName(_cls)->c_str());
}
BoxedClass* cls = static_cast<BoxedClass*>(_cls);
if (rewrite_args) {
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_ccls.addUse(), rewrite_args->destination, false);
// TODO: if tp_new != Py_CallPythonNew, call that instead?
new_attr = typeLookup(cls, _new_str, &grewrite_args);
if (!grewrite_args.out_success)
rewrite_args = NULL;
else {
assert(new_attr);
r_new = std::move(grewrite_args.out_rtn);
r_new.addGuard((intptr_t)new_attr);
}
// Special-case functions to allow them to still rewrite:
if (new_attr->cls != function_cls) {
Box* descr_r = processDescriptorOrNull(new_attr, None, cls);
if (descr_r) {
new_attr = descr_r;
rewrite_args = NULL;
}
}
} else {
new_attr = typeLookup(cls, _new_str, NULL);
new_attr = processDescriptor(new_attr, None, cls);
}
assert(new_attr && "This should always resolve");
if (rewrite_args) {
GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_ccls.addUse(), rewrite_args->destination, false);
init_attr = typeLookup(cls, _init_str, &grewrite_args);
if (!grewrite_args.out_success)
rewrite_args = NULL;
else {
if (init_attr) {
r_init = std::move(grewrite_args.out_rtn);
r_init.addGuard((intptr_t)init_attr);
}
}
} else {
init_attr = typeLookup(cls, _init_str, NULL);
}
// The init_attr should always resolve as well, but doesn't yet
Box* made;
RewriterVarUsage r_made(RewriterVarUsage::empty());
ArgPassSpec new_argspec = argspec;
if (npassed_args > 1 && new_attr == typeLookup(object_cls, _new_str, NULL)) {
if (init_attr == typeLookup(object_cls, _init_str, NULL)) {
raiseExcHelper(TypeError, objectNewParameterTypeErrorMsg());
} else {
new_argspec = ArgPassSpec(1);
}
}
if (rewrite_args) {
CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_new), rewrite_args->destination,
rewrite_args->call_done_guarding);
int new_npassed_args = new_argspec.totalPassed();
if (new_npassed_args >= 1)
srewrite_args.arg1 = std::move(r_ccls);
if (new_npassed_args >= 2)
srewrite_args.arg2 = rewrite_args->arg2.addUse();
if (new_npassed_args >= 3)
srewrite_args.arg3 = rewrite_args->arg3.addUse();
if (new_npassed_args >= 4)
srewrite_args.args = rewrite_args->args.addUse();
srewrite_args.args_guarded = true;
srewrite_args.func_guarded = true;
made = runtimeCallInternal(new_attr, &srewrite_args, new_argspec, cls, arg2, arg3, args, keyword_names);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else {
assert(rewrite_args->rewriter->isDoneGuarding());
r_made = std::move(srewrite_args.out_rtn);
}
} else {
made = runtimeCallInternal(new_attr, NULL, new_argspec, cls, arg2, arg3, args, keyword_names);
}
assert(made);
// Special-case (also a special case in CPython): if we just called type.__new__(arg), don't call __init__
if (cls == type_cls && argspec == ArgPassSpec(2))
return made;
// If this is true, not supposed to call __init__:
RELEASE_ASSERT(made->cls == cls, "allowed but unsupported (%s vs %s)", getNameOfClass(made->cls)->c_str(),
getNameOfClass(cls)->c_str());
if (init_attr && init_attr != typeLookup(object_cls, _init_str, NULL)) {
// TODO apply the same descriptor special-casing as in callattr?
Box* initrtn;
// Attempt to rewrite the basic case:
if (rewrite_args && init_attr->cls == function_cls) {
// Note: this code path includes the descriptor logic
CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_init), rewrite_args->destination, false);
if (npassed_args >= 1)
srewrite_args.arg1 = r_made.addUse();
if (npassed_args >= 2)
srewrite_args.arg2 = std::move(rewrite_args->arg2);
if (npassed_args >= 3)
srewrite_args.arg3 = std::move(rewrite_args->arg3);
if (npassed_args >= 4)
srewrite_args.args = std::move(rewrite_args->args);
srewrite_args.args_guarded = true;
srewrite_args.func_guarded = true;
// initrtn = callattrInternal(cls, &_init_str, INST_ONLY, &srewrite_args, argspec, made, arg2, arg3, args,
// keyword_names);
initrtn = runtimeCallInternal(init_attr, &srewrite_args, argspec, made, arg2, arg3, args, keyword_names);
if (!srewrite_args.out_success) {
rewrite_args = NULL;
} else {
rewrite_args->rewriter->call(false, (void*)assertInitNone, std::move(srewrite_args.out_rtn))
.setDoneUsing();
}
} else {
init_attr = processDescriptor(init_attr, made, cls);
ArgPassSpec init_argspec = argspec;
init_argspec.num_args--;
int passed = init_argspec.totalPassed();
// If we weren't passed the args array, it's not safe to index into it
if (passed <= 2)
initrtn = runtimeCallInternal(init_attr, NULL, init_argspec, arg2, arg3, NULL, NULL, keyword_names);
else
initrtn
= runtimeCallInternal(init_attr, NULL, init_argspec, arg2, arg3, args[0], &args[1], keyword_names);
}
assertInitNone(initrtn);
} else {
if (new_attr == NULL && npassed_args != 1) {
// TODO not npassed args, since the starargs or kwargs could be null
raiseExcHelper(TypeError, objectNewParameterTypeErrorMsg());
}
}
if (rewrite_args) {
rewrite_args->out_rtn = std::move(r_made);
rewrite_args->out_success = true;
}
// Some of these might still be in use if rewrite_args was set to NULL
r_init.ensureDoneUsing();
r_ccls.ensureDoneUsing();
r_made.ensureDoneUsing();
r_init.ensureDoneUsing();
if (rewrite_args) {
rewrite_args->arg2.ensureDoneUsing();
rewrite_args->arg3.ensureDoneUsing();
rewrite_args->args.ensureDoneUsing();
}
return made;
}
Box* typeCall(Box* obj, BoxedList* vararg) {
assert(vararg->cls == list_cls);
if (vararg->size == 0)
return typeCallInternal1(NULL, NULL, ArgPassSpec(1), obj);
else if (vararg->size == 1)
return typeCallInternal2(NULL, NULL, ArgPassSpec(2), obj, vararg->elts->elts[0]);
else if (vararg->size == 2)
return typeCallInternal3(NULL, NULL, ArgPassSpec(3), obj, vararg->elts->elts[0], vararg->elts->elts[1]);
else
abort();
}
extern "C" void delGlobal(BoxedModule* m, std::string* name) {
if (!m->getattr(*name)) {
raiseExcHelper(NameError, "name '%s' is not defined", name->c_str());
}
m->delattr(*name, NULL);
}
extern "C" Box* getGlobal(BoxedModule* m, std::string* name) {
static StatCounter slowpath_getglobal("slowpath_getglobal");
slowpath_getglobal.log();
static StatCounter nopatch_getglobal("nopatch_getglobal");
if (VERBOSITY() >= 2) {
#if !DISABLE_STATS
std::string per_name_stat_name = "getglobal__" + *name;
int id = Stats::getStatId(per_name_stat_name);
Stats::log(id);
#endif
}
{ /* anonymous scope to make sure destructors get run before we err out */
std::unique_ptr<Rewriter> rewriter(
Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "getGlobal"));
Box* r;
if (rewriter.get()) {
// rewriter->trap();
GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(),
false);
r = m->getattr(*name, &rewrite_args);
if (!rewrite_args.obj.isDoneUsing()) {
rewrite_args.obj.setDoneUsing();
}
if (!rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
}
if (r) {
if (rewriter.get()) {
rewriter->setDoneGuarding();
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
} else {
rewrite_args.out_rtn.setDoneUsing();
}
return r;
}
} else {
r = m->getattr(*name, NULL);
nopatch_getglobal.log();
if (r) {
return r;
}
}
static StatCounter stat_builtins("getglobal_builtins");
stat_builtins.log();
if ((*name) == "__builtins__") {
if (rewriter.get()) {
RewriterVarUsage r_rtn
= rewriter->loadConst((intptr_t)builtins_module, rewriter->getReturnDestination());
rewriter->setDoneGuarding();
rewriter->commitReturning(std::move(r_rtn));
}
return builtins_module;
}
Box* rtn;
if (rewriter.get()) {
RewriterVarUsage builtins = rewriter->loadConst((intptr_t)builtins_module, Location::any());
GetattrRewriteArgs rewrite_args(rewriter.get(), std::move(builtins), rewriter->getReturnDestination(),
true);
rtn = builtins_module->getattr(*name, &rewrite_args);
if (!rtn || !rewrite_args.out_success) {
rewrite_args.ensureAllDone();
rewriter.reset(NULL);
}
if (rewriter.get()) {
rewriter->commitReturning(std::move(rewrite_args.out_rtn));
}
} else {
rtn = builtins_module->getattr(*name, NULL);
}
if (rtn)
return rtn;
}
raiseExcHelper(NameError, "global name '%s' is not defined", name->c_str());
}
extern "C" Box* importFrom(Box* _m, const std::string* name) {
assert(_m->cls == module_cls);
BoxedModule* m = static_cast<BoxedModule*>(_m);
Box* r = m->getattr(*name, NULL);
if (r)
return r;
raiseExcHelper(ImportError, "cannot import name %s", name->c_str());
}
extern "C" Box* importStar(Box* _from_module, BoxedModule* to_module) {
assert(_from_module->cls == module_cls);
BoxedModule* from_module = static_cast<BoxedModule*>(_from_module);
static std::string all_str("__all__");
static std::string getitem_str("__getitem__");
Box* all = from_module->getattr(all_str);
if (all) {
Box* all_getitem = typeLookup(all->cls, getitem_str, NULL);
if (!all_getitem)
raiseExcHelper(TypeError, "'%s' object does not support indexing", getTypeName(all)->c_str());
int idx = 0;
while (true) {
Box* attr_name;
try {
attr_name = runtimeCallInternal2(all_getitem, NULL, ArgPassSpec(2), all, boxInt(idx));
} catch (Box* b) {
if (b->cls == IndexError)
break;
throw;
}
idx++;
if (attr_name->cls != str_cls)
raiseExcHelper(TypeError, "attribute name must be string, not '%s'", getTypeName(attr_name)->c_str());
BoxedString* casted_attr_name = static_cast<BoxedString*>(attr_name);
Box* attr_value = from_module->getattr(casted_attr_name->s);
if (!attr_value)
raiseExcHelper(AttributeError, "'module' object has no attribute '%s'", casted_attr_name->s.c_str());
to_module->setattr(casted_attr_name->s, attr_value, NULL);
}
return None;
}
HCAttrs* module_attrs = from_module->getAttrsPtr();
for (auto& p : module_attrs->hcls->attr_offsets) {
if (p.first[0] == '_')
continue;
to_module->setattr(p.first, module_attrs->attr_list->attrs[p.second], NULL);
}
return None;
}
}
| 38.594233
| 145
| 0.59301
|
amyvmiwei
|
ffaeb5b6af46af8b75dfd837172594f1836cdbf0
| 762
|
cpp
|
C++
|
Example/smartpointers_09/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/smartpointers_09/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/smartpointers_09/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
#include <boost/intrusive_ptr.hpp>
#include <atlbase.h>
#include <iostream>
void intrusive_ptr_add_ref(IDispatch *p) { p->AddRef(); }
void intrusive_ptr_release(IDispatch *p) { p->Release(); }
void check_windows_folder()
{
CLSID clsid;
CLSIDFromProgID(CComBSTR{"Scripting.FileSystemObject"}, &clsid);
void *p;
CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, __uuidof(IDispatch), &p);
boost::intrusive_ptr<IDispatch> disp{static_cast<IDispatch*>(p), false};
CComDispatchDriver dd{disp.get()};
CComVariant arg{"C:\\Windows"};
CComVariant ret{false};
dd.Invoke1(CComBSTR{"FolderExists"}, &arg, &ret);
std::cout << std::boolalpha << (ret.boolVal != 0) << '\n';
}
int main()
{
CoInitialize(0);
check_windows_folder();
CoUninitialize();
}
| 28.222222
| 76
| 0.708661
|
KwangjoJeong
|
ffafe8964fc691f8d19fe82fc728b7f7a5c4cbcf
| 1,267
|
cpp
|
C++
|
src/core/qloaderdata.cpp
|
sergeynaumovio/qtloader
|
21e17c62e63afe4b65a163402c77b51bda85be34
|
[
"0BSD"
] | null | null | null |
src/core/qloaderdata.cpp
|
sergeynaumovio/qtloader
|
21e17c62e63afe4b65a163402c77b51bda85be34
|
[
"0BSD"
] | null | null | null |
src/core/qloaderdata.cpp
|
sergeynaumovio/qtloader
|
21e17c62e63afe4b65a163402c77b51bda85be34
|
[
"0BSD"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2022 Sergey Naumov
**
** Permission to use, copy, modify, and/or distribute this
** software for any purpose with or without fee is hereby granted.
**
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
** THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
** CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
** LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
** NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
** CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
**
****************************************************************************/
#include "qloaderdata.h"
#include "qloaderstorage.h"
class QLoaderDataPrivate
{
public:
QList<QLoaderStorage*> storageList{};
};
QLoaderData::QLoaderData(QLoaderSettings *settings, QObject *parent)
: QObject(parent),
QLoaderSettings(settings),
d_ptr(new QLoaderDataPrivate)
{ }
QLoaderData::~QLoaderData()
{ }
void QLoaderData::addStorage(QLoaderStorage *storage)
{
d_ptr->storageList.append(storage);
}
| 30.902439
| 77
| 0.659826
|
sergeynaumovio
|
ffb7247aa8dc214775abccb10e9feb1a4297ed2f
| 3,577
|
hpp
|
C++
|
Math/Algebra/Round.hpp
|
AProgrammerFemale/Yet-another-c-framework
|
30fddcbff23cd3d95db4e8b83f0a30d060e1128f
|
[
"MIT"
] | 10
|
2019-08-25T07:59:43.000Z
|
2020-04-22T21:06:19.000Z
|
Math/Algebra/Round.hpp
|
AProgrammerFemale/Yet-another-c-framework
|
30fddcbff23cd3d95db4e8b83f0a30d060e1128f
|
[
"MIT"
] | 2
|
2019-08-25T18:17:32.000Z
|
2019-09-05T05:51:41.000Z
|
Math/Algebra/Round.hpp
|
AProgrammerFemale/Yet-another-c-framework
|
30fddcbff23cd3d95db4e8b83f0a30d060e1128f
|
[
"MIT"
] | 1
|
2019-09-05T21:04:02.000Z
|
2019-09-05T21:04:02.000Z
|
//Copyright Alice Framework, All Rights Reserved
#pragma once
#include <Basic/Types.hpp>
#include <Basic/Inline.hpp>
#include <Configuration.hpp>
#if defined(AliceSse)
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <xmmintrin.h>
#endif
#endif
#if defined(AliceSse2)
#if defined(_MSC_VER)
#if !defined(AliceSse)
#include <intrin.h>
#endif
#else
#include <emmintrin.h>
#endif
#endif
namespace Alice
{
namespace Math
{
namespace Algebra
{
template<class T> AliceInline T Round(f32 a) noexcept
{
return static_cast<T>(a + 0.5f);
}
template<> AliceInline f32 Round<f32>(f32 a) noexcept
{
#if defined(AliceSse)
__m128 b, c;
#if defined(_MSC_VER)
b.m128_f32[0] = a;
c.m128_f32[0] = 0.5f;
return _mm_cvt_si2ss(b, _mm_cvt_ss2si(_mm_add_ss(b, c))).m128_f32[0];
#else
b[0] = a;
c[0] = 0.5f;
return _mm_cvt_si2ss(b, _mm_cvt_ss2si(_mm_add_ss(b, c)))[0];
#endif
#else
return static_cast<f32>(static_cast<s32>(a + 0.5f));
#endif
}
template<> AliceInline f64 Round<f64>(f32 a) noexcept
{
#if defined(AliceSse2)
__m128 b, c;
__m128d d;
#if defined(_MSC_VER)
b.m128_f32[0] = a;
c.m128_f32[0] = 0.5f;
return _mm_cvtsi64_sd(d, _mm_cvttss_si64(_mm_add_ss(b, c))).m128d_f64[0];
#else
b[0] = a;
c[0] = 0.5f;
return _mm_cvtsi64_sd(d, _mm_cvttss_si64(_mm_add_ss(b, c)))[0];
#endif
#else
return static_cast<f64>(static_cast<s64>(a + 0.5f));
#endif
}
template<class T> AliceInline T Round(f64 a) noexcept
{
return static_cast<T>(static_cast<s64>(a + 0.5));
}
template<> AliceInline f32 Round<f32>(f64 a) noexcept
{
#if defined(AliceSse2)
__m128d b, c;
__m128 d;
#if defined(_MSC_VER)
b.m128d_f64[0] = a;
c.m128d_f64[0] = 0.5;
return _mm_cvtsi64_ss(d, _mm_cvtsd_si64(_mm_add_sd(b, c))).m128_f32[0];
#else
b[0] = a;
c[0] = 0.5;
return _mm_cvtsi64_ss(d, _mm_cvtsd_si64(_mm_add_sd(b, c)))[0];
#endif
#else
return static_cast<f32>(static_cast<s64>(a + 0.5));
#endif
}
template<> AliceInline f64 Round<f64>(f64 a) noexcept
{
#if defined(AliceSse2)
__m128d b, c;
#if defined(_MSC_VER)
b.m128d_f64[0] = a;
c.m128d_f64[0] = 0.5;
return _mm_cvtsi64_sd(b, _mm_cvtsd_si64(_mm_add_sd(b, c))).m128d_f64[0];
#else
b[0] = a;
c[0] = 0.5;
return _mm_cvtsi64_sd(b, _mm_cvtsd_si64(_mm_add_sd(b, c)))[0];
#endif
#else
return static_cast<f64>(static_cast<s64>(a + 0.5));
#endif
}
}
}
}
| 31.377193
| 90
| 0.448141
|
AProgrammerFemale
|
ffb84e55963aa3a2421bdaf8bf6f79b4cbfc520b
| 1,031
|
hpp
|
C++
|
addons/Outdated_WIP_Reference/Test_Weapon_01_Reference/CfgMagazines.hpp
|
hoxxii/Autismo_Seals_Unit_Mod
|
5e27dbac2066c435215859b70c861b0abbfb3b95
|
[
"OLDAP-2.3"
] | null | null | null |
addons/Outdated_WIP_Reference/Test_Weapon_01_Reference/CfgMagazines.hpp
|
hoxxii/Autismo_Seals_Unit_Mod
|
5e27dbac2066c435215859b70c861b0abbfb3b95
|
[
"OLDAP-2.3"
] | null | null | null |
addons/Outdated_WIP_Reference/Test_Weapon_01_Reference/CfgMagazines.hpp
|
hoxxii/Autismo_Seals_Unit_Mod
|
5e27dbac2066c435215859b70c861b0abbfb3b95
|
[
"OLDAP-2.3"
] | null | null | null |
class CfgMagazines
{
class Default;
class CA_Magazine;
class 30Rnd_test_mag: CA_Magazine
{
scope = public; /// or 2, to be precise
displayName = "Test magazine";
picture = "\A3\Weapons_F\Data\placeholder_co.paa"; /// just some icon
ammo = B_Test_Caseless;
count = 30; /// 30 rounds is enough
initSpeed = 795; /// standard muzzle speed
tracersEvery = 0; /// disable tracers by default
lastRoundsTracer = 4; /// tracers to track low ammo
descriptionShort = "Used to shoot test bullets"; /// on mouse-over in Inventory
magazineGroup[] = {"test_mag_group"}; /// all magazines in the same group may be used in weapon that has the group defined as compatible
};
class 30Rnd_test_mag_Tracer: 30Rnd_test_mag /// a magazine full of tracer rounds
{
tracersEvery = 1; /// moar tracers
lastRoundsTracer = 30; /// tracers everywhere
displayName = "Test tracer magazine";
descriptionShort = "Used to shoot test tracer bullets";
displaynameshort = "Tracers";
magazineGroup[] = {"test_mag_group"};
};
};
| 34.366667
| 138
| 0.71193
|
hoxxii
|
ffbd103c7a0a75cc4b37445da092e94c7af1b95c
| 1,732
|
cpp
|
C++
|
sources/Modules/Upnp/UdpConnection.cpp
|
palchukovsky/TunnelEx
|
ec645271ab8b79225e378345ff108795110c57de
|
[
"Apache-2.0"
] | null | null | null |
sources/Modules/Upnp/UdpConnection.cpp
|
palchukovsky/TunnelEx
|
ec645271ab8b79225e378345ff108795110c57de
|
[
"Apache-2.0"
] | null | null | null |
sources/Modules/Upnp/UdpConnection.cpp
|
palchukovsky/TunnelEx
|
ec645271ab8b79225e378345ff108795110c57de
|
[
"Apache-2.0"
] | null | null | null |
/**************************************************************************
* Created: 2010/06/07 2:09
* Author: Eugene V. Palchukovsky
* E-mail: eugene@palchukovsky.com
* -------------------------------------------------------------------
* Project: TunnelEx
* URL: http://tunnelex.net
**************************************************************************/
#include "Prec.h"
#include "UdpConnection.hpp"
#include "Modules/Inet/InetEndpointAddress.hpp"
using namespace TunnelEx;
using namespace TunnelEx::Mods;
using namespace TunnelEx::Mods::Upnp;
UdpConnection::UdpConnection(
unsigned short externalPort,
const Inet::UdpEndpointAddress &address,
const RuleEndpoint &ruleEndpoint,
SharedPtr<const EndpointAddress> ruleEndpointAddress)
: Base(address, ruleEndpoint, ruleEndpointAddress) {
const AutoPtr<EndpointAddress> openedAddress = Base::GetLocalAddress();
ServiceRule::Service service;
service.uuid = Helpers::Uuid().GetAsString().c_str();
service.name = L"Upnpc";
service.param = UpnpcService::CreateParam(
Client::PROTO_UDP,
externalPort,
boost::polymorphic_downcast<Inet::InetEndpointAddress *>(
openedAddress.Get())->GetHostName(),
boost::polymorphic_downcast<Inet::InetEndpointAddress *>(
openedAddress.Get())->GetPort(),
true, // @todo: see TEX-610
false);
SharedPtr<ServiceRule> rule(new ServiceRule);
// WString ruleUuid = rule->GetUuid();
rule->GetServices().Append(service);
//! @todo: see TEX-611 [2010/06/07 1:39]
/* m_server.UpdateRule(rule);
ruleUuid.Swap(m_upnpRuleUuid); */
m_upnpcService.reset(new UpnpcService(rule, rule->GetServices()[0]));
m_upnpcService->Start();
}
UdpConnection::~UdpConnection() throw() {
//...//
}
| 29.355932
| 76
| 0.632794
|
palchukovsky
|
ffbdec6bb0d5c58b44e382c02c0f7256af7257aa
| 61,718
|
cpp
|
C++
|
hgt_optimizer.cpp
|
lpsztemp/Bogdan-httpserv
|
068ac3504144d6907ad428e1359b00954c755f1b
|
[
"MIT"
] | null | null | null |
hgt_optimizer.cpp
|
lpsztemp/Bogdan-httpserv
|
068ac3504144d6907ad428e1359b00954c755f1b
|
[
"MIT"
] | null | null | null |
hgt_optimizer.cpp
|
lpsztemp/Bogdan-httpserv
|
068ac3504144d6907ad428e1359b00954c755f1b
|
[
"MIT"
] | null | null | null |
#include <list>
#include <memory>
#include <algorithm>
#include <vector>
#include <iterator>
#include <cassert>
#include <tuple>
#include <array>
#include <thread>
#include <future>
#include <atomic>
#include <cmath>
#include <cstring>
#include "basedefs.h"
#include "face.h"
#include "hgt_optimizer.h"
#include "binary_streams.h"
constexpr static double ADDITIVE_ERROR = 1E-6;
constexpr static short MIN_VALID_HGT_VALUE = -500;
constexpr static bool vertex_has_zero_height(const point_t& pt) noexcept
{
return pt.z >= 0?pt.z <= ADDITIVE_ERROR:pt.z >= -ADDITIVE_ERROR;
}
inline static bool vertex_has_zero_height(unsigned pt) noexcept;
constexpr static short bswap(short w) noexcept
{
return (short) ((unsigned short) w << 8) | ((unsigned short) w >> 8);
}
template <class FaceType>
inline static ConstantDomainDataId GetFaceDomainDataId(const FaceType& face) noexcept
{
for (const auto& pt:face)
{
if (!vertex_has_zero_height(pt))
return ConstantDomainDataId::SurfaceLand;
}
return ConstantDomainDataId::SurfaceWater;
}
template <class FaceType>
inline static bool SameDomainData(const FaceType& left, const FaceType& right) noexcept
{
return GetFaceDomainDataId(left) == GetFaceDomainDataId(right);
}
class Matrix
{
short* m_points = nullptr;
std::unique_ptr<std::int8_t[]> m_pVertexStatus;
unsigned short m_cColumns = 0, m_cRows = 0;
double m_eColumnResolution = 0, m_eRowResolution = 0;
short m_min_height = std::numeric_limits<short>::max();
short m_max_height = std::numeric_limits<short>::min();
public:
Matrix() = default;
Matrix(short* pPoints, unsigned short cColumns, unsigned short cRows, double eColumnResolution, double eRowResolution)
:m_points(pPoints), m_pVertexStatus(std::make_unique<std::int8_t[]>(std::size_t(cColumns) * cRows)),
m_cColumns(cColumns), m_cRows(cRows), m_eColumnResolution(eColumnResolution), m_eRowResolution(eRowResolution)
{
auto cBlocks = std::thread::hardware_concurrency();
auto cItemsTotal = unsigned(cColumns) * cRows;
auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks;
std::list<std::thread> threads;
std::atomic<unsigned> fence_1(unsigned(0)), fence_2(unsigned(0));
auto pMinMax = std::make_unique<std::pair<std::atomic<short>, std::atomic<short>>[]>(std::size_t(cBlocks));
for (unsigned iThread = 0; iThread < cBlocks; ++iThread)
{
threads.emplace_back([this, iThread, cBlock, cBlocks, cItemsTotal, &fence_1, &fence_2](std::pair<std::atomic<short>, std::atomic<short>>& prMinMax) -> void
{
auto iBegin = iThread * cBlock;
auto iEnd = std::min((iThread + 1) * cBlock, cItemsTotal);
for (auto iElement = iBegin; iElement < iEnd; ++iElement)
m_points[iElement] = height_data_bswap(iElement);
if (fence_1.fetch_add(1, std::memory_order_acq_rel) + 1 < cBlocks)
do {std::this_thread::yield();} while (fence_1.load(std::memory_order_acquire) < cBlocks);
std::unique_ptr<short[]> pBuf;
unsigned buf_begin;
{
for (auto iElement = iBegin; iElement < iEnd; ++iElement)
{
if (m_points[iElement] < MIN_VALID_HGT_VALUE)
{
pBuf = std::make_unique<short[]>(std::size_t(iEnd - iElement));
std::memcpy(pBuf.get(), &m_points[iElement], std::size_t(iEnd - iElement) * sizeof(short));
buf_begin = iElement;
do
{
pBuf[iElement - buf_begin] = average_invalid_height(iElement);
}while (++iElement < iEnd);
}
}
}
if (fence_2.fetch_add(1, std::memory_order_acq_rel) + 1 < cBlocks)
do {std::this_thread::yield();} while (fence_2.load(std::memory_order_acquire) < cBlocks);
if (bool(pBuf))
std::memcpy(&m_points[buf_begin], pBuf.get(), std::size_t(iEnd - buf_begin) * sizeof(short));
if (fence_1.fetch_sub(1, std::memory_order_acq_rel) - 1 > 0)
do {std::this_thread::yield();} while (fence_1.load(std::memory_order_acquire) > 0);
short min_height = std::numeric_limits<short>::max();
short max_height = std::numeric_limits<short>::min();
for (auto iElement = iThread * cBlock; iElement < iEnd; ++iElement)
{
m_pVertexStatus[iElement] = this->is_empty_point_no_cache(iElement);
if (m_points[iElement] < min_height)
min_height = m_points[iElement];
if (m_points[iElement] > max_height)
max_height = m_points[iElement];
}
prMinMax.first.store(min_height, std::memory_order_relaxed);
prMinMax.second.store(max_height, std::memory_order_relaxed);
}, std::ref(pMinMax[iThread]));
}
unsigned iThread = 0;
for (auto& thr:threads)
{
thr.join();
auto l_min_height = pMinMax[iThread].first.load(std::memory_order_relaxed);
auto l_max_height = pMinMax[iThread].second.load(std::memory_order_relaxed);
if (l_min_height < m_min_height)
m_min_height = l_min_height;
if (l_max_height > m_max_height)
m_max_height = l_max_height;
++iThread;
}
}
inline unsigned short columns() const noexcept
{
return m_cColumns;
}
inline unsigned short rows() const noexcept
{
return m_cRows;
}
bool is_empty_point(unsigned short col, unsigned short row) const noexcept
{
return is_empty_point(this->locate(col, row));
}
inline bool is_empty_point(unsigned index) const noexcept
{
return bool(m_pVertexStatus[index]);
}
inline unsigned short point_x(unsigned index) const noexcept
{
return index % this->columns();
}
inline unsigned short point_y(unsigned index) const noexcept
{
return index / this->columns();
}
inline short point_z(unsigned index) const noexcept
{
return m_points[index];
}
inline short point_z(unsigned short col, unsigned short row) const noexcept
{
return this->point_z(this->locate(col, row));
}
inline unsigned locate(unsigned short col, unsigned short row) const noexcept
{
return row * this->columns() + col;
}
inline point_t get_external_point(unsigned short col, unsigned short row) const noexcept
{
return {double(col) * m_eColumnResolution, double(row) * m_eRowResolution, double(point_z(col, row))};
}
inline point_t get_external_point(unsigned index) const noexcept
{
return {double(this->point_x(index)) * m_eColumnResolution, double(this->point_y(index)) * m_eRowResolution, double(point_z(index))};
}
inline short min_height() const
{
return m_min_height;
}
inline short max_height() const
{
return m_max_height;
}
private:
bool is_empty_point_no_cache(unsigned point_index) const
{
auto col = this->point_x(point_index);
auto row = this->point_y(point_index);
if (col > 0 && col < this->columns() - 1
&& row > 0 && row < this->rows() - 1
&& this->point_z(col, row) - this->point_z(col - 1, row) == this->point_z(col + 1, row) - this->point_z(col, row)
&& this->point_z(col, row) - this->point_z(col, row - 1) == this->point_z(col, row + 1) - this->point_z(col, row)
&& this->point_z(col, row - 1) - this->point_z(col - 1, row - 1) == this->point_z(col, row) - this->point_z(col - 1, row)
&& this->point_z(col, row + 1) - this->point_z(col - 1, row + 1) == this->point_z(col, row) - this->point_z(col - 1, row)
&& this->point_z(col + 1, row - 1) - this->point_z(col, row - 1) == this->point_z(col + 1, row) - this->point_z(col, row)
&& this->point_z(col + 1, row + 1) - this->point_z(col, row + 1) == this->point_z(col + 1, row) - this->point_z(col, row))
{
point_t v_tl = this->get_external_point(col - 1, row - 1);
point_t v_tp = this->get_external_point(col, row - 1);
point_t v_tr = this->get_external_point(col + 1, row - 1);
point_t v_lf = this->get_external_point(col - 1, row);
point_t v_md = this->get_external_point(col, row);
point_t v_rt = this->get_external_point(col + 1, row);
point_t v_bl = this->get_external_point(col - 1, row + 1);
point_t v_bt = this->get_external_point(col, row + 1);
point_t v_br = this->get_external_point(col + 1, row + 1);
point_t f_tl_lb[] = {v_tl, v_md, v_lf};
point_t f_tl_rt[] = {v_tl, v_tp, v_md};
point_t f_tr_lb[] = {v_tp, v_rt, v_md};
point_t f_tr_rt[] = {v_tp, v_tr, v_rt};
point_t f_bl_lb[] = {v_lf, v_bt, v_bl};
point_t f_bl_rt[] = {v_lf, v_md, v_bt};
point_t f_br_lb[] = {v_md, v_br, v_bt};
point_t f_br_rt[] = {v_md, v_rt, v_br};
return std::int8_t(SameDomainData(face_t(std::begin(f_tl_lb), std::end(f_tl_lb)), face_t(std::begin(f_tl_rt), std::end(f_tl_rt)))
&& SameDomainData(face_t(std::begin(f_tl_rt), std::end(f_tl_rt)), face_t(std::begin(f_tr_lb), std::end(f_tr_lb)))
&& SameDomainData(face_t(std::begin(f_tr_lb), std::end(f_tr_lb)), face_t(std::begin(f_tr_rt), std::end(f_tr_rt)))
&& SameDomainData(face_t(std::begin(f_tr_rt), std::end(f_tr_rt)), face_t(std::begin(f_bl_lb), std::end(f_bl_lb)))
&& SameDomainData(face_t(std::begin(f_bl_lb), std::end(f_bl_lb)), face_t(std::begin(f_bl_rt), std::end(f_bl_rt)))
&& SameDomainData(face_t(std::begin(f_bl_rt), std::end(f_bl_rt)), face_t(std::begin(f_br_lb), std::end(f_br_lb)))
&& SameDomainData(face_t(std::begin(f_br_lb), std::end(f_br_lb)), face_t(std::begin(f_br_rt), std::end(f_br_rt))));
}
return false;
}
inline short height_data_bswap(unsigned point_index) const noexcept
{
return bswap(m_points[point_index]);
}
short average_invalid_height(unsigned point_index) const noexcept
{
unsigned short cl, cr;
short vl = short(), vr = short();
unsigned short rt, rb;
short vt = short(), vb = short();
auto col = this->point_x(point_index);
auto row = this->point_y(point_index);
for (cr = col + 1; cr < this->columns(); ++cr)
{
if (m_points[point_index + cr - col] >= MIN_VALID_HGT_VALUE)
{
vr = m_points[point_index + cr - col];
break;
}
}
for (cl = 1; cl <= col; ++cl)
{
if (m_points[point_index - cl] >= MIN_VALID_HGT_VALUE)
{
cl = point_index - cl;
vl = m_points[cl];
break;
}
}
for (rb = row + 1; rb < this->rows(); ++rb)
{
if (this->point_z(col, rb) >= MIN_VALID_HGT_VALUE)
{
vb = this->point_z(col, rb);
break;
}
}
for (rt = 1; rt <= row; ++rt)
{
if (this->point_z(col, row - rt) >= MIN_VALID_HGT_VALUE)
{
rt = row - rt;
vt = this->point_z(col, rt);
break;
}
}
double eAve;
if (cr > cl)
{
eAve = double(vr - vl) / double(cr - cl) * (col - cl) + vl;
if (rb > rt)
return short((eAve + double(vb - vt) / double(rb - rt) * (row - rt) + vt) / 2);
return short(eAve);
}
return short(double(vb - vt) / double(rb - rt) * (row - rt) + vt);
}
};
Matrix g_matrix;
class Face
{
public:
typedef unsigned value_type; //index pointing to the matrix element
typedef unsigned* pointer;
typedef const unsigned* const_pointer;
typedef unsigned& reference;
typedef const unsigned& const_reference;
typedef unsigned* iterator;
typedef const unsigned* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef unsigned size_type;
typedef signed difference_type;
private:
static constexpr size_type SMALL_NUMBER = 4;
union
{
pointer m_vertices_big;
value_type m_vertices_small[SMALL_NUMBER];
};
pointer m_pVertices;
size_type m_vertices_count = 0;
public:
explicit operator face_t() const;
inline value_type point(size_type in_face_index) const noexcept
{
return m_pVertices[in_face_index];
}
inline size_type size() const noexcept
{
return m_vertices_count;
}
inline iterator begin() noexcept {return &m_pVertices[0];}
inline const_iterator cbegin() const noexcept {return const_cast<const unsigned*>(&m_pVertices[0]);}
inline const_iterator begin() const noexcept {return this->cbegin();}
inline iterator end() noexcept {return &m_pVertices[m_vertices_count];}
inline const_iterator cend() const noexcept {return const_cast<const unsigned*>(&m_pVertices[m_vertices_count]);}
inline const_iterator end() const noexcept {return this->cend();}
inline reverse_iterator rbegin() noexcept {return std::make_reverse_iterator(this->end());}
inline const_reverse_iterator crbegin() const noexcept {return std::make_reverse_iterator(this->end());}
inline const_reverse_iterator rbegin() const noexcept {return std::make_reverse_iterator(this->end());}
inline reverse_iterator rend() noexcept {return std::make_reverse_iterator(this->begin());}
inline const_reverse_iterator crend() const noexcept {return std::make_reverse_iterator(this->begin());}
inline const_reverse_iterator rend() const noexcept {return std::make_reverse_iterator(this->begin());}
bool is_complanar_to(const Face& right) const
{
auto n1 = cross_product(g_matrix.get_external_point(m_pVertices[1]) - g_matrix.get_external_point(m_pVertices[0]),
g_matrix.get_external_point(m_pVertices[2]) - g_matrix.get_external_point(m_pVertices[1]));
assert(fabs(n1.x) > ADDITIVE_ERROR || fabs(n1.y) > ADDITIVE_ERROR || fabs(n1.z) > ADDITIVE_ERROR);
auto n2 = cross_product(g_matrix.get_external_point(right.m_pVertices[1]) - g_matrix.get_external_point(right.m_pVertices[0]),
g_matrix.get_external_point(right.m_pVertices[2]) - g_matrix.get_external_point(right.m_pVertices[1]));
assert(fabs(n2.x) > ADDITIVE_ERROR || fabs(n2.y) > ADDITIVE_ERROR || fabs(n2.z) > ADDITIVE_ERROR);
auto res = cross_product(n1, n2);
return fabs(res.x) <= ADDITIVE_ERROR && fabs(res.y) <= ADDITIVE_ERROR && fabs(res.z) <= ADDITIVE_ERROR;
}
bool can_unite_with_quadruplet_left_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with_quadruplet_top_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with_quadruplet_right_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with_quadruplet_bottom_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with(const Face& right) const
{
return this->is_complanar_to(right) && SameDomainData(*this, right);
}
private:
class ReversedConstructor;
public:
Face() = default;
class Constructor
{
std::list<unsigned> m_lstEdgeVertices;
public:
Constructor() = default;
void add_point(unsigned short col, unsigned short row) noexcept
{
assert(!g_matrix.is_empty_point(col, row));
if (this->size() >= 2)
{
auto it_pp = m_lstEdgeVertices.rbegin();
auto it_p = it_pp++;
if ((g_matrix.point_y(*it_p) - g_matrix.point_y(*it_pp)) * (col - g_matrix.point_x(*it_p))
== (row - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_p) - g_matrix.point_x(*it_pp)))
*it_p = g_matrix.locate(col, row);
else
m_lstEdgeVertices.emplace_back(g_matrix.locate(col, row));
}else
m_lstEdgeVertices.emplace_back(g_matrix.locate(col, row));
}
void add_list(const Face& face)
{
auto it = face.begin();
auto pt = *it++;
this->add_point(g_matrix.point_x(pt), g_matrix.point_y(pt));
while (it != face.end())
m_lstEdgeVertices.emplace_back(*it);
}
void add_list(Face::Constructor&& right)
{
if (!right.empty())
{
if (m_lstEdgeVertices.empty())
m_lstEdgeVertices = std::move(right.m_lstEdgeVertices);
else
{
auto it_p = std::prev(m_lstEdgeVertices.end());
m_lstEdgeVertices.splice(m_lstEdgeVertices.end(), std::move(right.m_lstEdgeVertices));
auto it_n = it_p--;
auto it = it_n++;
if (it_n != m_lstEdgeVertices.end()
&& (g_matrix.point_y(*it) - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_n) - g_matrix.point_x(*it))
== (g_matrix.point_y(*it_n) - g_matrix.point_y(*it)) * (g_matrix.point_x(*it) - g_matrix.point_x(*it_p)))
m_lstEdgeVertices.erase(it);
}
}
}
typedef Face::ReversedConstructor Reversed;
void add_reversed_list(Reversed&& right);
//returns an index of the next quadruplet to analyze
unsigned add_face_to_the_right(unsigned short col, unsigned short row);
void add_face_to_the_bottom(unsigned short col, unsigned short row);
auto begin() {return m_lstEdgeVertices.begin();}
auto begin() const {return m_lstEdgeVertices.begin();}
auto cbegin() const {return m_lstEdgeVertices.cbegin();}
auto end() {return m_lstEdgeVertices.end();}
auto end() const {return m_lstEdgeVertices.end();}
auto cend() const {return m_lstEdgeVertices.cend();}
auto rbegin() {return m_lstEdgeVertices.rbegin();}
auto rbegin() const {return m_lstEdgeVertices.rbegin();}
auto crbegin() const {return m_lstEdgeVertices.crbegin();}
auto rend() {return m_lstEdgeVertices.rend();}
auto rend() const {return m_lstEdgeVertices.rend();}
auto crend() const {return m_lstEdgeVertices.crend();}
unsigned size() const {return unsigned(m_lstEdgeVertices.size());}
bool empty() const {return m_lstEdgeVertices.empty();}
};
Face(Constructor&& constr):Face(std::move(constr), int()) {}
//MSVC bug with fold expressions: https://developercommunity.visualstudio.com/content/problem/301623/fold-expressions-in-template-instantiations-fail-t.html
template <class ... Points, class = std::enable_if_t<
(sizeof ... (Points) > 1) && (sizeof ... (Points) <= SMALL_NUMBER) && std::conjunction_v<std::is_integral<Points> ...>>>
explicit Face(Points ... vertices):m_vertices_small{vertices...}, m_pVertices(m_vertices_small), m_vertices_count(unsigned(sizeof...(Points)))
{
static_assert(sizeof...(Points) >= 3, "Invalid number of vertices specified for a face");
/*assert((g_matrix.point_y(m_pVertices[sizeof...(Points) - 2]) - g_matrix.point_y(m_pVertices[sizeof...(Points) - 3]))
* (g_matrix.point_x(m_pVertices[sizeof...(Points) - 1]) - g_matrix.point_x(m_pVertices[sizeof...(Points) - 2]))
== (g_matrix.point_y(m_pVertices[sizeof...(Points) - 1]) - g_matrix.point_y(m_pVertices[sizeof...(Points) - 2]))
* (g_matrix.point_x(m_pVertices[sizeof...(Points) - 2]) - g_matrix.point_x(m_pVertices[sizeof...(Points) - 3])));*/
}
template <class ... Points, class = void, class = std::enable_if_t<(sizeof ... (Points) > SMALL_NUMBER) && std::conjunction_v<std::is_integral<Points> ...>>>
explicit Face(Points ... vertices):Face(std::array<typename std::tuple_element<0, std::tuple<Points...>>::type, sizeof ... (Points)>{vertices...}, int()) {}
Face(const Face&) = delete;
Face(Face&& right)
{
*this = std::move(right);
}
Face& operator=(const Face&) = delete;
Face& operator=(Face&& right)
{
if (this == &right)
return *this;
if (m_vertices_count > SMALL_NUMBER)
delete [] m_vertices_big;
if (right.m_vertices_count <= SMALL_NUMBER)
{
std::copy(&right.m_vertices_small[0], &right.m_vertices_small[right.m_vertices_count], &m_vertices_small[0]);
m_pVertices = m_vertices_small;
}else
{
m_vertices_big = right.m_vertices_big;
m_pVertices = m_vertices_big;
}
m_vertices_count = right.m_vertices_count;
right.m_vertices_count = 0;
return *this;
}
~Face() noexcept
{
if (m_vertices_count > SMALL_NUMBER)
delete [] m_vertices_big;
}
private:
class ReversedConstructor
{
Face::Constructor m_list;
public:
void add_point(unsigned short col, unsigned short row)
{
m_list.add_point(col, row);
}
auto begin() {return m_list.begin();}
auto begin() const {return m_list.begin();}
auto cbegin() const {return m_list.cbegin();}
auto end() {return m_list.end();}
auto end() const {return m_list.end();}
auto cend() const {return m_list.cend();}
auto rbegin() {return m_list.rbegin();}
auto rbegin() const {return m_list.rbegin();}
auto crbegin() const {return m_list.crbegin();}
auto rend() {return m_list.rend();}
auto rend() const {return m_list.rend();}
auto crend() const {return m_list.crend();}
unsigned size() const {return unsigned(m_list.size());}
bool empty() const {return m_list.empty();}
};
template <class Container>
Face(Container&& constr, int) noexcept
{
assert(constr.size() >= 3);
auto it_end = std::end(constr);
{
auto it_pp = std::rbegin(constr);
auto it_p = it_pp++;
auto col = g_matrix.point_x(*std::begin(constr));
auto row = g_matrix.point_y(*std::begin(constr));
if ((g_matrix.point_y(*it_p) - g_matrix.point_y(*it_pp)) * (col - g_matrix.point_x(*it_p))
== (row - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_p) - g_matrix.point_x(*it_pp)))
{
assert(constr.size() - 1 >= 3);
--it_end;
m_vertices_count = unsigned(constr.size() - 1);
}else
m_vertices_count = unsigned(constr.size());
}
if (m_vertices_count <= SMALL_NUMBER)
m_pVertices = m_vertices_small;
else
{
m_vertices_big = new unsigned [m_vertices_count];
m_pVertices = m_vertices_big;
}
std::move(std::begin(constr), it_end, &m_pVertices[0]);
}
};
void Face::Constructor::add_reversed_list(Face::Constructor::Reversed&& right)
{
for (auto it = std::rbegin(right); it != std::rend(right); ++it)
this->add_point(g_matrix.point_x(*it), g_matrix.point_y(*it));
}
struct vertex_converting_iterator
{
typedef std::input_iterator_tag iterator_category;
typedef point_t value_type;
typedef const point_t *pointer, &reference;
typedef unsigned size_type;
typedef signed difference_type;
reference operator*() const
{
if (!m_fLastVal)
{
m_ptLastVal = g_matrix.get_external_point(*m_it);
m_fLastVal = true;
}
return m_ptLastVal;
}
pointer operator->() const
{
if (!m_fLastVal)
{
m_ptLastVal = g_matrix.get_external_point(*m_it);
m_fLastVal = true;
}
return &m_ptLastVal;
}
vertex_converting_iterator& operator++()
{
++m_it;
this->invalidate_value();
return *this;
}
vertex_converting_iterator operator++(int)
{
auto old = *this;
++*this;
return old;
}
bool operator==(const vertex_converting_iterator& right) const
{
return m_it == right.m_it;
}
bool operator!=(const vertex_converting_iterator& right) const
{
return m_it != right.m_it;
}
vertex_converting_iterator() = default;
explicit vertex_converting_iterator(Face::const_iterator it):m_it(it) {}
vertex_converting_iterator(const vertex_converting_iterator& right):m_fLastVal(right.m_fLastVal), m_it(right.m_it)
{
if (m_fLastVal)
m_ptLastVal = right.m_ptLastVal;
}
vertex_converting_iterator(vertex_converting_iterator&& right):vertex_converting_iterator(right) {}
vertex_converting_iterator& operator=(const vertex_converting_iterator& right)
{
m_fLastVal = right.m_fLastVal;
m_it = right.m_it;
if (m_fLastVal)
m_ptLastVal = right.m_ptLastVal;
return *this;
}
vertex_converting_iterator& operator=(vertex_converting_iterator&& right)
{
return *this = right;
}
private:
mutable bool m_fLastVal = false;
mutable point_t m_ptLastVal;
Face::const_iterator m_it;
inline void invalidate_value() noexcept
{
m_fLastVal = false;
}
};
Face::operator face_t() const
{
return face_t(vertex_converting_iterator(this->begin()), vertex_converting_iterator(this->end()), this->size());
}
inline static bool vertex_has_zero_height(unsigned pt) noexcept
{
return g_matrix.point_z(pt) == 0;
}
struct FaceCompareLess
{
inline bool operator()(const Face& left, const Face& right) const noexcept
{
return std::lexicographical_compare(std::begin(left), std::end(left), std::begin(right), std::end(right));
}
};
struct FaceCompareEqual
{
inline bool operator()(const Face& left, const Face& right) const noexcept
{
return std::equal(std::begin(left), std::end(left), std::begin(right), std::end(right));
}
};
class FaceSet
{
std::vector<Face> m_vFaces;
public:
struct Constructor
{
Constructor()
{
m_vFaces.reserve((g_matrix.columns() - 1) * (g_matrix.rows() - 1) * 2);
}
Face& add_face(Face&& face)
{
m_vFaces.emplace_back(std::move(face));
return *m_vFaces.rbegin();
}
private:
friend class FaceSet;
std::vector<Face> m_vFaces;
};
FaceSet() = default;
FaceSet(Constructor&& constr):m_vFaces(std::move(constr.m_vFaces))
{
m_vFaces.shrink_to_fit();
#ifndef NDEBUG
if (m_vFaces.empty())
return;
std::sort(m_vFaces.begin(), m_vFaces.end(), FaceCompareLess());
FaceCompareEqual eq;
for (auto it = m_vFaces.begin(), it_n = std::next(m_vFaces.begin()); it_n != m_vFaces.end(); it = it_n++)
{
if (eq(*it, *it_n))
throw std::invalid_argument("Non-unique face is found in the input set"); //replace to it_n = m_vFaces.erase(++it, ++it_n);
}
#endif
}
auto begin() noexcept {return m_vFaces.begin();}
auto begin() const noexcept {return m_vFaces.begin();}
auto cbegin() const noexcept {return m_vFaces.cbegin();}
auto end() noexcept {return m_vFaces.end();}
auto end() const noexcept {return m_vFaces.end();}
auto cend() const noexcept {return m_vFaces.cend();}
auto size() const noexcept {return m_vFaces.size();}
bool empty() const noexcept {return m_vFaces.empty();}
};
/*
3 2
x x
x x
0 1
0) o o 1) o o 2) o o 3) o o
o o . o o . . .
4) o . 5) o . 6) o . 7) o .
o o . o o . . .
8) . o 9) . o 10) . o 11) . o
o o . o o . . .
12) . . 13) . . 14) . . 15) . .
o o . o o . . .
*/
unsigned char GetPointQuadrupletType(unsigned short quad_left_col, unsigned short quad_top_row)
{
assert(quad_left_col < g_matrix.columns() && quad_top_row < g_matrix.rows());
return
((unsigned char) (!g_matrix.is_empty_point(quad_left_col, quad_top_row)) << 3) | ((unsigned char)(!g_matrix.is_empty_point(quad_left_col + 1, quad_top_row)) << 2) |
((unsigned char) (!g_matrix.is_empty_point(quad_left_col, quad_top_row + 1)) << 0) | ((unsigned char) (!g_matrix.is_empty_point(quad_left_col + 1, quad_top_row + 1)) << 1);
}
bool Face::can_unite_with_quadruplet_left_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 11:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 13:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col, quad_top_row + 1)};
if (!this->can_unite_with(cur_face))
return false;
if (quad_top_row > 0)
return !cur_face.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1);
return true;
}
case 15:
{
Face face_lb = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
if (!this->can_unite_with(face_lb))
return false;
if (quad_top_row < g_matrix.rows() - 2 && face_lb.can_unite_with_quadruplet_top_edge(quad_left_col, quad_top_row + 1))
return false;
Face face_rt = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)};
return !face_lb.can_unite_with(face_rt) || quad_top_row == 0 || !face_rt.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1);
}
default:
return false;
};
}
bool Face::can_unite_with_quadruplet_top_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 13:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 14:
case 15:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
default:
return false;
};
}
bool Face::can_unite_with_quadruplet_right_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 7:
{
Face cur_face = Face{g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 14:
case 15:
{
Face face_rt = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)};
if (!this->can_unite_with(face_rt))
return false;
if (quad_top_row > 0 && face_rt.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1))
return false;
Face face_lb = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return !face_lb.can_unite_with(face_rt) || quad_top_row >= g_matrix.rows() - 2 || !face_lb.can_unite_with_quadruplet_top_edge(quad_left_col, quad_top_row + 1);
}
default:
return false;
};
}
bool Face::can_unite_with_quadruplet_bottom_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 7:
{
Face cur_face = Face{g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 11:
case 15:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
default:
return false;
};
}
//returns an index of the next quadruplet to analyze
unsigned Face::Constructor::add_face_to_the_right(unsigned short col, unsigned short row)
{
Face::Constructor::Reversed constrEnd;
unsigned short cur_col = col;
unsigned ret_index;
do
{
switch (GetPointQuadrupletType(cur_col, row))
{
case 11:
this->add_point(cur_col + 1, row + 1);
ret_index = g_matrix.locate(cur_col, row) + 1;
break;
case 13:
this->add_point(cur_col + 1, row);
ret_index = g_matrix.locate(cur_col, row) + 1;
break;
case 15:
{
Face lb_face = Face{g_matrix.locate(cur_col, row), g_matrix.locate(cur_col + 1, row + 1), g_matrix.locate(cur_col, row + 1)};
Face rt_face = Face{g_matrix.locate(cur_col, row), g_matrix.locate(cur_col + 1, row), g_matrix.locate(cur_col + 1, row + 1)};
if (lb_face.can_unite_with(rt_face) && (row == 0 || !rt_face.can_unite_with_quadruplet_bottom_edge(cur_col, row - 1)))
{
this->add_point(cur_col + 1, row);
constrEnd.add_point(cur_col + 1, row + 1);
if (cur_col < g_matrix.columns() - 2 && rt_face.can_unite_with_quadruplet_left_edge(cur_col + 1, row))
{
++cur_col;
continue;
}
ret_index = g_matrix.locate(cur_col, row) + 1;
}else
{
this->add_point(cur_col + 1, row + 1);
ret_index = g_matrix.locate(cur_col, row);
}
break;
}
default:
#ifndef NDEBUG
assert(false);
#endif
ret_index = g_matrix.locate(g_matrix.columns() - 1, g_matrix.rows() - 1) + 1;
}
break;
}while (true);
this->add_reversed_list(std::move(constrEnd));
return ret_index;
}
void Face::Constructor::add_face_to_the_bottom(unsigned short col, unsigned short row)
{
Face::Constructor::Reversed constrEnd;
unsigned short cur_row = row;
unsigned char cur_type = GetPointQuadrupletType(col, cur_row);
do
{
switch (cur_type)
{
case 13:
this->add_point(col, cur_row + 1);
break;
case 14:
this->add_point(col + 1, cur_row + 1);
break;
case 15:
{
Face rt_face = Face{g_matrix.locate(col, cur_row), g_matrix.locate(col + 1, cur_row), g_matrix.locate(col + 1, cur_row + 1)};
Face lb_face = Face{g_matrix.locate(col, cur_row), g_matrix.locate(col + 1, cur_row + 1), g_matrix.locate(col, cur_row + 1)};
if (lb_face.can_unite_with(rt_face))
{
this->add_point(col + 1, cur_row + 1);
constrEnd.add_point(col, cur_row + 1);
if (cur_row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, cur_row + 1))
{
cur_type = GetPointQuadrupletType(col, ++cur_row);
continue;
}
break;
}else
this->add_point(col + 1, cur_row + 1);
break;
}
#ifndef NDEBUG
default:
assert(false);
#endif
}
break;
}while (true);
this->add_reversed_list(std::move(constrEnd));
}
//returned object will be empty, if a vertex V is encountered for which V < g_matrix.locate(v1_col, v1_row)) is true
Face::Constructor obtain_big_face(unsigned short v1_col, unsigned short v1_row, unsigned short v2_col, unsigned short v2_row)
{
unsigned start = g_matrix.locate(v1_col, v1_row);
Face::Constructor constr;
unsigned short cur_col = v1_col;
unsigned short cur_row = v1_row;
unsigned short next_col = v2_col;
unsigned short next_row = v2_row;
unsigned next_index = g_matrix.locate(next_col, next_row);
constr.add_point(v1_col, v1_row);
do
{
if (next_index < start)
return Face::Constructor();
if (next_row == cur_row + 1)
{
if (next_col == cur_col + 1)
{
if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else //if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
assert(!g_matrix.is_empty_point(next_col, next_row - 1));
cur_col = next_col;
cur_row = next_row--;
}
}else if (next_col == cur_col)
{
if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else //if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
assert(!g_matrix.is_empty_point(next_col + 1, next_row - 1));
cur_col = next_col++;
cur_row = next_row--;
}
}else
{
assert(next_col == cur_col - 1);
if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else //if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
assert(!g_matrix.is_empty_point(next_col + 1, next_row));
cur_col = next_col++;
cur_row = next_row;
}
}
}else if (next_row == cur_row)
{
if (next_col == cur_col + 1)
{
if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else //if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
assert(!g_matrix.is_empty_point(next_col - 1, next_row - 1));
cur_col = next_col--;
cur_row = next_row--;
}
}else
{
assert(next_col == cur_col - 1);
if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else //if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
assert((!g_matrix.is_empty_point(next_col + 1, next_row + 1)));
cur_col = next_col++;
cur_row = next_row++;
}
}
}else
{
assert(next_row == cur_row - 1);
if (next_col == cur_col + 1)
{
if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else // if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
assert(!g_matrix.is_empty_point(next_col - 1, next_row));
cur_col = next_col--;
cur_row = next_row;
}
}else if (next_col == cur_col)
{
if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else //if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
assert(!g_matrix.is_empty_point(next_col - 1, next_row + 1));
cur_col = next_col--;
cur_row = next_row++;
}
}else
{
assert(next_col == cur_col - 1);
if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else //if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
assert(!g_matrix.is_empty_point(next_col, next_row + 1));
cur_col = next_col;
cur_row = next_row++;
}
}
}
constr.add_point(cur_col, cur_row);
}while ((next_index = g_matrix.locate(next_col, next_row)) != start);
return constr;
}
//returns an index of the last quadruplet included in the face
unsigned parse_vertex(FaceSet::Constructor& faces, unsigned short col, unsigned short row)
{
assert(col < g_matrix.columns() && row < g_matrix.rows());
if (col == g_matrix.columns() - 1)
return g_matrix.locate(col, row) + 1;
if (row == g_matrix.rows() - 1)
return g_matrix.columns() * g_matrix.rows();
switch (GetPointQuadrupletType(col, row))
{
case 7:
{
Face cur_face = Face{g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)};
if (row < g_matrix.rows() - 2 && cur_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return g_matrix.locate(col, row) + 1;
}else if (col < g_matrix.columns() - 2 && cur_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
Face::Constructor constr;
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}else
{
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
}
case 10:
{
if (g_matrix.is_empty_point(col - 1, row + 1))
return g_matrix.locate(col, row) + 1;
auto constr = obtain_big_face(col, row, col + 1, row + 1);
if (!constr.empty())
faces.add_face(std::move(constr));
return g_matrix.locate(col, row) + 1;
}
case 11:
{
Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)};
if (row < g_matrix.rows() - 2 && cur_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
}else if (col == 0 || !cur_face.can_unite_with_quadruplet_right_edge(col - 1, row))
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
case 12:
{
if (g_matrix.is_empty_point(col - 1, row + 1))
return g_matrix.locate(col, row) + 1;
auto constr = obtain_big_face(col, row, col + 1, row);
if (!constr.empty())
faces.add_face(std::move(constr));
return g_matrix.locate(col, row) + 1;
}
case 13:
{
Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col, row + 1)};
if ((col == 0 || !cur_face.can_unite_with_quadruplet_right_edge(col - 1, row))
&& (row == 0 || !cur_face.can_unite_with_quadruplet_bottom_edge(col, row - 1)))
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
case 14:
{
if (!g_matrix.is_empty_point(col - 1, row + 1))
{
auto constr = obtain_big_face(col, row, col + 1, row + 1);
if (!constr.empty())
faces.add_face(std::move(constr));
}
Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1)};
if (row > 0 && cur_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))
return g_matrix.locate(col, row) + 1;
if (col < g_matrix.columns() - 2 && cur_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}else
{
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
}
case 15:
{
Face lb_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)};
Face rt_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1)};
if (lb_face.can_unite_with(rt_face))
{
if (row > 0 && rt_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))
return g_matrix.locate(col, row) + 1;
if (row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return g_matrix.locate(col, row) + 1;
}
if (col > 0 && lb_face.can_unite_with_quadruplet_right_edge(col - 1, row))
return g_matrix.locate(col, row) + 1;
if (col == g_matrix.columns() - 2 || !rt_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
faces.add_face(Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)});
return g_matrix.locate(col, row) + 1;
}else
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}
}else
{
if (row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
}else if (col == 0 || !lb_face.can_unite_with_quadruplet_right_edge(col - 1, row))
faces.add_face(std::move(lb_face));
if (row == 0 || !rt_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))
{
if (col < g_matrix.columns() - 2 && rt_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}else
{
faces.add_face(std::move(rt_face));
return g_matrix.locate(col, row) + 1;
}
}else
return g_matrix.locate(col, row) + 1;
}
}
default:
return g_matrix.locate(col, row) + 1;
}
}
FaceSet parse_matrix(unsigned start_element /*= 0*/, unsigned end_element /*= g_matrix.columns() * g_matrix.rows()*/)
{
FaceSet::Constructor set;
for (unsigned index = start_element; index < end_element; )
{
index = parse_vertex(set, g_matrix.point_x(index), g_matrix.point_y(index));
}
return set;
}
#include <ostream>
static std::atomic_flag g_matrix_busy = ATOMIC_FLAG_INIT;
static unsigned convert_hgt_to_index_based_face(binary_ostream& os, short* pInput, unsigned short cColumns, unsigned short cRows, double eColumnResolution, double eRowResolution)
{
std::list<std::future<FaceSet>> futures;
while (g_matrix_busy.test_and_set(std::memory_order_acquire))
continue;
g_matrix = Matrix(pInput, cColumns, cRows, eColumnResolution, eRowResolution);
//auto cBlocks = unsigned(1);
auto cBlocks = unsigned(std::thread::hardware_concurrency());
auto cItemsTotal = unsigned(cColumns) * cRows;
auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks;
for (unsigned i = 0; i < cBlocks; ++i)
futures.emplace_back(std::async(std::launch::async, [i, cBlock, cItemsTotal]() -> auto
{
return parse_matrix(i * cBlock, std::min((i + 1) * cBlock, cItemsTotal));
}));
unsigned face_count = 0;
auto face_count_pos = os.tellp();
os.seekp(sizeof(unsigned), std::ios_base::cur);
for (auto& fut:futures)
{
auto set = fut.get();
face_count += unsigned(set.size());
for (const auto& face:set)
{
os << face.size();
for (auto pt:face)
os << g_matrix.point_x(pt) << g_matrix.point_y(pt) << g_matrix.point_z(pt);
}
}
g_matrix_busy.clear(std::memory_order_release);
auto endp = os.tellp();
os.seekp(face_count_pos);
os << face_count;
os.seekp(endp);
return face_count;
}
#if FILESYSTEM_CPP17
unsigned convert_hgt_to_index_based_face(std::filesystem::path input, std::filesystem::path output)
{
auto os = binary_ofstream(output);
std::ifstream is(input, std::ios_base::in | std::ios_base::binary);
is.seekg(0, std::ios_base::end);
auto cb = is.tellg();
if (cb % sizeof(short) != 0)
throw std::invalid_argument("Unexpected HGT file size");
is.seekg(0, std::ios_base::beg);
switch (cb)
{
case HGT_1.cColumns * HGT_1.cRows * sizeof(short):
{
auto pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is.read(reinterpret_cast<char*>(pInput.get()), cb);
return convert_hgt_to_index_based_face(os, pInput.get(), (unsigned short) (HGT_1.cColumns), (unsigned short) (HGT_1.cRows), HGT_1.dx, HGT_1.dy);
}
case HGT_3.cColumns * HGT_3.cRows * sizeof(short):
{
auto pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is.read(reinterpret_cast<char*>(pInput.get()), cb);
return convert_hgt_to_index_based_face(os, pInput.get(), (unsigned short) (HGT_3.cColumns), (unsigned short) (HGT_3.cRows), HGT_3.dx, HGT_3.dy);
}
default:
throw std::invalid_argument("Unexpected HGT file size");
};
}
#endif //FILESYSTEM_CPP17
struct conversion_result
{
conversion_result() = default;
conversion_result(std::vector<face_t>&& lstWater, std::vector<face_t>&& lstLand)
:m_WaterFaces(std::move(lstWater)), m_LandFaces(std::move(lstLand)) {}
inline std::vector<face_t>& water_faces() noexcept
{
return m_WaterFaces;
}
inline std::vector<face_t>& land_faces() noexcept
{
return m_LandFaces;
}
inline const std::vector<face_t>& water_faces() const noexcept
{
return m_WaterFaces;
}
inline const std::vector<face_t>& land_faces() const noexcept
{
return m_LandFaces;
}
private:
std::vector<face_t> m_WaterFaces;
std::vector<face_t> m_LandFaces;
};
template <class FaceType, class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void internal_face_to_external_face(std::true_type /*do_shift*/, FaceType&& face,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
auto domain_id = GetFaceDomainDataId(face);
auto ext = face_t(std::forward<FaceType>(face));
for (auto& pt:ext)
pt.z += -double(g_matrix.min_height());
switch (domain_id)
{
case ConstantDomainDataId::SurfaceLand:
std::forward<LandFacePlacementCallable>(land_callable)(std::move(ext));
break;
case ConstantDomainDataId::SurfaceWater:
std::forward<WaterFacePlacementCallable>(water_callable)(std::move(ext));
break;
default:
throw std::invalid_argument("Invalid face domain data in HGT");
}
}
template <class FaceType, class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void internal_face_to_external_face(std::false_type /*do_shift*/, FaceType&& face,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
switch (GetFaceDomainDataId(face))
{
case ConstantDomainDataId::SurfaceLand:
std::forward<LandFacePlacementCallable>(land_callable)(face_t(std::forward<FaceType>(face)));
break;
case ConstantDomainDataId::SurfaceWater:
std::forward<WaterFacePlacementCallable>(water_callable)(face_t(std::forward<FaceType>(face)));
break;
default:
throw std::invalid_argument("Invalid face domain data in HGT");
}
}
template <class fDoShift, class InternalFaceSetBeginIteratorType, class InternalFaceSetEndIteratorType,
class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void translate_internal_face_set(fDoShift do_shift, InternalFaceSetBeginIteratorType internal_set_begin, InternalFaceSetEndIteratorType internal_set_end,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
static_assert(std::is_same_v<fDoShift, std::true_type> || std::is_same_v<fDoShift, std::false_type>);
for (auto itFace = internal_set_begin; itFace != internal_set_end; ++itFace)
internal_face_to_external_face(do_shift, *itFace, std::forward<LandFacePlacementCallable>(land_callable),
std::forward<WaterFacePlacementCallable>(water_callable));
}
template <class FaceSetType, class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void translate_internal_face_set(FaceSetType&& face_set,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
if (g_matrix.min_height() < 0)
translate_internal_face_set(std::true_type(), std::begin(face_set), std::end(face_set), std::forward<LandFacePlacementCallable>(land_callable),
std::forward<WaterFacePlacementCallable>(water_callable));
else
translate_internal_face_set(std::false_type(), std::begin(face_set), std::end(face_set), std::forward<LandFacePlacementCallable>(land_callable),
std::forward<WaterFacePlacementCallable>(water_callable));
}
struct hgt_state
{
void start(binary_ostream& os, IDomainConverter& converter, unsigned points_to_process_at_start)
{
assert(m_pOs == nullptr && m_faces.empty() && process_land_face_ptr == nullptr && process_water_face_ptr == nullptr);
m_pOs = &os;
m_face_water_domain_data = converter.constant_face_domain_data(ConstantDomainDataId::SurfaceWater);
m_poly_water_domain_data = converter.constant_poly_domain_data(ConstantDomainDataId::SurfaceWater);
m_face_land_domain_data = converter.constant_face_domain_data(ConstantDomainDataId::SurfaceLand);
m_poly_land_domain_data = converter.constant_poly_domain_data(ConstantDomainDataId::SurfaceLand);
auto internal_set = parse_matrix(0, points_to_process_at_start);
process_land_face_ptr = &hgt_state::write_land_face_and_poly_header_to_stream;
process_water_face_ptr = &hgt_state::write_water_face_and_poly_header_to_stream;
std::vector<face_t> stored_faces;
stored_faces.reserve(internal_set.size());
translate_internal_face_set(internal_set,
[this](face_t&& face) {this->process_land_face(std::move(face));},
[&stored_faces](face_t&& face) {stored_faces.emplace_back(std::move(face));});
stored_faces.shrink_to_fit();
m_face_count_water = unsigned(stored_faces.size());
m_face_count_land = unsigned(internal_set.size()) - m_face_count_water;
m_faces.emplace_back(std::move(stored_faces));
}
void add_results(conversion_result&& res)
{
m_face_count_land += CAMaaS::size_type(res.land_faces().size());
m_face_count_water += CAMaaS::size_type(res.water_faces().size());
for (auto& face:res.land_faces())
process_land_face(std::move(face));
res.land_faces().clear();
m_faces.emplace_back(std::move(res.water_faces()));
}
hgt_t::conversion_statistics_t finalize()
{
if (m_face_count_land != 0)
{
m_pOs->seekp(m_face_count_pos);
*m_pOs << CAMaaS::size_type(m_face_count_land);
m_pOs->seekp(0, std::ios_base::end);
}
if (m_face_count_water != 0)
{
for (auto& vWater:m_faces)
{
for (auto& face:vWater)
this->process_water_face(std::move(face));
}
}
short min_height = g_matrix.min_height(), max_height = g_matrix.max_height();
if (min_height < 0)
{
max_height -= min_height;
min_height = 0;
}
hgt_t::conversion_statistics_t res{m_objects};
*this = hgt_state();
return res;
}
private:
CAMaaS::size_type m_objects = 0;
binary_ostream* m_pOs = nullptr;
binary_ostream::pos_type m_face_count_pos = 0;
CAMaaS::size_type m_face_count_land = 0;
CAMaaS::size_type m_face_count_water = 0;
std::list<std::vector<face_t>> m_faces;
void (hgt_state::*process_land_face_ptr)(face_t&& face) = nullptr;
void (hgt_state::*process_water_face_ptr)(face_t&& face) = nullptr;
domain_data_map m_face_water_domain_data, m_poly_water_domain_data, m_face_land_domain_data, m_poly_land_domain_data;
void write_poly_header(std::string_view poly_name, const domain_data_map& domain_data)
{
*m_pOs << std::uint32_t(poly_name.size());
m_pOs->write(poly_name.data(), poly_name.size());
*m_pOs << std::uint32_t(domain_data.size());
for (auto& prDomain:domain_data)
{
*m_pOs << std::uint32_t(prDomain.first.size());
m_pOs->write(prDomain.first.data(), prDomain.first.size());
*m_pOs << std::uint32_t(prDomain.second.size());
m_pOs->write(prDomain.second.data(), prDomain.second.size());
}
*m_pOs << CAMaaS::ObjectPoly;
m_face_count_pos = m_pOs->tellp();
}
inline void write_land_poly_header()
{
this->write_poly_header("HGT land", m_poly_land_domain_data);
*m_pOs << m_face_count_land;
}
void write_water_poly_header()
{
this->write_poly_header("HGT water", m_poly_water_domain_data);
*m_pOs << m_face_count_water;
}
void write_face_to_stream(face_t&& face, const domain_data_map& domain_data)
{
*m_pOs << std::uint32_t(face.size());
for (auto& pt:face)
*m_pOs << std::uint32_t(3) << pt.x << pt.y << pt.z;
*m_pOs << std::uint32_t(domain_data.size());
for (auto& prDomain:domain_data)
{
*m_pOs << std::uint32_t(prDomain.first.size());
m_pOs->write(prDomain.first.data(), prDomain.first.size());
*m_pOs << std::uint32_t(prDomain.second.size());
m_pOs->write(prDomain.second.data(), prDomain.second.size());
}
}
void write_water_face_to_stream(face_t&& face)
{
this->write_face_to_stream(std::move(face), m_face_water_domain_data);
}
void write_land_face_to_stream(face_t&& face)
{
this->write_face_to_stream(std::move(face), m_face_land_domain_data);
}
void write_water_face_and_poly_header_to_stream(face_t&& face)
{
++m_objects;
this->write_water_poly_header();
this->write_water_face_to_stream(std::move(face));
process_water_face_ptr = &hgt_state::write_water_face_to_stream;
}
void write_land_face_and_poly_header_to_stream(face_t&& face)
{
++m_objects;
this->write_land_poly_header();
this->write_land_face_to_stream(std::move(face));
process_land_face_ptr = &hgt_state::write_land_face_to_stream;
}
inline void process_land_face(face_t&& face)
{
return (this->*process_land_face_ptr)(std::move(face));
}
inline void process_water_face(face_t&& face)
{
return (this->*process_water_face_ptr)(std::move(face));
}
};
class hgt_impl_t:public hgt_t
{
std::unique_ptr<short[]> m_pInput;
IDomainConverter* m_pConverter;
hgt_t::attributes_t m_attr;
public:
hgt_impl_t() = default;
hgt_impl_t(std::istream& is_data, IDomainConverter& converter):m_pConverter(std::addressof(converter))
{
is_data.seekg(0, std::ios_base::end);
auto cb = is_data.tellg();
if (cb % sizeof(short) != 0)
throw std::invalid_argument("Unexpected HGT file size");
is_data.seekg(0, std::ios_base::beg);
switch (cb)
{
case HGT_1.cColumns * HGT_1.cRows * sizeof(short):
{
m_attr.resolution = HGT_1;
m_pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is_data.read(reinterpret_cast<char*>(m_pInput.get()), cb);
break;
}
case HGT_3.cColumns * HGT_3.cRows * sizeof(short):
{
m_attr.resolution = HGT_3;
m_pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is_data.read(reinterpret_cast<char*>(m_pInput.get()), cb);
break;
}
default:
throw std::invalid_argument("Unexpected HGT file size");
};
while (g_matrix_busy.test_and_set(std::memory_order_acquire))
continue;
g_matrix = Matrix(m_pInput.get(),
(unsigned short) m_attr.resolution.cColumns, (unsigned short) m_attr.resolution.cRows,
m_attr.resolution.dx, m_attr.resolution.dy);
m_attr.min_height = g_matrix.min_height();
m_attr.max_height = g_matrix.max_height();
m_attr.height_offset = m_attr.min_height < 0?-m_attr.min_height:0;
}
hgt_impl_t(const hgt_impl_t&) = default;
hgt_impl_t(hgt_impl_t&&) = default;
hgt_impl_t& operator=(const hgt_impl_t&) = default;
hgt_impl_t& operator=(hgt_impl_t&&) = default;
virtual ~hgt_impl_t()
{
g_matrix_busy.clear(std::memory_order_relaxed);
}
virtual const attributes_t& attributes() const
{
return m_attr;
}
virtual conversion_statistics_t write(binary_ostream& os) const
{
auto cBlocks = unsigned(std::thread::hardware_concurrency());
auto cItemsTotal = unsigned(m_attr.resolution.cColumns * m_attr.resolution.cRows);
auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks;
std::list<std::future<conversion_result>> futures;
for (unsigned i = 1; i < cBlocks; ++i)
futures.emplace_back(std::async(std::launch::async, [i, cBlock, cItemsTotal]() -> auto
{
std::vector<face_t> land_faces, water_faces;
unsigned start_element = i * cBlock;
unsigned end_element = std::min(start_element + cBlock, cItemsTotal);
auto internal_set = parse_matrix(start_element, end_element);
land_faces.reserve(internal_set.size());
water_faces.reserve(internal_set.size());
translate_internal_face_set(internal_set,
[&land_faces](face_t&& face) {land_faces.emplace_back(std::move(face));},
[&water_faces](face_t&& face) {water_faces.emplace_back(std::move(face));});
water_faces.shrink_to_fit();
land_faces.shrink_to_fit();
return conversion_result(std::move(water_faces), std::move(land_faces));
}));
hgt_state face_converter;
face_converter.start(os, *m_pConverter, std::min(cBlock, cItemsTotal));
for (auto& fut:futures)
face_converter.add_results(fut.get());
return face_converter.finalize();
}
};
std::unique_ptr<hgt_t> hgt_t::read(std::istream& is_data, IDomainConverter& converter)
{
return std::make_unique<hgt_impl_t>(is_data, converter);
}
| 35.778551
| 178
| 0.696312
|
lpsztemp
|
ffbedafd1c1ffd4835eac9d1aa99cbb8bc48a4f4
| 11,033
|
cpp
|
C++
|
project/src/backend/sdl/SDLSystem.cpp
|
ubald/lime
|
4c0d09368ebff06742dd062bb6872306a8a44d95
|
[
"MIT"
] | null | null | null |
project/src/backend/sdl/SDLSystem.cpp
|
ubald/lime
|
4c0d09368ebff06742dd062bb6872306a8a44d95
|
[
"MIT"
] | null | null | null |
project/src/backend/sdl/SDLSystem.cpp
|
ubald/lime
|
4c0d09368ebff06742dd062bb6872306a8a44d95
|
[
"MIT"
] | null | null | null |
#include <graphics/PixelFormat.h>
#include <math/Rectangle.h>
#include <system/Clipboard.h>
#include <system/JNI.h>
#include <system/System.h>
#ifdef HX_MACOS
#include <CoreFoundation/CoreFoundation.h>
#endif
#ifdef HX_WINDOWS
#include <shlobj.h>
#include <stdio.h>
//#include <io.h>
//#include <fcntl.h>
#ifdef __MINGW32__
#ifndef CSIDL_MYDOCUMENTS
#define CSIDL_MYDOCUMENTS CSIDL_PERSONAL
#endif
#ifndef SHGFP_TYPE_CURRENT
#define SHGFP_TYPE_CURRENT 0
#endif
#endif
#if UNICODE
#define WIN_StringToUTF8(S) SDL_iconv_string("UTF-8", "UTF-16LE", (char *)(S), (SDL_wcslen(S)+1)*sizeof(WCHAR))
#define WIN_UTF8ToString(S) (WCHAR *)SDL_iconv_string("UTF-16LE", "UTF-8", (char *)(S), SDL_strlen(S)+1)
#else
#define WIN_StringToUTF8(S) SDL_iconv_string("UTF-8", "ASCII", (char *)(S), (SDL_strlen(S)+1))
#define WIN_UTF8ToString(S) SDL_iconv_string("ASCII", "UTF-8", (char *)(S), SDL_strlen(S)+1)
#endif
#endif
#include <SDL.h>
#include <string>
namespace lime {
static int id_bounds;
static int id_currentMode;
static int id_height;
static int id_name;
static int id_pixelFormat;
static int id_refreshRate;
static int id_supportedModes;
static int id_width;
static bool init = false;
const char* Clipboard::GetText () {
return SDL_GetClipboardText ();
}
bool Clipboard::HasText () {
return SDL_HasClipboardText ();
}
void Clipboard::SetText (const char* text) {
SDL_SetClipboardText (text);
}
void *JNI::GetEnv () {
#ifdef ANDROID
return SDL_AndroidGetJNIEnv ();
#else
return 0;
#endif
}
const char* System::GetDirectory (SystemDirectory type, const char* company, const char* title) {
switch (type) {
case APPLICATION:
return SDL_GetBasePath ();
break;
case APPLICATION_STORAGE:
return SDL_GetPrefPath (company, title);
break;
case DESKTOP: {
#if defined (HX_WINRT)
Windows::Storage::StorageFolder folder = Windows::Storage::KnownFolders::HomeGroup;
std::wstring resultW (folder->Begin ());
std::string result (resultW.begin (), resultW.end ());
return result.c_str ();
#elif defined (HX_WINDOWS)
char result[MAX_PATH] = "";
SHGetFolderPath (NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, result);
return WIN_StringToUTF8 (result);
#else
std::string result = std::string (getenv ("HOME")) + std::string ("/Desktop");
return result.c_str ();
#endif
break;
}
case DOCUMENTS: {
#if defined (HX_WINRT)
Windows::Storage::StorageFolder folder = Windows::Storage::KnownFolders::DocumentsLibrary;
std::wstring resultW (folder->Begin ());
std::string result (resultW.begin (), resultW.end ());
return result.c_str ();
#elif defined (HX_WINDOWS)
char result[MAX_PATH] = "";
SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, result);
return WIN_StringToUTF8 (result);
#else
std::string result = std::string (getenv ("HOME")) + std::string ("/Documents");
return result.c_str ();
#endif
break;
}
case FONTS: {
#if defined (HX_WINRT)
return 0;
#elif defined (HX_WINDOWS)
char result[MAX_PATH] = "";
SHGetFolderPath (NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, result);
return WIN_StringToUTF8 (result);
#elif defined (HX_MACOS)
return "/Library/Fonts";
#elif defined (IPHONEOS)
return "/System/Library/Fonts/Cache";
#elif defined (ANDROID)
return "/system/fonts";
#elif defined (BLACKBERRY)
return "/usr/fonts/font_repository/monotype";
#else
return "/usr/share/fonts/truetype";
#endif
break;
}
case USER: {
#if defined (HX_WINRT)
Windows::Storage::StorageFolder folder = Windows::Storage::ApplicationData::Current->RoamingFolder;
std::wstring resultW (folder->Begin ());
std::string result (resultW.begin (), resultW.end ());
return result.c_str ();
#elif defined (HX_WINDOWS)
char result[MAX_PATH] = "";
SHGetFolderPath (NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, result);
return WIN_StringToUTF8 (result);
#else
std::string result = getenv ("HOME");
return result.c_str ();
#endif
break;
}
}
return 0;
}
value System::GetDisplay (int id) {
if (!init) {
id_bounds = val_id ("bounds");
id_currentMode = val_id ("currentMode");
id_height = val_id ("height");
id_name = val_id ("name");
id_pixelFormat = val_id ("pixelFormat");
id_refreshRate = val_id ("refreshRate");
id_supportedModes = val_id ("supportedModes");
id_width = val_id ("width");
init = true;
}
int numDisplays = GetNumDisplays ();
if (id < 0 || id >= numDisplays) {
return alloc_null ();
}
value display = alloc_empty_object ();
alloc_field (display, id_name, alloc_string (SDL_GetDisplayName (id)));
SDL_Rect bounds = { 0, 0, 0, 0 };
SDL_GetDisplayBounds (id, &bounds);
alloc_field (display, id_bounds, Rectangle (bounds.x, bounds.y, bounds.w, bounds.h).Value ());
SDL_DisplayMode currentDisplayMode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
SDL_DisplayMode displayMode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
SDL_GetCurrentDisplayMode (id, ¤tDisplayMode);
int numDisplayModes = SDL_GetNumDisplayModes (id);
value supportedModes = alloc_array (numDisplayModes);
value mode;
for (int i = 0; i < numDisplayModes; i++) {
SDL_GetDisplayMode (id, i, &displayMode);
if (displayMode.format == currentDisplayMode.format && displayMode.w == currentDisplayMode.w && displayMode.h == currentDisplayMode.h && displayMode.refresh_rate == currentDisplayMode.refresh_rate) {
alloc_field (display, id_currentMode, alloc_int (i));
}
mode = alloc_empty_object ();
alloc_field (mode, id_height, alloc_int (displayMode.h));
switch (displayMode.format) {
case SDL_PIXELFORMAT_ARGB8888:
alloc_field (mode, id_pixelFormat, alloc_int (ARGB32));
break;
case SDL_PIXELFORMAT_BGRA8888:
case SDL_PIXELFORMAT_BGRX8888:
alloc_field (mode, id_pixelFormat, alloc_int (BGRA32));
break;
default:
alloc_field (mode, id_pixelFormat, alloc_int (RGBA32));
}
alloc_field (mode, id_refreshRate, alloc_int (displayMode.refresh_rate));
alloc_field (mode, id_width, alloc_int (displayMode.w));
val_array_set_i (supportedModes, i, mode);
}
alloc_field (display, id_supportedModes, supportedModes);
return display;
}
int System::GetNumDisplays () {
return SDL_GetNumVideoDisplays ();
}
double System::GetTimer () {
return SDL_GetTicks ();
}
FILE* FILE_HANDLE::getFile () {
#ifndef HX_WINDOWS
switch (((SDL_RWops*)handle)->type) {
case SDL_RWOPS_STDFILE:
return ((SDL_RWops*)handle)->hidden.stdio.fp;
case SDL_RWOPS_JNIFILE:
{
#ifdef ANDROID
FILE* file = ::fdopen (((SDL_RWops*)handle)->hidden.androidio.fd, "rb");
::fseek (file, ((SDL_RWops*)handle)->hidden.androidio.offset, 0);
return file;
#endif
}
case SDL_RWOPS_WINFILE:
{
/*#ifdef HX_WINDOWS
printf("SDKFLJDSLFKJ\n");
int fd = _open_osfhandle ((intptr_t)((SDL_RWops*)handle)->hidden.windowsio.h, _O_RDONLY);
if (fd != -1) {
printf("SDKFLJDSLFKJ\n");
return ::fdopen (fd, "rb");
}
#endif*/
}
}
return NULL;
#else
return (FILE*)handle;
#endif
}
int FILE_HANDLE::getLength () {
#ifndef HX_WINDOWS
return SDL_RWsize (((SDL_RWops*)handle));
#else
return 0;
#endif
}
bool FILE_HANDLE::isFile () {
#ifndef HX_WINDOWS
return ((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE;
#else
return true;
#endif
}
int fclose (FILE_HANDLE *stream) {
#ifndef HX_WINDOWS
if (stream) {
int code = SDL_RWclose ((SDL_RWops*)stream->handle);
delete stream;
return code;
}
return 0;
#else
if (stream) {
int code = ::fclose ((FILE*)stream->handle);
delete stream;
return code;
}
return 0;
#endif
}
FILE_HANDLE *fdopen (int fd, const char *mode) {
#ifndef HX_WINDOWS
FILE* fp = ::fdopen (fd, mode);
SDL_RWops *result = SDL_RWFromFP (fp, SDL_TRUE);
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
#else
FILE* result = ::fdopen (fd, mode);
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
#endif
}
FILE_HANDLE *fopen (const char *filename, const char *mode) {
#ifndef HX_WINDOWS
SDL_RWops *result;
#ifdef HX_MACOS
result = SDL_RWFromFile (filename, "rb");
if (!result) {
CFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
CFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL);
CFRelease (str);
if (path) {
str = CFURLCopyPath (path);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8);
char *buffer = (char *)malloc (maxSize);
if (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) {
result = SDL_RWFromFP (::fopen (buffer, "rb"), SDL_TRUE);
free (buffer);
}
CFRelease (str);
CFRelease (path);
}
}
#else
result = SDL_RWFromFile (filename, mode);
#endif
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
#else
FILE* result = ::fopen (filename, mode);
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
#endif
}
size_t fread (void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {
#ifndef HX_WINDOWS
return SDL_RWread (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);
#else
return ::fread (ptr, size, count, (FILE*)stream->handle);
#endif
}
int fseek (FILE_HANDLE *stream, long int offset, int origin) {
#ifndef HX_WINDOWS
return SDL_RWseek (stream ? (SDL_RWops*)stream->handle : NULL, offset, origin);
#else
return ::fseek ((FILE*)stream->handle, offset, origin);
#endif
}
long int ftell (FILE_HANDLE *stream) {
#ifndef HX_WINDOWS
return SDL_RWtell (stream ? (SDL_RWops*)stream->handle : NULL);
#else
return ::ftell ((FILE*)stream->handle);
#endif
}
size_t fwrite (const void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {
#ifndef HX_WINDOWS
return SDL_RWwrite (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);
#else
return ::fwrite (ptr, size, count, (FILE*)stream->handle);
#endif
}
}
| 19.088235
| 202
| 0.628388
|
ubald
|
ffbf7e11e20dd95107c6ac3bcd024ed2ab30fbe9
| 707
|
cpp
|
C++
|
weekly-contest-129/binary-string-with-substrings-representing-1-to-n/binary-string-with-substrings-representing-1-to-n.cpp
|
Shuumatsu/leetcode-weekly-contest
|
6cc5cf8e8b57775e68b5bdeb932e30e327502c65
|
[
"MIT"
] | 1
|
2019-05-28T01:53:36.000Z
|
2019-05-28T01:53:36.000Z
|
weekly-contest-129/binary-string-with-substrings-representing-1-to-n/binary-string-with-substrings-representing-1-to-n.cpp
|
Shuumatsu/leetcode-weekly-contest
|
6cc5cf8e8b57775e68b5bdeb932e30e327502c65
|
[
"MIT"
] | null | null | null |
weekly-contest-129/binary-string-with-substrings-representing-1-to-n/binary-string-with-substrings-representing-1-to-n.cpp
|
Shuumatsu/leetcode-weekly-contest
|
6cc5cf8e8b57775e68b5bdeb932e30e327502c65
|
[
"MIT"
] | null | null | null |
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <vector>
using namespace std;
auto to_binary = [&](auto n) {
vector<char> b;
while (n != 0) {
b.push_back(n & 1 == 1 ? '1' : '0');
n /= 2;
}
reverse(b.begin(), b.end());
ostringstream bss;
std::copy(b.begin(), b.end(), ostream_iterator<char>(bss));
return bss.str();
};
class Solution {
public:
bool queryString(string str, int N) {
for (auto i = 0; i <= N; i++) {
if (str.find(to_binary(i)) == string::npos) {
return false;
}
}
return true;
}
};
| 19.108108
| 63
| 0.523338
|
Shuumatsu
|
ffc1ec7b7db76f37d39ecd7a2bc03c0e050477eb
| 11,817
|
cpp
|
C++
|
vlr-util/util.Unicode.cpp
|
nick42/vlr-util
|
937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91
|
[
"Artistic-2.0"
] | null | null | null |
vlr-util/util.Unicode.cpp
|
nick42/vlr-util
|
937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91
|
[
"Artistic-2.0"
] | null | null | null |
vlr-util/util.Unicode.cpp
|
nick42/vlr-util
|
937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91
|
[
"Artistic-2.0"
] | null | null | null |
#include "pch.h"
#include "util.Unicode.h"
#include "UtilMacros.Assertions.h"
#include "UtilMacros.General.h"
#include "util.range_checked_cast.h"
#include "util.CStringBufferAccess.h"
NAMESPACE_BEGIN( vlr )
NAMESPACE_BEGIN( util )
HRESULT CStringConversion::MultiByte_to_UTF16(
std::string_view svValue,
wchar_t* pOutputBuffer,
size_t nOutputBufferLengthBytes,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
if (svValue.empty())
{
return S_FALSE;
}
bool bInputBufferShouldIncludeNullTerminator = true
&& oStringConversionOptions.m_bInputStringIsNullTerminated
&& (!oStringConversionOptions.m_bGenerateResultNotNullTerminated)
;
auto nEffectiveInputBufferLengthChars = svValue.length() + (bInputBufferShouldIncludeNullTerminator ? 1 : 0);
auto nOutputBufferLengthChars = (nOutputBufferLengthBytes / sizeof( wchar_t ));
bool bNeedAdditionalSpaceInOutputBufferToAddNullTerminator = true
&& (!bInputBufferShouldIncludeNullTerminator)
&& (!oStringConversionOptions.m_bGenerateResultNotNullTerminated)
&& (!oStringConversionOptions.m_bInputStringIsNullTerminated)
;
size_t nOutputBufferLengthAdjustmentBytes = bNeedAdditionalSpaceInOutputBufferToAddNullTerminator ? sizeof( wchar_t ) : 0;
// Be sure we don't underflow, if we passed a zero for buffer length
auto nUsableOutputBufferLengthChars = (nOutputBufferLengthChars == 0) ? 0 : nOutputBufferLengthChars - nOutputBufferLengthAdjustmentBytes;
auto nResult = ::MultiByteToWideChar(
oStringConversionOptions.GetCodePageIdentifier(),
oStringConversionOptions.OnMultiByteToWideChar_GetFlags(),
svValue.data(),
range_checked_cast<int>(nEffectiveInputBufferLengthChars),
pOutputBuffer,
range_checked_cast<int>(nUsableOutputBufferLengthChars) );
if (nResult == 0)
{
return HRESULT_FROM_WIN32( GetLastError() );
}
VLR_IF_NOT_NULL( pStringConversionResults )->m_nOuputSizeBytes = (range_checked_cast<size_t>(nResult) * sizeof( wchar_t )) + nOutputBufferLengthAdjustmentBytes;
if (range_checked_cast<size_t>(nResult) > nUsableOutputBufferLengthChars)
{
return S_FALSE;
}
if (bNeedAdditionalSpaceInOutputBufferToAddNullTerminator)
{
ASSERT( range_checked_cast<size_t>(nResult) < nOutputBufferLengthChars );
pOutputBuffer[nResult] = L'\0';
}
return S_OK;
}
HRESULT CStringConversion::UTF16_to_MultiByte(
std::wstring_view svValue,
char* pOutputBuffer,
size_t nOutputBufferLengthBytes,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
if (svValue.empty())
{
return S_FALSE;
}
bool bInputBufferShouldIncludeNullTerminator = true
&& oStringConversionOptions.m_bInputStringIsNullTerminated
&& (!oStringConversionOptions.m_bGenerateResultNotNullTerminated)
;
auto nEffectiveInputBufferLengthChars = svValue.length() + (bInputBufferShouldIncludeNullTerminator ? 1 : 0);
auto nOutputBufferLengthChars = (nOutputBufferLengthBytes / sizeof( char ));
bool bNeedAdditionalSpaceInOutputBufferToAddNullTerminator = true
&& (!bInputBufferShouldIncludeNullTerminator)
&& (!oStringConversionOptions.m_bGenerateResultNotNullTerminated)
&& (!oStringConversionOptions.m_bInputStringIsNullTerminated)
;
size_t nOutputBufferLengthAdjustmentBytes = bNeedAdditionalSpaceInOutputBufferToAddNullTerminator ? sizeof( char ) : 0;
// Be sure we don't underflow, if we passed a zero for buffer length
auto nUsableOutputBufferLengthChars = (nOutputBufferLengthChars == 0) ? 0 : nOutputBufferLengthChars - nOutputBufferLengthAdjustmentBytes;
auto nResult = ::WideCharToMultiByte(
oStringConversionOptions.GetCodePageIdentifier(),
oStringConversionOptions.OnWideCharToMultiByte_GetFlags(),
svValue.data(),
range_checked_cast<int>(nEffectiveInputBufferLengthChars),
pOutputBuffer,
range_checked_cast<int>(nUsableOutputBufferLengthChars),
oStringConversionOptions.OnWideCharToMultiByte_GetDefaultChar(),
oStringConversionOptions.OnWideCharToMultiByte_GetUsedDefaultChar( pStringConversionResults ) );
if (nResult == 0)
{
return HRESULT_FROM_WIN32( GetLastError() );
}
VLR_IF_NOT_NULL( pStringConversionResults )->m_nOuputSizeBytes = (range_checked_cast<size_t>(nResult) * sizeof( char )) + nOutputBufferLengthAdjustmentBytes;
if (range_checked_cast<size_t>(nResult) > nUsableOutputBufferLengthChars)
{
return S_FALSE;
}
if (bNeedAdditionalSpaceInOutputBufferToAddNullTerminator)
{
ASSERT( range_checked_cast<size_t>(nResult) < nOutputBufferLengthChars );
pOutputBuffer[nResult] = '\0';
}
return S_OK;
}
HRESULT CStringConversion::MultiByte_to_UTF16(
vlr::zstring_view svValue,
wchar_t* pOutputBuffer,
size_t nOutputBufferLengthBytes,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
auto oStringConversionOptions_Updated = StringConversionOptions{ oStringConversionOptions }.WithNullTerminatedString( true );
return MultiByte_to_UTF16(
static_cast<std::string_view>(svValue),
pOutputBuffer,
nOutputBufferLengthBytes,
oStringConversionOptions_Updated,
pStringConversionResults );
}
HRESULT CStringConversion::UTF16_to_MultiByte(
vlr::wzstring_view svValue,
char* pOutputBuffer,
size_t nOutputBufferLengthBytes,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
auto oStringConversionOptions_Updated = StringConversionOptions{ oStringConversionOptions }.WithNullTerminatedString( true );
return UTF16_to_MultiByte(
static_cast<std::wstring_view>(svValue),
pOutputBuffer,
nOutputBufferLengthBytes,
oStringConversionOptions_Updated,
pStringConversionResults );
}
HRESULT CStringConversion::MultiByte_to_UTF16(
std::string_view svValue,
std::wstring& strOutput,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
HRESULT hr;
auto nOutputBufferSizeChars = svValue.length();
while (true)
{
strOutput.resize( nOutputBufferSizeChars );
auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( wchar_t );
auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true );
auto oStringConversionResults = StringConversionResults{};
hr = MultiByte_to_UTF16(
svValue,
strOutput.data(),
nOutputBufferSizeBytes,
oStringConversionOptions_Local,
&oStringConversionResults );
ON_HR_NON_S_OK__RETURN_HRESULT( hr );
auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( wchar_t );
if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes)
{
nOutputBufferSizeChars = nOutputSizeChars;
continue;
}
// resize() again to truncate as necessary
strOutput.resize( nOutputSizeChars );
VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults;
break;
}
return S_OK;
}
HRESULT CStringConversion::UTF16_to_MultiByte(
std::wstring_view svValue,
std::string& strOutput,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
HRESULT hr;
auto nOutputBufferSizeChars = svValue.length();
while (true)
{
strOutput.resize( nOutputBufferSizeChars );
auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( char );
auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true );
auto oStringConversionResults = StringConversionResults{};
hr = UTF16_to_MultiByte(
svValue,
strOutput.data(),
nOutputBufferSizeBytes,
oStringConversionOptions_Local,
&oStringConversionResults );
ON_HR_NON_S_OK__RETURN_HRESULT( hr );
auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( char );
if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes)
{
nOutputBufferSizeChars = nOutputSizeChars;
continue;
}
// resize() again to truncate as necessary
strOutput.resize( nOutputSizeChars );
VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults;
break;
}
return S_OK;
}
HRESULT CStringConversion::MultiByte_to_UTF16(
const std::string& strValue,
std::wstring& strOutput,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
return MultiByte_to_UTF16(
std::string_view{ strValue.c_str(), strValue.length() },
strOutput,
oStringConversionOptions,
pStringConversionResults );
}
HRESULT CStringConversion::UTF16_to_MultiByte(
const std::wstring& strValue,
std::string& strOutput,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
return UTF16_to_MultiByte(
std::wstring_view{ strValue.c_str(), strValue.length() },
strOutput,
oStringConversionOptions,
pStringConversionResults );
}
HRESULT CStringConversion::MultiByte_to_UTF16(
std::string_view svValue,
CStringW& sOutput,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
HRESULT hr;
auto nOutputBufferSizeChars = svValue.length();
while (true)
{
auto oOutputBufferAccess = GetCStringBufferAccess( sOutput, range_checked_cast<int>(nOutputBufferSizeChars) );
auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( wchar_t );
auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true );
auto oStringConversionResults = StringConversionResults{};
hr = MultiByte_to_UTF16(
svValue,
oOutputBufferAccess,
nOutputBufferSizeBytes,
oStringConversionOptions_Local,
&oStringConversionResults );
ON_HR_NON_S_OK__RETURN_HRESULT( hr );
auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( wchar_t );
if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes)
{
nOutputBufferSizeChars = nOutputSizeChars;
continue;
}
oOutputBufferAccess.ReleaseBufferPtr( range_checked_cast<int>(nOutputSizeChars) );
VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults;
break;
}
return S_OK;
}
HRESULT CStringConversion::UTF16_to_MultiByte(
std::wstring_view svValue,
CStringA& sOutput,
const StringConversionOptions& oStringConversionOptions /*= {}*/,
StringConversionResults* pStringConversionResults /*= nullptr*/ )
{
HRESULT hr;
auto nOutputBufferSizeChars = svValue.length();
while (true)
{
auto oOutputBufferAccess = GetCStringBufferAccess( sOutput, range_checked_cast<int>(nOutputBufferSizeChars) );
auto nOutputBufferSizeBytes = nOutputBufferSizeChars * sizeof( char );
auto oStringConversionOptions_Local = StringConversionOptions{ oStringConversionOptions }.With_GenerateResultNotNullTerminated( true );
auto oStringConversionResults = StringConversionResults{};
hr = UTF16_to_MultiByte(
svValue,
oOutputBufferAccess,
nOutputBufferSizeBytes,
oStringConversionOptions_Local,
&oStringConversionResults );
ON_HR_NON_S_OK__RETURN_HRESULT( hr );
auto nOutputSizeChars = oStringConversionResults.m_nOuputSizeBytes / sizeof( char );
if (oStringConversionResults.m_nOuputSizeBytes > nOutputBufferSizeBytes)
{
nOutputBufferSizeChars = nOutputSizeChars;
continue;
}
oOutputBufferAccess.ReleaseBufferPtr( range_checked_cast<int>(nOutputSizeChars) );
VLR_IF_NOT_NULL_DEREF( pStringConversionResults ) = oStringConversionResults;
break;
}
return S_OK;
}
NAMESPACE_END //( util )
NAMESPACE_END //( vlr )
| 32.643646
| 161
| 0.800288
|
nick42
|
ffc33ffe362865453ca5d4e153cd433cf9efa726
| 10,393
|
cpp
|
C++
|
Alien Engine/Alien Engine/ComponentCollider.cpp
|
OverPowered-Team/Alien-GameEngine
|
713a8846a95fdf253d0869bdcad4ecd006b2e166
|
[
"MIT"
] | 7
|
2020-02-20T15:11:11.000Z
|
2020-05-19T00:29:04.000Z
|
Alien Engine/Alien Engine/ComponentCollider.cpp
|
OverPowered-Team/Alien-GameEngine
|
713a8846a95fdf253d0869bdcad4ecd006b2e166
|
[
"MIT"
] | 125
|
2020-02-29T17:17:31.000Z
|
2020-05-06T19:50:01.000Z
|
Alien Engine/Alien Engine/ComponentCollider.cpp
|
OverPowered-Team/Alien-GameEngine
|
713a8846a95fdf253d0869bdcad4ecd006b2e166
|
[
"MIT"
] | 1
|
2020-05-19T00:29:06.000Z
|
2020-05-19T00:29:06.000Z
|
#include "Globals.h"
#include "Application.h"
#include "ModuleRenderer3D.h"
#include "ComponentCollider.h"
#include "ComponentTransform.h"
#include "ComponentRigidBody.h"
#include "ComponentPhysics.h"
#include "ComponentMesh.h"
#include "GameObject.h"
#include "ReturnZ.h"
#include "Time.h"
#include "Event.h"
#include "Gizmos.h"
#include "Physics.h"
ComponentCollider::ComponentCollider(GameObject* go ) : ComponentBasePhysic(go)
{
// Default values
center = float3::zero();
rotation = float3::zero();
material = App->physx->CreateMaterial();
InitMaterial();
#ifndef GAME_VERSION
App->objects->debug_draw_list.emplace(this, std::bind(&ComponentCollider::DrawScene, this));
#endif // !GAME_VERSION
}
ComponentCollider::~ComponentCollider()
{
if (!IsController()) {
go->SendAlientEventThis(this, AlienEventType::COLLIDER_DELETED);
shape->release();
shape = nullptr;
}
material->release();
material = nullptr;
#ifndef GAME_VERSION
App->objects->debug_draw_list.erase(App->objects->debug_draw_list.find(this));
#endif // !GAME_VERSION
}
// Colliders Functions --------------------------------
void ComponentCollider::SetCenter(const float3& value)
{
center = value;
if (IsController()) return;
PxTransform trans = shape->getLocalPose();
trans.p = F3_TO_PXVEC3(center.Mul(physics->scale));
BeginUpdateShape();
shape->setLocalPose(trans);
EndUpdateShape();
}
void ComponentCollider::SetRotation(const float3& value)
{
rotation = value;
if (IsController()) return;
PxTransform trans = shape->getLocalPose();
float3 rad_rotation = DEGTORAD * rotation;
trans.q = QUAT_TO_PXQUAT(Quat::FromEulerXYZ(rad_rotation.x, rad_rotation.y, rad_rotation.z));
BeginUpdateShape();
shape->setLocalPose(trans);
EndUpdateShape();
}
void ComponentCollider::SetIsTrigger(bool value)
{
is_trigger = value;
if (IsController()) return;
BeginUpdateShape();
if (is_trigger) {
shape->setFlag(physx::PxShapeFlag::Enum::eSIMULATION_SHAPE, false);
shape->setFlag(physx::PxShapeFlag::Enum::eTRIGGER_SHAPE, true);
}
else {
shape->setFlag(physx::PxShapeFlag::Enum::eTRIGGER_SHAPE, false);
shape->setFlag(physx::PxShapeFlag::Enum::eSIMULATION_SHAPE, true);
}
EndUpdateShape();
}
void ComponentCollider::SetBouncing(const float value)
{
bouncing = value;
bouncing = Clamp<float>(bouncing, 0.f, 1.f);
material->setRestitution(bouncing);
}
void ComponentCollider::SetStaticFriction(const float value)
{
static_friction = value;
static_friction = Clamp<float>(static_friction, 0.f, PX_MAX_F32);
material->setStaticFriction(static_friction);
}
void ComponentCollider::SetDynamicFriction(const float value)
{
dynamic_friction = value;
dynamic_friction = Clamp<float>(dynamic_friction, 0.f, PX_MAX_F32);
material->setDynamicFriction(dynamic_friction);
}
void ComponentCollider::SetFrictionCombineMode(CombineMode mode)
{
friction_combine = mode;
material->setFrictionCombineMode((PxCombineMode::Enum)(int)friction_combine);
}
void ComponentCollider::SetBouncingCombineMode(CombineMode mode)
{
bouncing_combine = mode;
material->setRestitutionCombineMode((PxCombineMode::Enum)(int)bouncing_combine);
}
void ComponentCollider::SetCollisionLayer(std::string layer)
{
int index = 0;
if (!physics->layers->GetIndexByName(layer, index)) return;
layer_num = index;
layer_name = layer;
BeginUpdateShape();
PxFilterData filter_data;
filter_data.word0 = index;
filter_data.word1 = physics->ID;
shape->setSimulationFilterData(filter_data);
shape->setQueryFilterData(filter_data);
EndUpdateShape();
physics->ChangedFilters();
}
std::string ComponentCollider::GetCollisionLayer()
{
return layer_name;
}
void ComponentCollider::SaveComponent(JSONArraypack* to_save)
{
to_save->SetBoolean("Enabled", enabled);
to_save->SetNumber("Type", (int)type);
to_save->SetFloat3("Center", center);
to_save->SetFloat3("Rotation", rotation);
to_save->SetBoolean("IsTrigger", is_trigger);
to_save->SetNumber("Bouncing", bouncing);
to_save->SetNumber("StaticFriction", static_friction);
to_save->SetNumber("DynamicFriction", dynamic_friction);
to_save->SetString("CollisionLayer", layer_name.c_str());
}
void ComponentCollider::LoadComponent(JSONArraypack* to_load)
{
enabled = to_load->GetBoolean("Enabled");
if (enabled == false) {
OnDisable();
}
BeginUpdateShape(true);
SetCenter(to_load->GetFloat3("Center"));
SetRotation(to_load->GetFloat3("Rotation"));
SetIsTrigger(to_load->GetBoolean("IsTrigger"));
SetBouncing(to_load->GetNumber("Bouncing"));
SetStaticFriction(to_load->GetNumber("StaticFriction"));
SetDynamicFriction(to_load->GetNumber("DynamicFriction"));
SetCollisionLayer(to_load->GetString("CollisionLayer", "Default"));
EndUpdateShape(true);
}
void ComponentCollider::OnEnable()
{
physics->AttachCollider(this);
}
void ComponentCollider::OnDisable()
{
physics->DettachCollider(this);
}
void ComponentCollider::DrawScene()
{
if (enabled && go->IsEnabled() && (go->IsSelected() || App->physx->debug_physics))
{
App->physx->DrawCollider(this);
}
}
void ComponentCollider::Reset()
{
BeginUpdateShape(true);
SetCenter(float3::zero());
SetRotation(float3::zero());
SetIsTrigger(false);
SetBouncing(0.1f);
SetStaticFriction(0.5f);
SetDynamicFriction(0.1f);
EndUpdateShape(true);
}
bool ComponentCollider::DrawInspector()
{
static bool check;
check = enabled;
ImGui::PushID(this);
if (ImGui::Checkbox("##CmpActive", &check)) {
enabled = check;
if (!enabled)
OnDisable();
else
OnEnable();
}
ImGui::SameLine();
if (ImGui::CollapsingHeader(name.c_str(), ¬_destroy))
{
ImGui::Spacing();
ImGui::SetCursorPosX(12.0f);
ImGui::Title(""); if (ImGui::Button("Fit Collider")) { Reset(); }
DrawLayersCombo();
float3 current_center = center;
float3 current_rotation = rotation;
bool current_is_trigger = is_trigger;
float current_bouncing = bouncing;
float current_static_friction = static_friction;
float current_dynamic_friction = dynamic_friction;
CombineMode current_f_mode = friction_combine;
CombineMode current_b_mode = bouncing_combine;
ImGui::Title("Center", 1); if (ImGui::DragFloat3("##center", current_center.ptr(), 0.05f)) { SetCenter(current_center); }
ImGui::Title("Rotation", 1); if (ImGui::DragFloat3("##rotation", current_rotation.ptr(), 0.2f)) { SetRotation(current_rotation); }
DrawSpecificInspector();
ImGui::Spacing();
ImGui::Spacing();
ImGui::Title("Is Trigger", 1); if (ImGui::Checkbox("##is_trigger", ¤t_is_trigger)) { SetIsTrigger(current_is_trigger); }
ImGui::Spacing();
ImGui::Title("Physic Material", 1); ImGui::Text("");
ImGui::Spacing();
ImGui::Spacing();
ImGui::Title("Bouncing", 2); if (ImGui::DragFloat("##bouncing", ¤t_bouncing, 0.01f, 0.00f, 1.f)) { SetBouncing(current_bouncing); }
ImGui::Title("Static Fric.", 2); if (ImGui::DragFloat("##static_friction", ¤t_static_friction, 0.01f, 0.00f, FLT_MAX)) { SetStaticFriction(current_static_friction); }
ImGui::Title("Dynamic Fric.", 2); if (ImGui::DragFloat("##dynamic_friction", ¤t_dynamic_friction, 0.01f, 0.00f, FLT_MAX)) { SetDynamicFriction(current_dynamic_friction); }
DrawCombineModeCombo(current_f_mode, 0);
DrawCombineModeCombo(current_b_mode, 1);
ImGui::Spacing();
}
ImGui::PopID();
return true;
}
void ComponentCollider::DrawLayersCombo()
{
ImGui::Title("Layer");
if (ImGui::BeginComboEx(std::string("##layers").c_str(), std::string(" " + physics->layers->names[layer_num]).c_str(), 200, ImGuiComboFlags_NoArrowButton))
{
for (int n = 0; n < physics->layers->names.size(); ++n)
{
bool is_selected = (layer_num == n);
if (ImGui::Selectable(std::string(" " + physics->layers->names[n]).c_str(), is_selected))
{
SetCollisionLayer(physics->layers->names[n]);
}
if (is_selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
}
void ComponentCollider::DrawCombineModeCombo(CombineMode& current_mode, int mode)
{
const char* name = (mode == 0) ? "Friction Combine" : "Bouncing Combine";
ImGui::PushID(name);
ImGui::Title(name, 2);
if (ImGui::BeginComboEx(std::string("##" + std::string(name)).c_str(), (std::string(" ") + mode_names[(int)current_mode]).c_str(), 200, ImGuiComboFlags_NoArrowButton))
{
for (int n = 0; n < (int)CombineMode::Unknown; ++n)
{
bool is_selected = ((int)current_mode == n);
if (ImGui::Selectable((std::string(" ") + mode_names[n]).c_str(), is_selected))
{
if (mode == 0)
SetFrictionCombineMode((CombineMode)n);
else
SetBouncingCombineMode((CombineMode)n);
}
if (is_selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
ImGui::PopID();
}
void ComponentCollider::HandleAlienEvent(const AlienEvent& e)
{
switch (e.type)
{
case AlienEventType::PHYSICS_SCALE_CHANGED: {
ScaleChanged();
break; }
case AlienEventType::COLLISION_LAYER_STATE_CHANGED: {
LayerChangedData* data = (LayerChangedData*)e.object;
if (data->LayerIsChanged(layer_num))
physics->WakeUp();
break; }
case AlienEventType::COLLISION_LAYER_REMOVED: {
int* layer_num = (int*)e.object;
if (layer_num)
SetCollisionLayer("Default");
break; }
}
}
void ComponentCollider::InitCollider()
{
shape->userData = this;
SetCollisionLayer("Default");
physics->AddCollider(this);
}
void ComponentCollider::InitMaterial()
{
SetStaticFriction(0.5f);
SetDynamicFriction(0.5f);
SetBouncing(0.5f);
SetFrictionCombineMode(CombineMode::Average);
SetBouncingCombineMode(CombineMode::Average);
}
void ComponentCollider::BeginUpdateShape(bool force_update)
{
if (IsController()) return;
if (!this->force_update)
physics->DettachCollider(this, true);
if (force_update)
this->force_update = true;
}
void ComponentCollider::EndUpdateShape(bool force_update)
{
if (IsController()) return;
if (force_update)
this->force_update = false;
if (!this->force_update)
physics->AttachCollider(this, true);
}
const float3 ComponentCollider::GetLocalMeshAabbSize() const
{
const ComponentMesh* mesh = GetMesh();
if (!mesh)
return float3::one();
return mesh->GetLocalAABB().Size();
}
const AABB ComponentCollider::GetLocalMeshAabb() const
{
const ComponentMesh* mesh = GetMesh();
if (!mesh)
AABB(Sphere(float3::zero(), 0.5f));
return mesh->GetLocalAABB();
}
const ComponentMesh* ComponentCollider::GetMesh() const
{
return game_object_attached->GetComponent<ComponentMesh>();
}
| 25.917706
| 179
| 0.726354
|
OverPowered-Team
|
ffcbfd889ee9e227f648268446c050fbe2c9a90f
| 3,403
|
cpp
|
C++
|
src/options.cpp
|
caetanosauer/fineline
|
03423d7f926435a01c2f0f2264763a11c8f332ce
|
[
"MIT"
] | null | null | null |
src/options.cpp
|
caetanosauer/fineline
|
03423d7f926435a01c2f0f2264763a11c8f332ce
|
[
"MIT"
] | null | null | null |
src/options.cpp
|
caetanosauer/fineline
|
03423d7f926435a01c2f0f2264763a11c8f332ce
|
[
"MIT"
] | null | null | null |
/*
* MIT License
*
* Copyright (c) 2016 Caetano Sauer
*
* 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 "options.h"
#include <mutex>
#include <fstream>
namespace fineline {
using std::string;
void Options::init_description(popt::options_description& opt)
{
opt.add_options()
/* General log manager options */
("logpath,l", popt::value<string>()->default_value("log"),
"Path in which log is stored (directory if file-based)")
("format", popt::value<bool>()->default_value(false)->implicit_value(true),
"Whether to format the log, deleting all existing log files or blocks")
("log_recycle", popt::value<bool>()->default_value(false)->implicit_value(true),
"Whether to clean-up log by deleting old files/partitions")
/* File-based log (legacy::log_storage) options */
("log_file_size", popt::value<unsigned>()->default_value(1024),
"Maximum size of a log file (in MB)")
("log_max_files", popt::value<unsigned>()->default_value(0),
"Maximum number of log files to maintain (0 = unlimited)")
("log_index_path", popt::value<string>()->default_value("index.db"),
"Path to log index file")
("log_index_path_relative", popt::value<bool>()->default_value(true),
"Whether log index path is relative to logpath or absolute")
;
}
popt::options_description& Options::get_description()
{
/*
* This code makes sure that the descriptions are initialized only once.
* After that, all callers will get the same descriptions, regardless of
* multi-threaded schedules.
*/
static std::once_flag init_once_flag;
static popt::options_description desc;
std::call_once(init_once_flag, init_description, std::ref(desc));
return desc;
}
Options::Options()
{
// Initialize with default option values
int argc = 0;
char* ptr = nullptr;
popt::store(popt::parse_command_line(argc, &ptr, get_description()), map_);
}
Options::Options(int argc, char** argv)
{
popt::store(popt::parse_command_line(argc, argv, get_description()), map_);
}
Options::Options(string config_file)
{
parse_from_file(config_file);
}
void Options::parse_from_file(string path)
{
std::ifstream is {path};
popt::store(popt::parse_config_file(is, get_description(), true), map_);
}
} // namespace fineline
| 36.98913
| 100
| 0.702615
|
caetanosauer
|
ffceb64ad0844a4e19e637c4f1f6311104cdfb74
| 10,308
|
cpp
|
C++
|
raygame/Player.cpp
|
DynashEtvala/Splat2D
|
44a296a834e5f1def9ef100f1b650174fcfe0d05
|
[
"MIT"
] | null | null | null |
raygame/Player.cpp
|
DynashEtvala/Splat2D
|
44a296a834e5f1def9ef100f1b650174fcfe0d05
|
[
"MIT"
] | null | null | null |
raygame/Player.cpp
|
DynashEtvala/Splat2D
|
44a296a834e5f1def9ef100f1b650174fcfe0d05
|
[
"MIT"
] | null | null | null |
#include "Player.h"
#include "Math.h"
#include "Controller.h"
#include "FloorTile.h"
#include "SpawnPad.h"
#include <math.h>
Player::Player()
{
weap = BASE_GUN;
speed = weap.walkSpeed;
teamColor = BLACK;
playerNumber = 0;
}
Player::Player(Vector2 start, Weapon w, Color tcol, Color ecol, int pnum)
{
static Texture2D _body = LoadTexture("Sprites/tankBeige_outline.png");
static Texture2D _barrel = LoadTexture("Sprites/barrelBeige_outline.png");
body = _body;
barrel = _barrel;
weap = w;
speed = weap.walkSpeed;
teamColor = tcol;
enemyColor = ecol;
playerNumber = pnum;
alive = true;
bodyRect1 = Rectangle{ 0, 0, (float)(body.width), (float)(body.height) };
bodyRect2 = Rectangle{ start.x, start.y, 35, 35};
barrelRect1 = Rectangle{ 0, 0, (float)(barrel.width), (float)(barrel.height) };
barrelRect2 = Rectangle{ start.x, start.y, 8, 22 };
}
Player::~Player()
{}
void Player::Update(Controller* controller, FloorTile*** ftile, SpawnPad * pads, Rectangle * walls, Rectangle * pits)
{
if (alive)
{
swimming = false;
if (speed != weap.walkSpeed)
{
speed = weap.walkSpeed;
}
//healing + enemy ink damage
if (pointOnScreen((int)(getCenter().x), (int)(getCenter().y)) && ftile[(int)(getCenter().y)][(int)(getCenter().x)]->color == enemyColor)
{
Damaged(0.05f, controller, ftile);
}
else if (timeSinceDamaged < 2.5f)
{
timeSinceDamaged += GetFrameTime();
}
else if(currHealth < maxHealth)
{
currHealth += GetFrameTime() * 40;
if (currHealth > maxHealth)
{
currHealth = maxHealth;
}
}
if (dirBody.x != 0 && dirBody.y != 0)
{
lastDirBody = NormalizeVector(dirBody);
}
dirBody = Vector2{ GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_LEFT_X), GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_LEFT_Y) };
if (VectorLength(dirBody) < 0.1)
{
dirBody = Vector2{ 0, 0 };
}
if (dirBarrel.x != 0 && dirBarrel.y != 0)
{
lastDirBarrel = dirBarrel;
}
dirBarrel = Vector2{ GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_RIGHT_X), GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_RIGHT_Y) };
if (VectorLength(dirBarrel) < 0.1)
{
dirBarrel = Vector2{ 0, 0 };
}
NormalizeVector(&dirBarrel);
// shooting
if (GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_RT) > 0.2f && (dirBarrel.y != 0 || dirBarrel.x != 0))
{
speed = weap.shootingSpeed;
if (fireTimer >= weap.fireRate && ammo > weap.ammoConsume && VectorLength(dirBarrel) > 0.1)
{
controller->addShot(Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, 10, 10 }, NormalizeVector(dirBarrel + Vector2{GetRandomValue( -weap.accuracy, weap.accuracy) * 0.01f, GetRandomValue(-weap.accuracy, weap.accuracy) * 0.01f }), weap.bulletSpeed, weap.damage, weap.range, weap.burstSize, weap.dripSize, teamColor);
ammo -= weap.ammoConsume;
fireTimer = 0;
}
reloadTimer = 0;
}
else if (GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_LT) > 0.2f)
{
swimming = true;
if (ftile[(int)(getCenter().y)][(int)(getCenter().x)]->color == teamColor)
{
speed = swimSpeed;
reloadTimer = 5;
ammo += 20 * GetFrameTime();
}
else
{
speed = drySwimSpeed;
}
}
if (pointOnScreen((int)(getCenter().x), (int)(getCenter().y)) && ftile[(int)(getCenter().y)][(int)(getCenter().x)]->color == enemyColor)
{
speed = enemyInkSpeed;
}
if (fireTimer < weap.fireRate)
{
fireTimer += GetFrameTime();
}
if (reloadTimer < 1)
{
reloadTimer += GetFrameTime();
}
else
{
if (ammo < 100)
{
ammo += 20 * GetFrameTime();
}
if (ammo > 100)
{
ammo = 100;
}
}
// movement
if (VectorLength(dirBody) >= 0.1)
{
barrelRect2.x = bodyRect2.x += dirBody.x * speed * GetFrameTime();
barrelRect2.y = bodyRect2.y += dirBody.y * speed * GetFrameTime();
for (int i = 0; i < maxObsticles; i++)
{
if (CheckCollisionPointRec(getCenter(), pits[i]))
{
currHealth = 0;
barrelRect2.x = bodyRect2.x = -100;
barrelRect2.y = bodyRect2.y = -100;
alive = false;
}
}
for (int i = 0; i < maxObsticles; i++)
{
if (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
switch (sideOfRect(walls[i]))
{
case LEFT:
barrelRect2.x = bodyRect2.x = walls[i].x - bodyRect2.width + 0.83f;
break;
case RIGHT:
barrelRect2.x = bodyRect2.x = walls[i].x + walls[i].width;
break;
case UP:
barrelRect2.y = bodyRect2.y = walls[i].y - bodyRect2.height + 0.83f;
break;
case DOWN:
barrelRect2.y = bodyRect2.y = walls[i].y + walls[i].height;
break;
case TOPLEFT:
if (dirBody.x < dirBody.y)
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.y--;
}
barrelRect2.y = bodyRect2.y += 1 - (bodyRect2.y - (int)(bodyRect2.y));
}
else
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.x--;
}
barrelRect2.x = bodyRect2.x += 1 - (bodyRect2.x - (int)(bodyRect2.x));
}
break;
case TOPRIGHT:
if (dirBody.x * -1 < dirBody.y)
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.y--;
}
barrelRect2.y = bodyRect2.y += 1 - (bodyRect2.y - (int)(bodyRect2.y));
}
else
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.x++;
}
bodyRect2.x -= bodyRect2.x - (int)(bodyRect2.x);
}
break;
case BOTTOMLEFT:
if (dirBody.x < dirBody.y * -1)
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.y++;
}
bodyRect2.y -= bodyRect2.y - (int)(bodyRect2.y);
}
else
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.x--;
}
barrelRect2.x = bodyRect2.x += 1 - (bodyRect2.x - (int)(bodyRect2.x));
}
break;
case BOTTOMRIGHT:
if (dirBody.x * -1 < dirBody.y * -1)
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.y++;
}
bodyRect2.y -= bodyRect2.y - (int)(bodyRect2.y);
}
else
{
while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i]))
{
bodyRect2.x++;
}
bodyRect2.x -= bodyRect2.x - (int)(bodyRect2.x);
}
break;
default:
case CENTER:
bodyRect2.x -= dirBody.x * speed * GetFrameTime();
bodyRect2.y -= dirBody.y * speed * GetFrameTime();
break;
}
}
}
}
}
else
{
if (timeSinceDamaged < 5)
{
timeSinceDamaged += GetFrameTime();
}
else if (currHealth < maxHealth)
{
currHealth += GetFrameTime() * 25;
if (currHealth > maxHealth)
{
currHealth = maxHealth;
Vector2 spawn = pads[playerNumber % 2].spawnSpaces[playerNumber/2];
barrelRect2.x = bodyRect2.x = spawn.x;
barrelRect2.y = bodyRect2.y = spawn.y;
ammo = 100;
alive = true;
}
}
}
}
void Player::Draw()
{
if (!swimming)
{
if (dirBody.x != 0 && dirBody.y != 0)
{
Vector2 norm = NormalizeVector(dirBody);
float rot = -atan2f(norm.x, norm.y) * 180 / PI;
DrawTexturePro(body, bodyRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, bodyRect2.width, bodyRect2.height }, Vector2{ bodyRect2.width / 2, bodyRect2.height / 2 }, rot - 180, teamColor);
}
else
{
Vector2 norm = NormalizeVector(lastDirBody);
float rot = -atan2f(norm.x, norm.y) * 180 / PI;
DrawTexturePro(body, bodyRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, bodyRect2.width, bodyRect2.height }, Vector2{ bodyRect2.width / 2, bodyRect2.height / 2 }, rot - 180, teamColor);
}
}
if (dirBarrel.x != 0 && dirBarrel.y != 0)
{
Vector2 norm = NormalizeVector(dirBarrel);
float rot = -atan2f(norm.x, norm.y) * 180 / PI;
DrawTexturePro(barrel, barrelRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, barrelRect2.width, barrelRect2.height }, Vector2{ barrelRect2.width / 2, barrelRect2.height }, rot - 180, teamColor);
}
else
{
Vector2 norm = NormalizeVector(lastDirBarrel);
float rot = -atan2f(norm.x, norm.y) * 180 / PI;
DrawTexturePro(barrel, barrelRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, barrelRect2.width, barrelRect2.height }, Vector2{ barrelRect2.width / 2, barrelRect2.height }, rot - 180, teamColor);
}
DrawRectangle(bodyRect2.x + bodyRect2.width, bodyRect2.y, 10, 35, BLACK);
DrawRectangle(bodyRect2.x + bodyRect2.width + 1, bodyRect2.y + 1, 8, 33, WHITE);
DrawRectangle(bodyRect2.x + bodyRect2.width + 1, bodyRect2.y + 34 - ammo * 0.33f, 8, ammo * 0.33f, teamColor);
}
void Player::Damaged(float dmg, Controller* controller, FloorTile*** ftile)
{
if (alive)
{
timeSinceDamaged = 0;
currHealth -= dmg;
if (currHealth <= 0)
{
currHealth = 0;
controller->paintFloor(getCenter(), deathPopSize, enemyColor, ftile);
barrelRect2.x = bodyRect2.x = -100;
barrelRect2.y = bodyRect2.y = -100;
alive = false;
}
}
}
float Player::GetHealth()
{
return currHealth;
}
Direction Player::sideOfRect(Rectangle r)
{
if (getCenter().x < r.x)
{
if (getCenter().y < r.y)
{
return TOPLEFT;
}
else if (getCenter().y > r.y + r.height)
{
return BOTTOMLEFT;
}
return LEFT;
}
else if (getCenter().x > r.x + r.width)
{
if (getCenter().y < r.y)
{
return TOPRIGHT;
}
else if (getCenter().y > r.y + r.height)
{
return BOTTOMRIGHT;
}
return RIGHT;
}
else if (getCenter().y < r.y)
{
return UP;
}
else if (getCenter().y > r.y + r.height)
{
return DOWN;
}
else
{
return CENTER;
}
}
Vector2 Player::getCenter()
{
return Vector2{ bodyRect2.x + getRadius(), bodyRect2.y + getRadius() };
}
float Player::getRadius()
{
return bodyRect2.height < bodyRect2.width ? bodyRect2.height / 2 : bodyRect2.width / 2;
}
bool Player::pointOnScreen(int x, int y)
{
if (x >= 0 && x < screenWidth && y >= 0 && y < screenHeight)
{
return true;
}
return false;
}
| 26.162437
| 351
| 0.617385
|
DynashEtvala
|
ffd7390f9b8f9ab2cf776fbcd187b4a6a79d3a4b
| 458
|
cpp
|
C++
|
C++/Maximizing XOR.cpp
|
karunagatiyala/hackerrank_problems-or-hackerearth_problems
|
645bb30465ee962733433a9a30fd5873b9fe33c2
|
[
"MIT"
] | 1
|
2019-10-15T09:14:29.000Z
|
2019-10-15T09:14:29.000Z
|
C++/Maximizing XOR.cpp
|
karunagatiyala/hackerrank_problems-or-hackerearth_problems
|
645bb30465ee962733433a9a30fd5873b9fe33c2
|
[
"MIT"
] | 5
|
2019-10-30T05:24:27.000Z
|
2019-10-30T05:28:03.000Z
|
C++/Maximizing XOR.cpp
|
karunagatiyala/hackerrank_problems-or-hackerearth_problems
|
645bb30465ee962733433a9a30fd5873b9fe33c2
|
[
"MIT"
] | 10
|
2019-10-15T03:04:17.000Z
|
2019-10-29T18:39:11.000Z
|
#include <bits/stdc++.h>
using namespace std;
// Complete the maximizingXor function below.
int maximizingXor(int l, int r) {
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int l;
cin >> l;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int r;
cin >> r;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int result = maximizingXor(l, r);
fout << result << "\n";
fout.close();
return 0;
}
| 14.774194
| 56
| 0.591703
|
karunagatiyala
|
ffda05a12aae3a915f386d16577289974c4d811f
| 10,998
|
cpp
|
C++
|
SDK/Samples/Plugins/Monitoring/AIDA64/AIDA64SetupSourceDlg.cpp
|
tjca1/MSI-Afterburner
|
5bbac4a0af16be326b1f2886ae016ca0a54487e8
|
[
"MIT"
] | null | null | null |
SDK/Samples/Plugins/Monitoring/AIDA64/AIDA64SetupSourceDlg.cpp
|
tjca1/MSI-Afterburner
|
5bbac4a0af16be326b1f2886ae016ca0a54487e8
|
[
"MIT"
] | 1
|
2021-11-21T01:40:59.000Z
|
2021-11-21T01:40:59.000Z
|
SDK/Samples/Plugins/Monitoring/AIDA64/AIDA64SetupSourceDlg.cpp
|
tjca1/MSI-Afterburner
|
5bbac4a0af16be326b1f2886ae016ca0a54487e8
|
[
"MIT"
] | 1
|
2021-12-25T03:40:50.000Z
|
2021-12-25T03:40:50.000Z
|
// AIDA64SetupSourceDlg.cpp : implementation file
//
// created by Unwinder
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "AIDA64SetupSourceDlg.h"
#include "AIDA64Globals.h"
#include "MAHMSharedMemory.h"
//////////////////////////////////////////////////////////////////////
// CAIDA64SetupSourceDlg dialog
//////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNAMIC(CAIDA64SetupSourceDlg, CDialog)
//////////////////////////////////////////////////////////////////////
CAIDA64SetupSourceDlg::CAIDA64SetupSourceDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAIDA64SetupSourceDlg::IDD, pParent)
, m_strSensorID(_T(""))
, m_strReadingName(_T(""))
, m_strSourceInstance(_T(""))
, m_strSourceName(_T(""))
, m_strSourceUnits(_T(""))
, m_strSourceFormat(_T(""))
, m_strSourceGroup(_T(""))
, m_strSourceMin(_T(""))
, m_strSourceMax(_T(""))
{
m_hBrush = NULL;
m_lpDesc = NULL;
}
//////////////////////////////////////////////////////////////////////
CAIDA64SetupSourceDlg::~CAIDA64SetupSourceDlg()
{
}
//////////////////////////////////////////////////////////////////////
void CAIDA64SetupSourceDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_SENSOR_ID_EDIT, m_strSensorID);
DDX_Control(pDX, IDC_SOURCE_ID_COMBO, m_sourceIdCombo);
DDX_Text(pDX, IDC_SOURCE_INSTANCE_EDIT, m_strSourceInstance);
DDX_Text(pDX, IDC_SOURCE_NAME_EDIT, m_strSourceName);
DDX_Text(pDX, IDC_SOURCE_UNITS_EDIT, m_strSourceUnits);
DDX_Text(pDX, IDC_SOURCE_FORMAT_EDIT, m_strSourceFormat);
DDX_Text(pDX, IDC_SOURCE_GROUP_EDIT, m_strSourceGroup);
DDX_Text(pDX, IDC_SOURCE_MIN_EDIT, m_strSourceMin);
DDX_Text(pDX, IDC_SOURCE_MAX_EDIT, m_strSourceMax);
}
//////////////////////////////////////////////////////////////////////
BEGIN_MESSAGE_MAP(CAIDA64SetupSourceDlg, CDialog)
ON_WM_DESTROY()
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDOK, &CAIDA64SetupSourceDlg::OnBnClickedOk)
END_MESSAGE_MAP()
//////////////////////////////////////////////////////////////////////
// CAIDA64SetupSourceDlg message handlers
//////////////////////////////////////////////////////////////////////
typedef struct AIDA64_READING_TYPE_DESC
{
DWORD dwType;
LPCSTR lpName;
} AIDA64_READING_TYPE_DESC, *LPAIDA64_READING_TYPE_DESC;
//////////////////////////////////////////////////////////////////////
typedef struct DATA_SOURCE_ID_DESC
{
DWORD dwID;
LPCSTR lpName;
} DATA_SOURCE_ID_DESC, *LPDATA_SOURCE_ID_DESC;
//////////////////////////////////////////////////////////////////////
BOOL CAIDA64SetupSourceDlg::OnInitDialog()
{
CDialog::OnInitDialog();
LocalizeWnd(m_hWnd);
AdjustWindowPos(this, GetParent());
if (m_lpDesc)
{
//sensor ID
m_strSensorID = m_lpDesc->szID;
//data source id
DATA_SOURCE_ID_DESC sourceIds[] =
{
{ MONITORING_SOURCE_ID_GPU_TEMPERATURE , "GPU temperature" },
{ MONITORING_SOURCE_ID_PCB_TEMPERATURE , "PCB temperature" },
{ MONITORING_SOURCE_ID_MEM_TEMPERATURE , "Memory temperature" },
{ MONITORING_SOURCE_ID_VRM_TEMPERATURE , "VRM temperature" },
{ MONITORING_SOURCE_ID_FAN_SPEED , "Fan speed" },
{ MONITORING_SOURCE_ID_FAN_TACHOMETER , "Fan tachometer" },
{ MONITORING_SOURCE_ID_CORE_CLOCK , "Core clock" },
{ MONITORING_SOURCE_ID_SHADER_CLOCK , "Shader clock" },
{ MONITORING_SOURCE_ID_MEMORY_CLOCK , "Memory clock" },
{ MONITORING_SOURCE_ID_GPU_USAGE , "GPU usage" },
{ MONITORING_SOURCE_ID_MEMORY_USAGE , "Memory usage" },
{ MONITORING_SOURCE_ID_FB_USAGE , "FB usage" },
{ MONITORING_SOURCE_ID_VID_USAGE , "VID usage" },
{ MONITORING_SOURCE_ID_BUS_USAGE , "BUS usage" },
{ MONITORING_SOURCE_ID_GPU_VOLTAGE , "GPU voltage" },
{ MONITORING_SOURCE_ID_AUX_VOLTAGE , "Aux voltage" },
{ MONITORING_SOURCE_ID_MEMORY_VOLTAGE , "Memory voltage" },
{ MONITORING_SOURCE_ID_FRAMERATE , "Framerate" },
{ MONITORING_SOURCE_ID_FRAMETIME , "Frametime" },
{ MONITORING_SOURCE_ID_FRAMERATE_MIN , "Framerate Min" },
{ MONITORING_SOURCE_ID_FRAMERATE_AVG , "Framerate Avg" },
{ MONITORING_SOURCE_ID_FRAMERATE_MAX , "Framerate Max" },
{ MONITORING_SOURCE_ID_FRAMERATE_1DOT0_PERCENT_LOW , "Framerate 1% Low" },
{ MONITORING_SOURCE_ID_FRAMERATE_0DOT1_PERCENT_LOW , "Framerate 0.1% Low" },
{ MONITORING_SOURCE_ID_GPU_REL_POWER , "Power percent" },
{ MONITORING_SOURCE_ID_GPU_ABS_POWER , "Power" },
{ MONITORING_SOURCE_ID_GPU_TEMP_LIMIT , "Temp limit" },
{ MONITORING_SOURCE_ID_GPU_POWER_LIMIT , "Power limit" },
{ MONITORING_SOURCE_ID_GPU_VOLTAGE_LIMIT , "Voltage limit" },
{ MONITORING_SOURCE_ID_GPU_UTIL_LIMIT , "No load limit" },
{ MONITORING_SOURCE_ID_CPU_USAGE , "CPU usage" },
{ MONITORING_SOURCE_ID_RAM_USAGE , "RAM usage" },
{ MONITORING_SOURCE_ID_PAGEFILE_USAGE , "Pagefile usage" },
{ MONITORING_SOURCE_ID_CPU_TEMPERATURE , "CPU temperature" },
{ MONITORING_SOURCE_ID_GPU_SLI_SYNC_LIMIT ,"SLI sync limit" },
{ MONITORING_SOURCE_ID_CPU_CLOCK , "CPU clock" },
{ MONITORING_SOURCE_ID_AUX2_VOLTAGE , "Aux2 voltage" },
{ MONITORING_SOURCE_ID_GPU_TEMPERATURE2 , "GPU temperature 2" },
{ MONITORING_SOURCE_ID_PCB_TEMPERATURE2 , "PCB temperature 2" },
{ MONITORING_SOURCE_ID_MEM_TEMPERATURE2 , "Memory temperature 2" },
{ MONITORING_SOURCE_ID_VRM_TEMPERATURE2 , "VRM temperature 2" },
{ MONITORING_SOURCE_ID_GPU_TEMPERATURE3 , "GPU temperature 3" },
{ MONITORING_SOURCE_ID_PCB_TEMPERATURE3 , "PCB temperature 3" },
{ MONITORING_SOURCE_ID_MEM_TEMPERATURE3 , "Memory temperature 3" },
{ MONITORING_SOURCE_ID_VRM_TEMPERATURE3 , "VRM temperature 3" },
{ MONITORING_SOURCE_ID_GPU_TEMPERATURE4 , "GPU temperature 4" },
{ MONITORING_SOURCE_ID_PCB_TEMPERATURE4 , "PCB temperature 4" },
{ MONITORING_SOURCE_ID_MEM_TEMPERATURE4 , "Memory temperature 4" },
{ MONITORING_SOURCE_ID_VRM_TEMPERATURE4 , "VRM temperature 4" },
{ MONITORING_SOURCE_ID_GPU_TEMPERATURE5 , "GPU temperature 5" },
{ MONITORING_SOURCE_ID_PCB_TEMPERATURE5 , "PCB temperature 5" },
{ MONITORING_SOURCE_ID_MEM_TEMPERATURE5 , "Memory temperature 5" },
{ MONITORING_SOURCE_ID_VRM_TEMPERATURE5 , "VRM temperature 5" },
{ MONITORING_SOURCE_ID_PLUGIN_GPU , "<GPU plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_CPU , "<CPU plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_MOBO , "<motherboard plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_RAM , "<RAM plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_HDD , "<HDD plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_NET , "<NET plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_PSU , "<PSU plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_UPS , "<UPS plugin>" },
{ MONITORING_SOURCE_ID_PLUGIN_MISC , "<miscellaneous plugin>" },
{ MONITORING_SOURCE_ID_CPU_POWER , "CPU power" }
};
m_sourceIdCombo.SetCurSel(0);
for (int iIndex=0; iIndex<_countof(sourceIds); iIndex++)
{
int iItem = m_sourceIdCombo.AddString(LocalizeStr(sourceIds[iIndex].lpName));
m_sourceIdCombo.SetItemData(iItem, sourceIds[iIndex].dwID);
if (m_lpDesc->dwID == sourceIds[iIndex].dwID)
m_sourceIdCombo.SetCurSel(iItem);
}
//data source instance
if (m_lpDesc->dwInstance != 0xFFFFFFFF)
m_strSourceInstance.Format("%d", m_lpDesc->dwInstance);
else
m_strSourceInstance = "";
//data source name
m_strSourceName = m_lpDesc->szName;
//data source units
m_strSourceUnits = m_lpDesc->szUnits;
//data source output format
m_strSourceFormat = m_lpDesc->szFormat;
//data source group
m_strSourceGroup = m_lpDesc->szGroup;
//data source range
m_strSourceMin.Format("%.1f", m_lpDesc->fltMinLimit);
m_strSourceMax.Format("%.1f", m_lpDesc->fltMaxLimit);
UpdateData(FALSE);
}
return TRUE;
}
//////////////////////////////////////////////////////////////////////
void CAIDA64SetupSourceDlg::SetSourceDesc(LPAIDA64_DATA_SOURCE_DESC lpDesc)
{
m_lpDesc = lpDesc;
}
//////////////////////////////////////////////////////////////////////
void CAIDA64SetupSourceDlg::OnDestroy()
{
if (m_hBrush)
{
DeleteObject(m_hBrush);
m_hBrush = NULL;
}
CDialog::OnDestroy();
}
//////////////////////////////////////////////////////////////////////
HBRUSH CAIDA64SetupSourceDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
COLORREF clrBk = g_dwHeaderBgndColor;
COLORREF clrText = g_dwHeaderTextColor;
UINT nID = pWnd->GetDlgCtrlID();
if ((nID == IDC_SENSOR_PROPERTIES_HEADER) ||
(nID == IDC_SOURCE_PROPERTIES_HEADER))
{
if (!m_hBrush)
m_hBrush = CreateSolidBrush(clrBk);
pDC->SetBkColor(clrBk);
pDC->SetTextColor(clrText);
}
else
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
return m_hBrush;
}
//////////////////////////////////////////////////////////////////////
void CAIDA64SetupSourceDlg::OnBnClickedOk()
{
int iItem;
UpdateData(TRUE);
if (!ValidateSource())
{
MessageBeep(MB_ICONERROR);
return;
}
if (m_lpDesc)
{
//sensor ID
strcpy_s(m_lpDesc->szID, sizeof(m_lpDesc->szID), m_strSensorID);
//data source id
iItem = m_sourceIdCombo.GetCurSel();
if (iItem != -1)
m_lpDesc->dwID = m_sourceIdCombo.GetItemData(iItem);
else
m_lpDesc->dwID = MONITORING_SOURCE_ID_UNKNOWN;
//data source instance
if (sscanf_s(m_strSourceInstance, "%d", &m_lpDesc->dwInstance) != 1)
m_lpDesc->dwInstance = 0xFFFFFFFF;
//data source name
strcpy_s(m_lpDesc->szName, sizeof(m_lpDesc->szName), m_strSourceName);
//data source units
strcpy_s(m_lpDesc->szUnits, sizeof(m_lpDesc->szUnits), m_strSourceUnits);
//data source output format
strcpy_s(m_lpDesc->szFormat, sizeof(m_lpDesc->szFormat), m_strSourceFormat);
//data source group
strcpy_s(m_lpDesc->szGroup, sizeof(m_lpDesc->szGroup), m_strSourceGroup);
//data source range
if (sscanf_s(m_strSourceMin, "%f", &m_lpDesc->fltMinLimit) != 1)
m_lpDesc->fltMinLimit = 0.0f;
if (sscanf_s(m_strSourceMax, "%f", &m_lpDesc->fltMaxLimit) != 1)
m_lpDesc->fltMaxLimit = 100.0f;
}
OnOK();
}
//////////////////////////////////////////////////////////////////////
BOOL CAIDA64SetupSourceDlg::ValidateSource()
{
m_strSensorID.Trim();
if (m_strSensorID.IsEmpty())
{
GetDlgItem(IDC_SENSOR_ID_EDIT)->SetFocus();
return FALSE;
}
m_strSourceName.Trim();
if (m_strSourceName.IsEmpty())
{
GetDlgItem(IDC_SOURCE_NAME_EDIT)->SetFocus();
return FALSE;
}
return TRUE;
}
//////////////////////////////////////////////////////////////////////
| 34.914286
| 81
| 0.619476
|
tjca1
|
ffdabdd4f68355ce6317c319adc23e98a1eb726e
| 1,852
|
cpp
|
C++
|
Gardenino_Sketch/SensorLogger.cpp
|
Diebanez/gardenino
|
88ce597e47dcaecbe1a99eb962bdc95a30bd5932
|
[
"MIT"
] | null | null | null |
Gardenino_Sketch/SensorLogger.cpp
|
Diebanez/gardenino
|
88ce597e47dcaecbe1a99eb962bdc95a30bd5932
|
[
"MIT"
] | 4
|
2021-12-31T13:22:59.000Z
|
2022-01-03T10:36:22.000Z
|
Gardenino_Sketch/SensorLogger.cpp
|
Diebanez/gardenino
|
88ce597e47dcaecbe1a99eb962bdc95a30bd5932
|
[
"MIT"
] | null | null | null |
#include "SensorLogger.h"
#include <SD.h>
#include "Debug.h"
SensorLogger::SensorLogger(Clock *logClock)
: PrintLogSpan(0, 1, 0, 0), LogClock(logClock)
{
}
void SensorLogger::AddSensorToLog(Sensor *target)
{
SensorToLog.AddElement(target);
}
void SensorLogger::Init(TimeSpan LogSpan)
{
PrintLogSpan = LogSpan;
Log();
}
void SensorLogger::Update()
{
DateTime now = LogClock->GetNow();
if (now.unixtime() - LastLogTime.unixtime() >= PrintLogSpan.totalseconds())
{
Log();
}
}
void SensorLogger::Log()
{
LastLogTime = LogClock->GetNow();
if (!SD.exists(LOGS_FOLDER))
{
SD.mkdir(LOGS_FOLDER);
}
String FileName = LOGS_FOLDER + String("/") + String(LastLogTime.day()) + String(LastLogTime.month()) + String(LastLogTime.year()) + String(".csv");
if (!SD.exists(FileName))
{
File newFile = SD.open(FileName, FILE_WRITE);
if (newFile)
{
String line = "Time;";
for (int i = 0; i < SensorToLog.GetElementsCount(); i++)
{
line += SensorToLog.GetElement(i)->GetName();
line += ";";
}
newFile.println(line);
newFile.close();
}
}
String newLine = String(LastLogTime.hour()) + String(":") + String(LastLogTime.minute()) + String(":") + String(LastLogTime.second()) + ";";
for (int i = 0; i < SensorToLog.GetElementsCount(); i++)
{
newLine += String(SensorToLog.GetElement(i)->GetValue());
newLine += ";";
}
File appendFile = SD.open(FileName, FILE_WRITE);
if (appendFile)
{
appendFile.println(newLine);
appendFile.close();
}
SERIAL_LOG("[" + String(LastLogTime.hour()) + ":" + String(LastLogTime.minute()) + ":" + String(LastLogTime.second()) + "] Logged data to sd")
}
| 24.368421
| 152
| 0.577214
|
Diebanez
|
ffde21b56ac873665291a65e9a9c13bcb998a662
| 1,064
|
cpp
|
C++
|
rabbitsLife/rabbitsLife/Draw/DrawTruckYellow.cpp
|
VitorNevess/Rabbits-Life
|
24d46ca84ad441b25a37bc2d9a4b2c65a03d3d46
|
[
"Apache-2.0"
] | null | null | null |
rabbitsLife/rabbitsLife/Draw/DrawTruckYellow.cpp
|
VitorNevess/Rabbits-Life
|
24d46ca84ad441b25a37bc2d9a4b2c65a03d3d46
|
[
"Apache-2.0"
] | 1
|
2019-11-16T00:54:00.000Z
|
2019-11-16T00:54:00.000Z
|
rabbitsLife/rabbitsLife/Draw/DrawTruckYellow.cpp
|
VitorNevess/Rabbits-Life
|
24d46ca84ad441b25a37bc2d9a4b2c65a03d3d46
|
[
"Apache-2.0"
] | null | null | null |
//
// DrawTruckYellow.cpp
// rabbitsLife
//
// Created by joao.vitor.f.naves on 13/10/19.
// Copyright © 2019 vitor.neves. All rights reserved.
//
#define GL_SILENCE_DEPRECATION
#include <GLUT/GLUT.h>
class DrawTruckYellow {
//public
public:
float xCloser = 0;//mais perto
float xFurther = 0;//mais longe
public: void truckYellow(int x){
glColor3f(1,1,0);
glBegin(GL_QUADS);
_truckYellow(x);
glEnd();
glColor3f(1,1,1);
glBegin(GL_POINTS);
wheelsTruckYellow(x);
glEnd();
}
//private
private: void _truckYellow(int x){
//CAMINHAO FRENTE
glVertex2f(x+1,26);//Ponto A
glVertex2f(x+3,26);//Ponto B
glVertex2f(x+3,28);//Ponto C
glVertex2f(x+1,28);//Ponto D
//CAMINHAO TRASEIRA
glVertex2f(x+2.5,26);//Ponto A
glVertex2f(x+5,26);//Ponto B
glVertex2f(x+5,29);//Ponto C
glVertex2f(x+2.5,29);//Ponto D
xCloser = x+1;
xFurther = x+5;
}
private: void wheelsTruckYellow(int x){
glVertex2f(x+2,26);//Ponto A
glVertex2f(x+4,26);//Ponto A
}
};
| 19.703704
| 54
| 0.620301
|
VitorNevess
|
ffe0ead6be26d6b7242ca321c59d350efa7b43b7
| 309
|
cpp
|
C++
|
GeneratorType.cpp
|
Xecutor/paparl
|
fb0096d49d11a4110ba4eb2b0d42508f9c87d4bc
|
[
"MIT"
] | null | null | null |
GeneratorType.cpp
|
Xecutor/paparl
|
fb0096d49d11a4110ba4eb2b0d42508f9c87d4bc
|
[
"MIT"
] | null | null | null |
GeneratorType.cpp
|
Xecutor/paparl
|
fb0096d49d11a4110ba4eb2b0d42508f9c87d4bc
|
[
"MIT"
] | null | null | null |
#include "GeneratorType.hpp"
std::string getGeneratorNameByType(GeneratorType gt)
{
using GT=GeneratorType;
switch(gt)
{
case GT::downtown:return "Downtown";
case GT::seaport:return "Seaport";
case GT::suburbs:return "Suburbs";
case GT::warehouse:return "Warehouse";
}
return "";
}
| 20.6
| 52
| 0.68932
|
Xecutor
|
ffe2da45917417d1bbc4c7e6d2fda4cb68ccf694
| 60,493
|
cpp
|
C++
|
c++/src/algo/blast/api/blast_options_cxx.cpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 31
|
2016-12-09T04:56:59.000Z
|
2021-12-31T17:19:10.000Z
|
c++/src/algo/blast/api/blast_options_cxx.cpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 6
|
2017-03-10T17:25:13.000Z
|
2021-09-22T15:49:49.000Z
|
c++/src/algo/blast/api/blast_options_cxx.cpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 20
|
2015-01-04T02:15:17.000Z
|
2021-12-03T02:31:43.000Z
|
#ifndef SKIP_DOXYGEN_PROCESSING
static char const rcsid[] =
"$Id: blast_options_cxx.cpp 371842 2012-08-13 13:56:38Z fongah2 $";
#endif /* SKIP_DOXYGEN_PROCESSING */
/* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
*/
/// @file blast_options_cxx.cpp
/// Implements the CBlastOptions class, which encapsulates options structures
/// from algo/blast/core
#include <ncbi_pch.hpp>
#include <algo/blast/api/blast_options.hpp>
#include "blast_setup.hpp"
#include "blast_options_local_priv.hpp"
#include "blast_memento_priv.hpp"
#include <algo/blast/core/blast_extend.h>
#include <objects/seqloc/Seq_loc.hpp>
#include <objects/blast/Blast4_cutoff.hpp>
#include <objects/blast/names.hpp>
/** @addtogroup AlgoBlast
*
* @{
*/
BEGIN_NCBI_SCOPE
USING_SCOPE(objects);
BEGIN_SCOPE(blast)
#ifndef SKIP_DOXYGEN_PROCESSING
/// Encapsulates all blast input parameters
class NCBI_XBLAST_EXPORT CBlastOptionsRemote : public CObject
{
public:
CBlastOptionsRemote(void)
: m_DefaultsMode(false)
{
m_ReqOpts.Reset(new objects::CBlast4_parameters);
}
~CBlastOptionsRemote()
{
}
/// Copy constructor
CBlastOptionsRemote(const CBlastOptionsRemote& optsRemote)
: m_DefaultsMode(false)
{
x_DoDeepCopy(optsRemote);
}
/// Assignment operator
CBlastOptionsRemote& operator=(const CBlastOptionsRemote& optsRemote)
{
x_DoDeepCopy(optsRemote);
return *this;
}
// the "new paradigm"
typedef ncbi::objects::CBlast4_parameters TBlast4Opts;
TBlast4Opts * GetBlast4AlgoOpts()
{
return m_ReqOpts;
}
typedef vector< CConstRef<objects::CSeq_loc> > TSeqLocVector;
// SetValue(x,y) with different types:
void SetValue(EBlastOptIdx opt, const EProgram & x);
void SetValue(EBlastOptIdx opt, const int & x);
void SetValue(EBlastOptIdx opt, const double & x);
void SetValue(EBlastOptIdx opt, const char * x);
void SetValue(EBlastOptIdx opt, const TSeqLocVector & x);
void SetValue(EBlastOptIdx opt, const ESeedContainerType & x);
void SetValue(EBlastOptIdx opt, const bool & x);
void SetValue(EBlastOptIdx opt, const Int8 & x);
// Pseudo-types:
void SetValue(EBlastOptIdx opt, const short & x)
{
int x2 = x; SetValue(opt, x2);
}
void SetValue(EBlastOptIdx opt, const unsigned int & x)
{
int x2 = x; SetValue(opt, x2);
}
void SetValue(EBlastOptIdx opt, const unsigned char & x)
{
int x2 = x; SetValue(opt, x2);
}
void SetValue(EBlastOptIdx opt, const objects::ENa_strand & x)
{
int x2 = x; SetValue(opt, x2);
}
/// Remove any objects matching this Blast4 field object.
///
/// The given field object represents a Blast4 field to remove
/// from the list of remote options.
///
/// @param opt Field object representing option to remove.
void ResetValue(CBlast4Field & opt)
{
x_ResetValue(opt);
}
void SetDefaultsMode(bool dmode)
{
m_DefaultsMode = dmode;
}
bool GetDefaultsMode()
{
return m_DefaultsMode;
}
private:
//CRef<objects::CBlast4_queue_search_request> m_Req;
CRef<objects::CBlast4_parameters> m_ReqOpts;
bool m_DefaultsMode;
/// Perform a "deep copy" of remote Blast options
/// @param optsRemote remote Blast options object to copy from.
void x_DoDeepCopy(const CBlastOptionsRemote& optsRemote)
{
if (&optsRemote != this)
{
m_ReqOpts.Reset(new objects::CBlast4_parameters);
m_ReqOpts->Assign(*optsRemote.m_ReqOpts);
m_DefaultsMode = optsRemote.m_DefaultsMode;
}
}
template<class T>
void x_SetParam(CBlast4Field & name, T & value)
{
x_SetOneParam(name, & value);
}
void x_SetOneParam(CBlast4Field & field, const int * x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetInteger(*x);
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_SetOneParam(CBlast4Field & field, const char ** x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetString().assign((x && (*x)) ? (*x) : "");
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_SetOneParam(CBlast4Field & field, const bool * x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetBoolean(*x);
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_SetOneParam(CBlast4Field & field, CRef<objects::CBlast4_cutoff> * x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetCutoff(**x);
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_SetOneParam(CBlast4Field & field, const double * x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetReal(*x);
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_SetOneParam(CBlast4Field & field, const Int8 * x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetBig_integer(*x);
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_SetOneParam(CBlast4Field & field, objects::EBlast4_strand_type * x)
{
CRef<objects::CBlast4_value> v(new objects::CBlast4_value);
v->SetStrand_type(*x);
CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter);
p->SetName(field.GetName());
p->SetValue(*v);
x_AttachValue(p);
}
void x_AttachValue(CRef<objects::CBlast4_parameter> p)
{
typedef objects::CBlast4_parameter TParam;
NON_CONST_ITERATE(list< CRef<TParam> >, iter, m_ReqOpts->Set()) {
if ((**iter).GetName() == p->GetName()) {
(*iter) = p;
return;
}
}
m_ReqOpts->Set().push_back(p);
}
/// Remove values for a given Blast4 field.
/// @param f Field to search for and remove.
void x_ResetValue(CBlast4Field & f)
{
typedef list< CRef<objects::CBlast4_parameter> > TParamList;
typedef TParamList::iterator TParamIter;
const string & nm = f.GetName();
TParamList & lst = m_ReqOpts->Set();
TParamIter pos = lst.begin(), end = lst.end();
while(pos != end) {
TParamIter current = pos;
pos++;
if ((**current).GetName() == nm) {
lst.erase(current);
}
}
}
void x_Throwx(const string& msg) const
{
NCBI_THROW(CBlastException, eInvalidOptions, msg);
}
};
CBlastOptions::CBlastOptions(EAPILocality locality)
: m_Local (0),
m_Remote(0),
m_DefaultsMode(false)
{
if (locality == eRemote)
locality = eBoth;
if (locality != eRemote) {
m_Local = new CBlastOptionsLocal();
}
if (locality != eLocal) {
m_Remote = new CBlastOptionsRemote();
}
}
CBlastOptions::~CBlastOptions()
{
if (m_Local) {
delete m_Local;
}
if (m_Remote) {
delete m_Remote;
}
}
CRef<CBlastOptions> CBlastOptions::Clone() const
{
CRef<CBlastOptions> optsRef;
optsRef.Reset(new CBlastOptions(GetLocality()));
optsRef->x_DoDeepCopy(*this);
return optsRef;
}
CBlastOptions::EAPILocality
CBlastOptions::GetLocality(void) const
{
if (! m_Remote) {
return eLocal;
}
if (! m_Local) {
return eRemote;
}
return eBoth;
}
// Note: only some of the options are supported for the remote case;
// An exception is thrown if the option is not available.
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const EProgram & v)
{
if (m_DefaultsMode) {
return;
}
switch(opt) {
case eBlastOpt_Program:
return;
default:
break;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%d), line (%d).",
int(opt), v, __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const int & v)
{
if (m_DefaultsMode) {
return;
}
switch(opt) {
case eBlastOpt_WordSize:
x_SetParam(CBlast4Field::Get(opt), v);
return;
// Added for rmblastn and the new masklevel option. -RMH-
case eBlastOpt_MaskLevel:
x_SetParam(CBlast4Field::Get(opt),v);
return;
case eBlastOpt_LookupTableType:
// do nothing, should be specified by the task
return;
case eBlastOpt_StrandOption:
{
typedef objects::EBlast4_strand_type TSType;
TSType strand;
bool set_strand = true;
switch(v) {
case 1:
strand = eBlast4_strand_type_forward_strand;
break;
case 2:
strand = eBlast4_strand_type_reverse_strand;
break;
case 3:
strand = eBlast4_strand_type_both_strands;
break;
default:
set_strand = false;
}
if (set_strand) {
x_SetParam(CBlast4Field::Get(opt), strand);
return;
}
}
case eBlastOpt_WindowSize:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapOpeningCost:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapExtensionCost:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_HitlistSize:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_CutoffScore:
if (0) {
typedef objects::CBlast4_cutoff TCutoff;
CRef<TCutoff> cutoff(new TCutoff);
cutoff->SetRaw_score(v);
x_SetParam(CBlast4Field::Get(opt), cutoff);
}
return;
case eBlastOpt_MatchReward:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_MismatchPenalty:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_WordThreshold:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_PseudoCount:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_CompositionBasedStats:
if (v < eNumCompoAdjustModes) {
x_SetParam(CBlast4Field::Get(opt), v);
return;
}
case eBlastOpt_MBTemplateLength:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_MBTemplateType:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapExtnAlgorithm:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapTracebackAlgorithm:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_SegFilteringWindow:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DustFilteringLevel:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DustFilteringWindow:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DustFilteringLinker:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_CullingLimit:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_LongestIntronLength:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_QueryGeneticCode:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DbGeneticCode:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_UnifiedP:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_WindowMaskerTaxId:
x_SetParam(CBlast4Field::Get(opt), v);
return;
//For handling rpsblast save search strategy with mutli-dbs
case eBlastOpt_DbSeqNum:
case eBlastOpt_DbLength:
return;
default:
break;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%d), line (%d).",
int(opt), v, __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const double & v)
{
if (m_DefaultsMode) {
return;
}
switch(opt) {
case eBlastOpt_EvalueThreshold:
{
typedef objects::CBlast4_cutoff TCutoff;
CRef<TCutoff> cutoff(new TCutoff);
cutoff->SetE_value(v);
x_SetParam(CBlast4Field::Get(opt), cutoff);
}
return;
case eBlastOpt_PercentIdentity:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_InclusionThreshold:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapXDropoff:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapXDropoffFinal:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_XDropoff:
//x_SetParam(B4Param_XDropoff, v);
return;
case eBlastOpt_SegFilteringLocut:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_SegFilteringHicut:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_GapTrigger:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_BestHitScoreEdge:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_BestHitOverhang:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DomainInclusionThreshold:
x_SetParam(CBlast4Field::Get(opt), v);
return;
default:
break;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%f), line (%d).",
int(opt), v, __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const char * v)
{
if (m_DefaultsMode) {
return;
}
switch(opt) {
case eBlastOpt_FilterString:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_RepeatFilteringDB:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_MatrixName:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_WindowMaskerDatabase:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_PHIPattern:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_MbIndexName:
x_SetParam(CBlast4Field::Get(opt), v);
return;
default:
break;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%.20s), line (%d).",
int(opt), v, __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const TSeqLocVector & v)
{
if (m_DefaultsMode) {
return;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and TSeqLocVector (size %zd), line (%d).",
int(opt), v.size(), __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const ESeedContainerType & v)
{
if (m_DefaultsMode) {
return;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%d), line (%d).",
int(opt), v, __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const bool & v)
{
if (m_DefaultsMode) {
return;
}
switch(opt) {
case eBlastOpt_GappedMode:
{
bool ungapped = ! v;
x_SetParam(CBlast4Field::Get(opt), ungapped); // inverted
return;
}
// Added for rmblastn and the new complexity adjusted scoring -RMH-
case eBlastOpt_ComplexityAdjMode:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_OutOfFrameMode:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_SegFiltering:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DustFiltering:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_RepeatFiltering:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_MaskAtHash:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_SumStatisticsMode:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_SmithWatermanMode:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_ForceMbIndex:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_IgnoreMsaMaster:
x_SetParam(CBlast4Field::Get(opt), v);
return;
default:
break;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%s), line (%d).",
int(opt), (v ? "true" : "false"), __LINE__);
x_Throwx(string("err:") + errbuf);
}
void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const Int8 & v)
{
if (m_DefaultsMode) {
return;
}
switch(opt) {
case eBlastOpt_EffectiveSearchSpace:
x_SetParam(CBlast4Field::Get(opt), v);
return;
case eBlastOpt_DbLength:
x_SetParam(CBlast4Field::Get(opt), v);
return;
default:
break;
}
char errbuf[1024];
sprintf(errbuf, "tried to set option (%d) and value (%f), line (%d).",
int(opt), double(v), __LINE__);
x_Throwx(string("err:") + errbuf);
}
const CBlastOptionsMemento*
CBlastOptions::CreateSnapshot() const
{
if ( !m_Local ) {
NCBI_THROW(CBlastException, eInvalidArgument,
"Cannot create CBlastOptionsMemento without a local "
"CBlastOptions object");
}
return new CBlastOptionsMemento(m_Local);
}
bool
CBlastOptions::operator==(const CBlastOptions& rhs) const
{
if (m_Local && rhs.m_Local) {
return (*m_Local == *rhs.m_Local);
} else {
NCBI_THROW(CBlastException, eNotSupported,
"Equality operator unsupported for arguments");
}
}
bool
CBlastOptions::operator!=(const CBlastOptions& rhs) const
{
return !(*this == rhs);
}
bool
CBlastOptions::Validate() const
{
bool local_okay = m_Local ? (m_Local ->Validate()) : true;
return local_okay;
}
EProgram
CBlastOptions::GetProgram() const
{
if (! m_Local) {
x_Throwx("Error: GetProgram() not available.");
}
return m_Local->GetProgram();
}
EBlastProgramType
CBlastOptions::GetProgramType() const
{
if (! m_Local) {
x_Throwx("Error: GetProgramType() not available.");
}
return m_Local->GetProgramType();
}
void
CBlastOptions::SetProgram(EProgram p)
{
if (m_Local) {
m_Local->SetProgram(p);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_Program, p);
}
}
/******************* Lookup table options ***********************/
double
CBlastOptions::GetWordThreshold() const
{
if (! m_Local) {
x_Throwx("Error: GetWordThreshold() not available.");
}
return m_Local->GetWordThreshold();
}
void
CBlastOptions::SetWordThreshold(double w)
{
if (m_Local) {
m_Local->SetWordThreshold(w);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_WordThreshold, static_cast<int>(w));
}
}
ELookupTableType
CBlastOptions::GetLookupTableType() const
{
if (! m_Local) {
x_Throwx("Error: GetLookupTableType() not available.");
}
return m_Local->GetLookupTableType();
}
void
CBlastOptions::SetLookupTableType(ELookupTableType type)
{
if (m_Local) {
m_Local->SetLookupTableType(type);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_LookupTableType, type);
}
}
int
CBlastOptions::GetWordSize() const
{
if (! m_Local) {
x_Throwx("Error: GetWordSize() not available.");
}
return m_Local->GetWordSize();
}
void
CBlastOptions::SetWordSize(int ws)
{
if (m_Local) {
m_Local->SetWordSize(ws);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_WordSize, ws);
}
}
/// Megablast only lookup table options
unsigned char
CBlastOptions::GetMBTemplateLength() const
{
if (! m_Local) {
x_Throwx("Error: GetMBTemplateLength() not available.");
}
return m_Local->GetMBTemplateLength();
}
void
CBlastOptions::SetMBTemplateLength(unsigned char len)
{
if (m_Local) {
m_Local->SetMBTemplateLength(len);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MBTemplateLength, len);
}
}
unsigned char
CBlastOptions::GetMBTemplateType() const
{
if (! m_Local) {
x_Throwx("Error: GetMBTemplateType() not available.");
}
return m_Local->GetMBTemplateType();
}
void
CBlastOptions::SetMBTemplateType(unsigned char type)
{
if (m_Local) {
m_Local->SetMBTemplateType(type);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MBTemplateType, type);
}
}
/******************* Query setup options ************************/
void
CBlastOptions::ClearFilterOptions()
{
SetDustFiltering(false);
SetSegFiltering(false);
SetRepeatFiltering(false);
SetMaskAtHash(false);
SetWindowMaskerTaxId(0);
SetWindowMaskerDatabase(NULL);
return;
}
char*
CBlastOptions::GetFilterString() const
{
if (! m_Local) {
x_Throwx("Error: GetFilterString() not available.");
}
return m_Local->GetFilterString();/* NCBI_FAKE_WARNING */
}
void
CBlastOptions::SetFilterString(const char* f, bool clear)
{
// Clear if clear is true or filtering set to FALSE.
if (clear == true || NStr::CompareNocase("F", f) == 0) {
ClearFilterOptions();
}
if (m_Local) {
m_Local->SetFilterString(f);/* NCBI_FAKE_WARNING */
}
if (m_Remote) {
// When maintaining this code, please insure the following:
//
// 1. This list of items is parallel to the list found
// below, in the "set" block.
//
// 2. Both lists should also correspond to the list of
// options in names.hpp and names.cpp that are related
// to filtering options.
//
// 3. Blast4's code in CCollectFilterOptions should also
// handle the set of options handled here.
//
// 4. CRemoteBlast and CRemoteBlastService's handling of
// filtering options (CBlastOptionsBuilder) should
// include all of these elements.
//
// 5. Libnet2blast should deal with all of these filtering
// options when it builds CBlastOptionsHandle objects.
//
// 6. Probably at least one or two other places that I forgot.
m_Remote->SetValue(eBlastOpt_MaskAtHash, m_Local->GetMaskAtHash());
bool do_dust(false), do_seg(false), do_rep(false);
if (Blast_QueryIsProtein(GetProgramType()) ||
Blast_QueryIsTranslated(GetProgramType())) {
do_seg = m_Local->GetSegFiltering();
m_Remote->SetValue(eBlastOpt_SegFiltering, do_seg);
} else {
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFiltering));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFilteringWindow));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFilteringLocut));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFilteringHicut));
}
if (Blast_QueryIsNucleotide(GetProgramType()) &&
!Blast_QueryIsTranslated(GetProgramType())) {
do_dust = m_Local->GetDustFiltering();
do_rep = m_Local->GetRepeatFiltering();
m_Remote->SetValue(eBlastOpt_DustFiltering, do_dust);
m_Remote->SetValue(eBlastOpt_RepeatFiltering, do_rep);
} else {
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFiltering));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFilteringLevel));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFilteringWindow));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFilteringLinker));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_RepeatFiltering));
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_RepeatFilteringDB));
}
if (do_dust) {
m_Remote->SetValue(eBlastOpt_DustFilteringLevel,
m_Local->GetDustFilteringLevel());
m_Remote->SetValue(eBlastOpt_DustFilteringWindow,
m_Local->GetDustFilteringWindow());
m_Remote->SetValue(eBlastOpt_DustFilteringLinker,
m_Local->GetDustFilteringLinker());
}
if (do_rep) {
m_Remote->SetValue(eBlastOpt_RepeatFilteringDB,
m_Local->GetRepeatFilteringDB());
}
if (do_seg) {
m_Remote->SetValue(eBlastOpt_SegFilteringWindow,
m_Local->GetSegFilteringWindow());
m_Remote->SetValue(eBlastOpt_SegFilteringLocut,
m_Local->GetSegFilteringLocut());
m_Remote->SetValue(eBlastOpt_SegFilteringHicut,
m_Local->GetSegFilteringHicut());
}
}
}
bool
CBlastOptions::GetMaskAtHash() const
{
if (! m_Local) {
x_Throwx("Error: GetMaskAtHash() not available.");
}
return m_Local->GetMaskAtHash();
}
void
CBlastOptions::SetMaskAtHash(bool val)
{
if (m_Local) {
m_Local->SetMaskAtHash(val);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MaskAtHash, val);
}
}
bool
CBlastOptions::GetDustFiltering() const
{
if (! m_Local) {
x_Throwx("Error: GetDustFiltering() not available.");
}
return m_Local->GetDustFiltering();
}
void
CBlastOptions::SetDustFiltering(bool val)
{
if (m_Local) {
m_Local->SetDustFiltering(val);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DustFiltering, val);
}
}
int
CBlastOptions::GetDustFilteringLevel() const
{
if (! m_Local) {
x_Throwx("Error: GetDustFilteringLevel() not available.");
}
return m_Local->GetDustFilteringLevel();
}
void
CBlastOptions::SetDustFilteringLevel(int m)
{
if (m_Local) {
m_Local->SetDustFilteringLevel(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DustFilteringLevel, m);
}
}
int
CBlastOptions::GetDustFilteringWindow() const
{
if (! m_Local) {
x_Throwx("Error: GetDustFilteringWindow() not available.");
}
return m_Local->GetDustFilteringWindow();
}
void
CBlastOptions::SetDustFilteringWindow(int m)
{
if (m_Local) {
m_Local->SetDustFilteringWindow(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DustFilteringWindow, m);
}
}
int
CBlastOptions::GetDustFilteringLinker() const
{
if (! m_Local) {
x_Throwx("Error: GetDustFilteringLinker() not available.");
}
return m_Local->GetDustFilteringLinker();
}
void
CBlastOptions::SetDustFilteringLinker(int m)
{
if (m_Local) {
m_Local->SetDustFilteringLinker(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DustFilteringLinker, m);
}
}
bool
CBlastOptions::GetSegFiltering() const
{
if (! m_Local) {
x_Throwx("Error: GetSegFiltering() not available.");
}
return m_Local->GetSegFiltering();
}
void
CBlastOptions::SetSegFiltering(bool val)
{
if (m_Local) {
m_Local->SetSegFiltering(val);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_SegFiltering, val);
}
}
int
CBlastOptions::GetSegFilteringWindow() const
{
if (! m_Local) {
x_Throwx("Error: GetSegFilteringWindow() not available.");
}
return m_Local->GetSegFilteringWindow();
}
void
CBlastOptions::SetSegFilteringWindow(int m)
{
if (m_Local) {
m_Local->SetSegFilteringWindow(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_SegFilteringWindow, m);
}
}
double
CBlastOptions::GetSegFilteringLocut() const
{
if (! m_Local) {
x_Throwx("Error: GetSegFilteringLocut() not available.");
}
return m_Local->GetSegFilteringLocut();
}
void
CBlastOptions::SetSegFilteringLocut(double m)
{
if (m_Local) {
m_Local->SetSegFilteringLocut(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_SegFilteringLocut, m);
}
}
double
CBlastOptions::GetSegFilteringHicut() const
{
if (! m_Local) {
x_Throwx("Error: GetSegFilteringHicut() not available.");
}
return m_Local->GetSegFilteringHicut();
}
void
CBlastOptions::SetSegFilteringHicut(double m)
{
if (m_Local) {
m_Local->SetSegFilteringHicut(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_SegFilteringHicut, m);
}
}
bool
CBlastOptions::GetRepeatFiltering() const
{
if (! m_Local) {
x_Throwx("Error: GetRepeatFiltering() not available.");
}
return m_Local->GetRepeatFiltering();
}
void
CBlastOptions::SetRepeatFiltering(bool val)
{
if (m_Local) {
m_Local->SetRepeatFiltering(val);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_RepeatFiltering, val);
}
}
const char*
CBlastOptions::GetRepeatFilteringDB() const
{
if (! m_Local) {
x_Throwx("Error: GetRepeatFilteringDB() not available.");
}
return m_Local->GetRepeatFilteringDB();
}
void
CBlastOptions::SetRepeatFilteringDB(const char* db)
{
if (m_Local) {
m_Local->SetRepeatFilteringDB(db);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_RepeatFilteringDB, db);
}
}
int
CBlastOptions::GetWindowMaskerTaxId() const
{
if (! m_Local) {
x_Throwx("Error: GetWindowMaskerTaxId() not available.");
}
return m_Local->GetWindowMaskerTaxId();
}
void
CBlastOptions::SetWindowMaskerTaxId(int value)
{
if (m_Local) {
m_Local->SetWindowMaskerTaxId(value);
}
if (m_Remote) {
if (value) {
m_Remote->SetValue(eBlastOpt_WindowMaskerTaxId, value);
} else {
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_WindowMaskerTaxId));
}
}
}
const char *
CBlastOptions::GetWindowMaskerDatabase() const
{
if (! m_Local) {
x_Throwx("Error: GetWindowMaskerDatabase() not available.");
}
return m_Local->GetWindowMaskerDatabase();
}
void
CBlastOptions::SetWindowMaskerDatabase(const char * value)
{
if (m_Local) {
m_Local->SetWindowMaskerDatabase(value);
}
if (m_Remote) {
if (value) {
m_Remote->SetValue(eBlastOpt_WindowMaskerDatabase, value);
} else {
m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_WindowMaskerDatabase));
}
}
}
objects::ENa_strand
CBlastOptions::GetStrandOption() const
{
if (! m_Local) {
x_Throwx("Error: GetStrandOption() not available.");
}
return m_Local->GetStrandOption();
}
void
CBlastOptions::SetStrandOption(objects::ENa_strand s)
{
if (m_Local) {
m_Local->SetStrandOption(s);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_StrandOption, s);
}
}
int
CBlastOptions::GetQueryGeneticCode() const
{
if (! m_Local) {
x_Throwx("Error: GetQueryGeneticCode() not available.");
}
return m_Local->GetQueryGeneticCode();
}
void
CBlastOptions::SetQueryGeneticCode(int gc)
{
if (m_Local) {
m_Local->SetQueryGeneticCode(gc);
m_GenCodeSingletonVar.AddGeneticCode(gc);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_QueryGeneticCode, gc);
}
}
/******************* Initial word options ***********************/
int
CBlastOptions::GetWindowSize() const
{
if (! m_Local) {
x_Throwx("Error: GetWindowSize() not available.");
}
return m_Local->GetWindowSize();
}
void
CBlastOptions::SetWindowSize(int w)
{
if (m_Local) {
m_Local->SetWindowSize(w);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_WindowSize, w);
}
}
int
CBlastOptions::GetOffDiagonalRange() const
{
if (! m_Local) {
x_Throwx("Error: GetOffDiagonalRange() not available.");
}
return m_Local->GetOffDiagonalRange();
}
void
CBlastOptions::SetOffDiagonalRange(int w)
{
if (m_Local) {
m_Local->SetOffDiagonalRange(w);
}
// N/A for the time being
//if (m_Remote) {
// m_Remote->SetValue(eBlastOpt_OffDiagonalRange, w);
//}
}
double
CBlastOptions::GetXDropoff() const
{
if (! m_Local) {
x_Throwx("Error: GetXDropoff() not available.");
}
return m_Local->GetXDropoff();
}
void
CBlastOptions::SetXDropoff(double x)
{
if (m_Local) {
m_Local->SetXDropoff(x);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_XDropoff, x);
}
}
/******************* Gapped extension options *******************/
double
CBlastOptions::GetGapXDropoff() const
{
if (! m_Local) {
x_Throwx("Error: GetGapXDropoff() not available.");
}
return m_Local->GetGapXDropoff();
}
void
CBlastOptions::SetGapXDropoff(double x)
{
if (m_Local) {
m_Local->SetGapXDropoff(x);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapXDropoff, x);
}
}
double
CBlastOptions::GetGapXDropoffFinal() const
{
if (! m_Local) {
x_Throwx("Error: GetGapXDropoffFinal() not available.");
}
return m_Local->GetGapXDropoffFinal();
}
void
CBlastOptions::SetGapXDropoffFinal(double x)
{
if (m_Local) {
m_Local->SetGapXDropoffFinal(x);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapXDropoffFinal, x);
}
}
double
CBlastOptions::GetGapTrigger() const
{
if (! m_Local) {
x_Throwx("Error: GetGapTrigger() not available.");
}
return m_Local->GetGapTrigger();
}
void
CBlastOptions::SetGapTrigger(double g)
{
if (m_Local) {
m_Local->SetGapTrigger(g);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapTrigger, g);
}
}
EBlastPrelimGapExt
CBlastOptions::GetGapExtnAlgorithm() const
{
if (! m_Local) {
x_Throwx("Error: GetGapExtnAlgorithm() not available.");
}
return m_Local->GetGapExtnAlgorithm();
}
void
CBlastOptions::SetGapExtnAlgorithm(EBlastPrelimGapExt a)
{
if (m_Local) {
m_Local->SetGapExtnAlgorithm(a);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapExtnAlgorithm, a);
}
}
EBlastTbackExt
CBlastOptions::GetGapTracebackAlgorithm() const
{
if (! m_Local) {
x_Throwx("Error: GetGapTracebackAlgorithm() not available.");
}
return m_Local->GetGapTracebackAlgorithm();
}
void
CBlastOptions::SetGapTracebackAlgorithm(EBlastTbackExt a)
{
if (m_Local) {
m_Local->SetGapTracebackAlgorithm(a);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapTracebackAlgorithm, a);
}
}
ECompoAdjustModes
CBlastOptions::GetCompositionBasedStats() const
{
if (! m_Local) {
x_Throwx("Error: GetCompositionBasedStats() not available.");
}
return m_Local->GetCompositionBasedStats();
}
void
CBlastOptions::SetCompositionBasedStats(ECompoAdjustModes mode)
{
if (m_Local) {
m_Local->SetCompositionBasedStats(mode);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_CompositionBasedStats, mode);
}
}
bool
CBlastOptions::GetSmithWatermanMode() const
{
if (! m_Local) {
x_Throwx("Error: GetSmithWatermanMode() not available.");
}
return m_Local->GetSmithWatermanMode();
}
void
CBlastOptions::SetSmithWatermanMode(bool m)
{
if (m_Local) {
m_Local->SetSmithWatermanMode(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_SmithWatermanMode, m);
}
}
int
CBlastOptions::GetUnifiedP() const
{
if (! m_Local) {
x_Throwx("Error: GetUnifiedP() not available.");
}
return m_Local->GetUnifiedP();
}
void
CBlastOptions::SetUnifiedP(int u)
{
if (m_Local) {
m_Local->SetUnifiedP(u);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_UnifiedP, u);
}
}
/******************* Hit saving options *************************/
int
CBlastOptions::GetHitlistSize() const
{
if (! m_Local) {
x_Throwx("Error: GetHitlistSize() not available.");
}
return m_Local->GetHitlistSize();
}
void
CBlastOptions::SetHitlistSize(int s)
{
if (m_Local) {
m_Local->SetHitlistSize(s);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_HitlistSize, s);
}
}
int
CBlastOptions::GetMaxNumHspPerSequence() const
{
if (! m_Local) {
x_Throwx("Error: GetMaxNumHspPerSequence() not available.");
}
return m_Local->GetMaxNumHspPerSequence();
}
void
CBlastOptions::SetMaxNumHspPerSequence(int m)
{
if (m_Local) {
m_Local->SetMaxNumHspPerSequence(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MaxNumHspPerSequence, m);
}
}
int
CBlastOptions::GetCullingLimit() const
{
if (! m_Local) {
x_Throwx("Error: GetCullingMode() not available.");
}
return m_Local->GetCullingLimit();
}
void
CBlastOptions::SetCullingLimit(int s)
{
if (m_Local) {
m_Local->SetCullingLimit(s);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_CullingLimit, s);
}
}
double
CBlastOptions::GetBestHitOverhang() const
{
if (! m_Local) {
x_Throwx("Error: GetBestHitOverhangMode() not available.");
}
return m_Local->GetBestHitOverhang();
}
void
CBlastOptions::SetBestHitOverhang(double overhang)
{
if (m_Local) {
m_Local->SetBestHitOverhang(overhang);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_BestHitOverhang, overhang);
}
}
double
CBlastOptions::GetBestHitScoreEdge() const
{
if (! m_Local) {
x_Throwx("Error: GetBestHitScoreEdgeMode() not available.");
}
return m_Local->GetBestHitScoreEdge();
}
void
CBlastOptions::SetBestHitScoreEdge(double score_edge)
{
if (m_Local) {
m_Local->SetBestHitScoreEdge(score_edge);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_BestHitScoreEdge, score_edge);
}
}
double
CBlastOptions::GetEvalueThreshold() const
{
if (! m_Local) {
x_Throwx("Error: GetEvalueThreshold() not available.");
}
return m_Local->GetEvalueThreshold();
}
void
CBlastOptions::SetEvalueThreshold(double eval)
{
if (m_Local) {
m_Local->SetEvalueThreshold(eval);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_EvalueThreshold, eval);
}
}
int
CBlastOptions::GetCutoffScore() const
{
if (! m_Local) {
x_Throwx("Error: GetCutoffScore() not available.");
}
return m_Local->GetCutoffScore();
}
void
CBlastOptions::SetCutoffScore(int s)
{
if (m_Local) {
m_Local->SetCutoffScore(s);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_CutoffScore, s);
}
}
double
CBlastOptions::GetPercentIdentity() const
{
if (! m_Local) {
x_Throwx("Error: GetPercentIdentity() not available.");
}
return m_Local->GetPercentIdentity();
}
void
CBlastOptions::SetPercentIdentity(double p)
{
if (m_Local) {
m_Local->SetPercentIdentity(p);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_PercentIdentity, p);
}
}
int
CBlastOptions::GetMinDiagSeparation() const
{
if (! m_Local) {
x_Throwx("Error: GetMinDiagSeparation() not available.");
}
return m_Local->GetMinDiagSeparation();
}
void
CBlastOptions::SetMinDiagSeparation(int d)
{
if (! m_Local) {
x_Throwx("Error: SetMinDiagSeparation() not available.");
}
m_Local->SetMinDiagSeparation(d);
}
bool
CBlastOptions::GetSumStatisticsMode() const
{
if (! m_Local) {
x_Throwx("Error: GetSumStatisticsMode() not available.");
}
return m_Local->GetSumStatisticsMode();
}
void
CBlastOptions::SetSumStatisticsMode(bool m)
{
if (m_Local) {
m_Local->SetSumStatisticsMode(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_SumStatisticsMode, m);
}
}
int
CBlastOptions::GetLongestIntronLength() const
{
if (! m_Local) {
x_Throwx("Error: GetLongestIntronLength() not available.");
}
return m_Local->GetLongestIntronLength();
}
void
CBlastOptions::SetLongestIntronLength(int l)
{
if (m_Local) {
m_Local->SetLongestIntronLength(l);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_LongestIntronLength, l);
}
}
bool
CBlastOptions::GetGappedMode() const
{
if (! m_Local) {
x_Throwx("Error: GetGappedMode() not available.");
}
return m_Local->GetGappedMode();
}
void
CBlastOptions::SetGappedMode(bool m)
{
if (m_Local) {
m_Local->SetGappedMode(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GappedMode, m);
}
}
// -RMH-
int
CBlastOptions::GetMaskLevel() const
{
if (! m_Local) {
x_Throwx("Error: GetMaskLevel() not available.");
}
return m_Local->GetMaskLevel();
}
// -RMH-
void
CBlastOptions::SetMaskLevel(int s)
{
if (m_Local) {
m_Local->SetMaskLevel(s);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MaskLevel, s);
}
}
// -RMH-
bool
CBlastOptions::GetComplexityAdjMode() const
{
if (! m_Local) {
x_Throwx("Error: GetComplexityAdjMode() not available.");
}
return m_Local->GetComplexityAdjMode();
}
// -RMH-
void
CBlastOptions::SetComplexityAdjMode(bool m)
{
if (m_Local) {
m_Local->SetComplexityAdjMode(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_ComplexityAdjMode, m);
}
}
double
CBlastOptions::GetLowScorePerc() const
{
if (! m_Local) {
x_Throwx("Error: GetLowScorePerc() not available.");
}
return m_Local->GetLowScorePerc();
}
void
CBlastOptions::SetLowScorePerc(double p)
{
if (m_Local)
m_Local->SetLowScorePerc(p);
}
/************************ Scoring options ************************/
const char*
CBlastOptions::GetMatrixName() const
{
if (! m_Local) {
x_Throwx("Error: GetMatrixName() not available.");
}
return m_Local->GetMatrixName();
}
void
CBlastOptions::SetMatrixName(const char* matrix)
{
if (m_Local) {
m_Local->SetMatrixName(matrix);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MatrixName, matrix);
}
}
int
CBlastOptions::GetMatchReward() const
{
if (! m_Local) {
x_Throwx("Error: GetMatchReward() not available.");
}
return m_Local->GetMatchReward();
}
void
CBlastOptions::SetMatchReward(int r)
{
if (m_Local) {
m_Local->SetMatchReward(r);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MatchReward, r);
}
}
int
CBlastOptions::GetMismatchPenalty() const
{
if (! m_Local) {
x_Throwx("Error: GetMismatchPenalty() not available.");
}
return m_Local->GetMismatchPenalty();
}
void
CBlastOptions::SetMismatchPenalty(int p)
{
if (m_Local) {
m_Local->SetMismatchPenalty(p);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_MismatchPenalty, p);
}
}
int
CBlastOptions::GetGapOpeningCost() const
{
if (! m_Local) {
x_Throwx("Error: GetGapOpeningCost() not available.");
}
return m_Local->GetGapOpeningCost();
}
void
CBlastOptions::SetGapOpeningCost(int g)
{
if (m_Local) {
m_Local->SetGapOpeningCost(g);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapOpeningCost, g);
}
}
int
CBlastOptions::GetGapExtensionCost() const
{
if (! m_Local) {
x_Throwx("Error: GetGapExtensionCost() not available.");
}
return m_Local->GetGapExtensionCost();
}
void
CBlastOptions::SetGapExtensionCost(int e)
{
if (m_Local) {
m_Local->SetGapExtensionCost(e);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_GapExtensionCost, e);
}
}
int
CBlastOptions::GetFrameShiftPenalty() const
{
if (! m_Local) {
x_Throwx("Error: GetFrameShiftPenalty() not available.");
}
return m_Local->GetFrameShiftPenalty();
}
void
CBlastOptions::SetFrameShiftPenalty(int p)
{
if (m_Local) {
m_Local->SetFrameShiftPenalty(p);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_FrameShiftPenalty, p);
}
}
bool
CBlastOptions::GetOutOfFrameMode() const
{
if (! m_Local) {
x_Throwx("Error: GetOutOfFrameMode() not available.");
}
return m_Local->GetOutOfFrameMode();
}
void
CBlastOptions::SetOutOfFrameMode(bool m)
{
if (m_Local) {
m_Local->SetOutOfFrameMode(m);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_OutOfFrameMode, m);
}
}
/******************** Effective Length options *******************/
Int8
CBlastOptions::GetDbLength() const
{
if (! m_Local) {
x_Throwx("Error: GetDbLength() not available.");
}
return m_Local->GetDbLength();
}
void
CBlastOptions::SetDbLength(Int8 l)
{
if (m_Local) {
m_Local->SetDbLength(l);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DbLength, l);
}
}
unsigned int
CBlastOptions::GetDbSeqNum() const
{
if (! m_Local) {
x_Throwx("Error: GetDbSeqNum() not available.");
}
return m_Local->GetDbSeqNum();
}
void
CBlastOptions::SetDbSeqNum(unsigned int n)
{
if (m_Local) {
m_Local->SetDbSeqNum(n);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DbSeqNum, n);
}
}
Int8
CBlastOptions::GetEffectiveSearchSpace() const
{
if (! m_Local) {
x_Throwx("Error: GetEffectiveSearchSpace() not available.");
}
return m_Local->GetEffectiveSearchSpace();
}
void
CBlastOptions::SetEffectiveSearchSpace(Int8 eff)
{
if (m_Local) {
m_Local->SetEffectiveSearchSpace(eff);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_EffectiveSearchSpace, eff);
}
}
void
CBlastOptions::SetEffectiveSearchSpace(const vector<Int8>& eff)
{
if (m_Local) {
m_Local->SetEffectiveSearchSpace(eff);
}
if (m_Remote) {
_ASSERT( !eff.empty() );
// This is the best we can do because remote BLAST only accepts one
// value for the effective search space
m_Remote->SetValue(eBlastOpt_EffectiveSearchSpace, eff.front());
}
}
int
CBlastOptions::GetDbGeneticCode() const
{
if (! m_Local) {
x_Throwx("Error: GetDbGeneticCode() not available.");
}
return m_Local->GetDbGeneticCode();
}
void
CBlastOptions::SetDbGeneticCode(int gc)
{
if (m_Local) {
m_Local->SetDbGeneticCode(gc);
m_GenCodeSingletonVar.AddGeneticCode(gc);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DbGeneticCode, gc);
}
}
const char*
CBlastOptions::GetPHIPattern() const
{
if (! m_Local) {
x_Throwx("Error: GetPHIPattern() not available.");
}
return m_Local->GetPHIPattern();
}
void
CBlastOptions::SetPHIPattern(const char* pattern, bool is_dna)
{
if (m_Local) {
m_Local->SetPHIPattern(pattern, is_dna);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_PHIPattern, pattern);
// For now I will assume this is handled when the data is passed to the
// code in blast4_options - i.e. that code will discriminate on the basis
// of the type of *OptionHandle that is passed in.
//
// if (is_dna) {
// m_Remote->SetProgram("blastn");
// } else {
// m_Remote->SetProgram("blastp");
// }
//
// m_Remote->SetService("phi");
}
}
/******************** PSIBlast options *******************/
double
CBlastOptions::GetInclusionThreshold() const
{
if (! m_Local) {
x_Throwx("Error: GetInclusionThreshold() not available.");
}
return m_Local->GetInclusionThreshold();
}
void
CBlastOptions::SetInclusionThreshold(double u)
{
if (m_Local) {
m_Local->SetInclusionThreshold(u);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_InclusionThreshold, u);
}
}
int
CBlastOptions::GetPseudoCount() const
{
if (! m_Local) {
x_Throwx("Error: GetPseudoCount() not available.");
}
return m_Local->GetPseudoCount();
}
void
CBlastOptions::SetPseudoCount(int u)
{
if (m_Local) {
m_Local->SetPseudoCount(u);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_PseudoCount, u);
}
}
bool
CBlastOptions::GetIgnoreMsaMaster() const
{
if (! m_Local) {
x_Throwx("Error: GetIgnoreMsaMaster() not available.");
}
return m_Local->GetIgnoreMsaMaster();
}
void
CBlastOptions::SetIgnoreMsaMaster(bool val)
{
if (m_Local) {
m_Local->SetIgnoreMsaMaster(val);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_IgnoreMsaMaster, val);
}
}
/******************** DELTA-Blast options *******************/
double
CBlastOptions::GetDomainInclusionThreshold() const
{
if (! m_Local) {
x_Throwx("Error: GetDomainInclusionThreshold() not available.");
}
return m_Local->GetDomainInclusionThreshold();
}
void
CBlastOptions::SetDomainInclusionThreshold(double th)
{
if (m_Local) {
m_Local->SetDomainInclusionThreshold(th);
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_DomainInclusionThreshold, th);
}
}
/// Allows to dump a snapshot of the object
void
CBlastOptions::DebugDump(CDebugDumpContext ddc, unsigned int depth) const
{
if (m_Local) {
m_Local->DebugDump(ddc, depth);
}
}
void
CBlastOptions::DoneDefaults() const
{
if (m_Remote) {
m_Remote->SetDefaultsMode(false);
}
}
// typedef ncbi::objects::CBlast4_queue_search_request TBlast4Req;
// CRef<TBlast4Req> GetBlast4Request() const
// {
// CRef<TBlast4Req> result;
// if (m_Remote) {
// result = m_Remote->GetBlast4Request();
// }
// return result;
// }
// the "new paradigm"
CBlastOptions::TBlast4Opts *
CBlastOptions::GetBlast4AlgoOpts()
{
TBlast4Opts * result = 0;
if (m_Remote) {
result = m_Remote->GetBlast4AlgoOpts();
}
return result;
}
bool CBlastOptions::GetUseIndex() const
{
if (! m_Local) {
x_Throwx("Error: GetUseIndex() not available.");
}
return m_Local->GetUseIndex();
}
bool CBlastOptions::GetForceIndex() const
{
if (! m_Local) {
x_Throwx("Error: GetForceIndex() not available.");
}
return m_Local->GetForceIndex();
}
bool CBlastOptions::GetIsOldStyleMBIndex() const
{
if (! m_Local) {
x_Throwx("Error: GetIsOldStyleMBIndex() not available.");
}
return m_Local->GetIsOldStyleMBIndex();
}
bool CBlastOptions::GetMBIndexLoaded() const
{
if (! m_Local) {
x_Throwx("Error: GetMBIndexLoaded() not available.");
}
return m_Local->GetMBIndexLoaded();
}
const string CBlastOptions::GetIndexName() const
{
if (! m_Local) {
x_Throwx("Error: GetIndexName() not available.");
}
return m_Local->GetIndexName();
}
void CBlastOptions::SetUseIndex(
bool use_index, const string & index_name,
bool force_index, bool old_style_index )
{
if (m_Local) {
m_Local->SetUseIndex(
use_index, index_name, force_index, old_style_index );
}
if (m_Remote) {
m_Remote->SetValue(eBlastOpt_ForceMbIndex, force_index);
if ( !index_name.empty() ) {
m_Remote->SetValue(eBlastOpt_MbIndexName, index_name.c_str());
}
}
}
void CBlastOptions::SetMBIndexLoaded( bool index_loaded )
{
if (! m_Local) {
x_Throwx("Error: SetMBIndexLoaded() not available.");
}
m_Local->SetMBIndexLoaded( index_loaded );
}
QuerySetUpOptions *
CBlastOptions::GetQueryOpts() const
{
return m_Local ? m_Local->GetQueryOpts() : 0;
}
LookupTableOptions *
CBlastOptions::GetLutOpts() const
{
return m_Local ? m_Local->GetLutOpts() : 0;
}
BlastInitialWordOptions *
CBlastOptions::GetInitWordOpts() const
{
return m_Local ? m_Local->GetInitWordOpts() : 0;
}
BlastExtensionOptions *
CBlastOptions::GetExtnOpts() const
{
return m_Local ? m_Local->GetExtnOpts() : 0;
}
BlastHitSavingOptions *
CBlastOptions::GetHitSaveOpts() const
{
return m_Local ? m_Local->GetHitSaveOpts() : 0;
}
PSIBlastOptions *
CBlastOptions::GetPSIBlastOpts() const
{
return m_Local ? m_Local->GetPSIBlastOpts() : 0;
}
BlastDatabaseOptions *
CBlastOptions::GetDbOpts() const
{
return m_Local ? m_Local->GetDbOpts() : 0;
}
BlastScoringOptions *
CBlastOptions::GetScoringOpts() const
{
return m_Local ? m_Local->GetScoringOpts() : 0;
}
BlastEffectiveLengthsOptions *
CBlastOptions::GetEffLenOpts() const
{
return m_Local ? m_Local->GetEffLenOpts() : 0;
}
void
CBlastOptions::x_Throwx(const string& msg) const
{
NCBI_THROW(CBlastException, eInvalidOptions, msg);
}
void CBlastOptions::SetDefaultsMode(bool dmode)
{
if (m_Remote) {
m_Remote->SetDefaultsMode(dmode);
}
}
bool CBlastOptions::GetDefaultsMode() const
{
if (m_Remote) {
return m_Remote->GetDefaultsMode();
}
else
return false;
}
void CBlastOptions::x_DoDeepCopy(const CBlastOptions& opts)
{
if (&opts != this)
{
// Clean up the old object
if (m_Local)
{
delete m_Local;
m_Local = 0;
}
if (m_Remote)
{
delete m_Remote;
m_Remote = 0;
}
// Copy the contents of the new object
if (opts.m_Remote)
{
m_Remote = new CBlastOptionsRemote(*opts.m_Remote);
}
if (opts.m_Local)
{
m_Local = new CBlastOptionsLocal(*opts.m_Local);
}
m_ProgramName = opts.m_ProgramName;
m_ServiceName = opts.m_ServiceName;
m_DefaultsMode = opts.m_DefaultsMode;
}
}
//////////////////////////////////////////////////////////////////////////
//added by kyzhao for GPU blastn
/* *********** START ************* */
int CBlastOptions::GetMethod() const
{
if (! m_Local) {
x_Throwx("Error: GetMethod() not available.");
}
return m_Local->GetMethod();
}
string CBlastOptions::GetQueryList() const
{
if (! m_Local) {
x_Throwx("Error: GetQueryList() not available.");
}
return m_Local->GetQueryList();
}
bool CBlastOptions::GetUseGpu() const
{
if (! m_Local) {
x_Throwx("Error: GetUseGPU() not available.");
}
return m_Local->GetUseGpu();
}
int CBlastOptions::GetGpuID() const
{
if (! m_Local) {
x_Throwx("Error: GetGpuID() not available.");
}
return m_Local->GetGpuID();
}
int CBlastOptions::GetPrepareNum() const
{
if (! m_Local) {
x_Throwx("Error: GetPrepareNum() not available.");
}
return m_Local->GetPrepareNum();
}
int CBlastOptions::GetPrelimNum() const
{
if (! m_Local) {
x_Throwx("Error: GetPrelimNum() not available.");
}
return m_Local->GetPrelimNum();
}
int CBlastOptions::GetTraceNum() const
{
if (! m_Local) {
x_Throwx("Error: GetTraceNum() not available.");
}
return m_Local->GetTraceNum();
}
int CBlastOptions::GetPrintNum() const
{
if (! m_Local) {
x_Throwx("Error: GetPrintNum() not available.");
}
return m_Local->GetPrintNum();
}
bool CBlastOptions::GetConverted() const
{
if (! m_Local)
{
x_Throwx("Error: GetConverted() not available.");
}
return m_Local->GetConverted();
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void CBlastOptions::SetMethod(int method)
{
if (m_Local) {
m_Local->SetMethod( method );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetQueryList(string query_list)
{
if (m_Local) {
m_Local->SetQueryList( query_list );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetUseGpu( bool use_gpu )
{
if (m_Local) {
m_Local->SetUseGpu( use_gpu );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetConverted(bool is_converted_db)
{
if (m_Local)
{
m_Local->SetConverted(is_converted_db);
}
if (m_Remote)
{
}
}
void CBlastOptions::SetGpuID( int gpu_id )
{
if (m_Local) {
m_Local->SetGpuID( gpu_id );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetPrepareNum( int prepare_num )
{
if (m_Local) {
m_Local->SetPrepareNum( prepare_num );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetPrelimNum( int prelim_num )
{
if (m_Local) {
m_Local->SetPrelimNum( prelim_num );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetTraceNum( int trace_num )
{
if (m_Local) {
m_Local->SetTraceNum( trace_num );
}
if (m_Remote) {
//
}
}
void CBlastOptions::SetPrintNum( int print_num )
{
if (m_Local) {
m_Local->SetPrintNum( print_num );
}
if (m_Remote) {
//
}
}
/* ********** FINISH ************* */
#endif /* SKIP_DOXYGEN_PROCESSING */
END_SCOPE(blast)
END_NCBI_SCOPE
/* @} */
| 23.257593
| 98
| 0.609277
|
OpenHero
|
ffe40f7d4488ee495de9bd09bb1b3f7358dff1b2
| 5,528
|
cpp
|
C++
|
src/Main/calculateEvec.cpp
|
pmu2022/lsms
|
3c5f266812cad0b6d570bef9f5abb590d044ef92
|
[
"BSD-3-Clause"
] | 1
|
2022-01-27T14:45:51.000Z
|
2022-01-27T14:45:51.000Z
|
src/Main/calculateEvec.cpp
|
pmu2022/lsms
|
3c5f266812cad0b6d570bef9f5abb590d044ef92
|
[
"BSD-3-Clause"
] | 3
|
2021-09-14T01:30:26.000Z
|
2021-09-25T14:05:10.000Z
|
src/Main/calculateEvec.cpp
|
pmu2022/lsms
|
3c5f266812cad0b6d570bef9f5abb590d044ef92
|
[
"BSD-3-Clause"
] | 1
|
2022-01-03T18:16:26.000Z
|
2022-01-03T18:16:26.000Z
|
#include "calculateEvec.hpp"
void calculateEvec(LSMSSystemParameters &lsms, LocalTypeInfo &local)
{
const Real tolerance = 1.0e-8;
for (int i=0; i<local.num_local; i++)
{
// Small part in mufind_c.f from LSMS 1.9
if (lsms.n_spin_cant == 2) // nspin >=3
{
// Calculate moment
Real moment[3];
moment[0] = local.atom[i].dosckint[1] + local.atom[i].evec[0] * local.atom[i].mcpsc_mt;
moment[1] = local.atom[i].dosckint[2] + local.atom[i].evec[1] * local.atom[i].mcpsc_mt;
moment[2] = local.atom[i].dosckint[3] + local.atom[i].evec[2] * local.atom[i].mcpsc_mt;
// getevec.f from LSMS 1.9
// Determine evecNew according to moment
Real evecMagnitude = std::sqrt(moment[0] * moment[0] + \
moment[1] * moment[1] + \
moment[2] * moment[2]);
if (lsms.global.iprint >= 0)
{
printf(" GETDOS: moment = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].dosckint[1],
local.atom[i].dosckint[2], local.atom[i].dosckint[3]);
printf(" GETCS: moment = (%12.8f, %12.8f, %12.8f)\n",
local.atom[i].evec[0] * local.atom[i].mcpsc_mt,
local.atom[i].evec[1] * local.atom[i].mcpsc_mt,
local.atom[i].evec[2] * local.atom[i].mcpsc_mt);
printf(" GETEVEC: moment = (%12.8f, %12.8f, %12.8f) magnitude = %12.8f\n",
moment[0],
moment[1],
moment[2],
evecMagnitude);
}
if (evecMagnitude > tolerance)
{
/*
=================================================================
evecNew is the new moment orientation:
evecNew[0] = the x-component of e-vector
evecNew[1] = the y-component of e-vector
evecNew[2] = the z-component of e-vector
it is determined by the total moment inside the muffin-tin sphere
=================================================================
*/
local.atom[i].evecNew[0] = moment[0] / evecMagnitude;
local.atom[i].evecNew[1] = moment[1] / evecMagnitude;
local.atom[i].evecNew[2] = moment[2] / evecMagnitude;
}
else
{
local.atom[i].evecNew[0] = local.atom[i].evec[0];
local.atom[i].evecNew[1] = local.atom[i].evec[1];
local.atom[i].evecNew[2] = local.atom[i].evec[2];
}
}
else // nspin = 1 or 2
{
local.atom[i].evecNew[0] = local.atom[i].evec[0];
local.atom[i].evecNew[1] = local.atom[i].evec[1];
local.atom[i].evecNew[2] = local.atom[i].evec[2];
}
/*
================================================================
Store direction & mag. mom. corresponding to output chg. den....
================================================================
Not yet implemented. (need to see where evec_out and mm_out are used for)
*/
if (lsms.global.iprint >= 0)
{
printf(" EVEC OLD: moment = %12.8f, %12.8f, %12.8f\n", local.atom[i].evecOut[0], local.atom[i].evecOut[1],local.atom[i].evecOut[2]);
printf(" EVEC FIX: moment = %12.8f, %12.8f, %12.8f\n", local.atom[i].evec[0], local.atom[i].evec[1],local.atom[i].evec[2]);
printf(" EVEC NEW: moment = %12.8f, %12.8f, %12.8f\n", local.atom[i].evecNew[0], local.atom[i].evecNew[1],local.atom[i].evecNew[2]);
}
local.atom[i].evecOut[0] = local.atom[i].evecNew[0];
local.atom[i].evecOut[1] = local.atom[i].evecNew[1];
local.atom[i].evecOut[2] = local.atom[i].evecNew[2];
// local.atom[i].magneticMomentOut = evecMagnitude;
}
return;
}
void mixEvec(LSMSSystemParameters &lsms, LocalTypeInfo &local, Real alpev)
{
/*
================================================================
perform simple mixing of evec_new and evec_old, and redefine
evec_new........................................................
================================================================
!! This should be placed in mixing.hpp !!
*/
Real tolerance = 1.0e-8;
for (int i=0; i<local.num_local; i++)
{
if (lsms.global.iprint > 0)
{
printf("Moment direction before mixing = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].evecNew[0], local.atom[i].evecNew[1], local.atom[i].evecNew[2]);
}
local.atom[i].evecNew[0] = alpev * local.atom[i].evecNew[0] + (1.0-alpev) * local.atom[i].evec[0];
local.atom[i].evecNew[1] = alpev * local.atom[i].evecNew[1] + (1.0-alpev) * local.atom[i].evec[1];
local.atom[i].evecNew[2] = alpev * local.atom[i].evecNew[2] + (1.0-alpev) * local.atom[i].evec[2];
Real evecMagnitude = std::sqrt(local.atom[i].evecNew[0] * local.atom[i].evecNew[0] + \
local.atom[i].evecNew[1] * local.atom[i].evecNew[1] + \
local.atom[i].evecNew[2] * local.atom[i].evecNew[2]);
if (evecMagnitude < tolerance)
{
printf("GETEVEC: magnitude of evec too small. (= %35.25f)\n", evecMagnitude);
}
local.atom[i].evecNew[0] = local.atom[i].evecNew[0] / evecMagnitude;
local.atom[i].evecNew[1] = local.atom[i].evecNew[1] / evecMagnitude;
local.atom[i].evecNew[2] = local.atom[i].evecNew[2] / evecMagnitude;
if (lsms.global.iprint > 0)
{
printf("Moment direction after mixing = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].evecNew[0], local.atom[i].evecNew[1], local.atom[i].evecNew[2]);
}
}
return;
}
| 38.124138
| 154
| 0.516281
|
pmu2022
|
ffe4485adf577a78dbafbdce23b9b679fdd896f5
| 774
|
cpp
|
C++
|
libsnes/bsnes/snes/chip/msu1/serialization.cpp
|
ircluzar/BizhawkLegacy-Vanguard
|
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
|
[
"MIT"
] | null | null | null |
libsnes/bsnes/snes/chip/msu1/serialization.cpp
|
ircluzar/BizhawkLegacy-Vanguard
|
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
|
[
"MIT"
] | null | null | null |
libsnes/bsnes/snes/chip/msu1/serialization.cpp
|
ircluzar/BizhawkLegacy-Vanguard
|
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
|
[
"MIT"
] | null | null | null |
#ifdef MSU1_CPP
void MSU1::serialize(serializer &s) {
Processor::serialize(s);
s.integer(mmio.data_offset);
s.integer(mmio.audio_offset);
s.integer(mmio.audio_loop_offset);
s.integer(mmio.audio_track);
s.integer(mmio.audio_volume);
s.integer(mmio.data_busy);
s.integer(mmio.audio_busy);
s.integer(mmio.audio_repeat);
s.integer(mmio.audio_play);
if(datafile.open()) datafile.close();
if(datafile.open(interface()->path(Cartridge::Slot::Base, "msu1.rom"), file::mode::read)) {
datafile.seek(mmio.data_offset);
}
if(audiofile.open()) audiofile.close();
if(audiofile.open(interface()->path(Cartridge::Slot::Base, { "track-", (unsigned)mmio.audio_track, ".pcm" }), file::mode::read)) {
audiofile.seek(mmio.audio_offset);
}
}
#endif
| 25.8
| 132
| 0.697674
|
ircluzar
|
ffe60ac81a3223be2a12b8dce2baa45abd78a8f1
| 3,982
|
cpp
|
C++
|
src/core/physics/body_template.cpp
|
texel-sensei/eversim
|
187262756186add9ee8583cbaa1d3ef9e6d0aa53
|
[
"Apache-2.0"
] | null | null | null |
src/core/physics/body_template.cpp
|
texel-sensei/eversim
|
187262756186add9ee8583cbaa1d3ef9e6d0aa53
|
[
"Apache-2.0"
] | 72
|
2017-07-18T16:38:29.000Z
|
2020-09-01T15:25:22.000Z
|
src/core/physics/body_template.cpp
|
texel-sensei/eversim
|
187262756186add9ee8583cbaa1d3ef9e6d0aa53
|
[
"Apache-2.0"
] | null | null | null |
#include "core/physics/body_template.h"
#include "core/physics/errors.h"
#include <fstream>
#include <sstream>
using namespace std;
namespace eversim { namespace core { namespace physics {
void body_template_loader::register_factory(std::string const& type, factory_ptr factory)
{
constraint_loaders[type] = move(factory);
}
body_template body_template_loader::parse(std::istream& data) const
{
data.exceptions(istream::badbit | istream::failbit);
body_template templ;
try{
load_particles(templ, data);
load_constraints(templ, data);
}
catch(ios::failure const& c)
{
if (c.code() == io_errc::stream)
{
EVERSIM_THROW(body_template_error::SyntaxError);
}
EVERSIM_THROW(c.code());
}
return templ;
}
shared_ptr<body_template_loader::value_type> body_template_loader::load_file(std::string const& path)
{
auto data = ifstream(path);
return make_shared<body_template>(parse(data));
}
void body_template_loader::load_particles(body_template& templ, std::istream& data) const
{
auto in = istringstream(load_line(data));
int num;
in >> num;
if(num <= 0)
{
EVERSIM_THROW(body_template_error::NotEnoughParticles);
}
templ.particles.resize(num);
for(int i = 0; i < num;++i)
{
auto line = load_line(data);
templ.particles[i] = particle_descriptor::parse(line);
}
}
void body_template_loader::load_constraints(body_template& templ, std::istream& data) const
{
auto in = istringstream(load_line(data));
int num;
in >> num;
if (num < 0)
{
EVERSIM_THROW(body_template_error::NotEnoughConstraints);
}
templ.constraints.resize(num);
for (int i = 0; i < num; ++i)
{
auto line = load_line(data);
auto c = constraint_descriptor::parse(line,
[this](string const& type) -> constraint_factory const&
{
return *constraint_loaders.at(type);
});
for(auto index : c.particles)
{
if(index >= templ.particles.size())
{
EVERSIM_THROW(body_template_error::InvalidIndex);
}
}
templ.constraints[i] = move(c);
}
}
string body_template_loader::load_line(istream& in) const
{
string line;
while(true){
in >> ws;
getline(in, line);
if(line.empty() || line[0] == '#')
{
continue;
}
return line;
}
}
namespace {
std::string get_remainder(istream& data)
{
if (data) {
data.exceptions(istream::badbit);
data >> ws;
string remainder;
getline(data, remainder);
auto pos = remainder.find('#');
if(pos != string::npos)
remainder = remainder.erase(pos);
remainder.erase(remainder.find_last_not_of(" \t") + 1);
return remainder;
}
return "";
}
}
particle_descriptor particle_descriptor::parse(std::string const& str)
{
auto desc = particle_descriptor{};
auto data = istringstream(str);
data.exceptions(istream::badbit | istream::failbit);
data >> desc.pos.x >> desc.pos.y >> desc.mass;
auto rem = get_remainder(data);
if(!rem.empty())
{
EVERSIM_THROW(body_template_error::SyntaxError, "Too much data while parsing particle! " + rem);
}
return desc;
}
constraint_descriptor constraint_descriptor::parse(
string const& str, factory_getter get_factory
){
auto desc = constraint_descriptor{};
auto data = istringstream(str);
data.exceptions(istream::badbit | istream::failbit);
data >> desc.arity;
desc.particles.resize(desc.arity);
for(int i = 0; i < desc.arity; ++i)
{
data >> desc.particles[i];
}
data >> desc.stiffness;
data >> desc.type;
auto rem = get_remainder(data);
auto extra = stringstream(rem);
auto const& f = get_factory(desc.type);
desc.factory = &f;
extra.exceptions(istream::badbit | istream::failbit);
desc.extra_data = f.parse(extra);
extra.exceptions(istream::badbit);
extra >> ws;
rem.clear();
getline(extra, rem);
if (!rem.empty())
{
EVERSIM_THROW(body_template_error::SyntaxError, "Too much data while parsing particle! " + rem);
}
return desc;
}
}}}
| 22
| 102
| 0.670517
|
texel-sensei
|
ffe7144243e30615abcc8e67abda78cfd1699428
| 448
|
cpp
|
C++
|
src/statusbar.cpp
|
roediger/tableau-log-viewer
|
4c63f8f91e71ebc0a1524f103a40459f9808bb06
|
[
"MIT"
] | 133
|
2016-10-14T04:36:10.000Z
|
2022-03-10T21:27:15.000Z
|
src/statusbar.cpp
|
Tableau-projects/tableau-log-viewer
|
4c63f8f91e71ebc0a1524f103a40459f9808bb06
|
[
"MIT"
] | 39
|
2016-10-14T06:28:35.000Z
|
2020-07-24T00:42:40.000Z
|
src/statusbar.cpp
|
Tableau-projects/tableau-log-viewer
|
4c63f8f91e71ebc0a1524f103a40459f9808bb06
|
[
"MIT"
] | 46
|
2016-10-18T15:38:10.000Z
|
2021-11-17T07:51:33.000Z
|
#include "statusbar.h"
StatusBar::StatusBar(QMainWindow* parent) :
m_qbar(parent->statusBar()),
m_statusLabel(new QLabel(parent))
{
m_statusLabel->setContentsMargins(0, 0, 8, 0);
m_qbar->addPermanentWidget(m_statusLabel);
}
void StatusBar::ShowMessage(const QString& message, int timeout)
{
m_qbar->showMessage(message, timeout);
}
void StatusBar::SetRightLabelText(const QString& text)
{
m_statusLabel->setText(text);
}
| 22.4
| 64
| 0.729911
|
roediger
|
ffee4de2ae3d9b280dac966a1ffced153c8a454c
| 11,699
|
cpp
|
C++
|
Engine/source/scene/zones/sceneZoneSpace.cpp
|
vbillet/Torque3D
|
ece8823599424ea675e5f79d9bcb44e42cba8cae
|
[
"MIT"
] | 2,113
|
2015-01-01T11:23:01.000Z
|
2022-03-28T04:51:46.000Z
|
Engine/source/scene/zones/sceneZoneSpace.cpp
|
Ashry00/Torque3D
|
33e3e41c8b7eb41c743a589558bc21302207ef97
|
[
"MIT"
] | 948
|
2015-01-02T01:50:00.000Z
|
2022-02-27T05:56:40.000Z
|
Engine/source/scene/zones/sceneZoneSpace.cpp
|
Ashry00/Torque3D
|
33e3e41c8b7eb41c743a589558bc21302207ef97
|
[
"MIT"
] | 944
|
2015-01-01T09:33:53.000Z
|
2022-03-15T22:23:03.000Z
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "scene/zones/sceneZoneSpace.h"
#include "scene/zones/sceneTraversalState.h"
#include "scene/zones/sceneZoneSpaceManager.h"
#include "scene/sceneRenderState.h"
#include "sim/netConnection.h"
#include "core/stream/bitStream.h"
#include "console/engineAPI.h"
//#define DEBUG_SPEW
ClassChunker< SceneZoneSpace::ZoneSpaceRef > SceneZoneSpace::smZoneSpaceRefChunker;
//-----------------------------------------------------------------------------
SceneZoneSpace::SceneZoneSpace()
: mManager( NULL ),
mZoneRangeStart( SceneZoneSpaceManager::InvalidZoneId ),
mZoneGroup( InvalidZoneGroup ),
mNumZones( 0 ),
mZoneFlags( ZoneFlag_IsClosedOffSpace ),
mConnectedZoneSpaces( NULL )
{
VECTOR_SET_ASSOCIATION( mOccluders );
}
//-----------------------------------------------------------------------------
SceneZoneSpace::~SceneZoneSpace()
{
AssertFatal( mConnectedZoneSpaces == NULL, "SceneZoneSpace::~SceneZoneSpace - Still have connected zone spaces!" );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::onSceneRemove()
{
_disconnectAllZoneSpaces();
Parent::onSceneRemove();
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::initPersistFields()
{
addGroup( "Zoning" );
addProtectedField( "zoneGroup", TypeS32, Offset( mZoneGroup, SceneZoneSpace ),
&_setZoneGroup, &defaultProtectedGetFn,
"ID of group the zone is part of." );
endGroup( "Zoning" );
Parent::initPersistFields();
}
//-----------------------------------------------------------------------------
bool SceneZoneSpace::writeField( StringTableEntry fieldName, const char* value )
{
// Don't write zoneGroup field if at default.
static StringTableEntry sZoneGroup = StringTable->insert( "zoneGroup" );
if( fieldName == sZoneGroup && getZoneGroup() == InvalidZoneGroup )
return false;
return Parent::writeField( fieldName, value );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::setZoneGroup( U32 group )
{
if( mZoneGroup == group )
return;
mZoneGroup = group;
setMaskBits( ZoneGroupMask );
// Rezone to establish new connectivity.
if( mManager )
mManager->notifyObjectChanged( this );
}
//-----------------------------------------------------------------------------
U32 SceneZoneSpace::packUpdate( NetConnection* connection, U32 mask, BitStream* stream )
{
U32 retMask = Parent::packUpdate( connection, mask, stream );
if( stream->writeFlag( mask & ZoneGroupMask ) )
stream->write( mZoneGroup );
return retMask;
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::unpackUpdate( NetConnection* connection, BitStream* stream )
{
Parent::unpackUpdate( connection, stream );
if( stream->readFlag() ) // ZoneGroupMask
{
U32 zoneGroup;
stream->read( &zoneGroup );
setZoneGroup( zoneGroup );
}
}
//-----------------------------------------------------------------------------
bool SceneZoneSpace::getOverlappingZones( SceneObject* obj, U32* outZones, U32& outNumZones )
{
return getOverlappingZones( obj->getWorldBox(), outZones, outNumZones );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_onZoneAddObject( SceneObject* object, const U32* zoneIDs, U32 numZones )
{
if( object->isVisualOccluder() )
_addOccluder( object );
// If this isn't the root zone and the object is zone space,
// see if we should automatically connect the two.
if( !isRootZone() && object->getTypeMask() & ZoneObjectType )
{
SceneZoneSpace* zoneSpace = dynamic_cast< SceneZoneSpace* >( object );
// Don't connect a zone space that has the same closed off status
// that we have except it is assigned to the same zone group.
if( zoneSpace &&
( zoneSpace->mZoneFlags.test( ZoneFlag_IsClosedOffSpace ) != mZoneFlags.test( ZoneFlag_IsClosedOffSpace ) ||
( zoneSpace->getZoneGroup() == getZoneGroup() &&
zoneSpace->getZoneGroup() != InvalidZoneGroup ) ) &&
_automaticallyConnectZoneSpace( zoneSpace ) )
{
connectZoneSpace( zoneSpace );
}
}
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_onZoneRemoveObject( SceneObject* object )
{
if( object->isVisualOccluder() )
_removeOccluder( object );
if( !isRootZone() && object->getTypeMask() & ZoneObjectType )
{
SceneZoneSpace* zoneSpace = dynamic_cast< SceneZoneSpace* >( object );
if( zoneSpace )
disconnectZoneSpace( zoneSpace );
}
}
//-----------------------------------------------------------------------------
bool SceneZoneSpace::_automaticallyConnectZoneSpace( SceneZoneSpace* zoneSpace ) const
{
//TODO: This is suboptimal. While it prevents the most blatantly wrong automatic connections,
// we need a true polyhedron/polyhedron intersection to accurately determine zone intersection
// when it comes to automatic connections.
U32 numZones = 0;
U32 zones[ SceneObject::MaxObjectZones ];
zoneSpace->getOverlappingZones( getWorldBox(), zones, numZones );
return ( numZones > 0 );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::connectZoneSpace( SceneZoneSpace* zoneSpace )
{
// If the zone space is already in the list, do nothing.
for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext )
if( ref->mZoneSpace == zoneSpace )
return;
// Link the zone space to the zone space refs.
ZoneSpaceRef* ref = smZoneSpaceRefChunker.alloc();
ref->mZoneSpace = zoneSpace;
ref->mNext = mConnectedZoneSpaces;
mConnectedZoneSpaces = ref;
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[SceneZoneSpace] Connecting %i-%i to %i-%i",
getZoneRangeStart(), getZoneRangeStart() + getZoneRange(),
zoneSpace->getZoneRangeStart(), zoneSpace->getZoneRangeStart() + zoneSpace->getZoneRange()
);
#endif
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::disconnectZoneSpace( SceneZoneSpace* zoneSpace )
{
ZoneSpaceRef* prev = NULL;
for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; prev = ref, ref = ref->mNext )
if( ref->mZoneSpace == zoneSpace )
{
if( prev )
prev->mNext = ref->mNext;
else
mConnectedZoneSpaces = ref->mNext;
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[SceneZoneSpace] Disconnecting %i-%i from %i-%i",
getZoneRangeStart(), getZoneRangeStart() + getZoneRange(),
zoneSpace->getZoneRangeStart(), zoneSpace->getZoneRangeStart() + zoneSpace->getZoneRange()
);
#endif
smZoneSpaceRefChunker.free( ref );
break;
}
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_disconnectAllZoneSpaces()
{
#ifdef DEBUG_SPEW
if( mConnectedZoneSpaces != NULL )
Platform::outputDebugString( "[SceneZoneSpace] Disconnecting all from %i-%i",
getZoneRangeStart(), getZoneRangeStart() + getZoneRange()
);
#endif
for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; )
{
ZoneSpaceRef* next = ref->mNext;
smZoneSpaceRefChunker.free( ref );
ref = next;
}
mConnectedZoneSpaces = NULL;
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_addOccluder( SceneObject* object )
{
AssertFatal( !mOccluders.contains( object ), "SceneZoneSpace::_addOccluder - Occluder already added to this zone space!" );
mOccluders.push_back( object );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_removeOccluder( SceneObject* object )
{
const U32 numOccluders = mOccluders.size();
for( U32 i = 0; i < numOccluders; ++ i )
if( mOccluders[ i ] == object )
{
mOccluders.erase_fast( i );
break;
}
AssertFatal( !mOccluders.contains( object ), "SceneZoneSpace::_removeOccluder - Occluder still added to this zone space!" );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_addOccludersToCullingState( SceneCullingState* state ) const
{
const U32 numOccluders = mOccluders.size();
for( U32 i = 0; i < numOccluders; ++ i )
state->addOccluder( mOccluders[ i ] );
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::_traverseConnectedZoneSpaces( SceneTraversalState* state )
{
// Hand the traversal over to all connected zone spaces.
for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext )
{
SceneZoneSpace* zoneSpace = ref->mZoneSpace;
zoneSpace->traverseZones( state );
}
}
//-----------------------------------------------------------------------------
void SceneZoneSpace::dumpZoneState( bool update )
{
// Nothing to dump if not registered.
if( !mManager )
return;
// If we should update, trigger rezoning for the space
// we occupy.
if( update )
mManager->_rezoneObjects( getWorldBox() );
Con::printf( "====== Zones in: %s =====", describeSelf().c_str() );
// Dump connections.
for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext )
Con::printf( "Connected to: %s", ref->mZoneSpace->describeSelf().c_str() );
// Dump objects.
for( U32 i = 0; i < getZoneRange(); ++ i )
{
U32 zoneId = getZoneRangeStart() + i;
Con::printf( "--- Zone %i", zoneId );
for( SceneZoneSpaceManager::ZoneContentIterator iter( mManager, zoneId, false ); iter.isValid(); ++ iter )
Con::printf( iter->describeSelf() );
}
}
//-----------------------------------------------------------------------------
bool SceneZoneSpace::_setZoneGroup( void* object, const char* index, const char* data )
{
SceneZoneSpace* zone = reinterpret_cast< SceneZoneSpace* >( object );
zone->setZoneGroup( EngineUnmarshallData< S32 >()( data ) );
return false;
}
| 32.22865
| 127
| 0.578511
|
vbillet
|
fff098f07b243bc508116a069c4da83d1a40d185
| 44,300
|
cc
|
C++
|
src/redis_strings.cc
|
WyattJia/blackwidow
|
5d070e2970f68fafde8105d358acd09c571ea398
|
[
"BSD-3-Clause"
] | 67
|
2018-08-01T05:52:25.000Z
|
2022-03-22T04:08:22.000Z
|
src/redis_strings.cc
|
WyattJia/blackwidow
|
5d070e2970f68fafde8105d358acd09c571ea398
|
[
"BSD-3-Clause"
] | 7
|
2018-11-30T01:48:07.000Z
|
2022-02-10T12:17:07.000Z
|
src/redis_strings.cc
|
WyattJia/blackwidow
|
5d070e2970f68fafde8105d358acd09c571ea398
|
[
"BSD-3-Clause"
] | 30
|
2018-08-15T06:34:31.000Z
|
2022-03-20T09:04:27.000Z
|
// Copyright (c) 2017-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "src/redis_strings.h"
#include <memory>
#include <climits>
#include <algorithm>
#include <limits>
#include "blackwidow/util.h"
#include "src/strings_filter.h"
#include "src/scope_record_lock.h"
#include "src/scope_snapshot.h"
namespace blackwidow {
RedisStrings::RedisStrings(BlackWidow* const bw, const DataType& type)
: Redis(bw, type) {
}
Status RedisStrings::Open(const BlackwidowOptions& bw_options,
const std::string& db_path) {
rocksdb::Options ops(bw_options.options);
ops.compaction_filter_factory = std::make_shared<StringsFilterFactory>();
// use the bloom filter policy to reduce disk reads
rocksdb::BlockBasedTableOptions table_ops(bw_options.table_options);
if (!bw_options.share_block_cache && bw_options.block_cache_size > 0) {
table_ops.block_cache = rocksdb::NewLRUCache(bw_options.block_cache_size);
}
table_ops.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(table_ops));
return rocksdb::DB::Open(ops, db_path, &db_);
}
Status RedisStrings::CompactRange(const rocksdb::Slice* begin,
const rocksdb::Slice* end,
const ColumnFamilyType& type) {
return db_->CompactRange(default_compact_range_options_, begin, end);
}
Status RedisStrings::GetProperty(const std::string& property, uint64_t* out) {
std::string value;
db_->GetProperty(property, &value);
*out = std::strtoull(value.c_str(), NULL, 10);
return Status::OK();
}
Status RedisStrings::ScanKeyNum(KeyInfo* key_info) {
uint64_t keys = 0;
uint64_t expires = 0;
uint64_t ttl_sum = 0;
uint64_t invaild_keys = 0;
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
int64_t curtime;
rocksdb::Env::Default()->GetCurrentTime(&curtime);
// Note: This is a string type and does not need to pass the column family as
// a parameter, use the default column family
rocksdb::Iterator* iter = db_->NewIterator(iterator_options);
for (iter->SeekToFirst();
iter->Valid();
iter->Next()) {
ParsedStringsValue parsed_strings_value(iter->value());
if (parsed_strings_value.IsStale()) {
invaild_keys++;
} else {
keys++;
if (!parsed_strings_value.IsPermanentSurvival()) {
expires++;
ttl_sum += parsed_strings_value.timestamp() - curtime;
}
}
}
delete iter;
key_info->keys = keys;
key_info->expires = expires;
key_info->avg_ttl = (expires != 0) ? ttl_sum / expires : 0;
key_info->invaild_keys = invaild_keys;
return Status::OK();
}
Status RedisStrings::ScanKeys(const std::string& pattern,
std::vector<std::string>* keys) {
std::string key;
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
// Note: This is a string type and does not need to pass the column family as
// a parameter, use the default column family
rocksdb::Iterator* iter = db_->NewIterator(iterator_options);
for (iter->SeekToFirst();
iter->Valid();
iter->Next()) {
ParsedStringsValue parsed_strings_value(iter->value());
if (!parsed_strings_value.IsStale()) {
key = iter->key().ToString();
if (StringMatch(pattern.data(),
pattern.size(), key.data(), key.size(), 0)) {
keys->push_back(key);
}
}
}
delete iter;
return Status::OK();
}
Status RedisStrings::PKPatternMatchDel(const std::string& pattern,
int32_t* ret) {
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
std::string key;
std::string value;
int32_t total_delete = 0;
Status s;
rocksdb::WriteBatch batch;
rocksdb::Iterator* iter = db_->NewIterator(iterator_options);
iter->SeekToFirst();
while (iter->Valid()) {
key = iter->key().ToString();
value = iter->value().ToString();
ParsedStringsValue parsed_strings_value(&value);
if (!parsed_strings_value.IsStale()
&& StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) {
batch.Delete(key);
}
// In order to be more efficient, we use batch deletion here
if (static_cast<size_t>(batch.Count()) >= BATCH_DELETE_LIMIT) {
s = db_->Write(default_write_options_, &batch);
if (s.ok()) {
total_delete += batch.Count();
batch.Clear();
} else {
*ret = total_delete;
return s;
}
}
iter->Next();
}
if (batch.Count()) {
s = db_->Write(default_write_options_, &batch);
if (s.ok()) {
total_delete += batch.Count();
batch.Clear();
}
}
*ret = total_delete;
return s;
}
Status RedisStrings::Append(const Slice& key, const Slice& value,
int32_t* ret) {
std::string old_value;
*ret = 0;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
*ret = value.size();
StringsValue strings_value(value);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
int32_t timestamp = parsed_strings_value.timestamp();
std::string old_user_value = parsed_strings_value.value().ToString();
std::string new_value = old_user_value + value.ToString();
StringsValue strings_value(new_value);
strings_value.set_timestamp(timestamp);
*ret = new_value.size();
return db_->Put(default_write_options_, key, strings_value.Encode());
}
} else if (s.IsNotFound()) {
*ret = value.size();
StringsValue strings_value(value);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
return s;
}
int GetBitCount(const unsigned char* value, int64_t bytes) {
int bit_num = 0;
static const unsigned char bitsinbyte[256] =
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
for (int i = 0; i < bytes; i++) {
bit_num += bitsinbyte[static_cast<unsigned int>(value[i])];
}
return bit_num;
}
Status RedisStrings::BitCount(const Slice& key,
int64_t start_offset, int64_t end_offset,
int32_t* ret, bool have_range) {
*ret = 0;
std::string value;
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
return Status::NotFound("Stale");
} else {
parsed_strings_value.StripSuffix();
const unsigned char* bit_value =
reinterpret_cast<const unsigned char*>(value.data());
int64_t value_length = value.length();
if (have_range) {
if (start_offset < 0) {
start_offset = start_offset + value_length;
}
if (end_offset < 0) {
end_offset = end_offset + value_length;
}
if (start_offset < 0) {
start_offset = 0;
}
if (end_offset < 0) {
end_offset = 0;
}
if (end_offset >= value_length) {
end_offset = value_length -1;
}
if (start_offset > end_offset) {
return Status::OK();
}
} else {
start_offset = 0;
end_offset = std::max(value_length - 1, static_cast<int64_t>(0));
}
*ret = GetBitCount(bit_value + start_offset,
end_offset - start_offset + 1);
}
} else {
return s;
}
return Status::OK();
}
std::string BitOpOperate(BitOpType op,
const std::vector<std::string> &src_values,
int64_t max_len) {
char* dest_value = new char[max_len];
char byte, output;
for (int64_t j = 0; j < max_len; j++) {
if (j < static_cast<int64_t>(src_values[0].size())) {
output = src_values[0][j];
} else {
output = 0;
}
if (op == kBitOpNot) {
output = ~(output);
}
for (size_t i = 1; i < src_values.size(); i++) {
if (static_cast<int64_t>(src_values[i].size()) - 1 >= j) {
byte = src_values[i][j];
} else {
byte = 0;
}
switch (op) {
case kBitOpNot:
break;
case kBitOpAnd:
output &= byte;
break;
case kBitOpOr:
output |= byte;
break;
case kBitOpXor:
output ^= byte;
break;
case kBitOpDefault:
break;
}
}
dest_value[j] = output;
}
std::string dest_str(dest_value, max_len);
delete[] dest_value;
return dest_str;
}
Status RedisStrings::BitOp(BitOpType op,
const std::string& dest_key,
const std::vector<std::string>& src_keys,
int64_t* ret) {
Status s;
if (op == kBitOpNot && src_keys.size() != 1) {
return Status::InvalidArgument("the number of source keys is not right");
} else if (src_keys.size() < 1) {
return Status::InvalidArgument("the number of source keys is not right");
}
int64_t max_len = 0, value_len = 0;
std::vector<std::string> src_values;
for (size_t i = 0; i < src_keys.size(); i++) {
std::string value;
s = db_->Get(default_read_options_, src_keys[i], &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
src_values.push_back(std::string(""));
value_len = 0;
} else {
parsed_strings_value.StripSuffix();
src_values.push_back(value);
value_len = value.size();
}
} else if (s.IsNotFound()) {
src_values.push_back(std::string(""));
value_len = 0;
} else {
return s;
}
max_len = std::max(max_len, value_len);
}
std::string dest_value = BitOpOperate(op, src_values, max_len);
*ret = dest_value.size();
StringsValue strings_value(Slice(dest_value.c_str(),
static_cast<size_t>(max_len)));
ScopeRecordLock l(lock_mgr_, dest_key);
return db_->Put(default_write_options_, dest_key, strings_value.Encode());
}
Status RedisStrings::Decrby(const Slice& key, int64_t value, int64_t* ret) {
std::string old_value;
std::string new_value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
*ret = -value;
new_value = std::to_string(*ret);
StringsValue strings_value(new_value);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
int32_t timestamp = parsed_strings_value.timestamp();
std::string old_user_value = parsed_strings_value.value().ToString();
char* end = nullptr;
int64_t ival = strtoll(old_user_value.c_str(), &end, 10);
if (*end != 0) {
return Status::Corruption("Value is not a integer");
}
if ((value >= 0 && LLONG_MIN + value > ival) ||
(value < 0 && LLONG_MAX + value < ival)) {
return Status::InvalidArgument("Overflow");
}
*ret = ival - value;
new_value = std::to_string(*ret);
StringsValue strings_value(new_value);
strings_value.set_timestamp(timestamp);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
} else if (s.IsNotFound()) {
*ret = -value;
new_value = std::to_string(*ret);
StringsValue strings_value(new_value);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
return s;
}
}
Status RedisStrings::Get(const Slice& key, std::string* value) {
value->clear();
Status s = db_->Get(default_read_options_, key, value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(value);
if (parsed_strings_value.IsStale()) {
value->clear();
return Status::NotFound("Stale");
} else {
parsed_strings_value.StripSuffix();
}
}
return s;
}
Status RedisStrings::GetBit(const Slice& key, int64_t offset, int32_t* ret) {
std::string meta_value;
Status s = db_->Get(default_read_options_, key, &meta_value);
if (s.ok() || s.IsNotFound()) {
std::string data_value;
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&meta_value);
if (parsed_strings_value.IsStale()) {
*ret = 0;
return Status::OK();
} else {
data_value = parsed_strings_value.value().ToString();
}
}
size_t byte = offset >> 3;
size_t bit = 7 - (offset & 0x7);
if (byte + 1 > data_value.length()) {
*ret = 0;
} else {
*ret = ((data_value[byte] & (1 << bit)) >> bit);
}
} else {
return s;
}
return Status::OK();
}
Status RedisStrings::Getrange(const Slice& key,
int64_t start_offset, int64_t end_offset,
std::string* ret) {
*ret = "";
std::string value;
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
return Status::NotFound("Stale");
} else {
parsed_strings_value.StripSuffix();
int64_t size = value.size();
int64_t start_t = start_offset >= 0 ? start_offset : size + start_offset;
int64_t end_t = end_offset >= 0 ? end_offset : size + end_offset;
if (start_t > size - 1 ||
(start_t != 0 && start_t > end_t) ||
(start_t != 0 && end_t < 0)
) {
return Status::OK();
}
if (start_t < 0) {
start_t = 0;
}
if (end_t >= size) {
end_t = size - 1;
}
if (start_t == 0 && end_t < 0) {
end_t = 0;
}
*ret = value.substr(start_t, end_t-start_t+1);
return Status::OK();
}
} else {
return s;
}
}
Status RedisStrings::GetSet(const Slice& key, const Slice& value,
std::string* old_value) {
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(old_value);
if (parsed_strings_value.IsStale()) {
*old_value = "";
} else {
parsed_strings_value.StripSuffix();
}
} else if (!s.IsNotFound()) {
return s;
}
StringsValue strings_value(value);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
Status RedisStrings::Incrby(const Slice& key, int64_t value, int64_t* ret) {
std::string old_value;
std::string new_value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
*ret = value;
char buf[32];
Int64ToStr(buf, 32, value);
StringsValue strings_value(buf);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
int32_t timestamp = parsed_strings_value.timestamp();
std::string old_user_value = parsed_strings_value.value().ToString();
char* end = nullptr;
int64_t ival = strtoll(old_user_value.c_str(), &end, 10);
if (*end != 0) {
return Status::Corruption("Value is not a integer");
}
if ((value >= 0 && LLONG_MAX - value < ival) ||
(value < 0 && LLONG_MIN - value > ival)) {
return Status::InvalidArgument("Overflow");
}
*ret = ival + value;
new_value = std::to_string(*ret);
StringsValue strings_value(new_value);
strings_value.set_timestamp(timestamp);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
} else if (s.IsNotFound()) {
*ret = value;
char buf[32];
Int64ToStr(buf, 32, value);
StringsValue strings_value(buf);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
return s;
}
}
Status RedisStrings::Incrbyfloat(const Slice& key, const Slice& value,
std::string* ret) {
std::string old_value, new_value;
long double long_double_by;
if (StrToLongDouble(value.data(), value.size(), &long_double_by) == -1) {
return Status::Corruption("Value is not a vaild float");
}
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
LongDoubleToStr(long_double_by, &new_value);
*ret = new_value;
StringsValue strings_value(new_value);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
int32_t timestamp = parsed_strings_value.timestamp();
std::string old_user_value = parsed_strings_value.value().ToString();
long double total, old_number;
if (StrToLongDouble(old_user_value.data(),
old_user_value.size(), &old_number) == -1) {
return Status::Corruption("Value is not a vaild float");
}
total = old_number + long_double_by;
if (LongDoubleToStr(total, &new_value) == -1) {
return Status::InvalidArgument("Overflow");
}
*ret = new_value;
StringsValue strings_value(new_value);
strings_value.set_timestamp(timestamp);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
} else if (s.IsNotFound()) {
LongDoubleToStr(long_double_by, &new_value);
*ret = new_value;
StringsValue strings_value(new_value);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else {
return s;
}
}
Status RedisStrings::MGet(const std::vector<std::string>& keys,
std::vector<ValueStatus>* vss) {
vss->clear();
Status s;
std::string value;
rocksdb::ReadOptions read_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
read_options.snapshot = snapshot;
for (const auto& key : keys) {
s = db_->Get(read_options, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
vss->push_back({std::string(), Status::NotFound("Stale")});
} else {
vss->push_back(
{parsed_strings_value.user_value().ToString(), Status::OK()});
}
} else if (s.IsNotFound()) {
vss->push_back({std::string(), Status::NotFound()});
} else {
vss->clear();
return s;
}
}
return Status::OK();
}
Status RedisStrings::MSet(const std::vector<KeyValue>& kvs) {
std::vector<std::string> keys;
for (const auto& kv : kvs) {
keys.push_back(kv.key);
}
MultiScopeRecordLock ml(lock_mgr_, keys);
rocksdb::WriteBatch batch;
for (const auto& kv : kvs) {
StringsValue strings_value(kv.value);
batch.Put(kv.key, strings_value.Encode());
}
return db_->Write(default_write_options_, &batch);
}
Status RedisStrings::MSetnx(const std::vector<KeyValue>& kvs,
int32_t* ret) {
Status s;
bool exists = false;
*ret = 0;
std::string value;
for (size_t i = 0; i < kvs.size(); i++) {
s = db_->Get(default_read_options_, kvs[i].key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (!parsed_strings_value.IsStale()) {
exists = true;
break;
}
}
}
if (!exists) {
s = MSet(kvs);
if (s.ok()) {
*ret = 1;
}
}
return s;
}
Status RedisStrings::Set(const Slice& key,
const Slice& value) {
StringsValue strings_value(value);
ScopeRecordLock l(lock_mgr_, key);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
Status RedisStrings::Setxx(const Slice& key,
const Slice& value,
int32_t* ret,
const int32_t ttl) {
bool not_found = true;
std::string old_value;
StringsValue strings_value(value);
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(old_value);
if (!parsed_strings_value.IsStale()) {
not_found = false;
}
} else if (!s.IsNotFound()) {
return s;
}
if (not_found) {
*ret = 0;
return s;
} else {
*ret = 1;
if (ttl > 0) {
strings_value.SetRelativeTimestamp(ttl);
}
return db_->Put(default_write_options_, key, strings_value.Encode());
}
}
Status RedisStrings::SetBit(const Slice& key, int64_t offset,
int32_t on, int32_t* ret) {
std::string meta_value;
if (offset < 0) {
return Status::InvalidArgument("offset < 0");
}
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &meta_value);
if (s.ok() || s.IsNotFound()) {
std::string data_value;
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&meta_value);
if (!parsed_strings_value.IsStale()) {
data_value = parsed_strings_value.value().ToString();
}
}
size_t byte = offset >> 3;
size_t bit = 7 - (offset & 0x7);
char byte_val;
size_t value_lenth = data_value.length();
if (byte + 1 > value_lenth) {
*ret = 0;
byte_val = 0;
} else {
*ret = ((data_value[byte] & (1 << bit)) >> bit);
byte_val = data_value[byte];
}
if (*ret == on) {
return Status::OK();
}
byte_val &= static_cast<char>(~(1 << bit));
byte_val |= static_cast<char>((on & 0x1) << bit);
if (byte + 1 <= value_lenth) {
data_value.replace(byte, 1, &byte_val, 1);
} else {
data_value.append(byte + 1 - value_lenth - 1, 0);
data_value.append(1, byte_val);
}
StringsValue strings_value(data_value);
return db_->Put(rocksdb::WriteOptions(), key, strings_value.Encode());
} else {
return s;
}
}
Status RedisStrings::Setex(const Slice& key, const Slice& value, int32_t ttl) {
if (ttl <= 0) {
return Status::InvalidArgument("invalid expire time");
}
StringsValue strings_value(value);
strings_value.SetRelativeTimestamp(ttl);
ScopeRecordLock l(lock_mgr_, key);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
Status RedisStrings::Setnx(const Slice& key,
const Slice& value,
int32_t* ret,
const int32_t ttl) {
*ret = 0;
std::string old_value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
StringsValue strings_value(value);
if (ttl > 0) {
strings_value.SetRelativeTimestamp(ttl);
}
s = db_->Put(default_write_options_, key, strings_value.Encode());
if (s.ok()) {
*ret = 1;
}
}
} else if (s.IsNotFound()) {
StringsValue strings_value(value);
if (ttl > 0) {
strings_value.SetRelativeTimestamp(ttl);
}
s = db_->Put(default_write_options_, key, strings_value.Encode());
if (s.ok()) {
*ret = 1;
}
}
return s;
}
Status RedisStrings::Setvx(const Slice& key,
const Slice& value,
const Slice& new_value,
int32_t* ret,
const int32_t ttl) {
*ret = 0;
std::string old_value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
*ret = 0;
} else {
if (!value.compare(parsed_strings_value.value())) {
StringsValue strings_value(new_value);
if (ttl > 0) {
strings_value.SetRelativeTimestamp(ttl);
}
s = db_->Put(default_write_options_, key, strings_value.Encode());
if (!s.ok()) {
return s;
}
*ret = 1;
} else {
*ret = -1;
}
}
} else if (s.IsNotFound()) {
*ret = 0;
} else {
return s;
}
return Status::OK();
}
Status RedisStrings::Delvx(const Slice& key, const Slice& value, int32_t* ret) {
*ret = 0;
std::string old_value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
if (parsed_strings_value.IsStale()) {
*ret = 0;
return Status::NotFound("Stale");
} else {
if (!value.compare(parsed_strings_value.value())) {
*ret = 1;
return db_->Delete(default_write_options_, key);
} else {
*ret = -1;
}
}
} else if (s.IsNotFound()) {
*ret = 0;
}
return s;
}
Status RedisStrings::Setrange(const Slice& key, int64_t start_offset,
const Slice& value, int32_t* ret) {
std::string old_value;
std::string new_value;
if (start_offset < 0) {
return Status::InvalidArgument("offset < 0");
}
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &old_value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&old_value);
parsed_strings_value.StripSuffix();
if (parsed_strings_value.IsStale()) {
std::string tmp(start_offset, '\0');
new_value = tmp.append(value.data());
*ret = new_value.length();
} else {
if (static_cast<size_t>(start_offset) > old_value.length()) {
old_value.resize(start_offset);
new_value = old_value.append(value.data());
} else {
std::string head = old_value.substr(0, start_offset);
std::string tail;
if (start_offset + value.size() - 1 < old_value.length() - 1) {
tail = old_value.substr(start_offset + value.size());
}
new_value = head + value.data() + tail;
}
}
*ret = new_value.length();
StringsValue strings_value(new_value);
return db_->Put(default_write_options_, key, strings_value.Encode());
} else if (s.IsNotFound()) {
std::string tmp(start_offset, '\0');
new_value = tmp.append(value.data());
*ret = new_value.length();
StringsValue strings_value(new_value);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
return s;
}
Status RedisStrings::Strlen(const Slice& key, int32_t *len) {
std::string value;
Status s = Get(key, &value);
if (s.ok()) {
*len = value.size();
} else {
*len = 0;
}
return s;
}
int32_t GetBitPos(const unsigned char* s, unsigned int bytes, int bit) {
uint64_t word = 0;
uint64_t skip_val = 0;
unsigned char* value = const_cast<unsigned char *>(s);
uint64_t* l = reinterpret_cast<uint64_t *>(value);
int pos = 0;
if (bit == 0) {
skip_val = std::numeric_limits<uint64_t>::max();
} else {
skip_val = 0;
}
// skip 8 bytes at one time, find the first int64 that should not be skipped
while (bytes >= sizeof(*l)) {
if (*l != skip_val) {
break;
}
l++;
bytes = bytes - sizeof(*l);
pos = pos + 8 * sizeof(*l);
}
unsigned char * c = reinterpret_cast<unsigned char *>(l);
for (size_t j = 0; j < sizeof(*l); j++) {
word = word << 8;
if (bytes) {
word = word | *c;
c++;
bytes--;
}
}
if (bit == 1 && word == 0) {
return -1;
}
// set each bit of mask to 0 except msb
uint64_t mask = std::numeric_limits<uint64_t>::max();
mask = mask >> 1;
mask = ~(mask);
while (mask) {
if (((word & mask) != 0) == bit) {
return pos;
}
pos++;
mask = mask >> 1;
}
return pos;
}
Status RedisStrings::BitPos(const Slice& key, int32_t bit,
int64_t* ret) {
Status s;
std::string value;
s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
if (bit == 1) {
*ret = -1;
} else if (bit == 0) {
*ret = 0;
}
return Status::NotFound("Stale");
} else {
parsed_strings_value.StripSuffix();
const unsigned char* bit_value =
reinterpret_cast<const unsigned char* >(value.data());
int64_t value_length = value.length();
int64_t start_offset = 0;
int64_t end_offset = std::max(value_length - 1, static_cast<int64_t>(0));
int64_t bytes = end_offset - start_offset + 1;
int64_t pos = GetBitPos(bit_value + start_offset, bytes, bit);
if (pos == (8 * bytes) && bit == 0) {
pos = -1;
}
if (pos != -1) {
pos = pos + 8 * start_offset;
}
*ret = pos;
}
} else {
return s;
}
return Status::OK();
}
Status RedisStrings::BitPos(const Slice& key, int32_t bit,
int64_t start_offset, int64_t* ret) {
Status s;
std::string value;
s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
if (bit == 1) {
*ret = -1;
} else if (bit == 0) {
*ret = 0;
}
return Status::NotFound("Stale");
} else {
parsed_strings_value.StripSuffix();
const unsigned char* bit_value =
reinterpret_cast<const unsigned char* >(value.data());
int64_t value_length = value.length();
int64_t end_offset = std::max(value_length - 1, static_cast<int64_t>(0));
if (start_offset < 0) {
start_offset = start_offset + value_length;
}
if (start_offset < 0) {
start_offset = 0;
}
if (start_offset > end_offset) {
*ret = -1;
return Status::OK();
}
if (start_offset > value_length - 1) {
*ret = -1;
return Status::OK();
}
int64_t bytes = end_offset - start_offset + 1;
int64_t pos = GetBitPos(bit_value + start_offset, bytes, bit);
if (pos == (8 * bytes) && bit == 0) {
pos = -1;
}
if (pos != -1) {
pos = pos + 8 * start_offset;
}
*ret = pos;
}
} else {
return s;
}
return Status::OK();
}
Status RedisStrings::BitPos(const Slice& key, int32_t bit,
int64_t start_offset, int64_t end_offset,
int64_t* ret) {
Status s;
std::string value;
s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
if (bit == 1) {
*ret = -1;
} else if (bit == 0) {
*ret = 0;
}
return Status::NotFound("Stale");
} else {
parsed_strings_value.StripSuffix();
const unsigned char* bit_value =
reinterpret_cast<const unsigned char* >(value.data());
int64_t value_length = value.length();
if (start_offset < 0) {
start_offset = start_offset + value_length;
}
if (start_offset < 0) {
start_offset = 0;
}
if (end_offset < 0) {
end_offset = end_offset + value_length;
}
// converting to int64_t just avoid warning
if (end_offset > static_cast<int64_t>(value.length()) - 1) {
end_offset = value_length - 1;
}
if (end_offset < 0) {
end_offset = 0;
}
if (start_offset > end_offset) {
*ret = -1;
return Status::OK();
}
if (start_offset > value_length - 1) {
*ret = -1;
return Status::OK();
}
int64_t bytes = end_offset - start_offset + 1;
int64_t pos = GetBitPos(bit_value + start_offset, bytes, bit);
if (pos == (8 * bytes) && bit == 0) {
pos = -1;
}
if (pos != -1) {
pos = pos + 8 * start_offset;
}
*ret = pos;
}
} else {
return s;
}
return Status::OK();
}
Status RedisStrings::PKSetexAt(const Slice& key, const Slice& value, int32_t timestamp) {
StringsValue strings_value(value);
ScopeRecordLock l(lock_mgr_, key);
strings_value.set_timestamp(timestamp);
return db_->Put(default_write_options_, key, strings_value.Encode());
}
Status RedisStrings::PKScanRange(const Slice& key_start,
const Slice& key_end,
const Slice& pattern,
int32_t limit,
std::vector<KeyValue>* kvs,
std::string* next_key) {
next_key->clear();
std::string key, value;
int32_t remain = limit;
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
bool start_no_limit = !key_start.compare("");
bool end_no_limit = !key_end.compare("");
if (!start_no_limit
&& !end_no_limit
&& (key_start.compare(key_end) > 0)) {
return Status::InvalidArgument("error in given range");
}
// Note: This is a string type and does not need to pass the column family as
// a parameter, use the default column family
rocksdb::Iterator* it = db_->NewIterator(iterator_options);
if (start_no_limit) {
it->SeekToFirst();
} else {
it->Seek(key_start);
}
while (it->Valid() && remain > 0
&& (end_no_limit || it->key().compare(key_end) <= 0)) {
ParsedStringsValue parsed_strings_value(it->value());
if (parsed_strings_value.IsStale()) {
it->Next();
} else {
key = it->key().ToString();
value = parsed_strings_value.value().ToString();
if (StringMatch(pattern.data(), pattern.size(),
key.data(), key.size(), 0)) {
kvs->push_back({key, value});
}
remain--;
it->Next();
}
}
while (it->Valid()
&& (end_no_limit || it->key().compare(key_end) <= 0)) {
ParsedStringsValue parsed_strings_value(it->value());
if (parsed_strings_value.IsStale()) {
it->Next();
} else {
*next_key = it->key().ToString();
break;
}
}
delete it;
return Status::OK();
}
Status RedisStrings::PKRScanRange(const Slice& key_start,
const Slice& key_end,
const Slice& pattern,
int32_t limit,
std::vector<KeyValue>* kvs,
std::string* next_key) {
std::string key, value;
int32_t remain = limit;
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
bool start_no_limit = !key_start.compare("");
bool end_no_limit = !key_end.compare("");
if (!start_no_limit
&& !end_no_limit
&& (key_start.compare(key_end) < 0)) {
return Status::InvalidArgument("error in given range");
}
// Note: This is a string type and does not need to pass the column family as
// a parameter, use the default column family
rocksdb::Iterator* it = db_->NewIterator(iterator_options);
if (start_no_limit) {
it->SeekToLast();
} else {
it->SeekForPrev(key_start);
}
while (it->Valid() && remain > 0
&& (end_no_limit || it->key().compare(key_end) >= 0)) {
ParsedStringsValue parsed_strings_value(it->value());
if (parsed_strings_value.IsStale()) {
it->Prev();
} else {
key = it->key().ToString();
value = parsed_strings_value.value().ToString();
if (StringMatch(pattern.data(), pattern.size(),
key.data(), key.size(), 0)) {
kvs->push_back({key, value});
}
remain--;
it->Prev();
}
}
while (it->Valid()
&& (end_no_limit || it->key().compare(key_end) >= 0)) {
ParsedStringsValue parsed_strings_value(it->value());
if (parsed_strings_value.IsStale()) {
it->Prev();
} else {
*next_key = it->key().ToString();
break;
}
}
delete it;
return Status::OK();
}
Status RedisStrings::Expire(const Slice& key, int32_t ttl) {
std::string value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
return Status::NotFound("Stale");
}
if (ttl > 0) {
parsed_strings_value.SetRelativeTimestamp(ttl);
return db_->Put(default_write_options_, key, value);
} else {
return db_->Delete(default_write_options_, key);
}
}
return s;
}
Status RedisStrings::Del(const Slice& key) {
std::string value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
return Status::NotFound("Stale");
}
return db_->Delete(default_write_options_, key);
}
return s;
}
bool RedisStrings::Scan(const std::string& start_key,
const std::string& pattern,
std::vector<std::string>* keys,
int64_t* count,
std::string* next_key) {
std::string key;
bool is_finish = true;
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
// Note: This is a string type and does not need to pass the column family as
// a parameter, use the default column family
rocksdb::Iterator* it = db_->NewIterator(iterator_options);
it->Seek(start_key);
while (it->Valid() && (*count) > 0) {
ParsedStringsValue parsed_strings_value(it->value());
if (parsed_strings_value.IsStale()) {
it->Next();
continue;
} else {
key = it->key().ToString();
if (StringMatch(pattern.data(), pattern.size(),
key.data(), key.size(), 0)) {
keys->push_back(key);
}
(*count)--;
it->Next();
}
}
std::string prefix = isTailWildcard(pattern) ?
pattern.substr(0, pattern.size() - 1) : "";
if (it->Valid()
&& (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) {
is_finish = false;
*next_key = it->key().ToString();
} else {
*next_key = "";
}
delete it;
return is_finish;
}
bool RedisStrings::PKExpireScan(const std::string& start_key,
int32_t min_timestamp, int32_t max_timestamp,
std::vector<std::string>* keys,
int64_t* leftover_visits,
std::string* next_key) {
bool is_finish = true;
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
rocksdb::Iterator* it = db_->NewIterator(iterator_options);
it->Seek(start_key);
while (it->Valid() && (*leftover_visits) > 0) {
ParsedStringsValue parsed_strings_value(it->value());
if (parsed_strings_value.IsStale()) {
it->Next();
continue;
} else {
if (min_timestamp < parsed_strings_value.timestamp()
&& parsed_strings_value.timestamp() < max_timestamp) {
keys->push_back(it->key().ToString());
}
(*leftover_visits)--;
it->Next();
}
}
if (it->Valid()) {
is_finish = false;
*next_key = it->key().ToString();
} else {
*next_key = "";
}
delete it;
return is_finish;
}
Status RedisStrings::Expireat(const Slice& key, int32_t timestamp) {
std::string value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
return Status::NotFound("Stale");
} else {
if (timestamp > 0) {
parsed_strings_value.set_timestamp(timestamp);
return db_->Put(default_write_options_, key, value);
} else {
return db_->Delete(default_write_options_, key);
}
}
}
return s;
}
Status RedisStrings::Persist(const Slice& key) {
std::string value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
return Status::NotFound("Stale");
} else {
int32_t timestamp = parsed_strings_value.timestamp();
if (timestamp == 0) {
return Status::NotFound("Not have an associated timeout");
} else {
parsed_strings_value.set_timestamp(0);
return db_->Put(default_write_options_, key, value);
}
}
}
return s;
}
Status RedisStrings::TTL(const Slice& key, int64_t* timestamp) {
std::string value;
ScopeRecordLock l(lock_mgr_, key);
Status s = db_->Get(default_read_options_, key, &value);
if (s.ok()) {
ParsedStringsValue parsed_strings_value(&value);
if (parsed_strings_value.IsStale()) {
*timestamp = -2;
return Status::NotFound("Stale");
} else {
*timestamp = parsed_strings_value.timestamp();
if (*timestamp == 0) {
*timestamp = -1;
} else {
int64_t curtime;
rocksdb::Env::Default()->GetCurrentTime(&curtime);
*timestamp = *timestamp - curtime >= 0 ? *timestamp - curtime : -2;
}
}
} else if (s.IsNotFound()) {
*timestamp = -2;
}
return s;
}
void RedisStrings::ScanDatabase() {
rocksdb::ReadOptions iterator_options;
const rocksdb::Snapshot* snapshot;
ScopeSnapshot ss(db_, &snapshot);
iterator_options.snapshot = snapshot;
iterator_options.fill_cache = false;
int32_t current_time = time(NULL);
printf("\n***************String Data***************\n");
auto iter = db_->NewIterator(iterator_options);
for (iter->SeekToFirst();
iter->Valid();
iter->Next()) {
ParsedStringsValue parsed_strings_value(iter->value());
int32_t survival_time = 0;
if (parsed_strings_value.timestamp() != 0) {
survival_time = parsed_strings_value.timestamp() - current_time > 0 ?
parsed_strings_value.timestamp() - current_time : -1;
}
printf("[key : %-30s] [value : %-30s] [timestamp : %-10d] [version : %d] [survival_time : %d]\n",
iter->key().ToString().c_str(),
parsed_strings_value.value().ToString().c_str(),
parsed_strings_value.timestamp(),
parsed_strings_value.version(),
survival_time);
}
delete iter;
}
} // namespace blackwidow
| 30.785268
| 101
| 0.599797
|
WyattJia
|
fff3c70ae2abda3d5d44cc736ac9dc25e5b28f4b
| 499
|
cpp
|
C++
|
BinarySearch/BinarySearch/BinarySearchIterative.cpp
|
gabrieltavares0123/AlgorithmDesignAndAnalysis
|
8c19772f0e6805812e4be74f7276637112c9b444
|
[
"Apache-2.0"
] | null | null | null |
BinarySearch/BinarySearch/BinarySearchIterative.cpp
|
gabrieltavares0123/AlgorithmDesignAndAnalysis
|
8c19772f0e6805812e4be74f7276637112c9b444
|
[
"Apache-2.0"
] | null | null | null |
BinarySearch/BinarySearch/BinarySearchIterative.cpp
|
gabrieltavares0123/AlgorithmDesignAndAnalysis
|
8c19772f0e6805812e4be74f7276637112c9b444
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
int binarySearchIterative(vector<int> vctr, int target)
{
int min = 0;
int max = vctr.size() - 1;
while (min < max)
{
int guess = (min + max) / 2;
if (vctr.at(guess) == target)
{
return guess;
}
else if (vctr.at(guess) < target)
{
min = guess + 1;
}
else
{
max = guess - 1;
}
}
return -1;
}
| 16.633333
| 56
| 0.442886
|
gabrieltavares0123
|
fffa5e882f086e22a2285b40d3032c15c0a7c0ee
| 96
|
cpp
|
C++
|
engine/tile.cpp
|
jarreed0/ArchGE
|
c995caf86b11f89f45fcfe1027c6068662dfcde0
|
[
"Apache-2.0"
] | 12
|
2017-02-09T21:03:41.000Z
|
2021-04-26T14:50:20.000Z
|
engine/tile.cpp
|
jarreed0/ArchGE
|
c995caf86b11f89f45fcfe1027c6068662dfcde0
|
[
"Apache-2.0"
] | null | null | null |
engine/tile.cpp
|
jarreed0/ArchGE
|
c995caf86b11f89f45fcfe1027c6068662dfcde0
|
[
"Apache-2.0"
] | null | null | null |
#include "tile.h"
Tile::Tile() {}
Tile::~Tile() {}
void Tile::setValue(int v) {
value = v;
}
| 12
| 28
| 0.5625
|
jarreed0
|
fffd62bbb6e1b8264051b74822bb0478aceb7ad0
| 1,159
|
cpp
|
C++
|
leetcode/_190_reverse_bits.cpp
|
WindyDarian/OJ_Submissions
|
a323595c3a32ed2e07af65374ef90c81d5333f96
|
[
"Apache-2.0"
] | 3
|
2017-02-19T14:38:32.000Z
|
2017-07-22T17:06:55.000Z
|
leetcode/_190_reverse_bits.cpp
|
WindyDarian/OJ_Submissions
|
a323595c3a32ed2e07af65374ef90c81d5333f96
|
[
"Apache-2.0"
] | null | null | null |
leetcode/_190_reverse_bits.cpp
|
WindyDarian/OJ_Submissions
|
a323595c3a32ed2e07af65374ef90c81d5333f96
|
[
"Apache-2.0"
] | null | null | null |
//==============================================================================
// Copyright 2016 Windy Darian (Ruoyu Fan)
//
// 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.
//==============================================================================
// https://leetcode.com/problems/reverse-bits/
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
n = (n & 0xFFFF0000) >> 16 | (n & 0x0000FFFF) << 16;
n = (n & 0xFF00FF00) >> 8 | (n & 0x00FF00FF) << 8;
n = (n & 0xF0F0F0F0) >> 4 | (n & 0x0F0F0F0F) << 4;
n = (n & 0xCCCCCCCC) >> 2 | (n & 0x33333333) << 2;
n = (n & 0xAAAAAAAA) >> 1 | (n & 0x55555555) << 1;
return n;
}
};
| 37.387097
| 80
| 0.572908
|
WindyDarian
|
fffe8b330a6e5fcd721da4dd534bc318934d6e1c
| 6,889
|
cc
|
C++
|
cc/jwt/jwt_object.cc
|
iambrosie/tink
|
33accb5bcdff71f34d7551a669831ec9a52674aa
|
[
"Apache-2.0"
] | 2
|
2020-11-09T11:25:34.000Z
|
2022-03-04T06:21:44.000Z
|
cc/jwt/jwt_object.cc
|
iambrosie/tink
|
33accb5bcdff71f34d7551a669831ec9a52674aa
|
[
"Apache-2.0"
] | null | null | null |
cc/jwt/jwt_object.cc
|
iambrosie/tink
|
33accb5bcdff71f34d7551a669831ec9a52674aa
|
[
"Apache-2.0"
] | 1
|
2020-08-11T04:52:46.000Z
|
2020-08-11T04:52:46.000Z
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include "tink/jwt/jwt_object.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/substitute.h"
#include "tink/jwt/json_object.h"
#include "tink/jwt/jwt_names.h"
namespace crypto {
namespace tink {
JwtObject::JwtObject(const JsonObject& payload) {
payload_ = payload;
}
JwtObject::JwtObject() {}
util::StatusOr<std::vector<std::string>> JwtObject::GetClaimAsStringList(
absl::string_view name) const {
return payload_.GetValueAsStringList(name);
}
util::StatusOr<std::vector<int>> JwtObject::GetClaimAsNumberList(
absl::string_view name) const {
return payload_.GetValueAsNumberList(name);
}
util::StatusOr<std::vector<std::string>> JwtObject::GetAudiences() const {
std::vector<std::string> vec;
auto aud_or = payload_.GetValueAsString(kJwtClaimAudience);
if (aud_or.status().ok()) {
vec.push_back(aud_or.ValueOrDie());
return vec;
}
return payload_.GetValueAsStringList(kJwtClaimAudience);
}
util::StatusOr<int> JwtObject::GetClaimAsNumber(absl::string_view name) const {
return payload_.GetValueAsNumber(name);
}
util::StatusOr<bool> JwtObject::GetClaimAsBool(absl::string_view name) const {
return payload_.GetValueAsBool(name);
}
util::StatusOr<std::string> JwtObject::GetSubject() const {
return payload_.GetValueAsString(kJwtClaimSubject);
}
util::StatusOr<absl::Time> JwtObject::GetExpiration() const {
return payload_.GetValueAsTime(kJwtClaimExpiration);
}
util::StatusOr<absl::Time> JwtObject::GetNotBefore() const {
return payload_.GetValueAsTime(kJwtClaimNotBefore);
}
util::StatusOr<absl::Time> JwtObject::GetIssuedAt() const {
return payload_.GetValueAsTime(kJwtClaimIssuedAt);
}
util::StatusOr<std::string> JwtObject::GetIssuer() const {
return payload_.GetValueAsString(kJwtClaimIssuer);
}
util::StatusOr<std::string> JwtObject::GetJwtId() const {
return payload_.GetValueAsString(kJwtClaimJwtId);
}
util::StatusOr<std::string> JwtObject::GetClaimAsString(
absl::string_view name) const {
return payload_.GetValueAsString(name);
}
util::Status JwtObject::SetIssuer(absl::string_view issuer) {
return payload_.SetValueAsString(kJwtClaimIssuer, issuer);
}
util::Status JwtObject::SetSubject(absl::string_view subject) {
return payload_.SetValueAsString(kJwtClaimSubject, subject);
}
util::Status JwtObject::SetJwtId(absl::string_view jwid) {
return payload_.SetValueAsString(kJwtClaimJwtId, jwid);
}
util::Status JwtObject::SetExpiration(absl::Time expiration) {
return payload_.SetValueAsTime(kJwtClaimExpiration, expiration);
}
util::Status JwtObject::SetNotBefore(absl::Time notBefore) {
return payload_.SetValueAsTime(kJwtClaimNotBefore, notBefore);
}
util::Status JwtObject::SetIssuedAt(absl::Time issuedAt) {
return payload_.SetValueAsTime(kJwtClaimIssuedAt, issuedAt);
}
util::Status JwtObject::AddAudience(absl::string_view audience) {
return payload_.AppendValueToStringList(kJwtClaimAudience, audience);
}
util::Status JwtObject::SetClaimAsString(absl::string_view name,
absl::string_view value) {
auto status = ValidatePayloadName(name);
if (status != util::Status::OK) {
return status;
}
return payload_.SetValueAsString(name, value);
}
util::Status JwtObject::SetClaimAsNumber(absl::string_view name, int value) {
auto status = ValidatePayloadName(name);
if (status != util::Status::OK) {
return status;
}
return payload_.SetValueAsNumber(name, value);
}
util::Status JwtObject::SetClaimAsBool(absl::string_view name, bool value) {
auto status = ValidatePayloadName(name);
if (status != util::Status::OK) {
return status;
}
return payload_.SetValueAsBool(name, value);
}
util::Status JwtObject::AppendClaimToStringList(absl::string_view name,
absl::string_view value) {
auto status = ValidatePayloadName(name);
if (status != util::Status::OK) {
return status;
}
return payload_.AppendValueToStringList(name, value);
}
util::Status JwtObject::AppendClaimToNumberList(absl::string_view name,
int value) {
auto status = ValidatePayloadName(name);
if (status != util::Status::OK) {
return status;
}
return payload_.AppendValueToNumberList(name, value);
}
util::StatusOr<absl::string_view> JwtObject::AlgorithmTypeToString(
const enum JwtAlgorithm algorithm) const {
switch (algorithm) {
case JwtAlgorithm::kHs256:
return kJwtAlgorithmHs256;
case JwtAlgorithm::kEs256:
return kJwtAlgorithmEs256;
case JwtAlgorithm::kRs256:
return kJwtAlgorithmRs256;
default:
return crypto::tink::util::Status(
util::error::UNIMPLEMENTED,
absl::Substitute(
"algorithm '$0' is not supported",
static_cast<std::underlying_type<JwtAlgorithm>::type>(
algorithm)));
}
}
util::StatusOr<absl::flat_hash_map<std::string, enum JsonFieldType>>
JwtObject::getClaimNamesAndTypes() {
return payload_.getFieldNamesAndTypes();
}
util::StatusOr<enum JwtAlgorithm> JwtObject::AlgorithmStringToType(
absl::string_view algo_name) const {
if (algo_name == kJwtAlgorithmHs256) {
return JwtAlgorithm::kHs256;
}
if (algo_name == kJwtAlgorithmEs256) {
return JwtAlgorithm::kEs256;
}
if (algo_name == kJwtAlgorithmRs256) {
return JwtAlgorithm::kRs256;
}
return crypto::tink::util::Status(
util::error::INVALID_ARGUMENT,
absl::Substitute("algorithm '$0' does not exist", algo_name));
}
util::Status JwtObject::ValidatePayloadName(absl::string_view name) {
if (IsRegisteredPayloadName(name)) {
return absl::InvalidArgumentError(absl::Substitute(
"claim '$0' is invalid because it's a registered name; "
"use the corresponding setter method.",
name));
}
return util::OkStatus();
}
bool JwtObject::IsRegisteredPayloadName(absl::string_view name) {
return name == kJwtClaimIssuer || name == kJwtClaimSubject ||
name == kJwtClaimAudience || name == kJwtClaimExpiration ||
name == kJwtClaimNotBefore || name == kJwtClaimIssuedAt ||
name == kJwtClaimJwtId;
}
} // namespace tink
} // namespace crypto
| 30.082969
| 79
| 0.710553
|
iambrosie
|
ffff16f67e2c31036540669161cfba4f91fd25a9
| 1,093
|
hpp
|
C++
|
agency/cuda/detail/concurrency/heterogeneous_barrier.hpp
|
nerikhman/agency
|
966ac59101f2fc3561a86b11874fbe8de361d0e4
|
[
"BSD-3-Clause"
] | 129
|
2016-08-18T23:24:15.000Z
|
2022-03-25T12:06:05.000Z
|
agency/cuda/detail/concurrency/heterogeneous_barrier.hpp
|
nerikhman/agency
|
966ac59101f2fc3561a86b11874fbe8de361d0e4
|
[
"BSD-3-Clause"
] | 86
|
2016-08-19T03:43:33.000Z
|
2020-07-20T14:27:41.000Z
|
agency/cuda/detail/concurrency/heterogeneous_barrier.hpp
|
nerikhman/agency
|
966ac59101f2fc3561a86b11874fbe8de361d0e4
|
[
"BSD-3-Clause"
] | 23
|
2016-08-18T23:52:13.000Z
|
2022-02-28T16:28:20.000Z
|
#include <agency/detail/config.hpp>
namespace agency
{
namespace cuda
{
namespace detail
{
template<class HostBarrier, class DeviceBarrier>
class heterogeneous_barrier
{
public:
using host_barrier_type = HostBarrier;
using device_barrier_type = DeviceBarrier;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
heterogeneous_barrier(size_t num_threads) :
#ifndef __CUDA_ARCH__
host_barrier_(num_threads)
#else
device_barrier_(num_threads)
#endif
{}
__agency_exec_check_disable__
__AGENCY_ANNOTATION
std::size_t count() const
{
#ifndef __CUDA_ARCH__
return host_barrier_.count();
#else
return device_barrier_.count();
#endif
}
__agency_exec_check_disable__
__AGENCY_ANNOTATION
void arrive_and_wait()
{
#ifndef __CUDA_ARCH__
host_barrier_.arrive_and_wait();
#else
device_barrier_.arrive_and_wait();
#endif
}
private:
#ifndef __CUDA_ARCH__
host_barrier_type host_barrier_;
#else
device_barrier_type device_barrier_;
#endif
};
} // end detail
} // end cuda
} // end agency
| 17.078125
| 48
| 0.732845
|
nerikhman
|
0800547f1460cf6d60e590ab2d6519d50a0acb5c
| 7,602
|
cpp
|
C++
|
wallet/api/v6_3/v6_3_api_parse.cpp
|
unwaz/beam
|
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
|
[
"Apache-2.0"
] | null | null | null |
wallet/api/v6_3/v6_3_api_parse.cpp
|
unwaz/beam
|
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
|
[
"Apache-2.0"
] | null | null | null |
wallet/api/v6_3/v6_3_api_parse.cpp
|
unwaz/beam
|
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2018 The Beam Team
//
// 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 "v6_3_api.h"
#include "version.h"
namespace beam::wallet
{
namespace
{
uint32_t parseTimeout(V63Api& api, const nlohmann::json& params)
{
if(auto otimeout = api.getOptionalParam<uint32_t>(params, "timeout"))
{
return *otimeout;
}
return 0;
}
bool ExtractPoint(ECC::Point::Native& point, const json& j)
{
auto s = type_get<NonEmptyString>(j);
auto buf = from_hex(s);
ECC::Point pt;
Deserializer dr;
dr.reset(buf);
dr& pt;
return point.ImportNnz(pt);
}
}
template<>
const char* type_name<ECC::Point::Native>()
{
return "hex encoded elliptic curve point";
}
template<>
bool type_check<ECC::Point::Native>(const json& j)
{
ECC::Point::Native pt;
return type_check<NonEmptyString>(j) && ExtractPoint(pt, j);
}
template<>
ECC::Point::Native type_get<ECC::Point::Native>(const json& j)
{
ECC::Point::Native pt;
ExtractPoint(pt, j);
return pt;
}
std::pair<IPFSAdd, IWalletApi::MethodInfo> V63Api::onParseIPFSAdd(const JsonRpcId& id, const nlohmann::json& params)
{
IPFSAdd message;
message.timeout = parseTimeout(*this, params);
json data = getMandatoryParam<NonEmptyJsonArray>(params, "data");
data.get<std::vector<uint8_t>>().swap(message.data);
if (auto opin = getOptionalParam<bool>(params, "pin"))
{
message.pin = *opin;
}
return std::make_pair(std::move(message), MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const IPFSAdd::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"hash", res.hash},
{"pinned", res.pinned}
}
}
};
}
std::pair<IPFSHash, IWalletApi::MethodInfo> V63Api::onParseIPFSHash(const JsonRpcId& id, const nlohmann::json& params)
{
IPFSHash message;
message.timeout = parseTimeout(*this, params);
json data = getMandatoryParam<NonEmptyJsonArray>(params, "data");
data.get<std::vector<uint8_t>>().swap(message.data);
return std::make_pair(std::move(message), MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const IPFSHash::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"hash", res.hash}
}
}
};
}
std::pair<IPFSGet, IWalletApi::MethodInfo> V63Api::onParseIPFSGet(const JsonRpcId& id, const nlohmann::json& params)
{
IPFSGet message;
message.timeout = parseTimeout(*this, params);
message.hash = getMandatoryParam<NonEmptyString>(params, "hash");
return std::make_pair(std::move(message), MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const IPFSGet::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"hash", res.hash},
{"data", res.data}
}
}
};
}
std::pair<IPFSPin, IWalletApi::MethodInfo> V63Api::onParseIPFSPin(const JsonRpcId& id, const nlohmann::json& params)
{
IPFSPin message;
message.timeout = parseTimeout(*this, params);
message.hash = getMandatoryParam<NonEmptyString>(params, "hash");
return std::make_pair(std::move(message), MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const IPFSPin::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"hash", res.hash}
}
}
};
}
std::pair<IPFSUnpin, IWalletApi::MethodInfo> V63Api::onParseIPFSUnpin(const JsonRpcId& id, const nlohmann::json& params)
{
IPFSUnpin message;
message.hash = getMandatoryParam<NonEmptyString>(params, "hash");
return std::make_pair(std::move(message), MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const IPFSUnpin::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"hash", res.hash}
}
}
};
}
std::pair<IPFSGc, IWalletApi::MethodInfo> V63Api::onParseIPFSGc(const JsonRpcId& id, const nlohmann::json& params)
{
IPFSGc message;
message.timeout = parseTimeout(*this, params);
return std::make_pair(message, MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const IPFSGc::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"result", true}
}
}
};
}
std::pair<SignMessage, IWalletApi::MethodInfo> V63Api::onParseSignMessage(const JsonRpcId& id, const nlohmann::json& params)
{
SignMessage message;
message.message = getMandatoryParam<NonEmptyString>(params, "message");
auto km = getMandatoryParam<NonEmptyString>(params, "key_material");
message.keyMaterial = from_hex(km);
return std::make_pair(message, MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const SignMessage::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result",
{
{"signature", res.signature}
}
}
};
}
std::pair<VerifySignature, IWalletApi::MethodInfo> V63Api::onParseVerifySignature(const JsonRpcId& id, const nlohmann::json& params)
{
VerifySignature message;
message.message = getMandatoryParam<NonEmptyString>(params, "message");
message.publicKey = getMandatoryParam<ECC::Point::Native>(params, "public_key");
message.signature = getMandatoryParam<ValidHexBuffer>(params, "signature");
return std::make_pair(message, MethodInfo());
}
void V63Api::getResponse(const JsonRpcId& id, const VerifySignature::Response& res, json& msg)
{
msg = json
{
{JsonRpcHeader, JsonRpcVersion},
{"id", id},
{"result", res.result }
};
}
}
| 30.408
| 136
| 0.549724
|
unwaz
|
08015cfc4fb0c74687667d358446a4aa478dd6b8
| 21,417
|
hpp
|
C++
|
source/utils/ImageCopiers.hpp
|
bobvodka/GameTextureLoader3
|
47db5781eb650b9746ffed327786c7e73410cbe0
|
[
"MIT"
] | null | null | null |
source/utils/ImageCopiers.hpp
|
bobvodka/GameTextureLoader3
|
47db5781eb650b9746ffed327786c7e73410cbe0
|
[
"MIT"
] | null | null | null |
source/utils/ImageCopiers.hpp
|
bobvodka/GameTextureLoader3
|
47db5781eb650b9746ffed327786c7e73410cbe0
|
[
"MIT"
] | null | null | null |
// A series of templated routines to copy image objects between memory buffers
#ifndef GTL_IMAGECOPIERS_HPP
#define GTL_IMAGECOPIERS_HPP
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include "Utils.hpp"
#include "memoryIterators.hpp"
//CHECK ALL THE OFFSET MATHS!!!
//IT FEELS LIKE BAD BAD VOODOO!!!
//
namespace GTLImageCopiers
{
// confirmed to work (or at least not crash)
template<class T>
void flipImageAndCopy(GTLUtils::flipResult flips,
GameTextureLoader3::DecoderImageData const &data, GTLCore::ImageImpl *img, int headeroffset = 0)
{
using namespace GTLMemoryIterators;
typedef typename forward_memory_iter<T> forward_mem_iter;
typedef typename reverse_memory_iter<T> reverse_mem_iter;
if(flips.flipBoth())
{
const int len = img->width_ * img->height_;
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset));
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len);
reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + len - 1);
std::copy(src,end,dest);
}
else if (flips.flipy())
{
for(int i = 0; i < img->height_; ++i)
{
// const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8);
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*i);
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + (i+1)*img->width_);
const int destoffset = img->width_ * img->height_ - ((i+1) * img->width_);
// reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset - 1);
forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset);
std::copy(src,end,dest);
}
}
else if(flips.flipx())
{
for (int i = 0; i < img->height_; ++i)
{
// const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8);
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*i);
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + (i+1)*img->width_);
const int destoffset = (img->width_ * (i +1)) - 1;
reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset);
std::copy(src,end,dest);
}
}
else
{
const int len = img->width_ * img->height_;
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset));
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len);
forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()));
std::copy(src,end,dest);
}
}
// confirmed to work (or at least not crash)
template<class T>
void flipRowAndCopy(GTLUtils::flipResult flips, T * data, GTLCore::ImageImpl *img, int rowcout )
{
using namespace GTLMemoryIterators;
typedef typename forward_memory_iter<T> forward_mem_iter;
typedef typename reverse_memory_iter<T> reverse_mem_iter;
forward_mem_iter src(reinterpret_cast<T*>(data));
forward_mem_iter end(reinterpret_cast<T*>(data) + img->width_);
if(flips.flipBoth())
{
reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + (img->width_ * (img->height_ - rowcout - 1) + (img->width_ - 1) ));
std::copy(src,end,dest);
}
else if (flips.flipy()) // confirmed to work
{
//forward_mem_iter dest(reinterpret_cast<T*>(data) + (img->width_ * (img->height_ - rowcout - 1)));
const int offset = img->width_ * (img->height_ - rowcout) - img->width_;
forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + offset);
std::copy(src,end,dest);
}
else if(flips.flipx())
{
const int offset = (img->width_ * (rowcout +1)) - 1;
reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + offset /*+ (img->width_ * rowcout) + (img->width_ - 1)*/);
std::copy(src,end,dest);
}
else
{
forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + (img->width_ * rowcout));
std::copy(src,end,dest);
}
}
// confirmed to work (or at least not crash)
template<class T>
void flipImageAndTransform(GTLUtils::flipResult flips,
GameTextureLoader3::DecoderImageData const &data, GTLCore::ImageImpl *img, boost::function<T (T const &)> func, int headeroffset = 0)
{
using namespace GTLMemoryIterators;
typedef typename forward_memory_iter<T> forward_mem_iter;
typedef typename reverse_memory_iter<T> reverse_mem_iter;
if(flips.flipBoth())
{
const int len = img->width_ * img->height_;
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset));
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len);
reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + len - 1);
std::transform(src,end,dest,func);
}
else if (flips.flipy())
{
for(int i = 0; i < img->height_; ++i)
{
// const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8);
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*i);
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*(i+1));
const int destoffset = img->width_ * img->height_ - ((i+1) * img->width_);
forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset);
std::transform(src,end,dest,func);
}
}
else if(flips.flipx())
{
for (int i = 0; i < img->height_; ++i)
{
// const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8);
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + i*img->width_);
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + (i+1)*img->width_);
// const int destoffset = (img->width_ * i) + (img->width_ - 1);
const int destoffset = (img->width_ * (i +1)) - 1;
reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset);
std::transform(src,end,dest,func);
}
}
else
{
const int len = img->width_ * img->height_;
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset));
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len);
forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()));
std::transform(src,end,dest,func);
}
}
// DXTn Copying routines
template<class T>
T fullFlipLookup(T src, T srcmask)
{
T dest = 0;
const int offset = (sizeof(T) * 8) - (2 * (sizeof(T)/4)); // for 32bit = 30, 64bit = 60
const int shiftamount = 2 * sizeof(T)/4; // for 32bit = 2, 64bit = 4
for (int i = 0; i < 16; i++)
{
int tmpshift = offset - (i * shiftamount);
T tmpdata = src & srcmask;
// shift to start of bit pattern
tmpdata = tmpdata >> (offset - tmpshift);
// then shift it to the correct location
T shiftdata = tmpdata << tmpshift;
dest |= shiftdata;
srcmask = srcmask << shiftamount;
}
return dest;
}
template<class T>
T yFlipLookup(T src, T srcmask)
{
T dest = 0;
// const int offset = (sizeof(T) * 8) - (2 * (sizeof(T)/4)); // for 32bit = 30, 64bit = 60
const int offset = (sizeof(T) * 8) - (2 * (sizeof(T))); // for 32bit = 24, 64bit = 48
const int shiftamount = 2 * sizeof(T)/4; // for 32bit = 2, 64bit = 4
const int incamount = sizeof(T); // for 32bit = 4, 64bit = 8
// for(int i = 0; i < 16; i+= incamount)
for(int i = 0; i < 16; i+= 4) // always moving 4 pixels at a time
{
int tmpshift = offset - i*shiftamount;
T tmpdata = src & srcmask;
//tmpdata = tmpdata >> (offset - tmpshift);
int tmpamount = i*shiftamount;
tmpdata = tmpdata >> tmpamount;
T shiftdata = tmpdata << tmpshift;
dest |= shiftdata;
srcmask = srcmask << (incamount*2);
}
return dest;
}
template<class T>
T xFlipLookup(T src, T /*original*/srcmask)
{
T dest = 0;
const int xoffset = (sizeof(T)/4) * 6; // for 32bit = 6, 64bit = 12
const int yoffset = (sizeof(T)*2); // for 32bit = 8, 64bit = 16
const int shiftamount = 2 * sizeof(T)/4; // for 32bit = 2, 64bit = 4
// const int incamount = (sizeof(T)/8) * 4; // for 32bit = 4, 64bit = 8
for (int i = 0; i < 4; i++)
{
// We don't need to move the mask as we move the src data!
//T srcmask = (originalsrcmask << (incamount*i*shiftamount));
for (int j = 0; j < 4; j++)
{
T srcbits = src & srcmask;
T xshift = xoffset - j*shiftamount;
T yshift = yoffset*i;
T totalshift = xshift + yshift;
// dest |= (srcbits << ((xoffset - j*shiftamount) + (yoffset*i)));
T tmpdata = srcbits << totalshift;
dest |= tmpdata;
src = src >> shiftamount;
}
}
return dest;
}
GTLUtils::dxt1 fullFlip(GTLUtils::dxt1 &src);
GTLUtils::dxt1 xFlip(GTLUtils::dxt1 &src);
GTLUtils::dxt1 yFlip(GTLUtils::dxt1 &src);
GTLUtils::dxt2 fullFlip(GTLUtils::dxt2 &src);
GTLUtils::dxt2 xFlip(GTLUtils::dxt2 &src);
GTLUtils::dxt2 yFlip(GTLUtils::dxt2 &src);
GTLUtils::dxt4 fullFlip(GTLUtils::dxt4 &src);
GTLUtils::dxt4 xFlip(GTLUtils::dxt4 &src);
GTLUtils::dxt4 yFlip(GTLUtils::dxt4 &src);
// We need to do the flips for each images and mipmap in the chain
// 3D textures might have to be ignored until I can think of some sane way to handle it
template<class T>
void flipDXTnImage(GTLUtils::flipResult flips,
GameTextureLoader3::DecoderImageData const &data, GTLCore::ImageImpl *img, int headeroffset = 0)
{
using namespace GTLMemoryIterators;
typedef typename forward_memory_iter<T> forward_mem_iter;
typedef typename reverse_memory_iter<T> reverse_mem_iter;
int realheight = (img->height_ < 16) ? img->height_ : img->height_/4;
int realwidth = (img->width_ < 16) ? img->width_ : img->width_/4;
const int numImages = img->getNumImages();
const int numMipMaps = img->getNumMipMaps();
const unsigned char* baseptr = img->getDataPtr();
for (int image = 0; image < numImages; ++image)
{
for (int mipmap = 0; mipmap < numMipMaps; ++mipmap)
{
int currentWidth = realwidth >> mipmap; if (currentWidth < 16) currentWidth = 16;
int currentHeight = realheight >> mipmap; if (currentHeight < 16) currentHeight = 16;
const ptrdiff_t offset = img->getDataPtr(mipmap,image) - baseptr; // get an offset in bytes to the correct image:mipmap data
if(flips.flipBoth())
{
const int len = currentHeight * currentWidth;
forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset + offset));
forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset + offset) + len);
reverse_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)) + len - 1);
std::transform(src,end,dest,boost::bind<T>(fullFlip, _1));
// std::transform(src,end,dest,fullFlip);
}// TODO: redo the below two functions to take into account the fact we are working with blocks of 16 pixels at a time
else if (flips.flipy())
{
for(int i = 0; i < currentHeight; ++i)
{
forward_mem_iter src(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*i);
forward_mem_iter end(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*(i+1));
const int destoffset = currentWidth * currentHeight - ((i+1) * currentWidth);
forward_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)) + destoffset);
std::transform(src,end,dest,boost::bind<T>(yFlip, _1));
//std::transform(src,end,dest,yFlip);
}
}
else if(flips.flipx())
{
for (int i = 0; i < currentHeight; ++i)
{
forward_mem_iter src(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*i);
forward_mem_iter end(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*(i+1));
const int destoffset = /*currentWidth*currentHeight -*/ ((i+1)*currentWidth) - 1;
reverse_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)) + destoffset);
std::transform(src,end,dest,boost::bind<T>(xFlip, _1));
//std::transform(src,end,dest,xFlip);
}
}
else
{
const int len = currentWidth * currentHeight;
forward_mem_iter src(reinterpret_cast<T*>(data.get()+headeroffset + offset));
forward_mem_iter end(reinterpret_cast<T*>(data.get()+headeroffset + offset) + len);
forward_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)));
//std::transform(src,end,dest,func);
std::copy(src,end,dest);
}
}
}
}
// TGA copying routines
template<class T, class U>
void PerformCopy(T src, T srcend, U dest)
{
std::copy(src,srcend, dest);
}
template<class T, class U>
void PerformRepeatedCopy(T src, U dest, int count)
{
std::fill_n(dest,count,*src);
}
template<class U>
void PerformCopy(GTLMemoryIterators::forward_memory_iter<GTLUtils::rgba> src, GTLMemoryIterators::forward_memory_iter<GTLUtils::rgba> srcend, U dest)
{
std::transform(src,srcend, dest, GTLUtils::convertBGRAtoRGBA);
}
template<class U>
void PerformRepeatedCopy(GTLMemoryIterators::forward_memory_iter<GTLUtils::rgba> src, U dest, int count)
{
GTLUtils::rgba val = GTLUtils::convertBGRAtoRGBA(*src);
std::fill_n(dest,count,val);
}
template<class T>
void CopyData(T * src, T* dest, int width, int height, int count, int offset, GTLUtils::flipResult flips, bool repeated)
{
using namespace GTLMemoryIterators;
typedef typename forward_memory_iter<T> forward_mem_iter;
typedef typename reverse_memory_iter<T> reverse_mem_iter;
if(flips.flipBoth())
{
const int imgsize = width * height;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + count);
reverse_mem_iter dest_itor(dest + imgsize - offset - 1);
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,count);
else
PerformCopy(src_itor,end_itor,dest_itor);
}
else if (flips.flipy())
{
const int imgsize = width * height;
while (count > 0)
{
int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...)
int rowRemains = width - (offset % width);
int copyAmount = (count > rowRemains) ? rowRemains : count;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + copyAmount);
forward_mem_iter dest_itor(dest + imgsize - ((row + 1) * width) + (width - rowRemains));
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,copyAmount);
else
PerformCopy(src_itor,end_itor,dest_itor);
count -= copyAmount;
offset += copyAmount;
src += copyAmount;
}
}
else if(flips.flipx())
{
// const int imgsize = width * height;
while (count > 0)
{
int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...)
int rowRemains = width - (offset % width);
int copyAmount = (count > rowRemains) ? rowRemains : count;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + copyAmount);
int rowoffset = ((row+1) * width) - (width - rowRemains) - 1;
reverse_mem_iter dest_itor(dest + rowoffset );
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,copyAmount);
else
PerformCopy(src_itor,end_itor,dest_itor);
count -= copyAmount;
offset += copyAmount;
src += copyAmount;
}
}
else
{
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + count);
forward_mem_iter dest_itor(dest + offset);
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,count);
else
PerformCopy(src_itor,end_itor,dest_itor);
}
/* if(flips.flipBoth())
{
const int imgsize = width * height;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + count);
reverse_mem_iter dest_itor(dest + imgsize - offset);
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,count);
else
PerformNormalCopy(src_itor,end_itor,dest_itor);
}
else if (flips.flipy())
{
const int imgsize = width * height;
while (count > 0)
{
int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...)
int rowRemains = width - (offset % width);
int copyAmount = (count > rowRemains) ? rowRemains : count;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + copyAmount);
forward_mem_iter dest_itor(dest + imgsize - (row * width));
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,copyAmount);
else
PerformNormalCopy(src_itor,end_itor,dest_itor);
count -= copyAmount;
offset += copyAmount;
}
}
else if(flips.flipx())
{
const int imgsize = width * height;
while (count > 0)
{
int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...)
int rowRemains = width - (offset % width);
int copyAmount = (count > rowRemains) ? rowRemains : count;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + copyAmount);
reverse_mem_iter dest_itor(dest + imgsize - (row * width) - (width - rowRemains));
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,copyAmount);
else
PerformNormalCopy(src_itor,end_itor,dest_itor);
count -= copyAmount;
offset += copyAmount;
}
}
else
{
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + count);
forward_mem_iter dest_itor(dest);
if (repeated)
PerformRepeatedCopy(src_itor,dest_itor,count);
else
PerformNormalCopy(src_itor,end_itor,dest_itor);
}
*/
}
/*
template<class T, class U>
void PerformTransformedCopy(T src, T srcend, U dest)
{
std::transform(src,srcend, dest, GTLUtils::convertBGRAtoRGBA);
}
template<class T, class U>
void PerformTransformedRepeatedCopy(T src, U dest, int count)
{
GTLUtils::rgba val = GTLUtils::convertBGRAtoRGBA(*src);
std::fill_n(dest,count,val);
}
template<>
void CopyData(GTLUtils::rgba * src, GTLUtils::rgba* dest, int width, int height, int count, int offset, GTLUtils::flipResult flips, bool repeated);
*/
/* {
using namespace GTLMemoryIterators;
typedef forward_memory_iter<GTLUtils::rgba> forward_mem_iter;
typedef reverse_memory_iter<GTLUtils::rgba> reverse_mem_iter;
if(flips.flipBoth())
{
const int imgsize = width * height;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + count);
reverse_mem_iter dest_itor(dest + imgsize - offset);
if (repeated)
PerformTransformedRepeatedCopy(src_itor,dest_itor,count);
else
PerformTransformedCopy(src_itor,end_itor,dest_itor);
}
else if (flips.flipy())
{
const int imgsize = width * height;
while (count > 0)
{
int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...)
int rowRemains = width - (offset % width);
int copyAmount = (count > rowRemains) ? rowRemains : count;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + copyAmount);
forward_mem_iter dest_itor(dest + imgsize - (row * width));
if (repeated)
PerformTransformedRepeatedCopy(src_itor,dest_itor,copyAmount);
else
PerformTransformedCopy(src_itor,end_itor,dest_itor);
count -= copyAmount;
offset += copyAmount;
}
}
else if(flips.flipx())
{
const int imgsize = width * height;
while (count > 0)
{
int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...)
int rowRemains = width - (offset % width);
int copyAmount = (count > rowRemains) ? rowRemains : count;
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + copyAmount);
reverse_mem_iter dest_itor(dest + imgsize - (row * width) - (width - rowRemains));
if (repeated)
PerformTransformedRepeatedCopy(src_itor,dest_itor,copyAmount);
else
PerformTransformedCopy(src_itor,end_itor,dest_itor);
count -= copyAmount;
offset += copyAmount;
}
}
else
{
forward_mem_iter src_itor(src);
forward_mem_iter end_itor(src + count);
forward_mem_iter dest_itor(dest);
if (repeated)
PerformTransformedRepeatedCopy(src_itor,dest_itor,count);
else
PerformTransformedCopy(src_itor,end_itor,dest_itor);
}
}
*/
template<class T>
bool decodeRLEData(GameTextureLoader3::ImagePtr image,
GameTextureLoader3::DecoderImageData data, GTLUtils::flipResult flips, int offset)
{
GTLCore::ImageImpl * img = dynamic_cast<GTLCore::ImageImpl*>(image.get());
const int pixelsize = img->colourdepth_/8;
const int size = img->width_ * img->height_ * pixelsize;
const bool repeated = true;
signed int currentbyte = 0;
GTLUtils::byte * bytedata = reinterpret_cast<GTLUtils::byte*>(data.get() + offset);
T * localimg = reinterpret_cast<T*>(img->imgdata_.get());
while(currentbyte < size )
{
GTLUtils::byte chunkheader = *bytedata; bytedata++;
// I'm pretty sure the line below here is wrong and shouldn't be there...
// ++currentbyte;
T * localdata = reinterpret_cast<T*>(bytedata);
if(chunkheader < 128) // Then the next chunkheader++ blocks of data are unique pixels
{
chunkheader++;
CopyData(localdata, localimg, img->width_, img->height_, chunkheader,(currentbyte/pixelsize),flips,!repeated);
bytedata += chunkheader * pixelsize;
}
else // RLE compressed data, chunkheader -127 gives us the total number of repeats
{
chunkheader -= 127;
CopyData(localdata,localimg, img->width_, img->height_, chunkheader,(currentbyte/pixelsize),flips,repeated);
bytedata+=pixelsize; // move on the size of a pixel
}
currentbyte += pixelsize * chunkheader;
}
return true;
}
}
#endif
| 33.780757
| 150
| 0.673344
|
bobvodka
|
0801e69aabfd892b207c36f3d04c8b5c070f3df5
| 280
|
cpp
|
C++
|
lib/AST/Break.cpp
|
yangzh1998/purpo
|
87cdf981580fa25f5b7062e5fd90c920c49ff116
|
[
"MIT"
] | 4
|
2021-11-25T14:26:39.000Z
|
2021-11-25T19:22:38.000Z
|
lib/AST/Break.cpp
|
yangzh1998/purpo
|
87cdf981580fa25f5b7062e5fd90c920c49ff116
|
[
"MIT"
] | null | null | null |
lib/AST/Break.cpp
|
yangzh1998/purpo
|
87cdf981580fa25f5b7062e5fd90c920c49ff116
|
[
"MIT"
] | null | null | null |
//
// Created by YANG Zehai on 2021/11/11.
//
#include "AST/Break.h"
using namespace pur;
using namespace pur::ast;
Break::Break(const pars::Location& loc): Stmt(ASTNodeType::kBreak, loc) {
/* empty */
}
void Break::Accept(Visitor& visitor) {
visitor.VisitBreak(*this);
}
| 16.470588
| 73
| 0.678571
|
yangzh1998
|
080ab7fa5adf4750d4a44aa398d617ffea615351
| 2,605
|
cc
|
C++
|
tests/test.cc
|
sv1990/automatic-differentiation
|
b2eb0685c0bb31086a57957464641965a5b6ae0c
|
[
"MIT"
] | null | null | null |
tests/test.cc
|
sv1990/automatic-differentiation
|
b2eb0685c0bb31086a57957464641965a5b6ae0c
|
[
"MIT"
] | null | null | null |
tests/test.cc
|
sv1990/automatic-differentiation
|
b2eb0685c0bb31086a57957464641965a5b6ae0c
|
[
"MIT"
] | null | null | null |
#include "ad/ad.hh"
#include "ad/ostream.hh"
#include <cassert>
#undef NDEBUG
template <typename T, typename U>
constexpr bool same_type(T, U) noexcept {
return std::is_same_v<T, U>;
}
template <typename T>
constexpr bool is_static_expression(T) {
return ad::detail::is_static_v<T>;
}
int main() {
using namespace ad::literals;
constexpr auto x = ad::_0;
constexpr auto y = ad::_1;
static_assert(same_type(123_c, ad::static_constant<123>{}));
static_assert(same_type(x.derive(x), 1_c));
static_assert(same_type(x.derive(y), 0_c));
static_assert(same_type(y.derive(x), 0_c));
static_assert(same_type(y.derive(y), 1_c));
static_assert(same_type(x.derive(x, x), 0_c));
static_assert(same_type((x * y).derive(x, y), 1_c));
static_assert(same_type(ad::log(x).derive(x), 1_c / x));
static_assert(same_type(ad::exp(x).derive(x), ad::exp(x)));
static_assert(same_type(ad::sin(x).derive(x), ad::cos(x)));
static_assert(same_type(ad::sin(x).derive(x, x), -ad::sin(x)));
static_assert(same_type(ad::sin(x).derive(x, x, x), -ad::cos(x)));
static_assert(same_type(ad::sin(x).derive(x, x, x, x), ad::sin(x)));
static_assert(same_type(ad::exp(ad::sin(x)).derive(x),
ad::cos(x) * ad::exp(ad::sin(x))));
static_assert(same_type((ad::exp(x) * ad::sin(x)).derive(x),
ad::exp(x) * ad::sin(x) + ad::exp(x) * ad::cos(x)));
static_assert(same_type(-(-x * 1_c), x));
static_assert(same_type(-0_c, 0_c));
static_assert(same_type(ad::pow(1_c / x, -1_c), x));
static_assert(same_type(ad::exp(1_c) * ad::exp(x), ad::exp(1_c + x)));
static_assert(same_type(ad::pow(ad::exp(x), 2_c), ad::exp(x * 2_c)));
static_assert(same_type(ad::pow(ad::pow(x, 2_c), 2_c), ad::pow(x, 4_c)));
#if __has_attribute(no_unique_address)
static_assert(sizeof(ad::exp(x)) == 1);
static_assert(sizeof(x + 1_c) == 1);
static_assert(sizeof((x + 1_c) * (x - 1_c)) <= 2);
#endif
assert(ad::to_string(1_c / (x * ad::exp(x))) == "1 / (x0 * exp(x0))");
assert(ad::to_string(1_c - (x + 1_c)) == "1 - (x0 + 1)");
assert(ad::to_string(1_c + (x + 1_c)) == "1 + x0 + 1");
assert(ad::to_string(2_c * (x * 2_c)) == "2 * x0 * 2");
assert(ad::to_string(-ad::exp(x)) == "-exp(x0)");
assert(ad::to_string(-(x + 2)) == "-(x0 + 2)");
assert(ad::to_string(-(x - 2)) == "-(x0 - 2)");
static_assert(is_static_expression(x));
static_assert(is_static_expression(x + 1_c));
static_assert(!is_static_expression(x + 1));
static_assert(same_type(ad::sin(x) - ad::sin(x), 0_c));
static_assert(same_type(ad::sin(x) / ad::sin(x), 1_c));
}
| 34.733333
| 78
| 0.619578
|
sv1990
|
080d328b2ae90baa12db3ff3a8778a02da56280c
| 133
|
cpp
|
C++
|
recursive/tests/failing_test.cpp
|
PhilipDaniels/autotools-template
|
e11ee788c7ca9f9b941778330cac4e562b23d8fe
|
[
"MIT"
] | 20
|
2016-02-01T13:07:45.000Z
|
2020-08-30T18:59:39.000Z
|
recursive/tests/failing_test.cpp
|
PhilipDaniels/autotools-template
|
e11ee788c7ca9f9b941778330cac4e562b23d8fe
|
[
"MIT"
] | null | null | null |
recursive/tests/failing_test.cpp
|
PhilipDaniels/autotools-template
|
e11ee788c7ca9f9b941778330cac4e562b23d8fe
|
[
"MIT"
] | 4
|
2018-05-13T19:05:28.000Z
|
2021-12-29T18:08:46.000Z
|
#define CATCH_CONFIG_MAIN
#include "mycatch.hpp"
#include "foo.hpp"
TEST_CASE("Testing works", "[works]")
{
REQUIRE(2 > 3);
}
| 12.090909
| 37
| 0.661654
|
PhilipDaniels
|
080e32a0c1261e77869375530610f956681a9dda
| 2,283
|
cpp
|
C++
|
gym/101190/E.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | 1
|
2021-07-16T19:59:39.000Z
|
2021-07-16T19:59:39.000Z
|
gym/101190/E.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | null | null | null |
gym/101190/E.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#ifdef DGC
#include "debug.h"
#else
#define debug(...)
#endif
typedef long long ll;
typedef long double ld;
typedef complex<ll> point;
#define F first
#define S second
struct info
{
ll a, b;
};
int main()
{
#ifdef DGC
freopen("a.txt", "r", stdin);
//freopen("b.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(0), cin.tie(0);
freopen("expect.in", "r", stdin);
freopen("expect.out", "w", stdout);
int n, q;
cin >> n >> q;
vector<info> a(n);
char ch;
for (auto &i : a)
{
cin >> ch >> i.a >> i.b;
if (ch == '+')
i.b *= -1;
}
vector<ll> sb(n); // sum of b
vector<pair<ll, int>> vp; // val, pos
for (int i = 0; i < n; ++i)
{
sb[i] = a[i].b;
if (i > 0) sb[i] += sb[i-1];
if (sb[i] > 0 && (vp.empty() || sb[i] > vp.back().F))
vp.push_back({ sb[i], i });
}
vector<ll> difa(n); // a[i+1]-a[i]
for (int i = n-2; i >= 0; --i)
difa[i] = a[i+1].a - a[i].a;
vector<pair<ll, int>> z(q);
for (auto &i : z) cin >> i.F, i.S = &i-&z[0];
sort(z.begin(), z.end());
vector<ll> ans(q, -2);
vector<ll> sump(q); // sum on prefix
vector<ll> sum2p(q); // sum2 on prefix
//vector<ll> sum3p(q); // sum3 on prefix
vector<ll> coef(q, 1LL);
for (int i = q-2; i >= 0; --i)
coef[i] = coef[i+1] + z[i+1].F-z[i].F;
debug(coef)
for (int i = 0; i < n-1; ++i)
{
ll x = sb[i];
auto it = lower_bound(z.begin(), z.end(), make_pair(x, 0));
if (it != z.begin())
{
int pos = prev(it) - z.begin();
ll init = -z[pos].F + x;
//sum3p[pos] += difa[i] * (init - 1);
sum2p[pos] += difa[i];
sump[pos] += difa[i] * (init - 1);
sump[pos] -= (coef[pos] - 1) * difa[i];
}
}
debug(sum2p)
debug(sump)
for (int i = q-2; i >= 0; --i)
{
sum2p[i] += sum2p[i+1];
sump[i] += sump[i+1];
}
debug(vp)
for (auto &temp : z)
{
ll init = -temp.F;
int pos = temp.S;
int pos2 = &temp-&z[0];
if (sb[n-1] + init > 0)
{
ans[pos] = -1;
continue;
}
/*auto it = lower_bound(vp.begin(), vp.end(), make_pair(-init, 1<<30));
if (it == vp.end())
{
ans[pos] = 0;
continue;
}*/
ans[pos] = sum2p[pos2] * coef[pos2] + sump[pos2];
debug(temp, ans[pos])
}
for (auto i : ans)
{
if (i == -1)
cout << "INFINITY\n";
else
cout << i << "\n";
}
return 0;
}
| 17.037313
| 73
| 0.505475
|
albexl
|
080ef9b7d80aaaad57c68515a6eeeef80697a3cb
| 545
|
cpp
|
C++
|
algorithm/kmp.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
algorithm/kmp.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
algorithm/kmp.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<string>
using namespace std;
string s1, s2;
void kmp()
{
string new_s = s2+"#"+s1;
vector<int> prefix_func(new_s.size());
for(int i = 1; i < new_s.size(); i++)
{
int j = prefix_func[i-1];
while(j>0&&new_s[j]!=new_s[i]) j=prefix_func[j-1];
if(new_s[i]==new_s[j]) j++;
prefix_func[i] = j;
}
cout << new_s << endl;
for(auto v:prefix_func) cout << v << " ";
cout << endl;
}
int main()
{
cin >> s1 >> s2;
kmp();
return 0;
}
| 18.166667
| 58
| 0.522936
|
freedomDR
|
081396bdef5c61cb3eccd6f19a0c2fe9e838fed5
| 8,925
|
cpp
|
C++
|
test/omp/test_omp_external_distance_interaction.cpp
|
yutakasi634/Mjolnir
|
ab7a29a47f994111e8b889311c44487463f02116
|
[
"MIT"
] | null | null | null |
test/omp/test_omp_external_distance_interaction.cpp
|
yutakasi634/Mjolnir
|
ab7a29a47f994111e8b889311c44487463f02116
|
[
"MIT"
] | 2
|
2020-04-07T11:41:45.000Z
|
2020-04-08T10:01:38.000Z
|
test/omp/test_omp_external_distance_interaction.cpp
|
yutakasi634/Mjolnir
|
ab7a29a47f994111e8b889311c44487463f02116
|
[
"MIT"
] | null | null | null |
#define BOOST_TEST_MODULE "test_omp_external_distance_interaction"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/math/math.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/AxisAlignedPlane.hpp>
#include <mjolnir/forcefield/external/LennardJonesWallPotential.hpp>
#include <mjolnir/omp/System.hpp>
#include <mjolnir/omp/RandomNumberGenerator.hpp>
#include <mjolnir/omp/UnlimitedGridCellList.hpp>
#include <mjolnir/omp/ExternalDistanceInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
BOOST_AUTO_TEST_CASE(omp_ExternalDistacne_calc_force)
{
constexpr double tol = 1e-8;
mjolnir::LoggerManager::set_default_logger("test_omp_external_distance_interaction.log");
using traits_type = mjolnir::OpenMPSimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using system_type = mjolnir::System<traits_type>;
using topology_type = mjolnir::Topology;
using potential_type = mjolnir::LennardJonesWallPotential<real_type>;
using parameter_type = typename potential_type::parameter_type;
using shape_type = mjolnir::AxisAlignedPlane<traits_type, mjolnir::PositiveZDirection<traits_type>>;
using interaction_type = mjolnir::ExternalDistanceInteraction<traits_type, potential_type, shape_type>;
using rng_type = mjolnir::RandomNumberGenerator<traits_type>;
using sequencial_system_type = mjolnir::System<
mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>>;
using sequencial_shape_type = mjolnir::AxisAlignedPlane<
mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>,
mjolnir::PositiveZDirection<traits_type>>;
using sequencial_interaction_type = mjolnir::ExternalDistanceInteraction<
mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>,
potential_type, sequencial_shape_type>;
const int max_number_of_threads = omp_get_max_threads();
BOOST_TEST_WARN(max_number_of_threads > 2);
BOOST_TEST_MESSAGE("maximum number of threads = " << max_number_of_threads);
const std::size_t N_particle = 64;
std::vector<std::pair<std::size_t, parameter_type>> parameters(N_particle);
for(std::size_t i=0; i<N_particle; ++i)
{
parameters.emplace_back(i, parameter_type(1.0, 1.0));
}
const potential_type potential(2.5, parameters);
for(int num_thread=1; num_thread<=max_number_of_threads; ++num_thread)
{
omp_set_num_threads(num_thread);
BOOST_TEST_MESSAGE("maximum number of threads = " << omp_get_max_threads());
rng_type rng(123456789);
system_type sys(N_particle, boundary_type{});
for(std::size_t i=0; i<sys.size(); ++i)
{
const auto i_x = i % 4;
const auto i_y = i / 4;
const auto i_z = i / 16;
sys.mass(i) = 1.0;
sys.position(i) = mjolnir::math::make_coordinate<coordinate_type>(i_x*2.0, i_y*2.0, i_z*2.0);
sys.velocity(i) = mjolnir::math::make_coordinate<coordinate_type>(0, 0, 0);
sys.force(i) = mjolnir::math::make_coordinate<coordinate_type>(0, 0, 0);
sys.name(i) = "X";
sys.group(i) = "TEST";
}
topology_type topol(N_particle);
// add perturbation
for(std::size_t i=0; i<sys.size(); ++i)
{
mjolnir::math::X(sys.position(i)) += rng.uniform_real(-0.1, 0.1);
mjolnir::math::Y(sys.position(i)) += rng.uniform_real(-0.1, 0.1);
mjolnir::math::Z(sys.position(i)) += rng.uniform_real(-0.1, 0.1);
}
// init sequential one with the same coordinates
sequencial_system_type seq_sys(N_particle, boundary_type{});
assert(sys.size() == seq_sys.size());
for(std::size_t i=0; i<sys.size(); ++i)
{
seq_sys.mass(i) = sys.mass(i);
seq_sys.position(i) = sys.position(i);
seq_sys.velocity(i) = sys.velocity(i);
seq_sys.force(i) = sys.force(i);
seq_sys.name(i) = sys.name(i);
seq_sys.group(i) = sys.group(i);
}
shape_type xyplane (0.0);
sequencial_shape_type seq_xyplane(0.0);
topol.construct_molecules();
xyplane .initialize(sys, potential);
seq_xyplane.initialize(seq_sys, potential);
interaction_type interaction(
std::move(xyplane), potential_type(potential));
sequencial_interaction_type seq_interaction(
std::move(seq_xyplane), potential_type(potential));
interaction .initialize(sys);
seq_interaction.initialize(seq_sys);
// calculate forces with openmp
interaction.calc_force(sys);
sys.postprocess_forces();
// calculate forces without openmp
seq_interaction.calc_force(seq_sys);
// check the values are the same
for(std::size_t i=0; i<sys.size(); ++i)
{
BOOST_TEST(mjolnir::math::X(seq_sys.force(i)) == mjolnir::math::X(sys.force(i)),
boost::test_tools::tolerance(tol));
BOOST_TEST(mjolnir::math::Y(seq_sys.force(i)) == mjolnir::math::Y(sys.force(i)),
boost::test_tools::tolerance(tol));
BOOST_TEST(mjolnir::math::Z(seq_sys.force(i)) == mjolnir::math::Z(sys.force(i)),
boost::test_tools::tolerance(tol));
}
BOOST_TEST(interaction.calc_energy(sys) == seq_interaction.calc_energy(seq_sys),
boost::test_tools::tolerance(tol));
}
}
BOOST_AUTO_TEST_CASE(omp_ExternalDistance_calc_force_and_energy)
{
mjolnir::LoggerManager::set_default_logger(
"test_omp_external_distance_interaction.log");
using traits_type = mjolnir::OpenMPSimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
using coordinate_type = traits_type::coordinate_type;
using boundary_type = traits_type::boundary_type;
using system_type = mjolnir::System<traits_type>;
using potential_type = mjolnir::LennardJonesWallPotential<real_type>;
using shape_type = mjolnir::AxisAlignedPlane<traits_type, mjolnir::PositiveZDirection<traits_type>>;
using interaction_type = mjolnir::ExternalDistanceInteraction<traits_type, potential_type, shape_type>;
interaction_type interaction(shape_type(0.0, 0.5),
potential_type(/* cutoff = */2.0, {
{0, {1.0, 1.0}}, {1, {1.0, 1.0}}
}));
system_type sys(2, boundary_type{});
sys.at(0).mass = 1.0;
sys.at(1).mass = 1.0;
sys.at(0).rmass = 1.0;
sys.at(1).rmass = 1.0;
sys.at(0).position = coordinate_type( 0.0, 0.0, 1.0);
sys.at(1).position = coordinate_type( 0.0, 0.0, 1.0);
sys.at(0).velocity = coordinate_type( 0.0, 0.0, 0.0);
sys.at(1).velocity = coordinate_type( 0.0, 0.0, 0.0);
sys.at(0).force = coordinate_type( 0.0, 0.0, 0.0);
sys.at(1).force = coordinate_type( 0.0, 0.0, 0.0);
sys.at(0).name = "X";
sys.at(1).name = "X";
sys.at(0).group = "NONE";
sys.at(1).group = "NONE";
std::mt19937 mt(123456789);
std::uniform_real_distribution<real_type> uni(-1.0, 1.0);
std::normal_distribution<real_type> gauss(0.0, 1.0);
for(int i = 0; i < 10000; ++i)
{
sys.at(0).position = coordinate_type(0.0, 0.0, 1.0);
sys.at(1).position = coordinate_type(0.0, 0.0, 1.0);
// move particles a bit, randomly. and reset forces.
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
sys.position(idx) += coordinate_type(0.01 * uni(mt), 0.01 * uni(mt), 0.01 * uni(mt));
sys.force(idx) = coordinate_type(0.0, 0.0, 0.0);
}
system_type ref_sys = sys;
constexpr real_type tol = 1e-4;
const auto energy = interaction.calc_force_and_energy(sys);
const auto ref_energy = interaction.calc_energy(ref_sys);
interaction.calc_force(ref_sys);
BOOST_TEST(ref_energy == energy, boost::test_tools::tolerance(tol));
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
BOOST_TEST(mjolnir::math::X(sys.force(idx)) == mjolnir::math::X(ref_sys.force(idx)), boost::test_tools::tolerance(tol));
BOOST_TEST(mjolnir::math::Y(sys.force(idx)) == mjolnir::math::Y(ref_sys.force(idx)), boost::test_tools::tolerance(tol));
BOOST_TEST(mjolnir::math::Z(sys.force(idx)) == mjolnir::math::Z(ref_sys.force(idx)), boost::test_tools::tolerance(tol));
}
}
}
| 41.901408
| 132
| 0.643249
|
yutakasi634
|
0819301c98d806c431bdf1c95c36fa35d20f7475
| 3,400
|
hpp
|
C++
|
IGC/Compiler/Optimizer/OpenCLPasses/ProgramScopeConstants/ProgramScopeConstantAnalysis.hpp
|
ConiKost/intel-graphics-compiler
|
f5227c9658da35d08d7f711552ebcb12638ebc18
|
[
"Intel",
"MIT"
] | 1
|
2020-09-03T17:11:47.000Z
|
2020-09-03T17:11:47.000Z
|
IGC/Compiler/Optimizer/OpenCLPasses/ProgramScopeConstants/ProgramScopeConstantAnalysis.hpp
|
ConiKost/intel-graphics-compiler
|
f5227c9658da35d08d7f711552ebcb12638ebc18
|
[
"Intel",
"MIT"
] | null | null | null |
IGC/Compiler/Optimizer/OpenCLPasses/ProgramScopeConstants/ProgramScopeConstantAnalysis.hpp
|
ConiKost/intel-graphics-compiler
|
f5227c9658da35d08d7f711552ebcb12638ebc18
|
[
"Intel",
"MIT"
] | null | null | null |
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#pragma once
#include "Compiler/MetaDataUtilsWrapper.h"
#include "common/LLVMWarningsPush.hpp"
#include <llvm/Pass.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/ADT/MapVector.h>
#include "common/LLVMWarningsPop.hpp"
namespace IGC
{
/// @brief This pass creates annotations for OpenCL program-scope structures.
// Currently this is program-scope constants, but for OpenCL 2.0, it should
// also support program-scope globals.
class ProgramScopeConstantAnalysis : public llvm::ModulePass
{
public:
// Pass identification, replacement for typeid
static char ID;
/// @brief Constructor
ProgramScopeConstantAnalysis();
/// @brief Destructor
~ProgramScopeConstantAnalysis() {}
/// @brief Provides name of pass
virtual llvm::StringRef getPassName() const override
{
return "ProgramScopeConstantAnalysisPass";
}
virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override
{
AU.setPreservesCFG();
AU.addRequired<MetaDataUtilsWrapper>();
AU.addRequired<CodeGenContextWrapper>();
}
/// @brief Main entry point.
/// Runs on all GlobalVariables in this module, finds the constants, and
/// generates annotations for them.
/// @param M The destination module.
virtual bool runOnModule(llvm::Module& M) override;
protected:
typedef std::vector<unsigned char> DataVector;
typedef llvm::MapVector<llvm::GlobalVariable*, int> BufferOffsetMap;
struct PointerOffsetInfo
{
unsigned AddressSpaceWherePointerResides;
uint64_t PointerOffsetFromBufferBase;
unsigned AddressSpacePointedTo;
PointerOffsetInfo(
unsigned AddressSpaceWherePointerResides,
uint64_t PointerOffsetFromBufferBase,
unsigned AddressSpacePointedTo) :
AddressSpaceWherePointerResides(AddressSpaceWherePointerResides),
PointerOffsetFromBufferBase(PointerOffsetFromBufferBase),
AddressSpacePointedTo(AddressSpacePointedTo) {}
};
typedef std::list<PointerOffsetInfo> PointerOffsetInfoList;
/// @brief Add data from the inline constant into the buffer.
/// @param initializer The initializer of the constant being added.
/// @param inlineConstantBuffer The buffer the data is being added to.
void addData(
llvm::Constant* initializer,
DataVector& inlineConstantBuffer,
PointerOffsetInfoList& pointerOffsetInfo,
BufferOffsetMap& inlineProgramScopeOffsets,
unsigned addressSpace);
/// @brief Align the buffer according to the required alignment
/// @param buffer The buffer to align.
/// @param alignment Required alignment in bytes.
void alignBuffer(DataVector& buffer, unsigned int alignment);
const llvm::DataLayout* m_DL;
ModuleMetaData* m_pModuleMd;
};
} // namespace IGC
| 35.789474
| 88
| 0.632059
|
ConiKost
|
08196178478447608c42dee8386ed18a7bd59944
| 26,759
|
hpp
|
C++
|
src/sframe/sframe.hpp
|
karthikdash/turicreate
|
86a6d9a339a77b7b55f67233352da0e7471400bc
|
[
"BSD-3-Clause"
] | 1
|
2018-04-11T19:06:57.000Z
|
2018-04-11T19:06:57.000Z
|
src/sframe/sframe.hpp
|
karthikdash/turicreate
|
86a6d9a339a77b7b55f67233352da0e7471400bc
|
[
"BSD-3-Clause"
] | null | null | null |
src/sframe/sframe.hpp
|
karthikdash/turicreate
|
86a6d9a339a77b7b55f67233352da0e7471400bc
|
[
"BSD-3-Clause"
] | 1
|
2019-01-12T01:07:34.000Z
|
2019-01-12T01:07:34.000Z
|
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_UNITY_LIB_SFRAME_HPP
#define TURI_UNITY_LIB_SFRAME_HPP
#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>
#include <logger/logger.hpp>
#include <flexible_type/flexible_type.hpp>
#include <sframe/sarray.hpp>
#include <sframe/dataframe.hpp>
#include <sframe/sframe_index_file.hpp>
#include <sframe/sframe_constants.hpp>
#include <sframe/output_iterator.hpp>
namespace turi {
// forward declaration of th csv_line_tokenizer to avoid a
// circular dependency
struct csv_line_tokenizer;
class sframe_reader;
class csv_writer;
typedef turi::sframe_function_output_iterator<
std::vector<flexible_type>,
std::function<void(const std::vector<flexible_type>&)>,
std::function<void(std::vector<flexible_type>&&)>,
std::function<void(const sframe_rows&)> >
sframe_output_iterator;
/**
* \ingroup sframe_physical
* \addtogroup sframe_main Main SFrame Objects
* \{
*/
/**
* The SFrame is an immutable object that represents a table with rows
* and columns. Each column is an \ref sarray<flexible_type>, which is a
* sequence of an object T split into segments. The sframe writes an sarray
* for each column of data it is given to disk, each with a prefix that extends
* the prefix given to open. The SFrame is referenced on disk by a single
* ".frame_idx" file which then has a list of file names, one file for each
* column.
*
* The SFrame is \b write-once, \b read-many. The SFrame can be opened for
* writing \b once, after which it is read-only.
*
* Since each column of the SFrame is an independent sarray, as an independent
* shared_ptr<sarray<flexible_type> > object, columns can be added / removed
* to form new sframes without problems. As such, certain operations
* (such as the object returned by add_column) recan be "ephemeral" in that
* there is no .frame_idx file on disk backing it. An "ephemeral" frame can be
* identified by checking the result of get_index_file(). If this is empty,
* it is an ephemeral frame.
*
* The interface for the SFrame pretty much matches that of the \ref sarray
* as in the SArray's stored type is std::vector<flexible_type>. The SFrame
* however, also provides a large number of other capabilities such as
* csv parsing, construction from sarrays, etc.
*/
class sframe : public swriter_base<sframe_output_iterator> {
public:
/// The reader type
typedef sframe_reader reader_type;
/// The iterator type which \ref get_output_iterator returns
typedef sframe_output_iterator iterator;
/// The type contained in the sframe
typedef std::vector<flexible_type> value_type;
/**************************************************************************/
/* */
/* Constructors */
/* */
/**************************************************************************/
/**
* default constructor; does nothing; use \ref open_for_read or
* \ref open_for_write after construction to read/create an sarray.
*/
inline sframe() { }
/**
* Copy constructor.
* If the source frame is opened for writing, this will throw
* an exception. Otherwise, this will create a frame opened for reading,
* which shares column arrays with the source frame.
*/
sframe(const sframe& other);
/**
* Move constructor.
*/
sframe(sframe&& other) : sframe() {
(*this) = std::move(other);
}
/**
* Assignment operator.
* If the source frame is opened for writing, this will throw
* an exception. Otherwise, this will create a frame opened for reading,
* which shares column arrays with the source frame.
*/
sframe& operator=(const sframe& other);
/**
* Move Assignment operator.
* Moves other into this. Other will be cleared as if it is a newly
* constructed sframe object.
*/
sframe& operator=(sframe&& other);
/**
* Attempts to construct an sframe which reads from the given frame
* index file. This should be a .frame_idx file.
* If the index cannot be opened, an exception is thrown.
*/
explicit inline sframe(std::string frame_idx_file) {
auto frame_index_info = read_sframe_index_file(frame_idx_file);
open_for_read(frame_index_info);
}
/**
* Construct an sframe from sframe index information.
*/
explicit inline sframe(sframe_index_file_information frame_index_info) {
open_for_read(frame_index_info);
};
/**
* Constructs an SFrame from a vector of Sarrays.
*
* \param columns List of sarrays to form as columns
* \param column_names List of the name for each column, with the indices
* corresponding with the list of columns. If the length of the column_names
* vector does not match columns, the column gets a default name.
* For example, if four columns are given and column_names = {id, num},
* the columns will be named {"id, "num", "X3", "X4"}. Entries that are
* zero-length strings will also be given a default name.
* \param fail_on_column_names If true, will throw an exception if any column
* names are unique. If false, will automatically adjust column names so
* they are unique.
*
* Throws an exception if any column names are not unique (if
* fail_on_column_names is true), or if the number of segments, segment
* sizes, or total sizes of each sarray is not equal. The constructed SFrame
* is ephemeral, and is not backed by a disk index.
*/
explicit inline sframe(
const std::vector<std::shared_ptr<sarray<flexible_type> > > &new_columns,
const std::vector<std::string>& column_names = {},
bool fail_on_column_names=true) {
open_for_read(new_columns, column_names, fail_on_column_names);
}
/**
* Constructs an SFrame from a csv file.
*
* All columns will be parsed into flex_string unless the column type is
* specified in the column_type_hints.
*
* \param path The url to the csv file. The url can points to local
* filesystem, hdfs, or s3. \param tokenizer The tokenization rules to use
* \param use_header If true, the first line will be parsed as column
* headers. Otherwise, R-style column names, i.e. X1, X2, X3... will be used.
* \param continue_on_failure If true, lines with parsing errors will be skipped.
* \param column_type_hints A map from column name to the column type.
* \param output_columns The subset of column names to output
* \param row_limit If non-zero, the maximum number of rows to read
* \param skip_rows If non-zero, the number of lines to skip at the start
* of each file
*
* Throws an exception if IO error or csv parse failed.
*/
std::map<std::string, std::shared_ptr<sarray<flexible_type>>> init_from_csvs(
const std::string& path,
csv_line_tokenizer& tokenizer,
bool use_header,
bool continue_on_failure,
bool store_errors,
std::map<std::string, flex_type_enum> column_type_hints,
std::vector<std::string> output_columns = std::vector<std::string>(),
size_t row_limit = 0,
size_t skip_rows = 0);
/**
* Constructs an SFrame from dataframe_t.
*
* \note Throw an exception if the dataframe contains undefined values (e.g.
* in sparse rows),
*/
sframe(const dataframe_t& data);
~sframe();
/**************************************************************************/
/* */
/* Openers */
/* */
/**************************************************************************/
/**
* Initializes the SFrame with an index_information.
* If the SFrame is already inited, this will throw an exception
*/
inline void open_for_read(sframe_index_file_information frame_index_info) {
Dlog_func_entry();
ASSERT_MSG(!inited, "Attempting to init an SFrame "
"which has already been inited.");
inited = true;
create_arrays_for_reading(frame_index_info);
}
/**
* Initializes the SFrame with a collection of columns. If the SFrame is
* already inited, this will throw an exception. Will throw an exception if
* column_names are not unique and fail_on_column_names is true.
*/
void open_for_read(
const std::vector<std::shared_ptr<sarray<flexible_type> > > &new_columns,
const std::vector<std::string>& column_names = {},
bool fail_on_column_names=true) {
Dlog_func_entry();
ASSERT_MSG(!inited, "Attempting to init an SFrame "
"which has already been inited.");
inited = true;
create_arrays_for_reading(new_columns, column_names, fail_on_column_names);
}
/**
* Opens the SFrame with an arbitrary temporary file.
* The array must not already been inited.
*
* \param column_names The name for each column. If the vector is shorter
* than column_types, or empty values are given, names are handled with
* default names of "X<column id+1>". Each column name must be unique.
* This will let you write non-unique column names, but if you do that,
* the sframe will throw an exception while constructing the output of
* this class.
* \param column_types The type of each column expressed as a
* flexible_type. Currently this is required to tell how many columns
* are a part of the sframe. Throws an exception if this is an empty
* vector.
* \param nsegments The number of parallel output segments on each
* sarray. Throws an exception if this is 0.
* \param frame_sidx_file If not specified, an argitrary temporary
* file will be created. Otherwise, all frame
* files will be written to the same location
* as the frame_sidx_file. Must end in
* ".frame_idx"
* \param fail_on_column_names If true, will throw an exception if any column
* names are unique. If false, will
* automatically adjust column names so they are
* unique.
*/
inline void open_for_write(const std::vector<std::string>& column_names,
const std::vector<flex_type_enum>& column_types,
const std::string& frame_sidx_file = "",
size_t nsegments = SFRAME_DEFAULT_NUM_SEGMENTS,
bool fail_on_column_names=true) {
Dlog_func_entry();
ASSERT_MSG(!inited, "Attempting to init an SFrame "
"which has already been inited.");
if (column_names.size() != column_types.size()) {
log_and_throw(std::string("Names and Types array length mismatch"));
}
inited = true;
create_arrays_for_writing(column_names, column_types,
nsegments, frame_sidx_file, fail_on_column_names);
}
/**************************************************************************/
/* */
/* Basic Accessors */
/* */
/**************************************************************************/
/**
* Returns true if the Array is opened for reading.
* i.e. get_reader() will succeed
*/
inline bool is_opened_for_read() const {
return (inited && !writing);
}
/**
* Returns true if the Array is opened for writing.
* i.e. get_output_iterator() will succeed
*/
inline bool is_opened_for_write() const {
return (inited && writing);
}
/**
* Return the index file of the sframe
*/
inline const std::string& get_index_file() const {
ASSERT_TRUE(inited);
return index_file;
}
/**
* Reads the value of a key associated with the sframe
* Returns true on success, false on failure.
*/
inline bool get_metadata(const std::string& key, std::string &val) const {
bool ret;
std::tie(ret, val) = get_metadata(key);
return ret;
}
/**
* Reads the value of a key associated with the sframe
* Returns a pair of (true, value) on success, and (false, empty_string)
* on failure.
*/
inline std::pair<bool, std::string> get_metadata(const std::string& key) const {
ASSERT_MSG(inited, "Invalid SFrame");
if (index_info.metadata.count(key)) {
return std::pair<bool, std::string>(true, index_info.metadata.at(key));
} else {
return std::pair<bool, std::string>(false, "");
}
}
/// Returns the number of columns in the SFrame. Does not throw.
inline size_t num_columns() const {
return index_info.ncolumns;
}
/// Returns the length of each sarray.
inline size_t num_rows() const {
return size();
}
/**
* Returns the number of elements in the sframe. If the sframe was not initialized, returns 0.
*/
inline size_t size() const {
return inited ? index_info.nrows : 0;
}
/**
* Returns the name of the given column. Throws an exception if the
* column id is out of range.
*/
inline std::string column_name(size_t i) const {
if(i >= index_info.column_names.size()) {
log_and_throw("Column index out of range!");
}
return index_info.column_names[i];
}
/**
* Returns the type of the given column. Throws an exception if the
* column id is out of range.
*/
inline flex_type_enum column_type(size_t i) const {
if (writing) {
if(i >= group_writer->get_index_info().columns.size()) {
log_and_throw("Column index out of range!");
}
return (flex_type_enum)
(atoi(group_writer->get_index_info().columns[i].metadata["__type__"].c_str()));
} else {
if(i >= columns.size()) {
log_and_throw("Column index out of range!");
}
return columns[i]->get_type();
}
}
/**
* Returns the type of the given column. Throws an exception if the
* column id is out of range.
* \overload
*/
inline flex_type_enum column_type(const std::string& column_name) const {
return columns[column_index(column_name)]->get_type();
}
/** Returns the column names as a single vector.
*/
inline const std::vector<std::string>& column_names() const {
return index_info.column_names;
}
/** Returns the column types as a single vector.
*/
inline std::vector<flex_type_enum> column_types() const {
std::vector<flex_type_enum> tv(num_columns());
for(size_t i = 0; i < num_columns(); ++i)
tv[i] = column_type(i);
return tv;
}
/**
* Returns true if the sframe contains the given column.
*/
inline bool contains_column(const std::string& column_name) const {
Dlog_func_entry();
auto iter = std::find(index_info.column_names.begin(),
index_info.column_names.end(),
column_name);
return iter != index_info.column_names.end();
}
/**
* Returns the number of segments that this SFrame will be
* written with. Never fails.
*/
inline size_t num_segments() const {
ASSERT_MSG(inited, "Invalid SFrame");
if (writing) {
return group_writer->num_segments();
} else {
if (index_info.ncolumns == 0) return 0;
return columns[0]->num_segments();
}
}
/**
* Return the number of segments in the collection.
* Will throw an exception if the writer is invalid (there is an error
* opening/writing files)
*/
inline size_t segment_length(size_t i) const {
DASSERT_MSG(inited, "Invalid SFrame");
if (index_info.ncolumns == 0) return 0;
else return columns[0]->segment_length(i);
}
/**
* Returns the column index of column_name.
*
* Throws an exception of the column_ does not exist.
*/
inline size_t column_index(const std::string& column_name) const {
auto iter = std::find(index_info.column_names.begin(),
index_info.column_names.end(),
column_name);
if (iter != index_info.column_names.end()) {
return (iter) - index_info.column_names.begin();
} else {
log_and_throw(std::string("Column name " + column_name + " does not exist."));
}
__builtin_unreachable();
}
/**
* Returns the current index info of the array.
*/
inline const sframe_index_file_information get_index_info() const {
return index_info;
}
/**
* Merges another SFrame with the same schema with the current SFrame
* returning a new SFrame.
* Both SFrames can be empty, but cannot be opened for writing.
*/
sframe append(const sframe& other) const;
/**
* Gets an sframe reader object with the segment layout of the first column.
*/
std::unique_ptr<reader_type> get_reader() const;
/**
* Gets an sframe reader object with num_segments number of logical segments.
*/
std::unique_ptr<reader_type> get_reader(size_t num_segments) const;
/**
* Gets an sframe reader object with a custom segment layout. segment_lengths
* must sum up to the same length as the original array.
*/
std::unique_ptr<reader_type> get_reader(const std::vector<size_t>& segment_lengths) const;
/**************************************************************************/
/* */
/* Other SFrame Unique Accessors */
/* */
/**************************************************************************/
/**
* Converts the sframe into a dataframe_t. Will reset iterators before
* and after the operation.
*/
dataframe_t to_dataframe();
/**
* Returns an sarray of the specific column.
*
* Throws an exception if the column does not exist.
*/
std::shared_ptr<sarray<flexible_type> > select_column(size_t column_id) const;
/**
* Returns an sarray of the specific column by name.
*
* Throws an exception if the column does not exist.
*/
std::shared_ptr<sarray<flexible_type> > select_column(const std::string &name) const;
/**
* Returns new sframe containing only the chosen columns in the same order.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* Throws an exception if the column name does not exist.
*/
sframe select_columns(const std::vector<std::string>& names) const;
/**
* Returns a new ephemeral SFrame with the new column added to the end.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* \param sarr_ptr Shared pointer to the SArray
* \param column_name The name to give this column. If empty it will
* be given a default name (X<column index>)
*
*/
sframe add_column(std::shared_ptr<sarray<flexible_type> > sarr_ptr,
const std::string& column_name=std::string("")) const;
/**
* Set the ith column name to name. This can be done when the
* frame is open in either reading or writing mode. Changes are ephemeral,
* and do not affect what is stored on disk.
*/
void set_column_name(size_t column_id, const std::string& name);
/**
* Returns a new ephemeral SFrame with the column removed.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* \param column_id The index of the column to remove.
*
*/
sframe remove_column(size_t column_id) const;
/**
* Returns a new ephemeral SFrame with two columns swapped.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* \param column_1 The index of the first column.
* \param column_2 The index of the second column.
*
*/
sframe swap_columns(size_t column_1, size_t column_2) const;
/**
* Replace the column of the given column name with a new sarray.
* Return the new sframe with old column_name sarray replaced by the new sarray.
*/
sframe replace_column(std::shared_ptr<sarray<flexible_type>> sarr_ptr,
const std::string& column_name) const;
/**************************************************************************/
/* */
/* Writing Functions */
/* */
/**************************************************************************/
// These functions are only valid when the array is opened for writing
/**
* Sets the number of segments in the output.
* Frame must be first opened for writing.
* Once an output iterator has been obtained, the number of segments
* can no longer be changed. Returns true on sucess, false on failure.
*/
bool set_num_segments(size_t numseg);
/**
* Gets an output iterator for the given segment. This can be used to
* write data to the segment, and is currently the only supported way
* to do so.
*
* The iterator is invalid once the segment is closed (See \ref close).
* Accessing the iterator after the writer is destroyed is undefined
* behavior.
*
* Cannot be called until the sframe is open.
*
* Example:
* \code
* // example to write the same vector to 7 rows of segment 1
* // let's say the sframe has 5 columns of type FLEX_TYPE_ENUM::INTEGER
* // and sfw is the sframe.
* auto iter = sfw.get_output_iterator(1);
* std::vector<flexible_type> vals{1,2,3,4,5}
* for(int i = 0; i < 7; ++i) {
* *iter = vals;
* ++iter;
* }
* \endcode
*/
iterator get_output_iterator(size_t segmentid);
/**
* Closes the sframe. close() also implicitly closes all segments. After
* the writer is closed, no segments can be written.
* After the sframe is closed, it becomes read only and can be read
* with the get_reader() function.
*/
void close();
/**
* Flush writes for a particular segment
*/
void flush_write_to_segment(size_t segment);
/**
* Saves a copy of the current sframe as a CSV file.
* Does not modify the current sframe.
*
* \param csv_file target CSV file to save into
* \param writer The CSV writer configuration
*/
void save_as_csv(std::string csv_file,
csv_writer& writer);
/**
* Adds meta data to the frame.
* Frame must be first opened for writing.
*/
bool set_metadata(const std::string& key, std::string val);
/**
* Saves a copy of the current sframe into a different location.
* Does not modify the current sframe.
*/
void save(std::string index_file) const;
/**
* SFrame serializer. oarc must be associated with a directory.
* Saves into a prefix inside the directory.
*/
void save(oarchive& oarc) const;
/**
* SFrame deserializer. iarc must be associated with a directory.
* Loads from the next prefix inside the directory.
*/
void load(iarchive& iarc);
bool delete_files_on_destruction();
/**
* Internal API.
* Used to obtain the internal writer object.
*/
inline
std::shared_ptr<sarray_group_format_writer<flexible_type> >
get_internal_writer() {
return group_writer;
}
private:
/**
* Clears all internal structures. Used by \ref create_arrays_for_reading
* and \ref create_arrays_for_writing to clear all the index information
* and column information
*/
void reset();
/**
* Internal function that actually writes the values to each SArray's
* output iterator. Used by the sframe_output_iterator.
*/
void write(size_t segmentid, const std::vector<flexible_type>& t);
/**
* Internal function that actually writes the values to each SArray's
* output iterator. Used by the sframe_output_iterator.
*/
void write(size_t segmentid, std::vector<flexible_type>&& t);
/**
* Internal function that actually writes the values to each SArray's
* output iterator. Used by the sframe_output_iterator.
*/
void write(size_t segmentid, const sframe_rows& t);
/**
* Internal function. Given the index_information, this function
* initializes each of the sarrays for reading; filling up
* the columns array
*/
void create_arrays_for_reading(sframe_index_file_information frame_index_info);
/**
* Internal function. Given a collection of sarray columns, this function
* makes an sframe representing the combination of all the columns. This
* sframe does not have an index file (it is ephemeral), and get_index_file
* will return an empty file. Will throw an exception if column_names are not
* unique and fail_on_column_names is true.
*/
void create_arrays_for_reading(
const std::vector<std::shared_ptr<sarray<flexible_type> > > &columns,
const std::vector<std::string>& column_names = {},
bool fail_on_column_names=true);
/**
* Internal function. Given the index_file, this function initializes each of
* the sarrays for writing; filling up the columns array. Will throw an
* exception if column_names are not unique and fail_on_column_names is true.
*/
void create_arrays_for_writing(const std::vector<std::string>& column_names,
const std::vector<flex_type_enum>& column_types,
size_t nsegments,
const std::string& frame_sidx_file,
bool fail_on_column_names);
void keep_array_file_ref();
/**
* Internal function. Resolve conflicts in column names.
*/
std::string generate_valid_column_name(const std::string &column_name) const;
sframe_index_file_information index_info;
std::string index_file;
std::vector<std::shared_ptr<fileio::file_ownership_handle> > index_file_handle;
std::vector<std::shared_ptr<sarray<flexible_type> > > columns;
std::shared_ptr<sarray_group_format_writer<flexible_type> > group_writer;
mutex lock;
bool inited = false;
bool writing = false;
friend class sframe_reader;
public:
/**
* For debug purpose, print the information about the sframe.
*/
void debug_print();
};
/// \}
} // end of namespace
#endif
#include <sframe/sframe_reader.hpp>
| 34.394602
| 96
| 0.630704
|
karthikdash
|
081fb04b87b9bf4a565b7e4702c1a2608373d1cc
| 67
|
cpp
|
C++
|
core/Instruments/AnalogDrums/AnalogDrum.cpp
|
ferluht/pocketdaw
|
0e40b32191e431cde54cd5944611c4b5b293ea68
|
[
"BSD-2-Clause"
] | null | null | null |
core/Instruments/AnalogDrums/AnalogDrum.cpp
|
ferluht/pocketdaw
|
0e40b32191e431cde54cd5944611c4b5b293ea68
|
[
"BSD-2-Clause"
] | null | null | null |
core/Instruments/AnalogDrums/AnalogDrum.cpp
|
ferluht/pocketdaw
|
0e40b32191e431cde54cd5944611c4b5b293ea68
|
[
"BSD-2-Clause"
] | 1
|
2022-03-29T19:45:51.000Z
|
2022-03-29T19:45:51.000Z
|
//
// Created by ibelikov on 23.12.19.
//
#include "AnalogDrum.h"
| 11.166667
| 35
| 0.641791
|
ferluht
|
0827622e6748b8e62d1effaf51041b021fb28ab8
| 794
|
cpp
|
C++
|
src/diff/deltas/asset_type_2_delta.cpp
|
kmichel/zizany
|
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
|
[
"MIT"
] | 3
|
2017-07-02T08:33:22.000Z
|
2019-03-16T00:48:11.000Z
|
src/diff/deltas/asset_type_2_delta.cpp
|
kmichel/zizany
|
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
|
[
"MIT"
] | null | null | null |
src/diff/deltas/asset_type_2_delta.cpp
|
kmichel/zizany
|
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
|
[
"MIT"
] | null | null | null |
#include "asset_type_2_delta.hpp"
#include "../../json_writer.hpp"
namespace zizany {
asset_type_2_delta::asset_type_2_delta(const int asset_id_, const int old_type_2_, const int new_type_2_)
: asset_id(asset_id_), old_type_2(old_type_2_), new_type_2(new_type_2_) {
}
void
asset_type_2_delta::print_action(json_writer &writer) const {
writer.add_string("change asset type 2");
}
void
asset_type_2_delta::print_details(json_writer &writer) const {
writer.start_object();
writer.add_key("asset_id");
writer.add_number(asset_id);
writer.add_key("old_type_2");
writer.add_number(old_type_2);
writer.add_key("new_type_2");
writer.add_number(new_type_2);
writer.end_object();
}
}
| 29.407407
| 109
| 0.675063
|
kmichel
|
082a0dec5a4414f0ce972588177e96140b513227
| 1,130
|
cpp
|
C++
|
libsnn/src/loss/hillinger.cpp
|
rahulsrma26/simpleNN
|
4a8858df503336ce5cf00850d89015e93e07cb36
|
[
"MIT"
] | 11
|
2019-11-02T13:48:36.000Z
|
2020-03-06T22:57:40.000Z
|
libsnn/src/loss/hillinger.cpp
|
rahulsrma26/simpleAI
|
4a8858df503336ce5cf00850d89015e93e07cb36
|
[
"MIT"
] | 1
|
2019-12-13T15:08:55.000Z
|
2019-12-15T17:16:08.000Z
|
libsnn/src/loss/hillinger.cpp
|
rahulsrma26/simpleAI
|
4a8858df503336ce5cf00850d89015e93e07cb36
|
[
"MIT"
] | null | null | null |
#include "snn/loss/hillinger.hpp"
namespace snn {
namespace losses {
constexpr real h_eps = 1e-5f;
hillinger::hillinger(const kwargs& args) { std::ignore = args; }
std::string hillinger::type() { return TEXT::HILLINGER; }
std::string hillinger::name() const { return this->type(); }
real hillinger::f(const tensor<real>& o, const tensor<real>& l) const {
real r = 0;
for (size_t i = 0; i < o.size(); i++) {
const real d = std::sqrt(o[i]) - std::sqrt(l[i]);
r += d * d;
}
return r / (std::sqrt(real(2.0)) * o.get_shape().front());
}
tensor<real> hillinger::df(const tensor<real>& o, const tensor<real>& l) const {
tensor<real> r(o.get_shape());
const auto n = o.get_shape().front();
for (uint i = 0; i < o.size(); i++) {
const real denom = std::sqrt(2.0f * o[i]);
r[i] = (std::sqrt(o[i]) - std::sqrt(l[i])) / ((h_eps + denom) * n);
}
return r;
}
void hillinger::save(std::ostream& os) const { std::ignore = os; }
hillinger::hillinger(std::istream& is) { std::ignore = is; }
} // namespace losses
} // namespace snn
| 28.974359
| 81
| 0.567257
|
rahulsrma26
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.