hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c70afa5c968204fb92f551e7a66a1b8713e1b0df | 2,789 | cpp | C++ | Projects/Library/Source/Exception.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | 1 | 2018-06-16T17:53:43.000Z | 2018-06-16T17:53:43.000Z | Projects/Library/Source/Exception.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | null | null | null | Projects/Library/Source/Exception.cpp | kalineh/KAI | 43ab555bcbad1886715cd00b2cdac89e12d5cfe5 | [
"MIT"
] | null | null | null |
#include "KAI/KAI.h"
#include "KAI/BuiltinTypes/Signed32.h"
KAI_BEGIN
namespace Exception
{
nstd::string Base::ToString() const
{
StringStream S;
std::string loc = location.ToString().c_str();
loc = loc.substr(loc.find_last_of('/') + 1);
S << loc.c_str() << text << ": ";
WriteExtendedInformation(S);
return S.ToString().c_str();
}
void TypeMismatch::WriteExtendedInformation(StringStream &S) const
{
S << "first=" << Type::Number(first).ToString() << ", second=" << Type::Number(second).ToString();
}
void UnknownTypeNumber::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number;
}
void UnknownObject::WriteExtendedInformation(StringStream &S) const
{
S << "handle=" << handle.GetValue();
}
void ObjectNotFound::WriteExtendedInformation(StringStream &S) const
{
S << "label=" << label;
}
void NoProperty::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number << ", type_property=" << type_property;
}
void PacketExtraction::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number;
}
void PacketInsertion::WriteExtendedInformation(StringStream &S) const
{
S << "type_number=" << type_number;
}
void CannotResolve::WriteExtendedInformation(StringStream &S) const
{
if (!path.Empty())
S << "path=" << path;
else if (!label.Empty())
S << "label=" << label;
else
S << "object=" << object;
}
void InvalidPathname::WriteExtendedInformation(StringStream &S) const
{
S << "text=" << text;
}
void ObjectNotInTree::WriteExtendedInformation(StringStream &S) const
{
S << "object=" << object;
}
void UnknownMethod::WriteExtendedInformation(StringStream &S) const
{
S << "name=" << name << ", class=" << class_name;
}
void UnknownHandle::WriteExtendedInformation(StringStream &S) const
{
S << "handle=" << handle.GetValue();
}
void InvalidStringLiteral::WriteExtendedInformation(StringStream &S) const
{
S << "text='" << text << "'";
}
void CannotNew::WriteExtendedInformation(StringStream &S) const
{
S << "object=" << arg;
}
void UnknownKey::WriteExtendedInformation(StringStream &S) const
{
S << "key=" << key;
}
void NotImplemented::WriteExtendedInformation(StringStream &S) const
{
S << "what=" << text;
}
void BadIndex::WriteExtendedInformation(StringStream &S) const
{
S << "index=" << index;
}
void InvalidIdentifier::WriteExtendedInformation(StringStream &S) const
{
S << "what='" << what << "'";
}
void FileNotFound::WriteExtendedInformation(StringStream &S) const
{
S << "filename='" << filename << "'";
}
void UnknownProperty::WriteExtendedInformation(StringStream &S) const
{
S << "class=" << klass << ", property=" << prop;
}
}
KAI_END
//EOF
| 22.134921 | 100 | 0.669416 | kalineh |
c70bb8e0a1fa398648d66bdc673df158b58f6ade | 10,580 | cpp | C++ | src/PropGenerator.cpp | ajmalk/RIGOR-cpp | 19300c2bd7d7a963d16ebd6b2544eb6e09967520 | [
"MIT"
] | null | null | null | src/PropGenerator.cpp | ajmalk/RIGOR-cpp | 19300c2bd7d7a963d16ebd6b2544eb6e09967520 | [
"MIT"
] | null | null | null | src/PropGenerator.cpp | ajmalk/RIGOR-cpp | 19300c2bd7d7a963d16ebd6b2544eb6e09967520 | [
"MIT"
] | null | null | null | //
// PropGenerator.cpp
// Rigor
//
// Created by Ajmal Kunnummal on 2/20/15.
// Copyright (c) 2015 ajmal. All rights reserved.
//
#include <opencv2/core/core.hpp>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "bk_dynamicgraphs.h"
#include "SLICSegment.h"
#include "PropGenerator.h"
#include "Parameters.h"
#include "SPImage.h"
#include "PixelImage.h"
#include "FuxinGraph.h"
#include "SimpleBK.h"
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
cv::Mat image;
cv::Mat sp_im;
PropGenerator::PropGenerator(Parameters ¶ms){
this->params = params;
}
void print_pos_val(int event, int x, int y, int flags, void* image){
if ( event == cv::EVENT_LBUTTONDOWN ) {
cv::Mat * imp = (cv::Mat *) image;
cv::Mat im = *imp;
cout << "click: " << ((cv::Mat *) image)->at<int>(y, x) << endl;
}
}
void show_in_color(string window, cv::Mat &image){
cv::namedWindow(window, cv::WINDOW_AUTOSIZE);
double min, max;
cv::minMaxIdx(image, &min, &max);
cv::Mat adj_sp_map;
// expand your range to 0..255. Similar to histEq();
image.convertTo(adj_sp_map, CV_8UC1, 255 / (max-min), -min);
// convert to a colormaped image
cv::applyColorMap(adj_sp_map, adj_sp_map, cv::COLORMAP_JET);
cv::imshow(window, adj_sp_map);
cv::setMouseCallback(window, print_pos_val, &image);
}
inline cv::Mat iterator_to_image(AbstractGraph::UnaryIterator it, int sx, int sy) {
cv::Mat cut_im = cv::Mat(sy, sx, CV_8U);
auto im_it = cut_im.begin<uchar>(), im_it_end = cut_im.end<uchar>();
auto p = 0;
for(; im_it != im_it_end; ++im_it, ++it) {
auto ed = (uchar) (*it).first;
*im_it = ed;
if(0 == (int) (*it).second) {
cout << (int) (uchar) (*it).first << endl;
}
}
return cut_im;
}
cv::Mat gradient(cv::Mat image){
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
GaussianBlur( image, image, cv::Size(3,3), 0, 0, cv::BORDER_DEFAULT );
/// Convert it to gray
cv::Mat image_gray;
cvtColor( image, image_gray, CV_RGB2GRAY );
/// Generate grad_x and grad_y
cv::Mat grad_x, grad_y;
cv::Mat abs_grad_x, abs_grad_y;
/// Gradient X
//Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );
Sobel( image_gray, grad_x, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT );
convertScaleAbs( grad_x, abs_grad_x );
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel( image_gray, grad_y, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT );
convertScaleAbs( grad_y, abs_grad_y );
/// Total Gradient (approximate)
cv::Mat grad;
addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );
cv::Mat gradf = cv::Mat(image.size[0], image.size[1], CV_64F);
auto i_it = grad.begin<uchar>();
for(auto f_it = gradf.begin<double>() ; f_it != gradf.end<double>(); ++i_it, ++f_it) {
*f_it = float(*i_it);
}
return gradf;
}
cv::Mat struct_edges(cv::Mat image){
/// Convert it to gray
cv::Mat image_gray;
cvtColor( image, image_gray, CV_RGB2GRAY );
cv::Mat grayf = cv::Mat(image.size[0], image.size[1], CV_64F);
auto i_it = image_gray.begin<uchar>();
for(auto f_it = grayf.begin<double>() ; f_it != grayf.end<double>(); ++i_it, ++f_it) {
*f_it = float(*i_it);
}
return grayf;
}
void PropGenerator::generate(fs::path filename){
image = cv::imread(filename.c_str());
if (image.empty()) {
// Check for invalid input
std::cout << "Could not open or find the image" << std::endl;
return;
}
if(params.debug){
cout << "Read image" << endl;
cv::namedWindow("Input Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Input Image", image);
}
cv::Mat edges = gradient(image);
//cv::Mat edges = cv::imread("/Users/ajmalkunnummal/Pictures/peppers_str_edges_fat.png");
//edges = struct_edges(edges);
if(params.debug){
cout << "Ran edge detection" << endl;
cv::namedWindow( "Edge Detector", CV_WINDOW_AUTOSIZE );
imshow( "Edge Detector", edges );
}
int num_sp = SPImage::slic_segmentation(image, sp_im, params.num_sp, params.compactness);
if(params.debug) {
cout << "Segmented image. Num of superpixels: " << num_sp << endl;
show_in_color("Superpixels", sp_im);
}
SPImage spixels = SPImage(image, sp_im, edges, num_sp);
if(params.debug) {
cout << "Setup graph and pairwise edges" << endl;
cv::namedWindow("Superpixel Colors", cv::WINDOW_AUTOSIZE);
cv::imshow("Superpixel Colors", spixels.get_color_sp_im());
}
vector< set<int> > seeds = SPImage::generate_seeds(sp_im, params.seeds, params.seed_radius = 5);
if(params.debug){
cout << "Generated " << seeds.size() << " seeds" << endl;
cv::imshow("Seeds", spixels.seeds_to_sp_im(seeds));
}
vector< unique_ptr<AbstractGraph> > graphs;
for ( auto& seed: seeds) {
for (auto graph_type: params.graph_types) {
graphs.push_back( graph_type(seed, &spixels) );
}
}
AbstractGraph::UnaryIterator unaries = graphs[0]->get_unaries(graphs[0]->lambdas[0],
graphs[0]->lambdas[graphs[0]->lambdas.size() - 1]);
vector<edgew> stats;
// for (int i = 0; i < graphs[0]->image->getNumPixels(); unaries++, i++) {
// std::pair<edgew, edgew> unary_pair = *unaries;
//// cout << unary_pair.first << " " << unary_pair.second << endl;
// stats.push_back(unary_pair.first);
// }
for(int i = 1; i < spixels.getNumPairwise(); i+=2) {
auto pw = spixels.get_pairwise(0, i);
stats.push_back(pw.w);
}
sort(stats.begin(), stats.end());
cout << spixels.getNumPairwise() << endl;
cout << stats[0] << endl;
cout << stats[stats.size() / 4] << endl;
cout << stats[stats.size() / 2] << endl;
cout << stats[stats.size() / 4 * 3] << endl;
cout << stats[stats.size() / 8 * 7] << endl;
cout << stats[stats.size() / 16 * 15] << endl;
cout << stats[stats.size() - 7] << endl;
cout << stats[stats.size() - 1] << endl;
if(params.debug){
cout << "Setup " << graphs.size() << " graphs (1 for each seed and graph type)" << endl;
}
auto cuts = nodynamic_param_maxflow(graphs);
if(params.debug){
cout << "Found " << cuts.size() / spixels.spixels.size() << " cuts" << endl;
// for(int i = 0; i < cuts.size() / spixels.spixels.size(); i++){
// for(int j = 0; j < spixels.spixels.size(); j++){
// cout << cuts[ i * spixels.spixels.size() + j];
// }
// cout << endl;
// }
for (auto cur_cut = cuts.begin(); cur_cut != cuts.end(); cur_cut += spixels.spixels.size() ) {
cv::imshow("Cut", spixels.cut_to_image(cur_cut));
cv::waitKey(0);
}
}
if(params.debug)
cv::waitKey(0);
}
void PropGenerator::generate_pix(fs::path filename){
image = cv::imread(filename.c_str());
if (image.empty()) {
// Check for invalid input
std::cout << "Could not open or find the image" << std::endl ;
return;
}
if(params.debug){
cout << "Read image" << endl;
cv::namedWindow("Input Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Input Image", image);
}
cv::Mat edges = gradient(image) ;
//cv::Mat edges = cv::imread("/Users/ajmalkunnummal/Pictures/peppers_str_edges_fat.png");
//edges = struct_edges(edges);
if(params.debug){
cout << "Ran edge detection" << endl;
cv::namedWindow( "Edge Detector", CV_WINDOW_AUTOSIZE );
imshow( "Edge Detector", edges);
}
PixelImage spixels = PixelImage(image, edges);
cout << "Num of pixels: " << spixels.getNumPixels() << endl;
cout << "unary color: " << spixels.get_color(0) << endl;
cout << "unary size:" << spixels.get_size(0) << endl;
cout << "unary ext:" << spixels.get_ext(0) << endl;
vector< set<int> > seeds = { { spixels.getNumPixels() / 2 + spixels.sx / 2 } };
if(params.debug) {
cout << "Generated " << seeds.size() << " seeds" << endl;
// cv::imshow("Seeds", spixels.seeds_to_sp_im(seeds));
}
vector< unique_ptr<AbstractGraph> > graphs;
for ( auto& seed: seeds) {
for (auto graph_type: params.graph_types) {
graphs.push_back( graph_type(seed, &spixels) );
}
}
auto unaries2 = graphs[0]->get_unaries(graphs[0]->lambdas[0],
graphs[0]->lambdas[graphs[0]->lambdas.size() - 0 - 1]);
imshow( "Unaries", iterator_to_image(unaries2, spixels.sx, spixels.sy) );
AbstractGraph::UnaryIterator unaries = graphs[0]->get_unaries(graphs[0]->lambdas[0],
graphs[0]->lambdas[graphs[0]->lambdas.size() - 0 - 1]);
vector<edgew> stats;
// for (int i = 0; i < graphs[0]->image->getNumPixels(); unaries++, i++) {
// std::pair<edgew, edgew> unary_pair = *unaries;
//// cout << unary_pair.first << " " << unary_pair.second << endl;
// stats.push_back(unary_pair.first);
// }
for(int i = 1; i < spixels.getNumPairwise(); i+=2) {
auto pw = spixels.get_pairwise(0, i);
stats.push_back(-pw.w);
}
sort(stats.begin(), stats.end());
cout << stats[0] << endl;
cout << stats[stats.size() / 4] << endl;
cout << stats[stats.size() / 2] << endl;
cout << stats[stats.size() / 4 * 3] << endl;
cout << stats[stats.size() / 8 * 7] << endl;
cout << stats[stats.size() / 16 * 15] << endl;
cout << stats[stats.size() - 7] << endl;
cout << stats[stats.size() - 1] << endl;
cout << "highest" << endl;
if(params.debug){
cout << "Setup " << graphs.size() << " graphs (1 for each seed and graph type)" << endl;
}
auto cuts = nodynamic_param_maxflow(graphs);
if(params.debug){
cout << "Found " << cuts.size() / spixels.getNumPixels() << " cuts" << endl;
for (auto cur_cut = cuts.begin(); cur_cut != cuts.end(); cur_cut += spixels.getNumPixels() ) {
cv::imshow("Cut", spixels.cut_to_image(cur_cut));
cv::waitKey(0);
}
}
if(params.debug)
cv::waitKey(0);
} | 31.58209 | 121 | 0.571267 | ajmalk |
c71593765c3930e695c248de4da51db1ea5354ae | 858 | cpp | C++ | 557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii_[AC1_22ms].cpp | i-square/LeetCode | 9b15114b7a3de8638d44b3030edb72f41d9a274e | [
"MIT"
] | 1 | 2019-10-09T11:25:10.000Z | 2019-10-09T11:25:10.000Z | 557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii_[AC1_22ms].cpp | i-square/LeetCode | 9b15114b7a3de8638d44b3030edb72f41d9a274e | [
"MIT"
] | null | null | null | 557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii_[AC1_22ms].cpp | i-square/LeetCode | 9b15114b7a3de8638d44b3030edb72f41d9a274e | [
"MIT"
] | 1 | 2021-03-31T08:45:51.000Z | 2021-03-31T08:45:51.000Z | // Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
//
// Example 1:
//
// Input: "Let's take LeetCode contest"
// Output: "s'teL ekat edoCteeL tsetnoc"
//
//
//
// Note:
// In the string, each word is separated by single space and there will not be any extra space in the string.
class Solution {
public:
void myReverse(char *a, char *b) {
while (a < b) {
*a ^= *b ^= *a ^= *b;
++a;
--b;
}
}
string reverseWords(string s) {
int i = 0, j = 0;
for (i = 0; i < s.size(); ++i) {
if (s[i] == ' ') {
myReverse(&s[j], &s[i - 1]);
j = i + 1;
}
}
myReverse(&s[j], &s[i - 1]);
return s;
}
};
| 23.833333 | 151 | 0.484848 | i-square |
c716f6f316a208d71eeeff6b0fb0b84bb82eaaae | 443 | hpp | C++ | Game.hpp | JTuthill01/Nightmare | e4b712e28c228c66a33664418cc176cf527c28c9 | [
"MIT"
] | null | null | null | Game.hpp | JTuthill01/Nightmare | e4b712e28c228c66a33664418cc176cf527c28c9 | [
"MIT"
] | null | null | null | Game.hpp | JTuthill01/Nightmare | e4b712e28c228c66a33664418cc176cf527c28c9 | [
"MIT"
] | null | null | null | #pragma once
#include <States/States.hpp>
#include <States/MainMenuState.hpp>
class Game
{
public:
Game();
~Game();
void run();
private:
void initWindow();
void render();
void update(const float& deltaTime);
void updateDeltaTime();
void initStates();
void events();
bool isClosed;
float mDeltaTime;
sf::RenderWindow* mWindow;
sf::Event e;
sf::Clock mClock;
std::stack<States*> mStates;
};
| 13.84375 | 38 | 0.641084 | JTuthill01 |
c718f61968dd07a288759f568967812dd56075ea | 2,065 | cpp | C++ | GTEngine/Source/Graphics/GL4/GteGL4RasterizerState.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | 4 | 2019-03-03T18:13:30.000Z | 2020-08-25T18:15:30.000Z | GTEngine/Source/Graphics/GL4/GteGL4RasterizerState.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | null | null | null | GTEngine/Source/Graphics/GL4/GteGL4RasterizerState.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | 6 | 2016-07-15T11:04:52.000Z | 2021-12-07T03:11:42.000Z | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#include <GTEnginePCH.h>
#include <LowLevel/GteLogger.h>
#include <Graphics/GL4/GteGL4RasterizerState.h>
using namespace gte;
GL4RasterizerState::GL4RasterizerState(RasterizerState const* rasterizerState)
:
GL4DrawingState(rasterizerState)
{
mFillMode = msFillMode[rasterizerState->fillMode];
mCullFace = msCullFace[rasterizerState->cullMode];
mFrontFace = (rasterizerState->frontCCW ? GL_CCW : GL_CW);
mDepthScale = rasterizerState->slopeScaledDepthBias;
mDepthBias = static_cast<float>(rasterizerState->depthBias);
mEnableScissor = (rasterizerState->enableScissor ? GL_TRUE : GL_FALSE);
}
std::shared_ptr<GEObject> GL4RasterizerState::Create(void*, GraphicsObject const* object)
{
if (object->GetType() == GT_RASTERIZER_STATE)
{
return std::make_shared<GL4RasterizerState>(
static_cast<RasterizerState const*>(object));
}
LogError("Invalid object type.");
return nullptr;
}
void GL4RasterizerState::Enable()
{
glPolygonMode(GL_FRONT_AND_BACK, mFillMode);
if (mCullFace != 0)
{
glEnable(GL_CULL_FACE);
glFrontFace(mFrontFace);
glCullFace(mCullFace);
}
else
{
glDisable(GL_CULL_FACE);
}
if (mDepthScale != 0.0f && mDepthBias != 0.0f)
{
glEnable(GL_POLYGON_OFFSET_FILL);
glEnable(GL_POLYGON_OFFSET_LINE);
glEnable(GL_POLYGON_OFFSET_POINT);
glPolygonOffset(mDepthScale, mDepthBias);
}
else
{
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_POLYGON_OFFSET_LINE);
glDisable(GL_POLYGON_OFFSET_POINT);
}
}
GLenum const GL4RasterizerState::msFillMode[] =
{
GL_FILL,
GL_LINE
};
GLenum const GL4RasterizerState::msCullFace[] =
{
0,
GL_FRONT,
GL_BACK
};
| 25.8125 | 89 | 0.6954 | pmjoniak |
c719344b3a34a9cd42a6bcc89c762dffc9340924 | 5,551 | cc | C++ | build/X86/mem/XBar.py.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/X86/mem/XBar.py.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | build/X86/mem/XBar.py.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_XBar[] = {
120,156,165,86,225,110,27,69,16,222,59,251,236,196,118,98,
199,73,220,34,40,92,11,8,83,104,140,144,34,33,129,16,
4,20,9,41,73,171,115,139,138,133,100,109,238,214,241,133,
187,219,211,237,154,218,253,73,249,201,19,240,34,188,15,47,
2,51,115,119,27,167,53,73,73,227,100,179,51,158,221,157,
249,230,155,217,245,89,241,83,129,191,111,92,139,169,191,97,
18,192,175,197,34,198,98,198,70,140,89,40,219,44,178,88,
108,177,145,149,203,21,22,217,236,113,49,171,228,179,42,139,
170,44,118,216,200,1,27,135,9,198,38,22,11,106,236,119,
198,94,48,246,211,168,198,130,58,19,53,210,174,25,109,157,
5,235,165,182,97,180,107,44,104,50,225,144,182,101,180,235,
44,216,96,98,141,180,155,70,219,96,65,187,212,118,140,182,
201,130,45,38,234,164,237,26,109,139,5,219,108,216,223,129,
48,195,127,224,167,111,193,76,175,195,112,44,226,135,167,231,
194,215,185,170,6,195,112,161,180,136,115,25,135,251,23,214,
195,176,176,214,107,32,29,112,37,158,30,240,204,95,198,243,
0,241,252,3,38,0,4,192,6,8,141,108,38,42,108,84,
69,120,1,36,8,26,112,125,1,243,58,186,15,72,226,28,
192,104,176,243,38,194,137,98,171,20,29,18,55,74,177,70,
226,38,137,109,4,22,197,14,19,91,136,45,206,187,244,213,
54,19,59,8,240,11,155,141,118,153,55,236,55,192,33,175,
10,131,106,194,16,139,120,48,63,229,217,222,116,170,238,129,
252,35,68,36,51,55,149,153,118,39,48,241,101,146,128,42,
76,206,220,152,3,24,153,82,119,175,54,83,17,255,85,40,
213,1,171,195,76,38,90,36,129,27,113,248,231,47,84,27,
149,50,123,198,179,11,29,26,122,66,165,50,81,194,40,223,
3,229,247,92,243,148,235,169,251,44,12,96,76,69,113,94,
255,116,161,133,250,88,61,0,155,71,43,28,224,137,43,83,
29,202,132,71,110,32,38,124,22,233,194,169,79,113,133,200,
192,62,118,121,16,100,224,38,68,149,166,184,10,55,209,83,
97,86,224,81,253,30,102,27,243,59,30,39,60,22,227,177,
110,144,16,203,96,22,161,136,56,234,69,42,104,242,56,155,
9,178,230,167,74,103,28,168,129,214,254,124,62,158,10,30,
136,76,183,13,114,67,244,7,157,215,14,102,2,37,221,49,
223,30,19,210,244,53,178,48,7,158,44,31,241,140,199,164,
252,110,225,71,66,209,162,73,1,243,184,64,143,206,153,228,
48,27,29,26,102,5,204,70,137,206,62,73,84,120,150,136,
128,246,39,168,201,237,37,31,234,216,18,114,88,40,206,3,
41,35,178,62,228,145,18,122,11,102,51,216,180,48,25,103,
60,57,19,125,44,130,139,65,125,8,195,96,42,99,49,120,
62,149,51,53,157,205,195,100,112,38,226,253,129,202,252,1,
178,16,203,103,47,93,16,53,63,195,37,8,126,205,162,143,
221,178,90,237,182,5,159,74,187,218,170,83,128,39,50,241,
229,84,100,34,209,151,42,207,42,43,111,231,165,202,195,154,
171,96,5,216,200,184,183,241,136,91,69,5,36,23,123,141,
139,106,232,163,31,30,70,233,33,220,30,130,224,53,46,5,
245,127,35,195,35,159,226,146,106,17,153,110,97,34,87,5,
97,218,71,178,50,8,81,101,231,78,217,59,106,36,154,14,
98,83,7,1,77,131,137,188,137,216,212,68,140,198,33,205,
6,105,160,125,180,217,121,135,186,9,40,183,16,30,138,244,
29,244,115,167,128,231,101,108,40,53,195,68,202,212,205,94,
174,220,93,252,74,68,192,99,17,184,138,108,38,97,132,141,
227,1,5,11,108,131,82,128,82,11,149,235,103,82,41,216,
146,10,47,149,97,162,93,57,113,139,211,96,175,193,107,174,
152,37,225,36,244,57,214,188,250,192,180,109,176,225,154,12,
205,170,83,17,201,228,76,185,90,238,245,187,255,145,95,15,
201,229,97,185,104,12,147,66,24,191,82,57,205,18,129,67,
10,142,234,226,228,201,209,17,165,52,95,147,135,237,221,198,
237,222,194,237,240,68,242,121,44,39,99,19,165,222,89,86,
47,133,226,153,107,8,170,30,208,215,72,10,158,44,72,165,
242,155,233,198,92,196,252,254,140,75,54,203,42,171,182,43,
93,167,91,237,86,188,119,177,107,189,194,196,227,171,153,88,
80,111,137,140,231,235,37,251,26,164,36,234,21,68,107,25,
162,225,97,106,187,32,218,50,112,192,179,208,42,61,60,146,
242,151,89,106,72,246,186,73,38,200,190,56,62,80,46,117,
180,121,24,207,98,215,135,91,197,15,245,2,153,179,76,208,
254,198,245,140,64,95,34,242,165,100,2,101,201,123,31,7,
244,202,195,20,228,13,84,196,50,91,12,195,231,130,56,17,
243,249,184,60,249,230,105,35,180,240,175,97,210,214,181,119,
43,68,137,163,207,87,183,144,47,87,38,14,82,102,222,33,
65,222,69,234,152,68,108,42,204,130,231,151,88,199,196,65,
154,144,218,33,2,72,233,8,113,111,239,35,244,189,121,25,
47,172,124,15,47,3,143,74,11,115,234,221,41,83,236,225,
6,30,222,55,222,189,55,106,162,247,193,242,55,67,92,187,
86,45,174,8,167,237,16,236,57,45,86,35,241,237,85,72,
84,8,9,187,68,162,74,141,114,9,9,28,155,136,7,6,
27,34,27,66,220,56,36,120,236,18,20,194,168,223,186,25,
50,119,223,28,158,79,192,242,79,92,210,185,12,79,165,237,
212,234,68,147,31,30,174,190,46,221,107,105,2,177,87,76,
236,182,9,182,118,109,176,55,15,7,95,108,127,225,146,181,
60,28,7,131,57,201,43,149,136,104,222,227,241,254,94,138,
143,35,69,143,26,148,50,57,95,228,165,183,191,103,94,235,
30,70,64,111,12,186,142,169,15,230,105,64,98,17,124,116,
232,141,93,166,227,191,202,31,136,95,227,158,116,89,118,172,
142,213,128,79,199,238,245,123,213,222,173,94,187,119,187,119,
231,95,158,139,213,113,
};
EmbeddedPython embedded_m5_objects_XBar(
"m5/objects/XBar.py",
"/home/zhoushuxin/gem5/src/mem/XBar.py",
"m5.objects.XBar",
data_m5_objects_XBar,
1366,
3454);
} // anonymous namespace
| 53.893204 | 66 | 0.660061 | zhoushuxin |
c71977f03a3da3cb0599c971b9a81ac72c6479ef | 2,898 | hpp | C++ | lib/sfml/src/Window.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | lib/sfml/src/Window.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | lib/sfml/src/Window.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | /*
** Window.h for Project-Master in /home/peixot_b/Epitech/Tek2/CPP/Arcade/cpp_arcade/lib/sfml/src
**
** Made by peixot_b
** Login <benjamin.peixoto@epitech.eu>
**
** Started on Thu Mar 23 13:35:43 2017 peixot_b
** Last update Thu Mar 23 13:35:45 2017 peixot_b
*/
#ifndef WINDOW_HPP_
# define WINDOW_HPP_
#include <iostream>
#include <unistd.h>
#include <memory>
#include "Vector3d.hpp"
#include "IWindows.hpp"
#include <SFML/Graphics.hpp>
namespace arcade
{
class Window : public IWindows {
public:
Window(std::shared_ptr<std::vector<std::shared_ptr<arcade::IObject>>>&, uint64_t height = 0, uint64_t width = 0);
virtual ~Window();
virtual bool isOpen() const;
virtual int32_t getHeight() const;
virtual int32_t getLenght() const;
virtual sf::RenderWindow const &get_Window() const;
virtual Vector3d const &getSize() const;
void setMapSize(uint32_t size);
virtual bool event();
virtual arcade::FrameType refresh();
virtual void addObject(std::shared_ptr<arcade::IObject> &, Vector3d const &);
virtual void addObject(std::shared_ptr<arcade::IObject> &);
virtual void moveObject(std::shared_ptr<arcade::IObject> &, Vector3d const &);
virtual void moveObject(std::string, Vector3d const &);
virtual void destroyObject(std::shared_ptr<arcade::IObject> &);
virtual std::shared_ptr<IEvenement> getEvent(void);
virtual void removeObserver(IObserver *);
virtual void registerObserver(IObserver *);
static uint32_t const WINSIZE = 1000;
static uint32_t MAPSIZE;
static float SIZECELL;
protected:
Vector3d _size;
bool _isopen;
sf::RenderWindow _window;
sf::Event _event;
std::shared_ptr<std::vector<std::shared_ptr<arcade::IObject>>> _objects;
int32_t _height;
int32_t _width;
std::vector<arcade::IObserver*> _observers;
Vector3d _min_size;
sf::Clock _clock;
sf::Int32 _calc;
virtual void notify(IEvenement const &);
};
}
#endif /* !WINDOW_HPP_ */ | 38.64 | 121 | 0.484127 | benjyup |
c71a0aa154320c6927d2607d92b198f61fcd1213 | 1,366 | hpp | C++ | Ruken/Source/Include/Containers/LinkedChunkListNode.hpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 4 | 2020-06-11T00:35:03.000Z | 2020-06-23T11:57:52.000Z | Ruken/Source/Include/Containers/LinkedChunkListNode.hpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 1 | 2020-03-17T13:34:16.000Z | 2020-03-17T13:34:16.000Z | Ruken/Source/Include/Containers/LinkedChunkListNode.hpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 2 | 2020-03-19T12:20:17.000Z | 2020-09-03T07:49:06.000Z |
#pragma once
#include <array>
#include "Build/Namespace.hpp"
#include "Types/FundamentalTypes.hpp"
BEGIN_RUKEN_NAMESPACE
/**
* \brief Represents a node in a LinkedChunkList
* \tparam TType Elements type of the node
* \tparam TChunkSize Size in octets of the chunk (node) (default is 16Kb or 2046 octets)
*/
template<typename TType, RkSize TChunkSize = 2048>
class LinkedChunkListNode
{
public:
static constexpr RkSize element_count = TChunkSize / sizeof(TType);
#pragma region Members
std::array<TType, element_count> data {};
LinkedChunkListNode<TType, TChunkSize>* next_node {nullptr};
LinkedChunkListNode<TType, TChunkSize>* prev_node {nullptr};
#pragma endregion
#pragma region Constructors
LinkedChunkListNode() = default;
LinkedChunkListNode(LinkedChunkListNode const& in_copy) = default;
LinkedChunkListNode(LinkedChunkListNode&& in_move) = default;
~LinkedChunkListNode() = default;
#pragma endregion
#pragma region Operators
LinkedChunkListNode& operator=(LinkedChunkListNode const& in_copy) = default;
LinkedChunkListNode& operator=(LinkedChunkListNode&& in_move) = default;
#pragma endregion
};
END_RUKEN_NAMESPACE | 28.458333 | 89 | 0.662518 | Renondedju |
c71d22ac5fb4586589d9b7ef1017735ebec18369 | 39,515 | cpp | C++ | Engine/Source/Developer/BlueprintNativeCodeGen/Private/BlueprintNativeCodeGenModule.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Developer/BlueprintNativeCodeGen/Private/BlueprintNativeCodeGenModule.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Developer/BlueprintNativeCodeGen/Private/BlueprintNativeCodeGenModule.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "BlueprintNativeCodeGenModule.h"
#include "Engine/Blueprint.h"
#include "HAL/FileManager.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Misc/ConfigCacheIni.h"
#include "UObject/UObjectHash.h"
#include "UObject/Package.h"
#include "Templates/Greater.h"
#include "Components/ActorComponent.h"
#include "Engine/BlueprintGeneratedClass.h"
#include "AssetData.h"
#include "Engine/UserDefinedEnum.h"
#include "Engine/UserDefinedStruct.h"
#include "Settings/ProjectPackagingSettings.h"
#include "PlatformInfo.h"
#include "AssetRegistryModule.h"
#include "BlueprintNativeCodeGenManifest.h"
#include "Blueprint/BlueprintSupport.h"
#include "BlueprintCompilerCppBackendInterface.h"
#include "IBlueprintCompilerCppBackendModule.h"
#include "BlueprintNativeCodeGenUtils.h"
#include "Engine/SCS_Node.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "Engine/InheritableComponentHandler.h"
#include "Animation/AnimBlueprint.h"
#include "Interfaces/ITargetPlatform.h"
/*******************************************************************************
* FBlueprintNativeCodeGenModule
******************************************************************************/
class FBlueprintNativeCodeGenModule : public IBlueprintNativeCodeGenModule
, public IBlueprintNativeCodeGenCore
{
public:
FBlueprintNativeCodeGenModule()
{
}
//~ Begin IModuleInterface interface
virtual void ShutdownModule();
//~ End IModuleInterface interface
//~ Begin IBlueprintNativeCodeGenModule interface
virtual void Convert(UPackage* Package, ESavePackageResult ReplacementType, const FName PlatformName) override;
virtual void SaveManifest() override;
virtual void MergeManifest(int32 ManifestIdentifier) override;
virtual void FinalizeManifest() override;
virtual void GenerateStubs() override;
virtual void GenerateFullyConvertedClasses() override;
void MarkUnconvertedBlueprintAsNecessary(TSoftObjectPtr<UBlueprint> BPPtr, const FCompilerNativizationOptions& NativizationOptions) override;
virtual const TMultiMap<FName, TSoftClassPtr<UObject>>& GetFunctionsBoundToADelegate() override;
FFileHelper::EEncodingOptions ForcedEncoding() const
{
return FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM;
}
virtual const FCompilerNativizationOptions& GetNativizationOptionsForPlatform(const ITargetPlatform* Platform) const override;
virtual void FillPlatformNativizationDetails(const ITargetPlatform* Platform, FPlatformNativizationDetails& OutDetails) override;
protected:
virtual void Initialize(const FNativeCodeGenInitData& InitData) override;
virtual void InitializeForRerunDebugOnly(const TArray<FPlatformNativizationDetails>& CodegenTargets) override;
//~ End IBlueprintNativeCodeGenModule interface
//~ Begin FScriptCookReplacmentCoordinator interface
virtual EReplacementResult IsTargetedForReplacement(const UPackage* Package, const FCompilerNativizationOptions& NativizationOptions) const override;
virtual EReplacementResult IsTargetedForReplacement(const UObject* Object, const FCompilerNativizationOptions& NativizationOptions) const override;
virtual UClass* FindReplacedClassForObject(const UObject* Object, const FCompilerNativizationOptions& NativizationOptions) const override;
virtual UObject* FindReplacedNameAndOuter(UObject* Object, FName& OutName, const FCompilerNativizationOptions& NativizationOptions) const override;
//~ End FScriptCookReplacmentCoordinator interface
private:
void ReadConfig();
void FillTargetedForReplacementQuery();
void FillIsFunctionUsedInADelegate();
FBlueprintNativeCodeGenManifest& GetManifest(const FName PlatformName);
void GenerateSingleStub(UBlueprint* BP, const FName PlatformName);
void CollectBoundFunctions(UBlueprint* BP);
void GenerateSingleAsset(UField* ForConversion, const FName PlatformName, TSharedPtr<FNativizationSummary> NativizationSummary = TSharedPtr<FNativizationSummary>());
struct FStatePerPlatform
{
// A stub-wrapper must be generated only if the BP is really accessed/required by some other generated code.
TSet<TSoftObjectPtr<UBlueprint>> StubsRequiredByGeneratedCode;
TSet<TSoftObjectPtr<UStruct>> UDSAssetsToGenerate;
TSet<TSoftObjectPtr<UBlueprint>> BPAssetsToGenerate;
// Cached values from IsTargetedForReplacement
mutable TMap<FSoftObjectPath, EReplacementResult> CachedIsTargetedForReplacement;
};
TMap< FName, FStatePerPlatform > StatesPerPlatform;
TMap< FName, TUniquePtr<FBlueprintNativeCodeGenManifest> > Manifests;
// Children of these classes won't be nativized
TArray<FString> ExcludedAssetTypes;
// Eg: +ExcludedBlueprintTypes=/Script/Engine.AnimBlueprint
TArray<TSoftClassPtr<UBlueprint>> ExcludedBlueprintTypes;
// Individually excluded assets
TSet<FSoftObjectPath> ExcludedAssets;
// Excluded folders. It excludes only BPGCs, enums and structures are still converted.
TArray<FString> ExcludedFolderPaths;
TArray<FName> TargetPlatformNames;
TMultiMap<FName, TSoftClassPtr<UObject>> FunctionsBoundToADelegate; // is a function could be bound to a delegate, then it must have UFUNCTION macro. So we cannot optimize it.
};
const FCompilerNativizationOptions& FBlueprintNativeCodeGenModule::GetNativizationOptionsForPlatform(const ITargetPlatform* Platform) const
{
const FName PlatformName = ensure(Platform) ? Platform->GetPlatformInfo().PlatformInfoName : NAME_None;
const TUniquePtr<FBlueprintNativeCodeGenManifest>* Result = Manifests.Find(PlatformName);
if (ensure(Result && Result->IsValid()))
{
const FBlueprintNativeCodeGenManifest& Manifest = **Result;
return Manifest.GetCompilerNativizationOptions();
}
UE_LOG(LogBlueprintCodeGen, Error, TEXT("Cannot find manifest for platform: %s"), *PlatformName.ToString());
static const FCompilerNativizationOptions FallbackNativizationOptions{};
return FallbackNativizationOptions;
}
void FBlueprintNativeCodeGenModule::ReadConfig()
{
GConfig->GetArray(TEXT("BlueprintNativizationSettings"), TEXT("ExcludedAssetTypes"), ExcludedAssetTypes, GEditorIni);
{
TArray<FString> ExcludedBlueprintTypesPath;
GConfig->GetArray(TEXT("BlueprintNativizationSettings"), TEXT("ExcludedBlueprintTypes"), ExcludedBlueprintTypesPath, GEditorIni);
for (FString& Path : ExcludedBlueprintTypesPath)
{
TSoftClassPtr<UBlueprint> ClassPtr;
ClassPtr = FSoftObjectPath(Path);
ClassPtr.LoadSynchronous();
ExcludedBlueprintTypes.Add(ClassPtr);
}
}
TArray<FString> ExcludedAssetPaths;
GConfig->GetArray(TEXT("BlueprintNativizationSettings"), TEXT("ExcludedAssets"), ExcludedAssetPaths, GEditorIni);
for (FString& Path : ExcludedAssetPaths)
{
ExcludedAssets.Add(FSoftObjectPath(Path));
}
GConfig->GetArray(TEXT("BlueprintNativizationSettings"), TEXT("ExcludedFolderPaths"), ExcludedFolderPaths, GEditorIni);
}
void FBlueprintNativeCodeGenModule::MarkUnconvertedBlueprintAsNecessary(TSoftObjectPtr<UBlueprint> BPPtr, const FCompilerNativizationOptions& NativizationOptions)
{
FStatePerPlatform* StateForCurrentPlatform = StatesPerPlatform.Find(NativizationOptions.PlatformName);
if (ensure(StateForCurrentPlatform))
{
StateForCurrentPlatform->StubsRequiredByGeneratedCode.Add(BPPtr);
}
}
void FBlueprintNativeCodeGenModule::FillTargetedForReplacementQuery()
{
IBlueprintCompilerCppBackendModule& BackEndModule = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
auto& ConversionQueryDelegate = BackEndModule.OnIsTargetedForConversionQuery();
auto ShouldConvert = [](const UObject* AssetObj, const FCompilerNativizationOptions& NativizationOptions)
{
if (ensure(IBlueprintNativeCodeGenCore::Get()))
{
EReplacementResult ReplacmentResult = IBlueprintNativeCodeGenCore::Get()->IsTargetedForReplacement(AssetObj, NativizationOptions);
return ReplacmentResult == EReplacementResult::ReplaceCompletely;
}
return false;
};
ConversionQueryDelegate.BindStatic(ShouldConvert);
auto LocalMarkUnconvertedBlueprintAsNecessary = [](TSoftObjectPtr<UBlueprint> BPPtr, const FCompilerNativizationOptions& NativizationOptions)
{
IBlueprintNativeCodeGenModule::Get().MarkUnconvertedBlueprintAsNecessary(BPPtr, NativizationOptions);
};
BackEndModule.OnIncludingUnconvertedBP().BindStatic(LocalMarkUnconvertedBlueprintAsNecessary);
}
namespace
{
void GetFieldFormPackage(const UPackage* Package, UStruct*& OutStruct, UEnum*& OutEnum, EObjectFlags ExcludedFlags = RF_Transient)
{
TArray<UObject*> Objects;
GetObjectsWithOuter(Package, Objects, false);
for (UObject* Entry : Objects)
{
if (Entry->HasAnyFlags(ExcludedFlags))
{
continue;
}
if (FBlueprintSupport::IsDeferredDependencyPlaceholder(Entry))
{
continue;
}
// Not a skeleton class
if (UClass* AsClass = Cast<UClass>(Entry))
{
if (UBlueprint* GeneratingBP = Cast<UBlueprint>(AsClass->ClassGeneratedBy))
{
if (AsClass != GeneratingBP->GeneratedClass)
{
continue;
}
}
}
OutStruct = Cast<UStruct>(Entry);
if (OutStruct)
{
break;
}
OutEnum = Cast<UEnum>(Entry);
if (OutEnum)
{
break;
}
}
}
}
void FBlueprintNativeCodeGenModule::CollectBoundFunctions(UBlueprint* BP)
{
TArray<UFunction*> Functions = IBlueprintCompilerCppBackendModule::CollectBoundFunctions(BP);
for (UFunction* Func : Functions)
{
if (Func)
{
FunctionsBoundToADelegate.AddUnique(Func->GetFName(), Func->GetOwnerClass());
}
}
}
const TMultiMap<FName, TSoftClassPtr<UObject>>& FBlueprintNativeCodeGenModule::GetFunctionsBoundToADelegate()
{
return FunctionsBoundToADelegate;
}
void FBlueprintNativeCodeGenModule::FillIsFunctionUsedInADelegate()
{
IBlueprintCompilerCppBackendModule& BackEndModule = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
auto IsFunctionUsed = [](const UFunction* InFunction) -> bool
{
auto& TargetFunctionsBoundToADelegate = IBlueprintNativeCodeGenModule::Get().GetFunctionsBoundToADelegate();
return InFunction && (nullptr != TargetFunctionsBoundToADelegate.FindPair(InFunction->GetFName(), InFunction->GetOwnerClass()));
};
BackEndModule.GetIsFunctionUsedInADelegateCallback().BindStatic(IsFunctionUsed);
}
void FBlueprintNativeCodeGenModule::Initialize(const FNativeCodeGenInitData& InitData)
{
StatesPerPlatform.Reset();
for (const FPlatformNativizationDetails& Platform : InitData.CodegenTargets)
{
StatesPerPlatform.Add(Platform.PlatformName);
}
ReadConfig();
IBlueprintNativeCodeGenCore::Register(this);
// Each platform will need a manifest, because each platform could cook different assets:
for (const FPlatformNativizationDetails& Platform : InitData.CodegenTargets)
{
const FString TargetPath = FBlueprintNativeCodeGenPaths::GetDefaultPluginPath(Platform.PlatformName);
const FBlueprintNativeCodeGenManifest& Manifest = *Manifests.Add(Platform.PlatformName, TUniquePtr<FBlueprintNativeCodeGenManifest>(new FBlueprintNativeCodeGenManifest(TargetPath, Platform.CompilerNativizationOptions, InitData.ManifestIdentifier)));
TargetPlatformNames.Add(Platform.PlatformName);
// Clear source code folder
const FString SourceCodeDir = Manifest.GetTargetPaths().PluginRootDir();
UE_LOG(LogBlueprintCodeGen, Log, TEXT("Clear nativized source code directory: %s"), *SourceCodeDir);
IFileManager::Get().DeleteDirectory(*SourceCodeDir, false, true);
}
FillTargetedForReplacementQuery();
FillIsFunctionUsedInADelegate();
}
void FBlueprintNativeCodeGenModule::InitializeForRerunDebugOnly(const TArray<FPlatformNativizationDetails>& CodegenTargets)
{
StatesPerPlatform.Reset();
for (const FPlatformNativizationDetails& Platform : CodegenTargets)
{
StatesPerPlatform.Add(Platform.PlatformName);
}
ReadConfig();
IBlueprintNativeCodeGenCore::Register(this);
FillTargetedForReplacementQuery();
FillIsFunctionUsedInADelegate();
for (const FPlatformNativizationDetails& Platform : CodegenTargets)
{
// load the old manifest:
FString OutputPath = FBlueprintNativeCodeGenPaths::GetDefaultManifestFilePath(Platform.PlatformName);
Manifests.Add(Platform.PlatformName, TUniquePtr<FBlueprintNativeCodeGenManifest>(new FBlueprintNativeCodeGenManifest(FPaths::ConvertRelativePathToFull(OutputPath))));
//FBlueprintNativeCodeGenManifest OldManifest(FPaths::ConvertRelativePathToFull(OutputPath));
// reconvert every assets listed in the manifest:
for (const auto& ConversionTarget : GetManifest(Platform.PlatformName).GetConversionRecord())
{
// load the package:
UPackage* Package = LoadPackage(nullptr, *ConversionTarget.Value.TargetObjPath, LOAD_None);
if (!Package)
{
UE_LOG(LogBlueprintCodeGen, Error, TEXT("Unable to load the package: %s"), *ConversionTarget.Value.TargetObjPath);
continue;
}
// reconvert it
Convert(Package, ESavePackageResult::ReplaceCompletely, Platform.PlatformName);
}
// reconvert every unconverted dependency listed in the manifest:
for (const auto& ConversionTarget : GetManifest(Platform.PlatformName).GetUnconvertedDependencies())
{
// load the package:
UPackage* Package = LoadPackage(nullptr, *ConversionTarget.Key.GetPlainNameString(), LOAD_None);
UStruct* Struct = nullptr;
UEnum* Enum = nullptr;
GetFieldFormPackage(Package, Struct, Enum);
UBlueprint* BP = Cast<UBlueprint>(CastChecked<UClass>(Struct)->ClassGeneratedBy);
if (ensure(BP))
{
CollectBoundFunctions(BP);
GenerateSingleStub(BP, Platform.PlatformName);
}
}
FStatePerPlatform* State = StatesPerPlatform.Find(Platform.PlatformName);
check(State);
for (TSoftObjectPtr<UStruct>& UDSPtr : State->UDSAssetsToGenerate)
{
UStruct* UDS = UDSPtr.LoadSynchronous();
if (ensure(UDS))
{
GenerateSingleAsset(UDS, Platform.PlatformName);
}
}
for (TSoftObjectPtr<UBlueprint>& BPPtr : State->BPAssetsToGenerate)
{
UBlueprint* BP = BPPtr.LoadSynchronous();
if (ensure(BP))
{
GenerateSingleAsset(BP->GeneratedClass, Platform.PlatformName);
}
}
}
}
void FBlueprintNativeCodeGenModule::ShutdownModule()
{
// Clear the current coordinator reference.
IBlueprintNativeCodeGenCore::Register(nullptr);
// Reset compiler module delegate function bindings.
IBlueprintCompilerCppBackendModule& BackEndModule = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
BackEndModule.GetIsFunctionUsedInADelegateCallback().Unbind();
BackEndModule.OnIsTargetedForConversionQuery().Unbind();
BackEndModule.OnIncludingUnconvertedBP().Unbind();
}
void FBlueprintNativeCodeGenModule::GenerateFullyConvertedClasses()
{
TSharedPtr<FNativizationSummary> NativizationSummary(new FNativizationSummary());
{
IBlueprintCompilerCppBackendModule& CodeGenBackend = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
CodeGenBackend.NativizationSummary() = NativizationSummary;
}
for (const FName& PlatformName : TargetPlatformNames)
{
FStatePerPlatform* State = StatesPerPlatform.Find(PlatformName);
check(State);
for (TSoftObjectPtr<UStruct>& UDSPtr : State->UDSAssetsToGenerate)
{
UStruct* UDS = UDSPtr.LoadSynchronous();
if (ensure(UDS))
{
GenerateSingleAsset(UDS, PlatformName, NativizationSummary);
}
}
for (TSoftObjectPtr<UBlueprint>& BPPtr : State->BPAssetsToGenerate)
{
UBlueprint* BP = BPPtr.LoadSynchronous();
if (ensure(BP))
{
GenerateSingleAsset(BP->GeneratedClass, PlatformName, NativizationSummary);
}
}
}
if (NativizationSummary->InaccessiblePropertyStat.Num())
{
UE_LOG(LogBlueprintCodeGen, Display, TEXT("Nativization Summary - Inaccessible Properties:"));
NativizationSummary->InaccessiblePropertyStat.ValueSort(TGreater<int32>());
for (auto& Iter : NativizationSummary->InaccessiblePropertyStat)
{
UE_LOG(LogBlueprintCodeGen, Display, TEXT("\t %s \t - %d"), *Iter.Key.ToString(), Iter.Value);
}
}
{
UE_LOG(LogBlueprintCodeGen, Display, TEXT("Nativization Summary - AnimBP:"));
UE_LOG(LogBlueprintCodeGen, Display, TEXT("Name, Children, Non-empty Functions (Empty Functions), Variables, FunctionUsage, VariableUsage"));
for (auto& Iter : NativizationSummary->AnimBlueprintStat)
{
UE_LOG(LogBlueprintCodeGen, Display
, TEXT("%s, %d, %d (%d), %d, %d, %d")
, *Iter.Key.ToString()
, Iter.Value.Children
, Iter.Value.Functions - Iter.Value.ReducibleFunctions
, Iter.Value.ReducibleFunctions
, Iter.Value.Variables
, Iter.Value.FunctionUsage
, Iter.Value.VariableUsage);
}
}
UE_LOG(LogBlueprintCodeGen, Display, TEXT("Nativization Summary - Shared Variables From Graph: %d"), NativizationSummary->MemberVariablesFromGraph);
}
FBlueprintNativeCodeGenManifest& FBlueprintNativeCodeGenModule::GetManifest(const FName PlatformName)
{
TUniquePtr<FBlueprintNativeCodeGenManifest>* Result = Manifests.Find(PlatformName);
check(Result->IsValid());
return **Result;
}
void FBlueprintNativeCodeGenModule::GenerateSingleStub(UBlueprint* BP, const FName PlatformName)
{
if (!ensure(BP))
{
return;
}
UClass* Class = BP->GeneratedClass;
if (!ensure(Class))
{
return;
}
// no PCHFilename should be necessary
const IAssetRegistry& Registry = FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry").Get();
FAssetData AssetInfo = Registry.GetAssetByObjectPath(*Class->GetPathName());
FString FileContents;
TUniquePtr<IBlueprintCompilerCppBackend> Backend_CPP(IBlueprintCompilerCppBackendModuleInterface::Get().Create());
// Apparently we can only generate wrappers for classes, so any logic that results in non classes requesting
// wrappers will fail here:
FileContents = Backend_CPP->GenerateWrapperForClass(Class, GetManifest(PlatformName).GetCompilerNativizationOptions());
if (!FileContents.IsEmpty())
{
FFileHelper::SaveStringToFile(FileContents
, *(GetManifest(PlatformName).CreateUnconvertedDependencyRecord(AssetInfo.PackageName, AssetInfo).GeneratedWrapperPath)
, ForcedEncoding());
}
// The stub we generate still may have dependencies on other modules, so make sure the module dependencies are
// still recorded so that the .build.cs is generated correctly. Without this you'll get include related errors
// (or possibly linker errors) in stub headers:
GetManifest(PlatformName).GatherModuleDependencies(BP->GetOutermost());
}
void FBlueprintNativeCodeGenModule::GenerateSingleAsset(UField* ForConversion, const FName PlatformName, TSharedPtr<FNativizationSummary> NativizationSummary)
{
IBlueprintCompilerCppBackendModule& BackEndModule = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
auto& BackendPCHQuery = BackEndModule.OnPCHFilenameQuery();
const IAssetRegistry& Registry = FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry").Get();
FAssetData AssetInfo = Registry.GetAssetByObjectPath(*ForConversion->GetPathName());
FBlueprintNativeCodeGenPaths TargetPaths = GetManifest(PlatformName).GetTargetPaths();
BackendPCHQuery.BindLambda([TargetPaths]()->FString
{
return TargetPaths.RuntimePCHFilename();
});
FConvertedAssetRecord& ConversionRecord = GetManifest(PlatformName).CreateConversionRecord(*ForConversion->GetPathName(), AssetInfo);
TSharedPtr<FString> HeaderSource(new FString());
TSharedPtr<FString> CppSource(new FString());
FBlueprintNativeCodeGenUtils::GenerateCppCode(ForConversion, HeaderSource, CppSource, NativizationSummary, GetManifest(PlatformName).GetCompilerNativizationOptions());
bool bSuccess = !HeaderSource->IsEmpty() || !CppSource->IsEmpty();
// Run the cpp first, because we cue off of the presence of a header for a valid conversion record (see
// FConvertedAssetRecord::IsValid)
if (!CppSource->IsEmpty())
{
if (!FFileHelper::SaveStringToFile(*CppSource, *ConversionRecord.GeneratedCppPath, ForcedEncoding()))
{
bSuccess &= false;
ConversionRecord.GeneratedCppPath.Empty();
}
CppSource->Empty(CppSource->Len());
}
else
{
ConversionRecord.GeneratedCppPath.Empty();
}
if (bSuccess && !HeaderSource->IsEmpty())
{
if (!FFileHelper::SaveStringToFile(*HeaderSource, *ConversionRecord.GeneratedHeaderPath, ForcedEncoding()))
{
bSuccess &= false;
ConversionRecord.GeneratedHeaderPath.Empty();
}
HeaderSource->Empty(HeaderSource->Len());
}
else
{
ConversionRecord.GeneratedHeaderPath.Empty();
}
if (bSuccess)
{
GetManifest(PlatformName).GatherModuleDependencies(ForConversion->GetOutermost());
}
else
{
UE_LOG(LogBlueprintCodeGen, Error, TEXT("FBlueprintNativeCodeGenModule::GenerateSingleAsset error: %s"), *GetPathNameSafe(ForConversion));
}
BackendPCHQuery.Unbind();
}
void FBlueprintNativeCodeGenModule::GenerateStubs()
{
for (FName& PlatformName : TargetPlatformNames)
{
FStatePerPlatform* StateForCurrentPlatform = StatesPerPlatform.Find(PlatformName);
if (!ensure(StateForCurrentPlatform))
{
continue;
}
TSet<TSoftObjectPtr<UBlueprint>> AlreadyGenerated;
while (AlreadyGenerated.Num() < StateForCurrentPlatform->StubsRequiredByGeneratedCode.Num())
{
const int32 OldGeneratedNum = AlreadyGenerated.Num();
TSet<TSoftObjectPtr<UBlueprint>> LocalCopyStubsRequiredByGeneratedCode = StateForCurrentPlatform->StubsRequiredByGeneratedCode;
for (TSoftObjectPtr<UBlueprint>& BPPtr : LocalCopyStubsRequiredByGeneratedCode)
{
bool bAlreadyGenerated = false;
AlreadyGenerated.Add(BPPtr, &bAlreadyGenerated);
if (bAlreadyGenerated)
{
continue;
}
GenerateSingleStub(BPPtr.LoadSynchronous(), PlatformName);
}
// make sure there was any progress
if (!ensure(OldGeneratedNum != AlreadyGenerated.Num()))
{
break;
}
}
}
}
void FBlueprintNativeCodeGenModule::Convert(UPackage* Package, ESavePackageResult CookResult, const FName PlatformName)
{
// Find the struct/enum to convert:
UStruct* Struct = nullptr;
UEnum* Enum = nullptr;
GetFieldFormPackage(Package, Struct, Enum);
// First we gather information about bound functions.
UClass* AsClass = Cast<UClass>(Struct);
UBlueprint* BP = AsClass ? Cast<UBlueprint>(AsClass->ClassGeneratedBy) : nullptr;
if (BP)
{
CollectBoundFunctions(BP);
}
if (CookResult != ESavePackageResult::ReplaceCompletely && CookResult != ESavePackageResult::GenerateStub)
{
// nothing to convert
return;
}
if (Struct == nullptr && Enum == nullptr)
{
ensure(false);
return;
}
FStatePerPlatform* State = StatesPerPlatform.Find(PlatformName);
if (!ensure(State))
{
return;
}
if (CookResult == ESavePackageResult::GenerateStub)
{
// No stub is generated for structs and enums.
ensure(!BP || !State->BPAssetsToGenerate.Contains(BP));
}
else
{
check(CookResult == ESavePackageResult::ReplaceCompletely);
if (AsClass)
{
if (ensure(BP))
{
State->BPAssetsToGenerate.Add(BP);
}
}
else if (Struct)
{
State->UDSAssetsToGenerate.Add(Struct);
}
else
{
GenerateSingleAsset((UField*)Enum, PlatformName);
}
}
}
void FBlueprintNativeCodeGenModule::SaveManifest()
{
for (FName& PlatformName : TargetPlatformNames)
{
GetManifest(PlatformName).Save();
}
}
void FBlueprintNativeCodeGenModule::MergeManifest(int32 ManifestIdentifier)
{
for (FName& PlatformName : TargetPlatformNames)
{
FBlueprintNativeCodeGenManifest& CurrentManifest = GetManifest(PlatformName);
FBlueprintNativeCodeGenManifest OtherManifest = FBlueprintNativeCodeGenManifest(CurrentManifest.GetTargetPaths().ManifestFilePath(ManifestIdentifier));
CurrentManifest.Merge(OtherManifest);
}
}
void FBlueprintNativeCodeGenModule::FinalizeManifest()
{
IBlueprintCompilerCppBackendModule& CodeGenBackend = (IBlueprintCompilerCppBackendModule&)IBlueprintCompilerCppBackendModule::Get();
TSharedPtr<FNativizationSummary> NativizationSummary = CodeGenBackend.NativizationSummary();
for(FName& PlatformName : TargetPlatformNames)
{
FBlueprintNativeCodeGenManifest& Manifest = GetManifest(PlatformName);
if (Manifest.GetConversionRecord().Num() > 0)
{
if (NativizationSummary.IsValid())
{
TSet<TSoftObjectPtr<UPackage>>* RequiredModules = NativizationSummary->ModulesRequiredByPlatform.Find(Manifest.GetCompilerNativizationOptions().PlatformName);
if (RequiredModules)
{
for (TSoftObjectPtr<UPackage> ItPackage : *RequiredModules)
{
if (UPackage* Pkg = ItPackage.Get())
{
Manifest.AddSingleModuleDependency(Pkg);
}
}
}
}
ensure(Manifest.GetManifestChunkId() == -1); // ensure this was intended to be the root manifest
Manifest.Save();
check(FBlueprintNativeCodeGenUtils::FinalizePlugin(Manifest));
}
}
}
UClass* FBlueprintNativeCodeGenModule::FindReplacedClassForObject(const UObject* Object, const FCompilerNativizationOptions& NativizationOptions) const
{
// we're only looking to replace class types:
if (Object && Object->IsA<UField>())
{
if (IsTargetedForReplacement(Object, NativizationOptions) == EReplacementResult::ReplaceCompletely)
{
for (const UClass* Class = Object->GetClass(); Class; Class = Class->GetSuperClass())
{
if (Class == UUserDefinedEnum::StaticClass())
{
return UEnum::StaticClass();
}
if (Class == UUserDefinedStruct::StaticClass())
{
return UScriptStruct::StaticClass();
}
if (Class == UBlueprintGeneratedClass::StaticClass())
{
return UDynamicClass::StaticClass();
}
}
}
else if (const UByteProperty* ByteProperty = Cast<UByteProperty>(Object))
{
// User-Defined Enum values are compiled as Byte properties, but get converted to Enum class properties during nativization. Thus,
// we have to account for that here and switch the property class to be an Enum property, since that's what will be generated by UHT.
// If we don't do this, then a dependent asset's import table will contain the incorrect property class for this value, if referenced.
if (ByteProperty->Enum && IsTargetedForReplacement(ByteProperty->Enum, NativizationOptions) == EReplacementResult::ReplaceCompletely)
{
return UEnumProperty::StaticClass();
}
}
}
return nullptr;
}
UObject* FBlueprintNativeCodeGenModule::FindReplacedNameAndOuter(UObject* Object, FName& OutName, const FCompilerNativizationOptions& NativizationOptions) const
{
OutName = NAME_None;
auto GetOuterBPGC = [](UObject* FirstOuter) -> UBlueprintGeneratedClass*
{
UBlueprintGeneratedClass* BPGC = nullptr;
for (UObject* OuterObject = FirstOuter; OuterObject && !BPGC; OuterObject = OuterObject->GetOuter())
{
if (OuterObject->HasAnyFlags(RF_ClassDefaultObject))
{
return nullptr;
}
BPGC = Cast<UBlueprintGeneratedClass>(OuterObject);
}
return BPGC;
};
UActorComponent* ActorComponent = Cast<UActorComponent>(Object);
if (ActorComponent)
{
//if is child of a BPGC and not child of a CDO
UBlueprintGeneratedClass* BPGC = GetOuterBPGC(ActorComponent->GetOuter());
FName NewName = NAME_None;
UObject* OuterCDO = nullptr;
for (UBlueprintGeneratedClass* SuperBPGC = BPGC; SuperBPGC && (NewName == NAME_None); SuperBPGC = Cast<UBlueprintGeneratedClass>(SuperBPGC->GetSuperClass()))
{
if (SuperBPGC->InheritableComponentHandler)
{
FComponentKey FoundKey = SuperBPGC->InheritableComponentHandler->FindKey(ActorComponent);
if (FoundKey.IsValid())
{
NewName = FoundKey.IsSCSKey() ? FoundKey.GetSCSVariableName() : ActorComponent->GetFName();
OuterCDO = BPGC->GetDefaultObject(false);
break;
}
}
if (SuperBPGC->SimpleConstructionScript)
{
for (auto Node : SuperBPGC->SimpleConstructionScript->GetAllNodes())
{
if (Node->ComponentTemplate == ActorComponent)
{
NewName = Node->GetVariableName();
if (NewName != NAME_None)
{
OuterCDO = BPGC->GetDefaultObject(false);
break;
}
}
}
}
}
if (OuterCDO && (EReplacementResult::ReplaceCompletely == IsTargetedForReplacement(OuterCDO->GetClass(), NativizationOptions)))
{
OutName = NewName;
UE_LOG(LogBlueprintCodeGen, Log, TEXT("Object '%s' has replaced name '%s' and outer: '%s'"), *GetPathNameSafe(Object), *OutName.ToString(), *GetPathNameSafe(OuterCDO));
return OuterCDO;
}
}
else
{
UChildActorComponent* OuterCAC = Cast<UChildActorComponent>(Object->GetOuter());
if (OuterCAC && OuterCAC->GetChildActorTemplate() == Object)
{
UBlueprintGeneratedClass* BPGC = GetOuterBPGC(OuterCAC->GetOuter());
if (BPGC && (EReplacementResult::ReplaceCompletely == IsTargetedForReplacement(BPGC, NativizationOptions)))
{
return BPGC;
}
}
}
return nullptr;
}
EReplacementResult FBlueprintNativeCodeGenModule::IsTargetedForReplacement(const UPackage* Package, const FCompilerNativizationOptions& NativizationOptions) const
{
// non-native packages with enums and structs should be converted, unless they are blacklisted:
UStruct* Struct = nullptr;
UEnum* Enum = nullptr;
GetFieldFormPackage(Package, Struct, Enum, RF_NoFlags);
UObject* Target = Struct;
if (Target == nullptr)
{
Target = Enum;
}
return IsTargetedForReplacement(Target, NativizationOptions);
}
EReplacementResult FBlueprintNativeCodeGenModule::IsTargetedForReplacement(const UObject* Object, const FCompilerNativizationOptions& NativizationOptions) const
{
if (Object == nullptr)
{
return EReplacementResult::DontReplace;
}
const UUserDefinedStruct* const UDStruct = Cast<const UUserDefinedStruct>(Object);
const UUserDefinedEnum* const UDEnum = Cast<const UUserDefinedEnum>(Object);
const UBlueprintGeneratedClass* const BlueprintClass = Cast<const UBlueprintGeneratedClass>(Object);
if (UDStruct == nullptr && UDEnum == nullptr && BlueprintClass == nullptr)
{
return EReplacementResult::DontReplace;
}
const FStatePerPlatform* StateForCurrentPlatform = StatesPerPlatform.Find(NativizationOptions.PlatformName);
check(StateForCurrentPlatform);
const FSoftObjectPath ObjectKey(Object);
{
const EReplacementResult* const CachedValue = StateForCurrentPlatform->CachedIsTargetedForReplacement.Find(ObjectKey); //THe referenced returned by FindOrAdd could be invalid later, when filled.
if (CachedValue)
{
return *CachedValue;
}
}
const UBlueprint* const Blueprint = BlueprintClass ? Cast<UBlueprint>(BlueprintClass->ClassGeneratedBy) : nullptr;
const UProjectPackagingSettings* const PackagingSettings = GetDefault<UProjectPackagingSettings>();
const bool bNativizeOnlySelectedBPs = PackagingSettings && PackagingSettings->BlueprintNativizationMethod == EProjectPackagingBlueprintNativizationMethod::Exclusive;
auto ObjectIsNotReplacedAtAll = [&]() -> bool
{
// EDITOR ON DEVELOPMENT OBJECT
{
auto IsDeveloperObject = [](const UObject* Obj) -> bool
{
auto IsObjectFromDeveloperPackage = [](const UObject* InObj) -> bool
{
return InObj && InObj->GetOutermost()->HasAllPackagesFlags(PKG_Developer);
};
if (Obj)
{
if (IsObjectFromDeveloperPackage(Obj))
{
return true;
}
const UStruct* StructToTest = Obj->IsA<UStruct>() ? CastChecked<const UStruct>(Obj) : Obj->GetClass();
for (; StructToTest; StructToTest = StructToTest->GetSuperStruct())
{
if (IsObjectFromDeveloperPackage(StructToTest))
{
return true;
}
}
}
return false;
};
if (Object && (IsEditorOnlyObject(Object) || IsDeveloperObject(Object)))
{
UE_LOG(LogBlueprintCodeGen, Warning, TEXT("Object %s depends on Editor or Development stuff. It shouldn't be cooked."), *GetPathNameSafe(Object));
return true;
}
}
// DATA ONLY BP
{
static const FBoolConfigValueHelper DontNativizeDataOnlyBP(TEXT("BlueprintNativizationSettings"), TEXT("bDontNativizeDataOnlyBP"));
if (DontNativizeDataOnlyBP && !bNativizeOnlySelectedBPs && Blueprint && FBlueprintEditorUtils::IsDataOnlyBlueprint(Blueprint))
{
return true;
}
}
// Don't convert objects like Default__WidgetBlueprintGeneratedClass
if (Object && (Object->HasAnyFlags(RF_ClassDefaultObject)))
{
return true;
}
return false;
};
if (ObjectIsNotReplacedAtAll())
{
StateForCurrentPlatform->CachedIsTargetedForReplacement.Add(ObjectKey, EReplacementResult::DontReplace);
return EReplacementResult::DontReplace;
}
auto ObjectGenratesOnlyStub = [&]() -> bool
{
// ExcludedFolderPaths
{
const FString ObjPathName = Object->GetPathName();
for (const FString& ExcludedPath : ExcludedFolderPaths)
{
if (ObjPathName.StartsWith(ExcludedPath))
{
return true;
}
}
for (const FString& ExcludedPath : NativizationOptions.ExcludedFolderPaths)
{
if (ObjPathName.StartsWith(ExcludedPath))
{
return true;
}
}
}
// ExcludedAssetTypes
{
// we can't use FindObject, because we may be converting a type while saving
if (UDEnum && ExcludedAssetTypes.Find(UDEnum->GetPathName()) != INDEX_NONE)
{
return true;
}
const UStruct* LocStruct = Cast<const UStruct>(Object);
while (LocStruct)
{
if (ExcludedAssetTypes.Find(LocStruct->GetPathName()) != INDEX_NONE)
{
return true;
}
LocStruct = LocStruct->GetSuperStruct();
}
}
// ExcludedAssets
{
if (ExcludedAssets.Contains(Object->GetOutermost()))
{
return true;
}
if (NativizationOptions.ExcludedAssets.Contains(Object->GetOutermost()))
{
return true;
}
}
if (Blueprint && BlueprintClass)
{
// Reducible AnimBP
{
static const FBoolConfigValueHelper NativizeAnimBPOnlyWhenNonReducibleFuncitons(TEXT("BlueprintNativizationSettings"), TEXT("bNativizeAnimBPOnlyWhenNonReducibleFuncitons"));
if (NativizeAnimBPOnlyWhenNonReducibleFuncitons)
{
if (const UAnimBlueprint* AnimBlueprint = Cast<UAnimBlueprint>(Blueprint))
{
ensure(AnimBlueprint->bHasBeenRegenerated);
if (AnimBlueprint->bHasAnyNonReducibleFunction == UBlueprint::EIsBPNonReducible::No)
{
UE_LOG(LogBlueprintCodeGen, Log, TEXT("AnimBP %s without non-reducible functions is excluded from nativization"), *GetPathNameSafe(Blueprint));
return true;
}
}
}
}
// Unconvertable Blueprint
{
const EBlueprintType UnconvertableBlueprintTypes[] = {
//BPTYPE_Const, // What is a "const" Blueprint?
BPTYPE_MacroLibrary,
BPTYPE_LevelScript,
};
const EBlueprintType BlueprintType = Blueprint->BlueprintType;
for (int32 TypeIndex = 0; TypeIndex < ARRAY_COUNT(UnconvertableBlueprintTypes); ++TypeIndex)
{
if (BlueprintType == UnconvertableBlueprintTypes[TypeIndex])
{
return true;
}
}
}
// ExcludedBlueprintTypes
for (TSoftClassPtr<UBlueprint> ExcludedBlueprintTypeAsset : ExcludedBlueprintTypes)
{
UClass* ExcludedBPClass = ExcludedBlueprintTypeAsset.Get();
if (!ExcludedBPClass)
{
ExcludedBPClass = ExcludedBlueprintTypeAsset.LoadSynchronous();
}
if (ExcludedBPClass && Blueprint->IsA(ExcludedBPClass))
{
return true;
}
}
const bool bFlaggedForNativization = (Blueprint->NativizationFlag == EBlueprintNativizationFlag::Dependency) ?
PackagingSettings->IsBlueprintAssetInNativizationList(Blueprint) :
(Blueprint->NativizationFlag == EBlueprintNativizationFlag::ExplicitlyEnabled);
// Blueprint is not selected
if (bNativizeOnlySelectedBPs && !bFlaggedForNativization && !FBlueprintEditorUtils::ShouldNativizeImplicitly(Blueprint))
{
return true;
}
// Parent Class in not converted
for (const UBlueprintGeneratedClass* ParentClassIt = Cast<UBlueprintGeneratedClass>(BlueprintClass->GetSuperClass())
; ParentClassIt; ParentClassIt = Cast<UBlueprintGeneratedClass>(ParentClassIt->GetSuperClass()))
{
const EReplacementResult ParentResult = IsTargetedForReplacement(ParentClassIt, NativizationOptions);
if (ParentResult != EReplacementResult::ReplaceCompletely)
{
if (bNativizeOnlySelectedBPs)
{
UE_LOG(LogBlueprintCodeGen, Error, TEXT("BP %s is selected for nativization, but its parent class %s is not nativized."), *GetPathNameSafe(Blueprint), *GetPathNameSafe(ParentClassIt));
}
return true;
}
}
// Interface class not converted
TArray<UClass*> InterfaceClasses;
FBlueprintEditorUtils::FindImplementedInterfaces(Blueprint, false, InterfaceClasses);
for (const UClass* InterfaceClassIt : InterfaceClasses)
{
const UBlueprintGeneratedClass* InterfaceBPGC = Cast<const UBlueprintGeneratedClass>(InterfaceClassIt);
if (InterfaceBPGC)
{
const EReplacementResult InterfaceResult = IsTargetedForReplacement(InterfaceBPGC, NativizationOptions);
if (InterfaceResult != EReplacementResult::ReplaceCompletely)
{
if (bNativizeOnlySelectedBPs)
{
UE_LOG(LogBlueprintCodeGen, Error, TEXT("BP %s is selected for nativization, but BP interface class %s is not nativized."), *GetPathNameSafe(Blueprint), *GetPathNameSafe(InterfaceClassIt));
}
return true;
}
}
else if (InterfaceClassIt->GetCppTypeInfo()->IsAbstract())
{
UE_LOG(LogBlueprintCodeGen, Error, TEXT("BP %s is selected for nativization, but it cannot be nativized because it currently implements an interface class (%s) that declares one or more pure virtual functions."), *GetPathNameSafe(Blueprint), *GetPathNameSafe(InterfaceClassIt));
return true;
}
}
}
return false;
};
if (ObjectGenratesOnlyStub())
{
StateForCurrentPlatform->CachedIsTargetedForReplacement.Add(ObjectKey, EReplacementResult::GenerateStub);
return EReplacementResult::GenerateStub;
}
StateForCurrentPlatform->CachedIsTargetedForReplacement.Add(ObjectKey, EReplacementResult::ReplaceCompletely);
return EReplacementResult::ReplaceCompletely;
}
void FBlueprintNativeCodeGenModule::FillPlatformNativizationDetails(const ITargetPlatform* Platform, FPlatformNativizationDetails& Details)
{
check(Platform);
const PlatformInfo::FPlatformInfo& PlatformInfo = Platform->GetPlatformInfo();
Details.PlatformName = PlatformInfo.TargetPlatformName;
Details.CompilerNativizationOptions.PlatformName = Details.PlatformName;
Details.CompilerNativizationOptions.ClientOnlyPlatform = Platform->IsClientOnly();
Details.CompilerNativizationOptions.ServerOnlyPlatform = Platform->IsServerOnly();
auto GatherExcludedStuff = [&](const TCHAR* KeyForExcludedModules, const TCHAR* KeyForExcludedPaths, const TCHAR* KeyForExcludedAssets)
{
const TCHAR* ConfigSection = TEXT("BlueprintNativizationSettings");
{
TArray<FString> ExcludedModuls;
GConfig->GetArray(ConfigSection, KeyForExcludedModules, ExcludedModuls, GEditorIni);
for (const FString& NameStr : ExcludedModuls)
{
Details.CompilerNativizationOptions.ExcludedModules.Add(FName(*NameStr));
}
}
GConfig->GetArray(ConfigSection, KeyForExcludedPaths, Details.CompilerNativizationOptions.ExcludedFolderPaths, GEditorIni);
{
TArray<FString> ExcludedAssetPaths;
GConfig->GetArray(ConfigSection, KeyForExcludedAssets, ExcludedAssetPaths, GEditorIni);
for (FString& Path : ExcludedAssetPaths)
{
Details.CompilerNativizationOptions.ExcludedAssets.Add(FSoftObjectPath(Path));
}
}
};
if (Details.CompilerNativizationOptions.ServerOnlyPlatform)
{
GatherExcludedStuff(TEXT("ModulsExcludedFromNativizedServer"), TEXT("ExcludedFolderPathsFromServer"), TEXT("ExcludedAssetsFromServer"));
}
if (Details.CompilerNativizationOptions.ClientOnlyPlatform)
{
GatherExcludedStuff(TEXT("ModulsExcludedFromNativizedClient"), TEXT("ExcludedFolderPathsFromClient"), TEXT("ExcludedAssetsFromClient"));
}
}
IMPLEMENT_MODULE(FBlueprintNativeCodeGenModule, BlueprintNativeCodeGen);
| 35.825023 | 283 | 0.765152 | windystrife |
c7219c2913ef430684a381dd287e2157ac8464d5 | 1,248 | hpp | C++ | attdet/alglin/include/alglin/array.hpp | zenitheesc/AttitudeDetermination | 090418f7ac5554ca7a958cf636967d5993e04898 | [
"MIT"
] | null | null | null | attdet/alglin/include/alglin/array.hpp | zenitheesc/AttitudeDetermination | 090418f7ac5554ca7a958cf636967d5993e04898 | [
"MIT"
] | null | null | null | attdet/alglin/include/alglin/array.hpp | zenitheesc/AttitudeDetermination | 090418f7ac5554ca7a958cf636967d5993e04898 | [
"MIT"
] | 1 | 2022-03-12T10:40:44.000Z | 2022-03-12T10:40:44.000Z | #ifndef ARRAY_HPP
#define ARRAY_HPP
#if __cplusplus >= 201703L
#define CONSTEXPR_17 constexpr
#else
#define CONSTEXPR_17
#endif
namespace alglin {
template<class Type, int N> class array {
struct iterator {
/* not "real" iterator */
// using iterator_category = std::forward_iterator_tag;
constexpr iterator(Type *ptr) : m_ptr(ptr) {}
constexpr Type &operator*() const { return *m_ptr; }
Type *operator->() { return m_ptr; }
iterator &operator++() {
m_ptr++;
return *this;
}
iterator operator++(int) {
iterator tmp = *this;
++(*this);
return tmp;
}
constexpr friend bool operator==(const iterator &a, const iterator &b) {
return a.m_ptr == b.m_ptr;
};
constexpr friend bool operator!=(const iterator &a, const iterator &b) {
return a.m_ptr != b.m_ptr;
}
private:
Type *m_ptr;
};
private:
Type elem[N];
public:
constexpr array() = default;
array(Type from[]) : elem{ from } {}
constexpr Type operator[](int i) const { return elem[i]; }
Type &operator[](int i) { return elem[i]; }
Type *data() { return elem; }
iterator begin() { return iterator(&elem[0]); }
iterator end() { return iterator(&elem[N]); }// one pass the end
};
}// namespace alglin
#undef CONSTEXPR_17
#endif
| 21.894737 | 74 | 0.655449 | zenitheesc |
c721fdcc2303702580d1ab10c781f783c5e57df0 | 3,069 | cpp | C++ | test/TextDestroy.cpp | Shoegzer/SPIRV-Tools | 27a2bbb865ef638afe4260bf214110425a2b904b | [
"Unlicense"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | test/TextDestroy.cpp | Shoegzer/SPIRV-Tools | 27a2bbb865ef638afe4260bf214110425a2b904b | [
"Unlicense"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | test/TextDestroy.cpp | Shoegzer/SPIRV-Tools | 27a2bbb865ef638afe4260bf214110425a2b904b | [
"Unlicense"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and/or associated documentation files (the
// "Materials"), to deal in the Materials without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Materials, and to
// permit persons to whom the Materials are 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 Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
// https://www.khronos.org/registry/
//
// THE MATERIALS ARE 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
// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
#include "UnitSPIRV.h"
namespace {
TEST(TextDestroy, DestroyNull) { spvBinaryDestroy(nullptr); }
TEST(TextDestroy, Default) {
spv_context context = spvContextCreate(SPV_ENV_UNIVERSAL_1_0);
char textStr[] = R"(
OpSource OpenCL_C 12
OpMemoryModel Physical64 OpenCL
OpSourceExtension "PlaceholderExtensionName"
OpEntryPoint Kernel %0 ""
OpExecutionMode %0 LocalSizeHint 1 1 1
%1 = OpTypeVoid
%2 = OpTypeBool
%3 = OpTypeInt 8 0
%4 = OpTypeInt 8 1
%5 = OpTypeInt 16 0
%6 = OpTypeInt 16 1
%7 = OpTypeInt 32 0
%8 = OpTypeInt 32 1
%9 = OpTypeInt 64 0
%10 = OpTypeInt 64 1
%11 = OpTypeFloat 16
%12 = OpTypeFloat 32
%13 = OpTypeFloat 64
%14 = OpTypeVector %3 2
)";
spv_binary binary = nullptr;
spv_diagnostic diagnostic = nullptr;
EXPECT_EQ(SPV_SUCCESS, spvTextToBinary(context, textStr, strlen(textStr),
&binary, &diagnostic));
EXPECT_NE(nullptr, binary);
EXPECT_NE(nullptr, binary->code);
EXPECT_NE(0u, binary->wordCount);
if (diagnostic) {
spvDiagnosticPrint(diagnostic);
ASSERT_TRUE(false);
}
spv_text resultText = nullptr;
EXPECT_EQ(SPV_SUCCESS,
spvBinaryToText(context, binary->code, binary->wordCount, 0,
&resultText, &diagnostic));
spvBinaryDestroy(binary);
if (diagnostic) {
spvDiagnosticPrint(diagnostic);
spvDiagnosticDestroy(diagnostic);
ASSERT_TRUE(false);
}
EXPECT_NE(nullptr, resultText->str);
EXPECT_NE(0u, resultText->length);
spvTextDestroy(resultText);
spvContextDestroy(context);
}
} // anonymous namespace
| 35.686047 | 75 | 0.701531 | Shoegzer |
d176b52d1274f155c5119c6baab8dd3aec2fa13f | 5,434 | cpp | C++ | src/py/wrapper_170cacd8da615406967b5b7d712829ee.cpp | nikhilkalige/ClangLite | dcb6d7385cca25c0a888bb56ae3ec1eb951cd752 | [
"Apache-2.0"
] | 5 | 2017-11-13T18:34:24.000Z | 2021-08-10T02:22:22.000Z | src/py/wrapper_170cacd8da615406967b5b7d712829ee.cpp | nikhilkalige/ClangLite | dcb6d7385cca25c0a888bb56ae3ec1eb951cd752 | [
"Apache-2.0"
] | 4 | 2017-11-15T13:13:36.000Z | 2019-02-26T00:21:14.000Z | src/py/wrapper_170cacd8da615406967b5b7d712829ee.cpp | nikhilkalige/ClangLite | dcb6d7385cca25c0a888bb56ae3ec1eb951cd752 | [
"Apache-2.0"
] | 7 | 2017-11-15T11:58:33.000Z | 2021-03-15T18:16:16.000Z | #include "_clanglite.h"
void (::clang::FunctionTemplateDecl::*method_pointer_07e658462c875c48a75cf9c1fe151a87)()const= &::clang::FunctionTemplateDecl::LoadLazySpecializations;
class ::clang::FunctionDecl * (::clang::FunctionTemplateDecl::*method_pointer_8b97df53407b512bb7ae6d8038314a0b)()const= &::clang::FunctionTemplateDecl::getTemplatedDecl;
bool (::clang::FunctionTemplateDecl::*method_pointer_741f0e28617353cc9cab5887153792f7)()const= &::clang::FunctionTemplateDecl::isThisDeclarationADefinition;
class ::clang::FunctionTemplateDecl * (::clang::FunctionTemplateDecl::*method_pointer_1e69ff3aa9ea587a8991aa70d447c8a0)()= &::clang::FunctionTemplateDecl::getCanonicalDecl;
class ::clang::FunctionTemplateDecl const * (::clang::FunctionTemplateDecl::*method_pointer_7a8d1a99c0b75186b999aa13fb702162)()const= &::clang::FunctionTemplateDecl::getCanonicalDecl;
class ::clang::FunctionTemplateDecl * (::clang::FunctionTemplateDecl::*method_pointer_6447bed6e7f75a93b3237a5937ce1361)()= &::clang::FunctionTemplateDecl::getPreviousDecl;
class ::clang::FunctionTemplateDecl const * (::clang::FunctionTemplateDecl::*method_pointer_b6cb4f42097a5ee6a79912493be9f6d6)()const= &::clang::FunctionTemplateDecl::getPreviousDecl;
class ::clang::FunctionTemplateDecl * (::clang::FunctionTemplateDecl::*method_pointer_c831a976e0995c66bda3f276fa7bfde9)()= &::clang::FunctionTemplateDecl::getMostRecentDecl;
class ::clang::FunctionTemplateDecl const * (::clang::FunctionTemplateDecl::*method_pointer_f6dc8290c58a55e3bb72dc50a8436b91)()const= &::clang::FunctionTemplateDecl::getMostRecentDecl;
class ::clang::FunctionTemplateDecl * (::clang::FunctionTemplateDecl::*method_pointer_d9c33e789b66576290fc99749a1d9db2)()const= &::clang::FunctionTemplateDecl::getInstantiatedFromMemberTemplate;
class ::clang::FunctionTemplateDecl * (*method_pointer_1aa0bf8c011d52918b3086f3b387fbfc)(class ::clang::ASTContext &, unsigned int )= ::clang::FunctionTemplateDecl::CreateDeserialized;
bool (*method_pointer_ec8e2de8b65d5585bf38a81b41501d30)(class ::clang::Decl const *)= ::clang::FunctionTemplateDecl::classof;
bool (*method_pointer_75074d7c261e514fad79157b259a6074)(enum ::clang::Decl::Kind )= ::clang::FunctionTemplateDecl::classofKind;
namespace autowig {
}
void wrapper_170cacd8da615406967b5b7d712829ee(pybind11::module& module)
{
pybind11::class_<class ::clang::FunctionTemplateDecl, autowig::HolderType< class ::clang::FunctionTemplateDecl >::Type, class ::clang::RedeclarableTemplateDecl > class_170cacd8da615406967b5b7d712829ee(module, "FunctionTemplateDecl", "");
class_170cacd8da615406967b5b7d712829ee.def("load_lazy_specializations", method_pointer_07e658462c875c48a75cf9c1fe151a87, "Load any lazily-loaded specializations from the external source.\n\n:Return Type:\n :cpp:any:`void`\n\n");
class_170cacd8da615406967b5b7d712829ee.def("get_templated_decl", method_pointer_8b97df53407b512bb7ae6d8038314a0b, pybind11::return_value_policy::reference_internal, ":Return Type:\n :cpp:class:`::clang::FunctionDecl`\n\n");
class_170cacd8da615406967b5b7d712829ee.def("is_this_declaration_a_definition", method_pointer_741f0e28617353cc9cab5887153792f7, ":Return Type:\n :cpp:any:`bool`\n\n");
class_170cacd8da615406967b5b7d712829ee.def("get_canonical_decl", method_pointer_1e69ff3aa9ea587a8991aa70d447c8a0, pybind11::return_value_policy::reference_internal, "");
class_170cacd8da615406967b5b7d712829ee.def("get_canonical_decl", method_pointer_7a8d1a99c0b75186b999aa13fb702162, pybind11::return_value_policy::reference_internal, "");
class_170cacd8da615406967b5b7d712829ee.def("get_previous_decl", method_pointer_6447bed6e7f75a93b3237a5937ce1361, pybind11::return_value_policy::reference_internal, "Retrieve the previous declaration of this function template, or NULL if\nno such declaration exists.\n\n:Return Type:\n :cpp:class:`::clang::FunctionTemplateDecl`\n\n");
class_170cacd8da615406967b5b7d712829ee.def("get_previous_decl", method_pointer_b6cb4f42097a5ee6a79912493be9f6d6, pybind11::return_value_policy::reference_internal, "Retrieve the previous declaration of this function template, or NULL if\nno such declaration exists.\n\n:Return Type:\n :cpp:class:`::clang::FunctionTemplateDecl`\n\n");
class_170cacd8da615406967b5b7d712829ee.def("get_most_recent_decl", method_pointer_c831a976e0995c66bda3f276fa7bfde9, pybind11::return_value_policy::reference_internal, "");
class_170cacd8da615406967b5b7d712829ee.def("get_most_recent_decl", method_pointer_f6dc8290c58a55e3bb72dc50a8436b91, pybind11::return_value_policy::reference_internal, "");
class_170cacd8da615406967b5b7d712829ee.def("get_instantiated_from_member_template", method_pointer_d9c33e789b66576290fc99749a1d9db2, pybind11::return_value_policy::reference_internal, "");
class_170cacd8da615406967b5b7d712829ee.def_static("create_deserialized", method_pointer_1aa0bf8c011d52918b3086f3b387fbfc, pybind11::return_value_policy::reference_internal, "Create an empty function template node.\n\n:Parameters:\n - `C` (:cpp:class:`::clang::ASTContext`) - Undocumented\n - `ID` (:cpp:any:`unsigned` int) - Undocumented\n\n:Return Type:\n :cpp:class:`::clang::FunctionTemplateDecl`\n\n");
class_170cacd8da615406967b5b7d712829ee.def_static("classof", method_pointer_ec8e2de8b65d5585bf38a81b41501d30, "");
class_170cacd8da615406967b5b7d712829ee.def_static("classof_kind", method_pointer_75074d7c261e514fad79157b259a6074, "");
} | 143 | 415 | 0.828303 | nikhilkalige |
d178c61c4e9ba53f25a034559952c4317d482ead | 838 | cpp | C++ | AquilaEngine/src/SimpleProfiler.cpp | vblanco20-1/AquilaEngine | 7cd972f96f1c5f4ae3ccf7980eed7e223daf8d1b | [
"Unlicense"
] | 6 | 2020-04-23T00:53:05.000Z | 2021-11-11T08:51:14.000Z | AquilaEngine/src/SimpleProfiler.cpp | vblanco20-1/AquilaEngine | 7cd972f96f1c5f4ae3ccf7980eed7e223daf8d1b | [
"Unlicense"
] | null | null | null | AquilaEngine/src/SimpleProfiler.cpp | vblanco20-1/AquilaEngine | 7cd972f96f1c5f4ae3ccf7980eed7e223daf8d1b | [
"Unlicense"
] | 2 | 2020-11-11T13:30:24.000Z | 2020-12-11T05:39:38.000Z | #include <PrecompiledHeader.h>
#include "SimpleProfiler.h"
SimpleProfiler * g_SimpleProfiler = nullptr;
void DrawSystemPerformanceUnits(std::vector<SystemPerformanceUnit>& units)
{
ImGui::Begin("Performance Info");
std::sort(units.begin(), units.end(), [](SystemPerformanceUnit&a, SystemPerformanceUnit&b) {
return a.miliseconds > b.miliseconds;
});
for (auto &p : units)
{
float ms = p.miliseconds / (float)p.iterations;
ImGui::Text("%s : t=%f ms", p.EventName.c_str(), ms);
}
//units.clear();
//ImGui::Text("Delta Time : %f", info.deltaTime);
//ImGui::Text("Averaged Delta Time: %f", info.averagedDeltaTime);
//ImGui::Text("Drawcalls : %i", info.Drawcalls);
//ImGui::Text("Simulation Time : %f", info.SimTime);
//ImGui::Text("Rendering Time : %f", info.RenderTime);
ImGui::End();
}
| 27.032258 | 93 | 0.661098 | vblanco20-1 |
d178db30d927111c285ec01596affdf6f742b947 | 6,005 | cpp | C++ | src/utils/DataExtractor.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | src/utils/DataExtractor.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | src/utils/DataExtractor.cpp | tryboy/polarphp | f6608c4dc26add94e61684ed0edd3d5c7e86e768 | [
"PHP-3.01"
] | null | null | null | // This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/07/03.
#include "polarphp/utils/DataExtractor.h"
#include "polarphp/utils/ErrorHandling.h"
#include "polarphp/utils/Host.h"
#include "polarphp/utils/SwapByteOrder.h"
namespace polar {
namespace utils {
template <typename T>
static T getU(uint32_t *offsetPtr, const DataExtractor *extractor,
bool isLittleEndian, const char *data)
{
T value = 0;
uint32_t offset = *offsetPtr;
if (extractor->isValidOffsetForDataOfSize(offset, sizeof(value))) {
std::memcpy(&value, &data[offset], sizeof(value));
if (sys::sg_isLittleEndianHost != isLittleEndian) {
polar::utils::swap_byte_order(value);
}
// Advance the offset
*offsetPtr += sizeof(value);
}
return value;
}
template <typename T>
static T *getUs(uint32_t *offsetPtr, T *dst, uint32_t count,
const DataExtractor *extractor, bool isLittleEndian, const char *data)
{
uint32_t offset = *offsetPtr;
if (count > 0 && extractor->isValidOffsetForDataOfSize(offset, sizeof(*dst)*count)) {
for (T *value_ptr = dst, *end = dst + count; value_ptr != end;
++value_ptr, offset += sizeof(*dst)) {
*value_ptr = getU<T>(offsetPtr, extractor, isLittleEndian, data);
}
// Advance the offset
*offsetPtr = offset;
// Return a non-NULL pointer to the converted data as an indicator of
// success
return dst;
}
return nullptr;
}
uint8_t DataExtractor::getU8(uint32_t *offsetPtr) const
{
return getU<uint8_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint8_t *
DataExtractor::getU8(uint32_t *offsetPtr, uint8_t *dst, uint32_t count) const
{
return getUs<uint8_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint16_t DataExtractor::getU16(uint32_t *offsetPtr) const
{
return getU<uint16_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint16_t *DataExtractor::getU16(uint32_t *offsetPtr, uint16_t *dst,
uint32_t count) const
{
return getUs<uint16_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint32_t DataExtractor::getU24(uint32_t *offsetPtr) const
{
uint24_t ExtractedVal =
getU<uint24_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
// The 3 bytes are in the correct byte order for the host.
return ExtractedVal.getAsUint32(sys::sg_isLittleEndianHost);
}
uint32_t DataExtractor::getU32(uint32_t *offsetPtr) const
{
return getU<uint32_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint32_t *DataExtractor::getU32(uint32_t *offsetPtr, uint32_t *dst,
uint32_t count) const
{
return getUs<uint32_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint64_t DataExtractor::getU64(uint32_t *offsetPtr) const
{
return getU<uint64_t>(offsetPtr, this, m_isLittleEndian, m_data.getData());
}
uint64_t *DataExtractor::getU64(uint32_t *offsetPtr, uint64_t *dst,
uint32_t count) const
{
return getUs<uint64_t>(offsetPtr, dst, count, this, m_isLittleEndian,
m_data.getData());
}
uint64_t
DataExtractor::getUnsigned(uint32_t *offsetPtr, uint32_t byte_size) const
{
switch (byte_size) {
case 1:
return getU8(offsetPtr);
case 2:
return getU16(offsetPtr);
case 4:
return getU32(offsetPtr);
case 8:
return getU64(offsetPtr);
}
polar_unreachable("getUnsigned unhandled case!");
}
int64_t
DataExtractor::getSigned(uint32_t *offsetPtr, uint32_t byte_size) const {
switch (byte_size) {
case 1:
return (int8_t)getU8(offsetPtr);
case 2:
return (int16_t)getU16(offsetPtr);
case 4:
return (int32_t)getU32(offsetPtr);
case 8:
return (int64_t)getU64(offsetPtr);
}
polar_unreachable("getSigned unhandled case!");
}
const char *DataExtractor::getCStr(uint32_t *offsetPtr) const {
uint32_t offset = *offsetPtr;
StringRef::size_type pos = m_data.find('\0', offset);
if (pos != StringRef::npos) {
*offsetPtr = pos + 1;
return m_data.getData() + offset;
}
return nullptr;
}
StringRef DataExtractor::getCStrRef(uint32_t *OffsetPtr) const {
uint32_t Start = *OffsetPtr;
StringRef::size_type Pos = m_data.find('\0', Start);
if (Pos != StringRef::npos) {
*OffsetPtr = Pos + 1;
return StringRef(m_data.getData() + Start, Pos - Start);
}
return StringRef();
}
uint64_t DataExtractor::getULEB128(uint32_t *offsetPtr) const {
uint64_t result = 0;
if (m_data.empty())
return 0;
unsigned shift = 0;
uint32_t offset = *offsetPtr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = m_data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0)
break;
}
*offsetPtr = offset;
return result;
}
int64_t DataExtractor::getSLEB128(uint32_t *offsetPtr) const
{
int64_t result = 0;
if (m_data.empty()) {
return 0;
}
unsigned shift = 0;
uint32_t offset = *offsetPtr;
uint8_t byte = 0;
while (isValidOffset(offset)) {
byte = m_data[offset++];
result |= uint64_t(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
break;
}
}
// Sign bit of byte is 2nd high order bit (0x40)
if (shift < 64 && (byte & 0x40)) {
result |= -(1ULL << shift);
}
*offsetPtr = offset;
return result;
}
} // utils
} // polar
| 28.060748 | 88 | 0.654621 | tryboy |
d17becb7a7c285721fcb2478501b527750f33067 | 3,059 | cpp | C++ | Draw.cpp | sheirys/tankai-praktika | 42f77ee3c30560179c2015d7400d18a7d4de5ec0 | [
"MIT"
] | null | null | null | Draw.cpp | sheirys/tankai-praktika | 42f77ee3c30560179c2015d7400d18a7d4de5ec0 | [
"MIT"
] | null | null | null | Draw.cpp | sheirys/tankai-praktika | 42f77ee3c30560179c2015d7400d18a7d4de5ec0 | [
"MIT"
] | null | null | null | #include "Game.h"
#include "CLoad_image.h"
void Game::Draw(Engine* game)
{
SDL_FillRect( game->screen, &game->screen->clip_rect, SDL_MapRGB( game->screen->format, 0, 0, 0 ) );
data.apply(game->screen);
//int X = T.getX();
//int Y = T.getY();
//int kk=0;
/* kk=0;
while(kk<Lektuvai.size())
{
int X = Lektuvai[kk].GetX();
int Y = Lektuvai[kk].GetY();
Load::draw_img(X, Y, Ekranas, Lektuvai[kk].GetSurface(0.5));
kk++;
}*/
//-----------------------------------------------------------------------------
/*
Uint32 colorkey = SDL_MapRGB( Tk->format, 0, 255, 0 );
SDL_SetColorKey( Tk, SDL_SRCCOLORKEY, colorkey );
SDL_Surface* temp = new SDL_Surface;
temp = SDL_DisplayFormatAlpha(Tk);
std::swap(Tk, temp);
SDL_FreeSurface(temp);
delete(temp);
Load::draw_img(400, 50, Ekranas, Tk);
*/
//-----------------------------------------------------------------------------
/* T.render(Ekranas);
kuris++;
if(kuris>30)
kuris=0;
//Piesiamos ciakros apie tanka
Load::draw_img(X + T.rotation->w/2 - A[kuris]->w/2, Y+T.rotation->h/2 - A[kuris]->h/2, Ekranas, A[kuris]);
*/
/*SDL_SetColorKey( Tk, SDL_SRCCOLORKEY, colorkey );
Tk=SDL_DisplayFormatAlpha(Tk);
Load::draw_img(400, 50, Ekranas, Tk);*/
//-----------------------------------------------------------------------------
for(int i = 0; i < kulkos.size() ; i++)
{
if(kulkos.size()!=0)
{
int kx, ky; //Dabartines kulkos koordinates
kx= kulkos[i]->GetX();
ky= kulkos[i]->GetY();
Load::draw_img(kulkos[i]->GetX(),kulkos[i]->GetY(), game->screen, kulkos[i]->KPasukta);
}
}
//-----------------------------------------------------------------------------
/*Pieesiami visi vektoriuje esantys tankai*/
int tmp = tankai.size();
if(tmp!=0)
for(int i = 0; i < tmp; i++)
{
tankai[i]->render(game->screen);
}
//Load::draw_img(400, 50, Ekranas, Tk);
//-----------------------------------------------------------------------------
/*kk=0;
while(kk<Lektuvai.size())
{
int X = Lektuvai[kk].GetX();
int Y = Lektuvai[kk].GetY();
Load::draw_img(X, Y, Ekranas, Lektuvai[kk].GetSurface(1));
kk++;
}*/
//-----------------------------------------------------------------------------
int kk=0;
while(kk<anim.Sprogimai.size())
{
int X = anim.Sprogimai[kk].x;
int Y = anim.Sprogimai[kk].y;
Load::draw_img(X, Y, game->screen, anim.GetFrame( anim.Sprogimai[kk].kadras ) );
kk++;
}
//-----------------------------------------------------------------------------
//SDL_BlitSurface(bg, NULL, game->screen, NULL);
//SDL_UpdateRect(game->screen, 0, 0, 0, 0);
SDL_Flip(game->screen);
//SDL_FreeSurface(Laikinas);
// SDL_FreeSurface(Laikinas1);
//SDL_FreeSurface(Tk);
}
| 28.858491 | 113 | 0.436417 | sheirys |
d17d41fb0ad510c733f6f7a216e65519987dcd04 | 6,593 | cpp | C++ | src/main/pass/coverage/block/BlockCoveragePass.cpp | kkysen/DifferentiableFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | 1 | 2019-06-19T06:03:03.000Z | 2019-06-19T06:03:03.000Z | src/main/pass/coverage/block/BlockCoveragePass.cpp | kkysen/SmartNeuralFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | null | null | null | src/main/pass/coverage/block/BlockCoveragePass.cpp | kkysen/SmartNeuralFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | null | null | null | //
// Created by Khyber on 3/14/2019.
//
#include "src/main/pass/coverage/includes.h"
#include "src/share/llvm/lib/conversions.h"
#include "src/share/llvm/debug.h"
#include "src/share/io/fse.h"
#include "src/share/io/env/Argv.h"
#include "src/share/stde/compareEnds.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FileSystem.h"
#include <numeric>
#include <fstream>
namespace {
using env::Argv;
using llvm::Module;
std::string_view tryGetSourceMapNameFromArgv() {
bool next = false;
for (const auto& arg : Argv::get()) {
if (arg == "-o") {
next = true;
} else if (next) {
const std::string_view ext = ".0.6.coverage.";
const auto i = arg.find(ext);
if (i != std::string_view::npos) {
return arg.substr(0, i);
}
break;
}
}
return {};
}
void getSourceMapName(const Module& module, fs::path& path) {
const std::string_view argvName = tryGetSourceMapNameFromArgv();
if (argvName.data()) {
path = argvName;
} else {
path = module.getSourceFileName();
path.replace_extension();
}
}
}
namespace llvm::pass::coverage::block {
/**
* Block Indices Source Map Format
*
* For every function, it is formatted as (using JS-style `` strings)
* `\nfunction ${function}\n${function.blocks.map(block => `${block}`).join("\n")}`,
* where `${function}` = `${function.name} at ${!function : "?:?" : `${fileName}:${lineNumber}`}`,
* where `${function.name}` = demangled name w/ debug info or else raw name
* where `${block}` = `\t${index}: ${block?.lineNumber}:${block?.columnNumber}}`,
* where `${number}` = !number ? "?" : `${number}`,
* where !function and !block are true if there's no debug info for them,
* and where `${index}` is the global index of the block.
*/
class SourceMap {
private:
raw_fd_ostream _out;
constexpr raw_ostream& out() noexcept {
return _out;
}
class Output {
private:
std::error_code ec;
public:
fs::path path;
explicit Output(const Module& module) {
getSourceMapName(module, path);
path += ".blocks.map";
}
raw_fd_ostream open() {
return raw_fd_ostream(path.string(), ec);
}
void check() const {
if (ec) {
fse::_throw(fs::filesystem_error("cannot open source map output", path, ec));
}
}
};
explicit SourceMap(Output output) : _out(output.open()) {
output.check();
}
public:
explicit SourceMap(const Module& module) : SourceMap(Output(module)) {}
private:
static std::string getDIPath(const DIScope& di) {
using convert::view;
// TODO fs::path::lexically_normal() should be used
// since fs::canonical requires the path to exist and makes a bunch of syscalls
// but it appears lexically_normal() isn't implemented in libstdc++ yet.
return fs::canonical(fs::path()
/ view(di.getDirectory())
/ view(di.getFilename()))
.string();
}
bool hasDI = true;
const DISubprogram* currentFunction = nullptr;
public:
void function(u64 index, const Function& function) {
hasDI = function.getSubprogram();
out() << "\n" << index << ": ";
if (!hasDI) {
// can always default to raw name, which has to exist
out() << function.getName() << " at " << "?:?";
} else {
const auto& di = *function.getSubprogram();
currentFunction = &di;
out() << di.getName() << " at " << getDIPath(di) << ":" << di.getLine();
}
out() << "\n";
}
void block(u64 index, const Instruction& instruction, bool entryBlock) {
out() << "\t" << index << ": ";
const bool instHasDI = instruction.getDebugLoc();
if (!hasDI || (!instHasDI && !entryBlock)) {
out() << "?:?";
} else {
if (entryBlock) {
const auto& di = *currentFunction;
out() << di.getLine() << ":" << "?";
} else {
const auto& di = *instruction.getDebugLoc();
out() << di.getLine() << ":" << di.getColumn();
}
}
out() << "\n";
}
};
class BlockCoveragePass : public NamedRegisteredPass<BlockCoveragePass> {
public:
static constexpr auto name = "Block Coverage Pass";
bool runOnModule(Module& module) override {
const Api api("BlockCoverage", module);
FunctionCallee onFunction = api.func<void(u64)>("onFunction");
FunctionCallee onBlock = api.func<void(u64)>("onBlock");
u64 functionIndex = 0;
u64 blockIndex = 0;
SourceMap sourceMap(module);
IRBuilderExt irbe(module);
return filteredFunctions(module)
.forEach([&](BasicBlock& block) -> bool {
irbe.setInsertPoint(block, true);
const auto& callInst = irbe.callIndex(onBlock, blockIndex);
sourceMap.block(blockIndex, callInst, &block == &block.getParent()->front());
blockIndex++;
return true;
}, [&](Function& function) {
// errs() << "Block: " << function.getName() << "\n";
irbe.setInsertPoint(function, true);
irbe.callIndex(onFunction, functionIndex);
sourceMap.function(functionIndex, function);
functionIndex++;
});
}
};
const bool registered = BlockCoveragePass::register_();
}
| 33.130653 | 103 | 0.481116 | kkysen |
d17ea87cdd324bd1c305427f0989e04d76736ab9 | 24,509 | inl | C++ | mediaLib/include/Rendering/mSpriteBatch.inl | rainerzufalldererste/mediaLib | ed36ca9dc7e6737fd6918ce3995b28bb06a6de26 | [
"MIT"
] | 1 | 2018-08-19T15:56:13.000Z | 2018-08-19T15:56:13.000Z | mediaLib/include/Rendering/mSpriteBatch.inl | rainerzufalldererste/mediaLib | ed36ca9dc7e6737fd6918ce3995b28bb06a6de26 | [
"MIT"
] | null | null | null | mediaLib/include/Rendering/mSpriteBatch.inl | rainerzufalldererste/mediaLib | ed36ca9dc7e6737fd6918ce3995b28bb06a6de26 | [
"MIT"
] | null | null | null | // Copyright 2018 Christoph Stiller
//
// 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 "mSpriteBatch.h"
#include "mForwardTuple.h"
template <typename ...Args>
mFUNCTION(mSpriteBatch_Create_Internal, IN_OUT mSpriteBatch<Args...> *pSpriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Destroy_Internal, IN_OUT mSpriteBatch<Args...> *pSpriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_SetAlphaBlending, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_SetDrawOrder, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_SetTextureFilterMode, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_InitializeMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_BindMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch);
template <typename ...Args>
bool mSpriteBatch_Internal_DrawInstantly(mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
return spriteBatch->spriteSortMode == mSB_SSM_None || spriteBatch->alphaMode == mSB_AM_Additive || spriteBatch->alphaMode == mSB_AM_NoAlpha;
}
//////////////////////////////////////////////////////////////////////////
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Create, OUT mPtr<mSpriteBatch<Args...>> *pSpriteBatch, IN mAllocator *pAllocator)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSharedPointer_Allocate(pSpriteBatch, pAllocator, (std::function<void(mSpriteBatch<Args...> *)>)[](mSpriteBatch<Args...> *pData) {mSpriteBatch_Destroy_Internal(pData);}, 1));
mERROR_CHECK(mSpriteBatch_Create_Internal(pSpriteBatch->GetPointer()));
mERROR_CHECK(mSpriteBatch_Internal_InitializeMesh(*pSpriteBatch));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Destroy, IN_OUT mPtr<mSpriteBatch<Args...>> *pSpriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(pSpriteBatch == nullptr, mR_ArgumentNull);
mASSERT_DEBUG((*pSpriteBatch)->isStarted == false, "The sprite batch should currently not be started.");
mERROR_CHECK(mSharedPointer_Destroy(pSpriteBatch));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Begin, mPtr<mSpriteBatch<Args...>>& spriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(spriteBatch == nullptr, mR_ArgumentNull);
mERROR_IF(spriteBatch->isStarted, mR_ResourceStateInvalid);
spriteBatch->isStarted = true;
if (mSpriteBatch_Internal_DrawInstantly(spriteBatch))
{
mERROR_CHECK(mSpriteBatch_Internal_BindMesh(spriteBatch));
mERROR_CHECK(mShader_Bind(*spriteBatch->shader.GetPointer()));
mERROR_CHECK(mSpriteBatch_Internal_SetAlphaBlending(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetDrawOrder(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetTextureFilterMode(spriteBatch));
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Begin, mPtr<mSpriteBatch<Args...>>& spriteBatch, const mSpriteBatch_SpriteSortMode spriteSortMode, const mSpriteBatch_AlphaMode alphaMode, const mSpriteBatch_TextureSampleMode sampleMode /* = mSB_TSM_LinearFiltering */)
{
mFUNCTION_SETUP();
mERROR_IF(spriteBatch == nullptr, mR_ArgumentNull);
mERROR_IF(spriteBatch->isStarted, mR_ResourceStateInvalid);
spriteBatch->spriteSortMode = spriteSortMode;
spriteBatch->alphaMode = alphaMode;
spriteBatch->textureSampleMode = sampleMode;
mERROR_CHECK(mSpriteBatch_Begin(spriteBatch));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_DrawWithDepth, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture>& texture, const mVec2f & position, const float_t depth, Args && ...args)
{
mFUNCTION_SETUP();
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Create(&renderObject, texture, position, texture->resolutionF, depth, std::forward<Args>(args)...));
if (mSpriteBatch_Internal_DrawInstantly(spriteBatch))
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
else
mERROR_CHECK(mQueue_PushBack(spriteBatch->enqueuedRenderObjects, renderObject));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_DrawWithDepth, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture>& texture, const mRectangle2D<float_t>& rect, const float_t depth, Args && ...args)
{
mFUNCTION_SETUP();
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Create(&renderObject, texture, mVec2f(rect.x, rect.y), mVec2f(rect.w, rect.h), depth, std::forward<Args>(args)...));
if (mSpriteBatch_Internal_DrawInstantly(spriteBatch))
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
else
mERROR_CHECK(mQueue_PushBack(spriteBatch->enqueuedRenderObjects, renderObject));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Draw, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture> &texture, const mVec2f & position, Args && ...args)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_DrawWithDepth(spriteBatch, texture, position, 0, std::forward<Args>(args)...));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Draw, mPtr<mSpriteBatch<Args...>>& spriteBatch, mPtr<mTexture>& texture, const mRectangle2D<float_t>& rect, Args && ...args)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_DrawWithDepth(spriteBatch, texture, rect, 0, std::forward<Args>(args)...));
mRETURN_SUCCESS();
}
template <typename ...Args>
mFUNCTION(mSpriteBatch_QuickSortRenderObjects, mPtr<mQueue<mSpriteBatch_Internal_RenderObject<Args...>>> &queue, size_t left, size_t right)
{
mFUNCTION_SETUP();
if (left == right)
mRETURN_SUCCESS();
size_t l = left;
size_t r = right;
const size_t pivotIndex = (left + right) / 2;
mSpriteBatch_Internal_RenderObject<Args...> *pRenderObject;
mERROR_CHECK(mQueue_PointerAt(queue, pivotIndex, &pRenderObject));
const float_t pivot = pRenderObject->position.z;
while (l <= r)
{
mSpriteBatch_Internal_RenderObject<Args...> *pRenderObjectL = nullptr;
mSpriteBatch_Internal_RenderObject<Args...> *pRenderObjectR = nullptr;
while (true)
{
mERROR_CHECK(mQueue_PointerAt(queue, l, &pRenderObjectL));
if (pRenderObjectL->position.z < pivot)
l++;
else
break;
}
while (true)
{
mERROR_CHECK(mQueue_PointerAt(queue, r, &pRenderObjectR));
if (pRenderObjectR->position.z > pivot)
r--;
else
break;
}
if (l <= r)
{
std::swap(*pRenderObjectL, *pRenderObjectR);
l++;
r--;
}
};
if (left < r)
mERROR_CHECK(mSpriteBatch_QuickSortRenderObjects(queue, left, r));
if (l < right)
mERROR_CHECK(mSpriteBatch_QuickSortRenderObjects(queue, l, right));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_End, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(!spriteBatch->isStarted, mR_ResourceStateInvalid);
spriteBatch->isStarted = false;
if (!mSpriteBatch_Internal_DrawInstantly(spriteBatch))
{
mERROR_CHECK(mSpriteBatch_Internal_BindMesh(spriteBatch));
mERROR_CHECK(mShader_Bind(*spriteBatch->shader.GetPointer()));
mERROR_CHECK(mSpriteBatch_Internal_SetAlphaBlending(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetDrawOrder(spriteBatch));
mERROR_CHECK(mSpriteBatch_Internal_SetTextureFilterMode(spriteBatch));
size_t count;
mERROR_CHECK(mQueue_GetCount(spriteBatch->enqueuedRenderObjects, &count));
mERROR_CHECK(mSpriteBatch_QuickSortRenderObjects(spriteBatch->enqueuedRenderObjects, 0, count - 1));
if (spriteBatch->spriteSortMode == mSpriteBatch_SpriteSortMode::mSB_SSM_BackToFront)
{
for (size_t i = 0; i < count; ++i)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopFront(spriteBatch->enqueuedRenderObjects, &renderObject));
mDEFER_DESTRUCTION(&renderObject, mSpriteBatch_Internal_RenderObject_Destroy);
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
}
}
else
{
for (int64_t i = (int64_t)count - 1; i >= 0; i--)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopBack(spriteBatch->enqueuedRenderObjects, &renderObject));
mDEFER_DESTRUCTION(&renderObject, mSpriteBatch_Internal_RenderObject_Destroy);
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render(renderObject, spriteBatch));
}
}
}
else
{
size_t count;
mERROR_CHECK(mQueue_GetCount(spriteBatch->enqueuedRenderObjects, &count));
for (size_t i = 0; i < count; ++i)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopFront(spriteBatch->enqueuedRenderObjects, &renderObject));
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Destroy(&renderObject));
}
}
mRETURN_SUCCESS();
}
//////////////////////////////////////////////////////////////////////////
template<typename ...Args>
struct mSpriteBatch_GenerateShader;
template<>
struct mSpriteBatch_GenerateShader <>
{
static mFUNCTION(UnpackParams, mSpriteBatch_ShaderParams *)
{
mFUNCTION_SETUP();
mRETURN_SUCCESS();
}
};
template<typename T>
struct mSpriteBatch_GenerateShader <T>
{
static mFUNCTION(UnpackParams, mSpriteBatch_ShaderParams *pParams)
{
mFUNCTION_SETUP();
mERROR_IF(pParams == nullptr, mR_ArgumentNull);
switch (T::type)
{
case mSBE_T_Colour:
mERROR_IF(pParams->colour != 0, mR_InvalidParameter); // Colour parameter cannot be set twice.
pParams->colour = 1;
break;
case mSBE_T_TextureCrop:
mERROR_IF(pParams->textureCrop != 0, mR_InvalidParameter); // TextureCrop parameter cannot be set twice.
pParams->textureCrop = 1;
break;
case mSBE_T_Rotation:
mERROR_IF(pParams->rotation != 0, mR_InvalidParameter); // Rotation parameter cannot be set twice.
pParams->rotation = 1;
break;
case mSBE_T_MatrixTransform:
mERROR_IF(pParams->matrixTransform != 0, mR_InvalidParameter); // MatrixTransform parameter cannot be set twice.
pParams->matrixTransform = 1;
break;
case mSBE_T_TextureFlip:
mERROR_IF(pParams->textureFlip != 0, mR_InvalidParameter); // TextureFlip parameter cannot be set twice.
pParams->textureFlip = 1;
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
};
template<typename T, typename ...Args>
struct mSpriteBatch_GenerateShader <T, Args...>
{
static mFUNCTION(UnpackParams, mSpriteBatch_ShaderParams *pParams)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_GenerateShader<T>::UnpackParams(pParams));
mERROR_CHECK(mSpriteBatch_GenerateShader<Args...>::UnpackParams(pParams));
mRETURN_SUCCESS();
}
};
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Create_Internal, IN_OUT mSpriteBatch<Args...>* pSpriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(pSpriteBatch == nullptr, mR_ArgumentNull);
mERROR_CHECK(mQueue_Create(&pSpriteBatch->enqueuedRenderObjects, nullptr));
pSpriteBatch->isStarted = false;
pSpriteBatch->alphaMode = mSpriteBatch_AlphaMode::mSB_AM_AlphaBlend;
pSpriteBatch->spriteSortMode = mSpriteBatch_SpriteSortMode::mSB_SSM_BackToFront;
pSpriteBatch->textureSampleMode = mSpriteBatch_TextureSampleMode::mSB_TSM_LinearFiltering;
pSpriteBatch->shaderParams = { 0 };
mERROR_CHECK(mSpriteBatch_GenerateShader<Args...>::UnpackParams(&pSpriteBatch->shaderParams));
// Vertex Shader.
char vertexShader[1024] = "";
mERROR_IF(0 > sprintf_s(vertexShader, "#version 150 core\n\nin vec2 position0;\nin vec2 texCoord0;\nout vec2 _texCoord0;\n\nuniform vec2 screenSize0;\nuniform vec3 startOffset0;\nuniform vec2 scale0;\n"), mR_InternalError);
if (pSpriteBatch->shaderParams.rotation)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\nuniform float " mSBERotation_UniformName ";", vertexShader), mR_InternalError);
if (pSpriteBatch->shaderParams.matrixTransform)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\nuniform mat4 " mSBEMatrixTransform_UniformName ";", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\nvoid main()\n{\n\t_texCoord0 = texCoord0;\n\tvec4 position = vec4(position0, 0.0, 1.0);\n", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition.xy *= scale0;", vertexShader), mR_InternalError);
if (pSpriteBatch->shaderParams.rotation)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tvec2 oldPos = position.xy;\n\tposition.x = cos(" mSBERotation_UniformName ") * oldPos.x - sin(" mSBERotation_UniformName ") * oldPos.y;\n\tposition.y = sin(" mSBERotation_UniformName ") * oldPos.x + cos(" mSBERotation_UniformName ") * oldPos.y;", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition.xy = (position.xy + startOffset0.xy * 2 + scale0) / (screenSize0 * 2);", vertexShader), mR_InternalError);
if (pSpriteBatch->shaderParams.matrixTransform)
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition *= " mSBEMatrixTransform_UniformName ";", vertexShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(vertexShader, "%s\n\tposition.xy = position.xy * 2 - 1;\n\tposition.y = -position.y;\n\tposition.z = startOffset0.z;\n\n\tgl_Position = position;\n}\n", vertexShader), mR_InternalError);
// Fragment Shader.
char fragmentShader[1024] = "";
mERROR_IF(0 > sprintf_s(fragmentShader, "#version 150 core\n\nout vec4 fragColour0;\n\nin vec2 _texCoord0;\nuniform sampler2D texture0;\n"), mR_InternalError);
if (pSpriteBatch->shaderParams.colour)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\nuniform vec4 " mSBEColour_UniformName ";", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureFlip)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\nuniform vec2 " mSBETextureFlip_UniformName ";", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureCrop)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\nuniform vec4 " mSBETextureCrop_UniformName ";", fragmentShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\nvoid main()\n{\n\tvec2 texturePosition = _texCoord0;", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureFlip)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\ttexturePosition = texturePosition * (1 - 2 * " mSBETextureFlip_UniformName ") + " mSBETextureFlip_UniformName ";", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.textureCrop)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\ttexturePosition *= (" mSBETextureCrop_UniformName ".zw - " mSBETextureCrop_UniformName ".xy);\n\ttexturePosition += " mSBETextureCrop_UniformName ".xy;", fragmentShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\tfragColour0 = texture(texture0, texturePosition);", fragmentShader), mR_InternalError);
if (pSpriteBatch->shaderParams.colour)
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n\tfragColour0 *= " mSBEColour_UniformName ";", fragmentShader), mR_InternalError);
mERROR_IF(0 > sprintf_s(fragmentShader, "%s\n}\n", fragmentShader), mR_InternalError);
mERROR_CHECK(mSharedPointer_Allocate(&pSpriteBatch->shader, nullptr, (std::function<void(mShader *)>)[](mShader *pData) {mShader_Destroy(pData);}, 1));
mERROR_CHECK(mShader_Create(pSpriteBatch->shader.GetPointer(), vertexShader, fragmentShader, "fragColour0"));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Destroy_Internal, IN_OUT mSpriteBatch<Args...> *pSpriteBatch)
{
mFUNCTION_SETUP();
mERROR_IF(pSpriteBatch == nullptr, mR_ArgumentNull);
size_t queueSize = 0;
mERROR_CHECK(mQueue_GetCount(pSpriteBatch->enqueuedRenderObjects, &queueSize));
for (size_t i = 0; i < queueSize; ++i)
{
mSpriteBatch_Internal_RenderObject<Args...> renderObject;
mERROR_CHECK(mQueue_PopFront(pSpriteBatch->enqueuedRenderObjects, &renderObject));
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Destroy(&renderObject));
}
mERROR_CHECK(mSharedPointer_Destroy(&pSpriteBatch->shader));
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_SetAlphaBlending, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
switch (spriteBatch->alphaMode)
{
case mSB_AM_NoAlpha:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(false));
break;
case mSB_AM_Additive:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(true));
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
case mSB_AM_AlphaBlend:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(true));
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case mSB_AM_Premultiplied:
mERROR_CHECK(mRenderParams_SetBlendingEnabled(true));
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_SetDrawOrder, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
switch (spriteBatch->spriteSortMode)
{
case mSB_SSM_None:
glDisable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
break;
case mSB_SSM_BackToFront:
mERROR_CHECK(mRenderParams_ClearDepth());
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
break;
case mSB_SSM_FrontToBack:
mERROR_CHECK(mRenderParams_ClearDepth());
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_SetTextureFilterMode, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
switch (spriteBatch->textureSampleMode)
{
case mSB_TSM_NearestNeighbor:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case mSB_TSM_LinearFiltering:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_InitializeMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mVec2f buffer[8] = { {-1, -1}, {0, 0}, {-1, 1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}, {1, 1} };
glGenBuffers(1, &spriteBatch->vbo);
glBindBuffer(GL_ARRAY_BUFFER, spriteBatch->vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(buffer), buffer, GL_STATIC_DRAW);
mGL_DEBUG_ERROR_CHECK();
mRETURN_SUCCESS();
}
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_BindMesh, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mUnused(spriteBatch);
glBindBuffer(GL_ARRAY_BUFFER, spriteBatch->vbo);
glEnableVertexAttribArray((GLuint)0);
glVertexAttribPointer((GLuint)0, (GLint)2, GL_FLOAT, GL_FALSE, (GLsizei)sizeof(mVec2f) * 2, (const void *)0);
glEnableVertexAttribArray((GLuint)1);
glVertexAttribPointer((GLuint)1, (GLint)2, GL_FLOAT, GL_FALSE, (GLsizei)sizeof(mVec2f) * 2, (const void *)sizeof(mVec2f));
mRETURN_SUCCESS();
}
//////////////////////////////////////////////////////////////////////////
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_RenderObject_Create, OUT mSpriteBatch_Internal_RenderObject<Args...>* pRenderObject, const mPtr<mTexture>& texture, const mVec2f position, const mVec2f size, const float_t depth, Args && ...args)
{
mFUNCTION_SETUP();
mERROR_IF(pRenderObject == nullptr, mR_ArgumentNull);
pRenderObject->texture = texture;
pRenderObject->position = mVec3f(position, depth);
pRenderObject->size = size;
pRenderObject->args = std::make_tuple<Args...>(std::forward<Args>(args)...);
mRETURN_SUCCESS();
}
template <typename ...Args>
mFUNCTION(mSpriteBatch_Internal_RenderObject_Destroy, IN_OUT mSpriteBatch_Internal_RenderObject<Args...> *pRenderObject)
{
mFUNCTION_SETUP();
mERROR_IF(pRenderObject == nullptr, mR_ArgumentNull);
mERROR_CHECK(mSharedPointer_Destroy(&pRenderObject->texture));
pRenderObject->args.~tuple();
mRETURN_SUCCESS();
}
template<typename ...Args>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker;
template<>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker<>
{
static mFUNCTION(Unpack, mShader &)
{
mFUNCTION_SETUP();
mRETURN_SUCCESS();
}
};
template<typename T>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker<T>
{
static mFUNCTION(Unpack, mShader &shader, T t)
{
mFUNCTION_SETUP();
switch (T::type)
{
case mSBE_T_Colour:
mERROR_CHECK(mShader_SetUniform(shader, mSBEColour_UniformName, t));
break;
case mSBE_T_TextureCrop:
mERROR_CHECK(mShader_SetUniform(shader, mSBETextureCrop_UniformName, t));
break;
case mSBE_T_Rotation:
mERROR_CHECK(mShader_SetUniform(shader, mSBERotation_UniformName, t));
break;
case mSBE_T_MatrixTransform:
mERROR_CHECK(mShader_SetUniform(shader, mSBEMatrixTransform_UniformName, t));
break;
case mSBE_T_TextureFlip:
mERROR_CHECK(mShader_SetUniform(shader, mSBETextureFlip_UniformName, t));
break;
default:
mRETURN_RESULT(mR_OperationNotSupported);
break;
}
mRETURN_SUCCESS();
}
};
template<typename T, typename ...Args>
struct mSpriteBatch_Internal_RenderObject_Render_Unpacker<T, Args...>
{
static mFUNCTION(Unpack, mShader &shader, T t, Args... args)
{
mFUNCTION_SETUP();
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render_Unpacker<T>::Unpack(shader, t));
mERROR_CHECK(mSpriteBatch_Internal_RenderObject_Render_Unpacker<Args...>::Unpack(shader, std::forward<Args>(args)...));
mRETURN_SUCCESS();
}
};
template<typename ...Args>
inline mFUNCTION(mSpriteBatch_Internal_RenderObject_Render, mSpriteBatch_Internal_RenderObject<Args...> &renderObject, mPtr<mSpriteBatch<Args...>> &spriteBatch)
{
mFUNCTION_SETUP();
mERROR_CHECK(mShader_Bind(*spriteBatch->shader.GetPointer()));
mERROR_CHECK(mTexture_Bind(*renderObject.texture.GetPointer()));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "texture0", renderObject.texture));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "screenSize0", mRenderParams_CurrentRenderResolutionF));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "scale0", renderObject.size));
mERROR_CHECK(mShader_SetUniform(spriteBatch->shader, "startOffset0", renderObject.position));
// Set uniforms.
mERROR_CHECK(mForwardTuple(mSpriteBatch_Internal_RenderObject_Render_Unpacker<Args...>::Unpack, *spriteBatch->shader.GetPointer(), renderObject.args));
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
mRETURN_SUCCESS();
}
| 35.468886 | 462 | 0.746991 | rainerzufalldererste |
d1801e6e18ea9acf89550577865c582946405fda | 1,465 | cpp | C++ | vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_skinned_drawable_gpu_data.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | 1 | 2020-04-24T22:55:51.000Z | 2020-04-24T22:55:51.000Z | vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_skinned_drawable_gpu_data.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | null | null | null | vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_skinned_drawable_gpu_data.cpp | asilvaigor/opengl_winter | 0081c6ee39d493eb4f9e0ac92222937062866776 | [
"MIT"
] | null | null | null | //
// Created by igor on 14/05/2020.
//
#include "opengl/debug/opengl_debug.hpp"
#include "mesh_skinned_drawable_gpu_data.hpp"
namespace vcl {
mesh_skinned_drawable_gpu_data::mesh_skinned_drawable_gpu_data() : mesh_drawable_gpu_data(), vbo_skeleton(0) {}
mesh_skinned_drawable_gpu_data::mesh_skinned_drawable_gpu_data(const mesh_skinned &mesh_cpu_arg) :
mesh_drawable_gpu_data(mesh_cpu_arg) {
// temp copy of the mesh to fill all empty fields
mesh_skinned mesh_cpu = mesh_cpu_arg;
mesh_cpu.fill_empty_fields();
// Fill VBO for skeleton
glGenBuffers(1, &vbo_skeleton);
glBindBuffer(GL_ARRAY_BUFFER, vbo_skeleton);
if (!mesh_cpu.bones.empty())
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_bone_data) * mesh_cpu.bones.size(),
&mesh_cpu.bones[0], GL_STATIC_DRAW);
else
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(vao);
// Bones ids at layout 4
glBindBuffer(GL_ARRAY_BUFFER, vbo_skeleton);
glEnableVertexAttribArray(4);
glVertexAttribIPointer(4, 4, GL_INT, sizeof(vertex_bone_data), (const GLvoid *) nullptr);
// Bones weights at layout 5
glBindBuffer(GL_ARRAY_BUFFER, vbo_skeleton);
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_bone_data), (const GLvoid *) 16);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
} | 33.295455 | 111 | 0.733788 | asilvaigor |
d1814e87fd208b7a408d02149b61cdf8870840ca | 1,267 | hpp | C++ | events/gamepads_handler.hpp | MrTAB/aabGameEngine | dc51c6e443bf087ca10e14e6884e4dfa6caef4a8 | [
"MIT"
] | null | null | null | events/gamepads_handler.hpp | MrTAB/aabGameEngine | dc51c6e443bf087ca10e14e6884e4dfa6caef4a8 | [
"MIT"
] | null | null | null | events/gamepads_handler.hpp | MrTAB/aabGameEngine | dc51c6e443bf087ca10e14e6884e4dfa6caef4a8 | [
"MIT"
] | null | null | null |
/**
*
* gamepads_handler.hpp
*
* Phased out in favour of port handler and auto handler implementations
**/
#if !defined(AAB_EVENTS_GAMEPADS_HANDLER_CLASS)
#define AAB_EVENTS_GAMEPADS_HANDLER_CLASS
#include"gamepad_handler.hpp"
#include"gamepad_port_handler.hpp"
#include"imports.hpp"
#include<map>
namespace aab {
namespace events{
/*
class GamepadsHandler : public GamepadPortHandler
{
private:
//typedef std::map <int, GamepadHandler::Ptr> HandlerMap;
//HandlerMap handlersG;
public:
typedef aab::types::Smart <GamepadsHandler>::Ptr Ptr;
typedef aab::input::HatPosition HatPosition;
explicit GamepadsHandler (GamepadHandler::Ptr, int id = 0);
explicit GamepadsHandler ();
virtual ~GamepadsHandler () throw ();
//void setHandler (GamepadHandler::Ptr, int id);
//void clearHandler (int id);
//void clearHandlers ();
//GamepadHandler::Ptr getHandler (int id);
//bool hasHandler (int id) const;
//int countHandlers () const;
void buttonPressed (int, int);
void buttonReleased (int, int);
void axisMove (int, int, double);
void ballMove (int, int, double, double);
void hatMove (int, int, HatPosition);
};
*/
} // events
} // aab
#endif // AAB_EVENTS_GAMEPADS_HANDLER_CLASS
| 22.22807 | 74 | 0.700868 | MrTAB |
d1848fc6a0544ad7d0f1dcaa883452f99d5cd3f2 | 8,585 | cpp | C++ | src/b_bot.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | 2 | 2018-01-18T21:30:20.000Z | 2018-01-19T02:24:46.000Z | src/b_bot.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | src/b_bot.cpp | raa-eruanna/ProjectPanther | 7d703c162b4ede25faa3e99cacacb4fc79fb77da | [
"RSA-MD"
] | null | null | null | /*
**
**
**---------------------------------------------------------------------------
** Copyright 1999 Martin Colberg
** Copyright 1999-2016 Randy Heit
** Copyright 2005-2016 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
**---------------------------------------------------------------------------
**
*/
// Cajun bot
//
// [RH] Moved console commands out of d_netcmd.c (in Cajun source), because
// they don't really belong there.
#include "c_cvars.h"
#include "c_dispatch.h"
#include "b_bot.h"
#include "m_argv.h"
#include "doomstat.h"
#include "p_local.h"
#include "cmdlib.h"
#include "teaminfo.h"
#include "d_net.h"
#include "serializer.h"
#include "d_player.h"
#include "vm.h"
IMPLEMENT_CLASS(DBot, false, true)
IMPLEMENT_POINTERS_START(DBot)
IMPLEMENT_POINTER(dest)
IMPLEMENT_POINTER(prev)
IMPLEMENT_POINTER(enemy)
IMPLEMENT_POINTER(missile)
IMPLEMENT_POINTER(mate)
IMPLEMENT_POINTER(last_mate)
IMPLEMENT_POINTERS_END
DEFINE_FIELD(DBot, dest)
DBot::DBot ()
: DThinker(STAT_BOT)
{
Clear ();
}
void DBot::Clear ()
{
player = NULL;
Angle = 0.;
dest = NULL;
prev = NULL;
enemy = NULL;
missile = NULL;
mate = NULL;
last_mate = NULL;
memset(&skill, 0, sizeof(skill));
t_active = 0;
t_respawn = 0;
t_strafe = 0;
t_react = 0;
t_fight = 0;
t_roam = 0;
t_rocket = 0;
first_shot = true;
sleft = false;
allround = false;
increase = false;
old = { 0, 0 };
}
FSerializer &Serialize(FSerializer &arc, const char *key, botskill_t &skill, botskill_t *def)
{
if (arc.BeginObject(key))
{
arc("aiming", skill.aiming)
("perfection", skill.perfection)
("reaction", skill.reaction)
("isp", skill.isp)
.EndObject();
}
return arc;
}
void DBot::Serialize(FSerializer &arc)
{
Super::Serialize (arc);
arc("player", player)
("angle", Angle)
("dest", dest)
("prev", prev)
("enemy", enemy)
("missile", missile)
("mate", mate)
("lastmate", last_mate)
("skill", skill)
("active", t_active)
("respawn", t_respawn)
("strafe", t_strafe)
("react", t_react)
("fight", t_fight)
("roam", t_roam)
("rocket", t_rocket)
("firstshot", first_shot)
("sleft", sleft)
("allround", allround)
("increase", increase)
("old", old);
}
void DBot::Tick ()
{
Super::Tick ();
if (player->mo == NULL || bglobal.freeze)
{
return;
}
BotThinkCycles.Clock();
bglobal.m_Thinking = true;
Think ();
bglobal.m_Thinking = false;
BotThinkCycles.Unclock();
}
CVAR (Int, bot_next_color, 11, 0)
CVAR (Bool, bot_observer, false, 0)
CCMD (addbot)
{
if (gamestate != GS_LEVEL && gamestate != GS_INTERMISSION)
{
Printf ("Bots cannot be added when not in a game!\n");
return;
}
if (!players[consoleplayer].settings_controller)
{
Printf ("Only setting controllers can add bots\n");
return;
}
if (argv.argc() > 2)
{
Printf ("addbot [botname] : add a bot to the game\n");
return;
}
if (argv.argc() > 1)
bglobal.SpawnBot (argv[1]);
else
bglobal.SpawnBot (NULL);
}
void FCajunMaster::ClearPlayer (int i, bool keepTeam)
{
if (players[i].mo)
{
players[i].mo->Destroy ();
players[i].mo = NULL;
}
botinfo_t *bot = botinfo;
while (bot && stricmp (players[i].userinfo.GetName(), bot->name))
bot = bot->next;
if (bot)
{
bot->inuse = BOTINUSE_No;
bot->lastteam = keepTeam ? players[i].userinfo.GetTeam() : TEAM_NONE;
}
if (players[i].Bot != NULL)
{
players[i].Bot->Destroy ();
players[i].Bot = NULL;
}
players[i].~player_t();
::new(&players[i]) player_t;
players[i].userinfo.Reset();
playeringame[i] = false;
}
CCMD (removebots)
{
if (!players[consoleplayer].settings_controller)
{
Printf ("Only setting controllers can remove bots\n");
return;
}
Net_WriteByte (DEM_KILLBOTS);
}
CCMD (freeze)
{
if (CheckCheatmode ())
return;
if (netgame && !players[consoleplayer].settings_controller)
{
Printf ("Only setting controllers can use freeze mode\n");
return;
}
Net_WriteByte (DEM_GENERICCHEAT);
Net_WriteByte (CHT_FREEZE);
}
CCMD (listbots)
{
botinfo_t *thebot = bglobal.botinfo;
int count = 0;
while (thebot)
{
Printf ("%s%s\n", thebot->name, thebot->inuse == BOTINUSE_Yes ? " (active)" : "");
thebot = thebot->next;
count++;
}
Printf ("> %d bots\n", count);
}
// set the bot specific weapon information
// This is intentionally not in the weapon definition anymore.
void InitBotStuff()
{
static struct BotInit
{
const char *type;
int movecombatdist;
int weaponflags;
const char *projectile;
} botinits[] = {
{ "Pistol", 25000000, 0, NULL },
{ "Shotgun", 24000000, 0, NULL },
{ "SuperShotgun", 15000000, 0, NULL },
{ "Chaingun", 27000000, 0, NULL },
{ "RocketLauncher", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "Rocket" },
{ "PlasmaRifle", 27000000, 0, "PlasmaBall" },
{ "BFG9000", 10000000, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_BFG, "BFGBall" },
{ "GoldWand", 25000000, 0, NULL },
{ "GoldWandPowered", 25000000, 0, NULL },
{ "Crossbow", 24000000, 0, "CrossbowFX1" },
{ "CrossbowPowered", 24000000, 0, "CrossbowFX2" },
{ "Blaster", 27000000, 0, NULL },
{ "BlasterPowered", 27000000, 0, "BlasterFX1" },
{ "SkullRod", 27000000, 0, "HornRodFX1" },
{ "SkullRodPowered", 27000000, 0, "HornRodFX2" },
{ "PhoenixRod", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "PhoenixFX1" },
{ "Mace", 27000000, WIF_BOT_REACTION_SKILL_THING, "MaceFX2" },
{ "MacePowered", 27000000, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "MaceFX4" },
{ "FWeapHammer", 22000000, 0, "HammerMissile" },
{ "FWeapQuietus", 20000000, 0, "FSwordMissile" },
{ "CWeapStaff", 25000000, 0, "CStaffMissile" },
{ "CWeapFlane", 27000000, 0, "CFlameMissile" },
{ "MWeapWand", 25000000, 0, "MageWandMissile" },
{ "CWeapWraithverge", 22000000, 0, "HolyMissile" },
{ "MWeapFrost", 19000000, 0, "FrostMissile" },
{ "MWeapLightning", 23000000, 0, "LightningFloor" },
{ "MWeapBloodscourge", 20000000, 0, "MageStaffFX2" },
{ "StrifeCrossbow", 24000000, 0, "ElectricBolt" },
{ "StrifeCrossbow2", 24000000, 0, "PoisonBolt" },
{ "AssaultGun", 27000000, 0, NULL },
{ "MiniMissileLauncher", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "MiniMissile" },
{ "FlameThrower", 24000000, 0, "FlameMissile" },
{ "Mauler", 15000000, 0, NULL },
{ "Mauler2", 10000000, 0, "MaulerTorpedo" },
{ "StrifeGrenadeLauncher", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "HEGrenade" },
{ "StrifeGrenadeLauncher2", 18350080, WIF_BOT_REACTION_SKILL_THING|WIF_BOT_EXPLOSIVE, "PhosphorousGrenade" },
};
for(unsigned i=0;i<sizeof(botinits)/sizeof(botinits[0]);i++)
{
const PClass *cls = PClass::FindClass(botinits[i].type);
if (cls != NULL && cls->IsDescendantOf(NAME_Weapon))
{
AWeapon *w = (AWeapon*)GetDefaultByType(cls);
if (w != NULL)
{
w->MoveCombatDist = botinits[i].movecombatdist/65536.;
w->WeaponFlags |= botinits[i].weaponflags;
w->ProjectileType = PClass::FindActor(botinits[i].projectile);
}
}
}
static const char *warnbotmissiles[] = { "PlasmaBall", "Ripper", "HornRodFX1" };
for(unsigned i=0;i<countof(warnbotmissiles);i++)
{
AActor *a = GetDefaultByName (warnbotmissiles[i]);
if (a != NULL)
{
a->flags3|=MF3_WARNBOT;
}
}
}
| 26.578947 | 111 | 0.672103 | raa-eruanna |
d1858c3f1c1dffc93b1e44784dbdace07a833ef4 | 55,855 | cpp | C++ | Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessMotionBlur.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessMotionBlur.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessMotionBlur.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
PostProcessMotionBlur.cpp: Post process MotionBlur implementation.
=============================================================================*/
#include "RendererPrivate.h"
#include "ScenePrivate.h"
#include "SceneFilterRendering.h"
#include "PostProcessAmbientOcclusion.h"
#include "PostProcessMotionBlur.h"
#include "PostProcessAmbientOcclusion.h"
#include "PostProcessing.h"
#include "SceneUtils.h"
#include "GPUSkinVertexFactory.h"
#include "../../Engine/Private/SkeletalRenderGPUSkin.h"
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
static TAutoConsoleVariable<int32> CVarMotionBlurFiltering(
TEXT("r.MotionBlurFiltering"),
0,
TEXT("Useful developer variable\n")
TEXT("0: off (default, expected by the shader for better quality)\n")
TEXT("1: on"),
ECVF_Cheat | ECVF_RenderThreadSafe);
#endif
static TAutoConsoleVariable<int32> CVarMotionBlurSmoothMax(
TEXT("r.MotionBlurSmoothMax"),
0,
TEXT("Useful developer variable\n")
TEXT("0: off (default, expected by the shader for better quality)\n")
TEXT("1: on"),
ECVF_Cheat | ECVF_RenderThreadSafe);
/** Encapsulates the post processing motion blur vertex shader. */
class FPostProcessMotionBlurSetupVS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessMotionBlurSetupVS,Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
/** Default constructor. */
FPostProcessMotionBlurSetupVS() {}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter;
return bShaderHasOutdatedParameters;
}
/** to have a similar interface as all other shaders */
void SetParameters(const FRenderingCompositePassContext& Context)
{
const auto ShaderRHI = GetVertexShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
PostprocessParameter.SetVS(ShaderRHI, Context, TStaticSamplerState<SF_Point, AM_Clamp, AM_Clamp, AM_Clamp>::GetRHI());
}
public:
FPostProcessPassParameters PostprocessParameter;
/** Initialization constructor. */
FPostProcessMotionBlurSetupVS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
}
};
IMPLEMENT_SHADER_TYPE(,FPostProcessMotionBlurSetupVS,TEXT("PostProcessMotionBlur"),TEXT("SetupVS"),SF_Vertex);
/** Encapsulates the post processing motion blur pixel shader. */
class FPostProcessMotionBlurSetupPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessMotionBlurSetupPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
/** Default constructor. */
FPostProcessMotionBlurSetupPS() {}
public:
FPostProcessPassParameters PostprocessParameter;
FShaderParameter VelocityScale;
/** Initialization constructor. */
FPostProcessMotionBlurSetupPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
VelocityScale.Bind( Initializer.ParameterMap, TEXT("VelocityScale") );
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter << VelocityScale;
return bShaderHasOutdatedParameters;
}
void SetParameters(const FRenderingCompositePassContext& Context)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Point, AM_Clamp, AM_Clamp, AM_Clamp>::GetRHI());
{
const float SizeX = Context.View.ViewRect.Width();
const float SizeY = Context.View.ViewRect.Height();
const float InvAspectRatio = SizeY / SizeX;
const FSceneViewState* ViewState = (FSceneViewState*) Context.View.State;
const float MotionBlurTimeScale = ViewState ? ViewState->MotionBlurTimeScale : 1.0f;
const float ViewMotionBlurScale = 0.5f * MotionBlurTimeScale * Context.View.FinalPostProcessSettings.MotionBlurAmount;
// 0:no 1:full screen width
float MaxVelocity = Context.View.FinalPostProcessSettings.MotionBlurMax / 100.0f;
float InvMaxVelocity = 1.0f / MaxVelocity;
float ObjectScaleX = ViewMotionBlurScale * InvMaxVelocity;
float ObjectScaleY = ViewMotionBlurScale * InvMaxVelocity * InvAspectRatio;
SetShaderValue(Context.RHICmdList, ShaderRHI, VelocityScale, FVector4(ObjectScaleX, -ObjectScaleY, 0, 0));
}
}
};
IMPLEMENT_SHADER_TYPE(,FPostProcessMotionBlurSetupPS, TEXT("PostProcessMotionBlur"), TEXT("SetupPS"), SF_Pixel);
void FRCPassPostProcessMotionBlurSetup::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, MotionBlurSetup);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
const FSceneViewFamily& ViewFamily = *(View.Family);
FIntPoint SrcSize = InputDesc->Extent;
FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent;
// e.g. 4 means the input texture is 4x smaller than the buffer size
uint32 ScaleFactor = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY().X / SrcSize.X;
FIntRect SrcRect = View.ViewRect / ScaleFactor;
// Viewport size not even also causes issue
FIntRect DestRect = FIntRect::DivideAndRoundUp(SrcRect, 2);
const FSceneRenderTargetItem& DestRenderTarget0 = PassOutputs[0].RequestSurface(Context);
const FSceneRenderTargetItem& DestRenderTarget1 = PassOutputs[1].RequestSurface(Context);
// Set the view family's render target/viewport.
FTextureRHIParamRef RenderTargets[] =
{
DestRenderTarget0.TargetableTexture,
DestRenderTarget1.TargetableTexture
};
SetRenderTargets(Context.RHICmdList, ARRAY_COUNT(RenderTargets), RenderTargets, FTextureRHIParamRef(), 0, NULL);
// is optimized away if possible (RT size=view size, )
FLinearColor ClearColors[2] = {FLinearColor(0,0,0,0), FLinearColor(0,0,0,0)};
Context.RHICmdList.ClearMRT(true, 2, ClearColors, false, 1.0f, false, 0, DestRect);
Context.SetViewportAndCallRHI(0, 0, 0.0f, DestSize.X, DestSize.Y, 1.0f );
// set the state
Context.RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
TShaderMapRef<FPostProcessMotionBlurSetupVS> VertexShader(Context.GetShaderMap());
{
TShaderMapRef<FPostProcessMotionBlurSetupPS > PixelShader(Context.GetShaderMap());
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(Context.RHICmdList, Context.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
PixelShader->SetParameters(Context);
VertexShader->SetParameters(Context);
}
// Draw a quad mapping scene color to the view's render target
DrawRectangle(
Context.RHICmdList,
DestRect.Min.X, DestRect.Min.Y,
DestRect.Width(), DestRect.Height(),
SrcRect.Min.X, SrcRect.Min.Y,
SrcRect.Width(), SrcRect.Height(),
DestSize,
SrcSize,
*VertexShader,
EDRF_UseTriangleOptimization);
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget0.TargetableTexture, DestRenderTarget0.ShaderResourceTexture, false, FResolveParams());
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget1.TargetableTexture, DestRenderTarget1.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessMotionBlurSetup::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
if(InPassOutputId == ePId_Output0)
{
// downsampled velocity
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.Extent /= 2;
Ret.Extent.X = FMath::Max(1, Ret.Extent.X);
Ret.Extent.Y = FMath::Max(1, Ret.Extent.Y);
// we need at least a format in the range 0..1 with RGB channels, A is unused
// Ret.Format = PF_A2B10G10R10;
// we need alpha to renormalize
Ret.Format = PF_FloatRGBA;
Ret.TargetableFlags &= ~TexCreate_UAV;
Ret.TargetableFlags |= TexCreate_RenderTargetable;
Ret.DebugName = TEXT("MotionBlurSetup0");
return Ret;
}
else
{
check(InPassOutputId == ePId_Output1);
// scene color with depth in alpha
FPooledRenderTargetDesc Ret = GetInput(ePId_Input1)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.Extent /= 2;
Ret.Extent.X = FMath::Max(1, Ret.Extent.X);
Ret.Extent.Y = FMath::Max(1, Ret.Extent.Y);
Ret.Format = PF_FloatRGBA;
Ret.TargetableFlags &= ~TexCreate_UAV;
Ret.TargetableFlags |= TexCreate_RenderTargetable;
Ret.DebugName = TEXT("MotionBlurSetup1");
return Ret;
}
}
/**
* @param Quality 0: visualize, 1:low, 2:medium, 3:high, 4:very high
* Encapsulates a MotionBlur pixel shader.
*/
template <uint32 Quality>
class FPostProcessMotionBlurPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessMotionBlurPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("MOTION_BLUR_QUALITY"), Quality);
}
/** Default constructor. */
FPostProcessMotionBlurPS() {}
public:
FPostProcessPassParameters PostprocessParameter;
FDeferredPixelShaderParameters DeferredParameters;
FShaderParameter PrevViewProjMatrix;
FShaderParameter TextureViewMad;
FShaderParameter MotionBlurParameters;
FShaderResourceParameter BoneMatrices0;
FShaderResourceParameter BoneMatrices1;
/** Initialization constructor. */
FPostProcessMotionBlurPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
DeferredParameters.Bind(Initializer.ParameterMap);
PrevViewProjMatrix.Bind(Initializer.ParameterMap, TEXT("PrevViewProjMatrix"));
TextureViewMad.Bind(Initializer.ParameterMap, TEXT("TextureViewMad"));
MotionBlurParameters.Bind(Initializer.ParameterMap, TEXT("MotionBlurParameters"));
BoneMatrices0.Bind(Initializer.ParameterMap,TEXT("BoneMatrices0"));
BoneMatrices1.Bind(Initializer.ParameterMap,TEXT("BoneMatrices1"));
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter << DeferredParameters << PrevViewProjMatrix << TextureViewMad << MotionBlurParameters << BoneMatrices0 << BoneMatrices1;
return bShaderHasOutdatedParameters;
}
void SetParameters(const FRenderingCompositePassContext& Context)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
DeferredParameters.Set(Context.RHICmdList, ShaderRHI, Context.View);
{
bool bFiltered = false;
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
bFiltered = CVarMotionBlurFiltering.GetValueOnRenderThread() != 0;
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
if(bFiltered)
{
PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Bilinear,AM_Border,AM_Border,AM_Clamp>::GetRHI());
}
else
{
PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Point,AM_Border,AM_Border,AM_Clamp>::GetRHI());
}
}
if( Context.View.Family->EngineShowFlags.CameraInterpolation )
{
// Instead of finding the world space position of the current pixel, calculate the world space position offset by the camera position,
// then translate by the difference between last frame's camera position and this frame's camera position,
// then apply the rest of the transforms. This effectively avoids precision issues near the extents of large levels whose world space position is very large.
FVector ViewOriginDelta = Context.View.ViewMatrices.ViewOrigin - Context.View.PrevViewMatrices.ViewOrigin;
SetShaderValue(Context.RHICmdList, ShaderRHI, PrevViewProjMatrix, FTranslationMatrix(ViewOriginDelta) * Context.View.PrevViewRotationProjMatrix);
}
else
{
SetShaderValue(Context.RHICmdList, ShaderRHI, PrevViewProjMatrix, Context.View.ViewMatrices.GetViewRotationProjMatrix());
}
TRefCountPtr<IPooledRenderTarget> InputPooledElement = Context.Pass->GetInput(ePId_Input0)->GetOutput()->RequestInput();
// to mask out samples from outside of the view
{
FIntPoint BufferSize = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY();
FVector2D InvBufferSize(1.0f / BufferSize.X, 1.0f / BufferSize.Y);
FIntRect ClipRect = Context.View.ViewRect;
// to avoid leaking in content from the outside because of bilinear filtering, shrink
ClipRect.InflateRect(-1);
FVector2D MinUV(ClipRect.Min.X * InvBufferSize.X, ClipRect.Min.Y * InvBufferSize.Y);
FVector2D MaxUV(ClipRect.Max.X * InvBufferSize.X, ClipRect.Max.Y * InvBufferSize.Y);
FVector2D SizeUV = MaxUV - MinUV;
FVector2D Mul(1.0f / SizeUV.X, 1.0f / SizeUV.Y);
FVector2D Add = - MinUV * Mul;
FVector4 TextureViewMadValue(Mul.X, Mul.Y, Add.X, Add.Y);
SetShaderValue(Context.RHICmdList, ShaderRHI, TextureViewMad, TextureViewMadValue);
}
{
const float SizeX = Context.View.ViewRect.Width();
const float SizeY = Context.View.ViewRect.Height();
const float AspectRatio = SizeX / SizeY;
const float InvAspectRatio = SizeY / SizeX;
const FSceneViewState* ViewState = (FSceneViewState*) Context.View.State;
float MotionBlurTimeScale = ViewState ? ViewState->MotionBlurTimeScale : 1.0f;
float ViewMotionBlurScale = 0.5f * MotionBlurTimeScale * Context.View.FinalPostProcessSettings.MotionBlurAmount;
// MotionBlurInstanceScale was needed to hack some cases where motion blur wasn't working well, this shouldn't be needed any more, can clean this up later
float MotionBlurInstanceScale = 1;
float ObjectMotionBlurScale = MotionBlurInstanceScale * ViewMotionBlurScale;
// 0:no 1:full screen width, percent conversion
float MaxVelocity = Context.View.FinalPostProcessSettings.MotionBlurMax / 100.0f;
float InvMaxVelocity = 1.0f / MaxVelocity;
// *2 to convert to -1..1 -1..1 screen space
// / MaxFraction to map screenpos to -1..1 normalized MaxFraction
FVector4 MotionBlurParametersValue(
ObjectMotionBlurScale * InvMaxVelocity,
- ObjectMotionBlurScale * InvMaxVelocity * InvAspectRatio,
MaxVelocity * 2,
- MaxVelocity * 2 * AspectRatio);
SetShaderValue(Context.RHICmdList, ShaderRHI, MotionBlurParameters, MotionBlurParametersValue);
}
SetSRVParameter(Context.RHICmdList, ShaderRHI, BoneMatrices0, GPrevPerBoneMotionBlur.GetBoneDataVertexBuffer(0)->BoneBuffer.VertexBufferSRV);
SetSRVParameter(Context.RHICmdList, ShaderRHI, BoneMatrices1, GPrevPerBoneMotionBlur.GetBoneDataVertexBuffer(1)->BoneBuffer.VertexBufferSRV);
}
static const TCHAR* GetSourceFilename()
{
return TEXT("PostProcessMotionBlur");
}
static const TCHAR* GetFunctionName()
{
return TEXT("MainPS");
}
};
// #define avoids a lot of code duplication
#define VARIATION1(A) typedef FPostProcessMotionBlurPS<A> FPostProcessMotionBlurPS##A; \
IMPLEMENT_SHADER_TYPE2(FPostProcessMotionBlurPS##A, SF_Pixel);
VARIATION1(0) VARIATION1(1) VARIATION1(2) VARIATION1(3) VARIATION1(4)
#undef VARIATION1
// @param Quality 0: visualize, 1:low, 2:medium, 3:high, 4:very high
template <uint32 Quality>
static void SetMotionBlurShaderTempl(const FRenderingCompositePassContext& Context)
{
TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
TShaderMapRef<FPostProcessMotionBlurPS<Quality> > PixelShader(Context.GetShaderMap());
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(Context.RHICmdList, Context.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
VertexShader->SetParameters(Context);
PixelShader->SetParameters(Context);
}
FRCPassPostProcessMotionBlur::FRCPassPostProcessMotionBlur(uint32 InQuality)
: Quality(InQuality)
{
// internal error
check(Quality >= 1 && Quality <= 4);
}
void FRCPassPostProcessMotionBlur::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, MotionBlur);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
FIntPoint TexSize = InputDesc->Extent;
// we assume the input and output is full resolution
FIntPoint SrcSize = InputDesc->Extent;
FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent;
// e.g. 4 means the input texture is 4x smaller than the buffer size
uint32 ScaleFactor = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY().X / SrcSize.X;
FIntRect SrcRect = FIntRect::DivideAndRoundUp(View.ViewRect, ScaleFactor);
FIntRect DestRect = SrcRect;
const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);
// Set the view family's render target/viewport.
SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef());
// is optimized away if possible (RT size=view size, )
Context.RHICmdList.Clear(true, FLinearColor::Black, false, 1.0f, false, 0, SrcRect);
Context.SetViewportAndCallRHI(SrcRect);
// set the state
Context.RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
if(Quality == 1)
{
SetMotionBlurShaderTempl<1>(Context);
}
else if(Quality == 2)
{
SetMotionBlurShaderTempl<2>(Context);
}
else if(Quality == 3)
{
SetMotionBlurShaderTempl<3>(Context);
}
else
{
check(Quality == 4);
SetMotionBlurShaderTempl<4>(Context);
}
TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
// Draw a quad mapping scene color to the view's render target
DrawRectangle(
Context.RHICmdList,
0, 0,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Min.X, SrcRect.Min.Y,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Size(),
SrcSize,
*VertexShader,
EDRF_UseTriangleOptimization);
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessMotionBlur::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.DebugName = TEXT("MotionBlur");
return Ret;
}
/** Encapsulates a MotionBlur recombine pixel shader. */
class FPostProcessMotionBlurRecombinePS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessMotionBlurRecombinePS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
}
/** Default constructor. */
FPostProcessMotionBlurRecombinePS() {}
public:
FPostProcessPassParameters PostprocessParameter;
/** Initialization constructor. */
FPostProcessMotionBlurRecombinePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter;
return bShaderHasOutdatedParameters;
}
void SetParameters(const FRenderingCompositePassContext& Context, bool bBilinear)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
if(bBilinear)
{
PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Bilinear, AM_Border, AM_Border, AM_Clamp>::GetRHI());
}
else
{
PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Point, AM_Border, AM_Border, AM_Clamp>::GetRHI());
}
}
};
IMPLEMENT_SHADER_TYPE(,FPostProcessMotionBlurRecombinePS,TEXT("PostProcessMotionBlur"),TEXT("MainRecombinePS"),SF_Pixel);
void FRCPassPostProcessMotionBlurRecombine::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, MotionBlurRecombine);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
FIntPoint TexSize = InputDesc->Extent;
// we assume the input and output is full resolution
FIntPoint SrcSize = InputDesc->Extent;
FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent;
// e.g. 4 means the input texture is 4x smaller than the buffer size
uint32 ScaleFactor = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY().X / SrcSize.X;
FIntRect SrcRect = View.ViewRect / ScaleFactor;
FIntRect DestRect = SrcRect;
const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);
// Set the view family's render target/viewport.
SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef());
// is optimized away if possible (RT size=view size, )
Context.RHICmdList.Clear(true, FLinearColor::Black, false, 1.0f, false, 0, SrcRect);
Context.SetViewportAndCallRHI(SrcRect);
// set the state
Context.RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
TShaderMapRef<FPostProcessMotionBlurRecombinePS> PixelShader(Context.GetShaderMap());
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(Context.RHICmdList, Context.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
// with point filtering we can better debug in Visualize MotionBlur
const bool bBilinear = !View.Family->EngineShowFlags.VisualizeMotionBlur;
VertexShader->SetParameters(Context);
PixelShader->SetParameters(Context, bBilinear);
// Draw a quad mapping scene color to the view's render target
DrawRectangle(
Context.RHICmdList,
0, 0,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Min.X, SrcRect.Min.Y,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Size(),
SrcSize,
*VertexShader,
EDRF_UseTriangleOptimization);
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessMotionBlurRecombine::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
// we don't need the alpha channel and 32bit is faster and costs less memory
Ret.Format = PF_FloatRGB;
Ret.DebugName = TEXT("MotionBlurRecombine");
return Ret;
}
FIntPoint GetNumTiles16x16( FIntPoint PixelExtent )
{
uint32 TilesX = (PixelExtent.X + 15) / 16;
uint32 TilesY = (PixelExtent.Y + 15) / 16;
return FIntPoint( TilesX, TilesY );
}
class FPostProcessVelocityFlattenCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessVelocityFlattenCS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
}
FPostProcessVelocityFlattenCS() {}
public:
FShaderParameter OutVelocityFlat; // UAV
FShaderParameter OutMaxTileVelocity; // UAV
FPostProcessVelocityFlattenCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
OutVelocityFlat.Bind(Initializer.ParameterMap, TEXT("OutVelocityFlat"));
OutMaxTileVelocity.Bind(Initializer.ParameterMap, TEXT("OutMaxTileVelocity"));
}
void SetCS( FRHICommandList& RHICmdList, const FRenderingCompositePassContext& Context, const FSceneView& View )
{
const FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
FGlobalShader::SetParameters(RHICmdList, ShaderRHI, Context.View);
PostprocessParameter.SetCS(ShaderRHI, Context, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI());
SetUniformBufferParameter(RHICmdList, ShaderRHI, GetUniformBufferParameter<FCameraMotionParameters>(), CreateCameraMotionParametersUniformBuffer(Context.View));
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter;
Ar << OutVelocityFlat;
Ar << OutMaxTileVelocity;
return bShaderHasOutdatedParameters;
}
private:
FPostProcessPassParameters PostprocessParameter;
};
IMPLEMENT_SHADER_TYPE(,FPostProcessVelocityFlattenCS,TEXT("PostProcessVelocityFlatten"),TEXT("VelocityFlattenMain"),SF_Compute);
FRCPassPostProcessVelocityFlatten::FRCPassPostProcessVelocityFlatten()
: AsyncJobFenceID(-1)
{}
void FRCPassPostProcessVelocityFlatten::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, VelocityFlatten);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if (AsyncJobFenceID != -1)
{
// If we run with AsyncCompute we use the same node twice, once to start the AsyncCompute and once to wait for the result.
// The later one is happening here.
Context.RHICmdList.GraphicsWaitOnAsyncComputeJob(AsyncJobFenceID);
AsyncJobFenceID = -1;
return;
}
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
const FSceneViewFamily& ViewFamily = *(View.Family);
const FSceneRenderTargetItem& DestRenderTarget0 = PassOutputs[0].RequestSurface(Context);
const FSceneRenderTargetItem& DestRenderTarget1 = PassOutputs[1].RequestSurface(Context);
TShaderMapRef< FPostProcessVelocityFlattenCS > ComputeShader( Context.GetShaderMap() );
const bool bAsyncComputeEnabled = IsAsyncComputeEnabled();
SetRenderTarget(Context.RHICmdList, FTextureRHIRef(), FTextureRHIRef());
if(bAsyncComputeEnabled)
{
// If AsyncCompute is enabled we start recording the commands for that
Context.RHICmdList.BeginAsyncComputeJob_DrawThread(AsyncComputePriority_Default);
}
Context.SetViewportAndCallRHI( View.ViewRect );
Context.RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
// set destination
Context.RHICmdList.SetUAVParameter(ComputeShader->GetComputeShader(), ComputeShader->OutVelocityFlat.GetBaseIndex(), DestRenderTarget0.UAV);
Context.RHICmdList.SetUAVParameter(ComputeShader->GetComputeShader(), ComputeShader->OutMaxTileVelocity.GetBaseIndex(), DestRenderTarget1.UAV);
ComputeShader->SetCS(Context.RHICmdList, Context, View);
FIntPoint ThreadGroupCountValue = GetNumTiles16x16(View.ViewRect.Size());
DispatchComputeShader(Context.RHICmdList, *ComputeShader, ThreadGroupCountValue.X, ThreadGroupCountValue.Y, 1);
#if USE_ASYNC_COMPUTE_CONTEXT
if ( AsyncJobFenceID != -1 )
{
Context.RHICmdList.GraphicsWaitOnAsyncComputeJob(AsyncJobFenceID);
AsyncJobFenceID = -1;
}
#endif
// void FD3D11DynamicRHI::RHIGraphicsWaitOnAsyncComputeJob( uint32 FenceIndex )
Context.RHICmdList.FlushComputeShaderCache();
// un-set destination
Context.RHICmdList.SetUAVParameter(ComputeShader->GetComputeShader(), ComputeShader->OutVelocityFlat.GetBaseIndex(), NULL);
Context.RHICmdList.SetUAVParameter(ComputeShader->GetComputeShader(), ComputeShader->OutMaxTileVelocity.GetBaseIndex(), NULL);
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget0.TargetableTexture, DestRenderTarget0.ShaderResourceTexture, false, FResolveParams());
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget1.TargetableTexture, DestRenderTarget1.ShaderResourceTexture, false, FResolveParams());
// we want this pass to be executed another time
// so we do this: CompositeContext.Process(VelocityFlattenPass, TEXT("VelocityFlattenPass"));
// and this: bProcessWasCalled = false;
if(bAsyncComputeEnabled)
{
// we end recording the commands for AsyncCompute and get back a number to wait for it with GraphicsWaitOnAsyncComputeJob()
AsyncJobFenceID = Context.RHICmdList.EndAsyncComputeJob_DrawThread();
// mark it not processed so it gets executed a second time
bProcessWasCalled = false;
// we run this Process() two times and want to not get the dependencies processed twice (could be moved into the ComposingGraph iteration, slower but easier coding)
SetInput(ePId_Input0, FRenderingCompositeOutputRef());
SetInput(ePId_Input1, FRenderingCompositeOutputRef());
}
}
FPooledRenderTargetDesc FRCPassPostProcessVelocityFlatten::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
if( InPassOutputId == ePId_Output0 )
{
// Flattened velocity
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.ClearValue = FClearValueBinding::None;
Ret.Format = PF_FloatR11G11B10;
Ret.TargetableFlags |= TexCreate_UAV;
Ret.TargetableFlags |= TexCreate_RenderTargetable;
Ret.DebugName = TEXT("VelocityFlat");
return Ret;
}
else
{
// Max tile velocity
FPooledRenderTargetDesc UnmodifiedRet = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
UnmodifiedRet.Reset();
FIntPoint PixelExtent = UnmodifiedRet.Extent;
FIntPoint TileCount = GetNumTiles16x16(PixelExtent);
FPooledRenderTargetDesc Ret(FPooledRenderTargetDesc::Create2DDesc(TileCount, PF_FloatRGBA, FClearValueBinding::None, TexCreate_None, TexCreate_RenderTargetable | TexCreate_UAV, false));
Ret.DebugName = TEXT("MaxVelocity");
return Ret;
}
}
class FScatterQuadIndexBuffer : public FIndexBuffer
{
public:
virtual void InitRHI() override
{
const uint32 Size = sizeof(uint16) * 6 * 8;
const uint32 Stride = sizeof(uint16);
FRHIResourceCreateInfo CreateInfo;
void* Buffer = nullptr;
IndexBufferRHI = RHICreateAndLockIndexBuffer( Stride, Size, BUF_Static, CreateInfo, Buffer );
uint16* Indices = (uint16*)Buffer;
for (uint32 SpriteIndex = 0; SpriteIndex < 8; ++SpriteIndex)
{
#if PLATFORM_MAC // Avoid a driver bug on OSX/NV cards that causes driver to generate an unwound index buffer
Indices[SpriteIndex*6 + 0] = SpriteIndex*6 + 0;
Indices[SpriteIndex*6 + 1] = SpriteIndex*6 + 1;
Indices[SpriteIndex*6 + 2] = SpriteIndex*6 + 2;
Indices[SpriteIndex*6 + 3] = SpriteIndex*6 + 3;
Indices[SpriteIndex*6 + 4] = SpriteIndex*6 + 4;
Indices[SpriteIndex*6 + 5] = SpriteIndex*6 + 5;
#else
Indices[SpriteIndex*6 + 0] = SpriteIndex*4 + 0;
Indices[SpriteIndex*6 + 1] = SpriteIndex*4 + 3;
Indices[SpriteIndex*6 + 2] = SpriteIndex*4 + 2;
Indices[SpriteIndex*6 + 3] = SpriteIndex*4 + 0;
Indices[SpriteIndex*6 + 4] = SpriteIndex*4 + 1;
Indices[SpriteIndex*6 + 5] = SpriteIndex*4 + 3;
#endif
}
RHIUnlockIndexBuffer( IndexBufferRHI );
}
};
TGlobalResource< FScatterQuadIndexBuffer > GScatterQuadIndexBuffer;
class FPostProcessVelocityScatterVS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessVelocityScatterVS,Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
/** Default constructor. */
FPostProcessVelocityScatterVS() {}
public:
FPostProcessPassParameters PostprocessParameter;
FShaderParameter DrawMax;
FShaderParameter VelocityScale;
/** Initialization constructor. */
FPostProcessVelocityScatterVS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
DrawMax.Bind(Initializer.ParameterMap, TEXT("bDrawMax"));
VelocityScale.Bind( Initializer.ParameterMap, TEXT("VelocityScale") );
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter << DrawMax << VelocityScale;
return bShaderHasOutdatedParameters;
}
/** to have a similar interface as all other shaders */
void SetParameters(const FRenderingCompositePassContext& Context, int32 bDrawMax)
{
const FVertexShaderRHIParamRef ShaderRHI = GetVertexShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
PostprocessParameter.SetVS(ShaderRHI, Context, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI());
SetShaderValue(Context.RHICmdList, ShaderRHI, DrawMax, bDrawMax);
{
const FSceneViewState* ViewState = (FSceneViewState*) Context.View.State;
const float MotionBlurTimeScale = ViewState ? ViewState->MotionBlurTimeScale : 1.0f;
const float ViewMotionBlurScale = 0.5f * MotionBlurTimeScale * Context.View.FinalPostProcessSettings.MotionBlurAmount;
SetShaderValue(Context.RHICmdList, ShaderRHI, VelocityScale, FVector4(ViewMotionBlurScale, ViewMotionBlurScale, 0, 0));
}
}
static const TCHAR* GetSourceFilename()
{
return TEXT("PostProcessMotionBlur");
}
static const TCHAR* GetFunctionName()
{
return TEXT("VelocityScatterVS");
}
};
class FPostProcessVelocityScatterPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessVelocityScatterPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
/** Default constructor. */
FPostProcessVelocityScatterPS() {}
public:
/** Initialization constructor. */
FPostProcessVelocityScatterPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{}
void SetParameters(const FRenderingCompositePassContext& Context)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
}
};
IMPLEMENT_SHADER_TYPE(,FPostProcessVelocityScatterVS,TEXT("PostProcessMotionBlur"),TEXT("VelocityScatterVS"),SF_Vertex);
IMPLEMENT_SHADER_TYPE(,FPostProcessVelocityScatterPS,TEXT("PostProcessMotionBlur"),TEXT("VelocityScatterPS"),SF_Pixel);
void FRCPassPostProcessVelocityScatter::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, VelocityScatter);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
FIntPoint SrcSize = InputDesc->Extent;
FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent;
FIntPoint TileCount = GetNumTiles16x16( View.ViewRect.Size() );
const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);
TRefCountPtr<IPooledRenderTarget> DepthTarget;
FPooledRenderTargetDesc Desc( FPooledRenderTargetDesc::Create2DDesc( DestSize, PF_ShadowDepth, FClearValueBinding::DepthOne, TexCreate_None, TexCreate_DepthStencilTargetable, false ) );
GRenderTargetPool.FindFreeElement( Desc, DepthTarget, TEXT("VelocityScatterDepth") );
// Set the view family's render target/viewport.
FRHIRenderTargetView ColorView(DestRenderTarget.TargetableTexture, 0, -1, ERenderTargetLoadAction::ELoad, ERenderTargetStoreAction::EStore);
FRHIDepthRenderTargetView DepthView(DepthTarget->GetRenderTargetItem().TargetableTexture, ERenderTargetLoadAction::EClear, ERenderTargetStoreAction::EStore, ERenderTargetLoadAction::ELoad, ERenderTargetStoreAction::EStore);
FRHISetRenderTargetsInfo RTInfo(1, &ColorView, DepthView);
// clear depth
// Max >= Min so no need to clear on second pass
Context.SetViewportAndCallRHI(0, 0, 0.0f, TileCount.X, TileCount.Y, 1.0f);
Context.RHICmdList.SetRenderTargetsAndClear(RTInfo);
// Min,Max
for( int i = 0; i < 2; i++ )
{
if( i == 0 )
{
// min
Context.RHICmdList.SetBlendState( TStaticBlendStateWriteMask< CW_RGBA >::GetRHI() );
Context.RHICmdList.SetRasterizerState( TStaticRasterizerState<>::GetRHI() );
Context.RHICmdList.SetDepthStencilState( TStaticDepthStencilState< true, CF_Less >::GetRHI() );
}
else
{
// max
Context.RHICmdList.SetBlendState( TStaticBlendStateWriteMask< CW_BA >::GetRHI() );
Context.RHICmdList.SetRasterizerState( TStaticRasterizerState<>::GetRHI() );
Context.RHICmdList.SetDepthStencilState( TStaticDepthStencilState< true, CF_Greater >::GetRHI() );
}
TShaderMapRef< FPostProcessVelocityScatterVS > VertexShader(Context.GetShaderMap());
TShaderMapRef< FPostProcessVelocityScatterPS > PixelShader(Context.GetShaderMap());
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(Context.RHICmdList, Context.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
VertexShader->SetParameters( Context, i );
PixelShader->SetParameters( Context );
// needs to be the same on shader side (faster on NVIDIA and AMD)
int32 QuadsPerInstance = 8;
Context.RHICmdList.SetStreamSource(0, NULL, 0, 0);
Context.RHICmdList.DrawIndexedPrimitive(GScatterQuadIndexBuffer.IndexBufferRHI, PT_TriangleList, 0, 0, 32, 0, 2 * QuadsPerInstance, FMath::DivideAndRoundUp(TileCount.X * TileCount.Y, QuadsPerInstance));
}
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessVelocityScatter::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.DebugName = TEXT("ScatteredMaxVelocity");
return Ret;
}
class FPostProcessVelocityGatherCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessVelocityGatherCS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
}
/** Default constructor. */
FPostProcessVelocityGatherCS() {}
public:
FShaderParameter OutScatteredMaxVelocity;
/** Initialization constructor. */
FPostProcessVelocityGatherCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
OutScatteredMaxVelocity.Bind(Initializer.ParameterMap, TEXT("OutScatteredMaxVelocity"));
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter;
Ar << OutScatteredMaxVelocity;
return bShaderHasOutdatedParameters;
}
void SetParameters(const FRenderingCompositePassContext& Context)
{
const FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
PostprocessParameter.SetCS(ShaderRHI, Context, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI());
}
private:
FPostProcessPassParameters PostprocessParameter;
};
IMPLEMENT_SHADER_TYPE(,FPostProcessVelocityGatherCS,TEXT("PostProcessVelocityFlatten"),TEXT("VelocityGatherCS"),SF_Compute);
void FRCPassPostProcessVelocityGather::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, VelocityDilate);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
FIntPoint TileCount = GetNumTiles16x16( View.ViewRect.Size() );
const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);
SetRenderTarget(Context.RHICmdList, FTextureRHIRef(), FTextureRHIRef());
Context.SetViewportAndCallRHI( 0, 0, 0.0f, TileCount.X, TileCount.Y, 1.0f );
TShaderMapRef< FPostProcessVelocityGatherCS > ComputeShader( Context.GetShaderMap() );
Context.RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
// set destination
Context.RHICmdList.SetUAVParameter( ComputeShader->GetComputeShader(), ComputeShader->OutScatteredMaxVelocity.GetBaseIndex(), DestRenderTarget.UAV );
ComputeShader->SetParameters( Context );
DispatchComputeShader(Context.RHICmdList, *ComputeShader, TileCount.X, TileCount.Y, 1);
// un-set destination
Context.RHICmdList.SetUAVParameter( ComputeShader->GetComputeShader(), ComputeShader->OutScatteredMaxVelocity.GetBaseIndex(), NULL );
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessVelocityGather::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.TargetableFlags |= TexCreate_UAV;
Ret.TargetableFlags |= TexCreate_RenderTargetable;
Ret.DebugName = TEXT("ScatteredMaxVelocity");
return Ret;
}
/**
* @param Quality 0: visualize, 1:low, 2:medium, 3:high, 4:very high
*/
template< uint32 Quality >
class FPostProcessMotionBlurNewPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FPostProcessMotionBlurNewPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("MOTION_BLUR_QUALITY"), Quality);
}
/** Default constructor. */
FPostProcessMotionBlurNewPS() {}
public:
FPostProcessPassParameters PostprocessParameter;
FDeferredPixelShaderParameters DeferredParameters;
FShaderParameter MotionBlurParameters;
/** Initialization constructor. */
FPostProcessMotionBlurNewPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
PostprocessParameter.Bind(Initializer.ParameterMap);
DeferredParameters.Bind(Initializer.ParameterMap);
MotionBlurParameters.Bind(Initializer.ParameterMap, TEXT("MotionBlurParameters"));
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << PostprocessParameter << DeferredParameters << MotionBlurParameters;
return bShaderHasOutdatedParameters;
}
void SetParameters(const FRenderingCompositePassContext& Context)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);
DeferredParameters.Set(Context.RHICmdList, ShaderRHI, Context.View);
{
bool bFiltered = false;
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
bFiltered = CVarMotionBlurFiltering.GetValueOnRenderThread() != 0;
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
if(bFiltered)
{
//PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Bilinear,AM_Border,AM_Border,AM_Clamp>::GetRHI());
FSamplerStateRHIParamRef Filters[] =
{
TStaticSamplerState<SF_Bilinear,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
};
PostprocessParameter.SetPS( ShaderRHI, Context, 0, false, Filters );
}
else if( CVarMotionBlurSmoothMax.GetValueOnRenderThread() )
{
FSamplerStateRHIParamRef Filters[] =
{
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
TStaticSamplerState<SF_Bilinear,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(),
};
PostprocessParameter.SetPS( ShaderRHI, Context, 0, false, Filters );
}
else
{
PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI());
}
}
TRefCountPtr<IPooledRenderTarget> InputPooledElement = Context.Pass->GetInput(ePId_Input0)->GetOutput()->RequestInput();
{
const float SizeX = Context.View.ViewRect.Width();
const float SizeY = Context.View.ViewRect.Height();
const float AspectRatio = SizeX / SizeY;
const float InvAspectRatio = SizeY / SizeX;
const FSceneViewState* ViewState = (FSceneViewState*) Context.View.State;
const float MotionBlurTimeScale = ViewState ? ViewState->MotionBlurTimeScale : 1.0f;
const float ViewMotionBlurScale = 0.5f * MotionBlurTimeScale * Context.View.FinalPostProcessSettings.MotionBlurAmount;
// 0:no 1:full screen width
float MaxVelocity = Context.View.FinalPostProcessSettings.MotionBlurMax / 100.0f;
float InvMaxVelocity = 1.0f / MaxVelocity;
// *2 to convert to -1..1 -1..1 screen space
// / MaxFraction to map screenpos to -1..1 normalized MaxFraction
FVector4 MotionBlurParametersValue(
ViewMotionBlurScale,
AspectRatio,
MaxVelocity,
InvMaxVelocity);
SetShaderValue(Context.RHICmdList, ShaderRHI, MotionBlurParameters, MotionBlurParametersValue);
}
}
static const TCHAR* GetSourceFilename()
{
return TEXT("PostProcessMotionBlur");
}
static const TCHAR* GetFunctionName()
{
return TEXT("MainNewPS");
}
};
// #define avoids a lot of code duplication
#define VARIATION1(A) typedef FPostProcessMotionBlurNewPS<A> FPostProcessMotionBlurNewPS##A; \
IMPLEMENT_SHADER_TYPE2(FPostProcessMotionBlurNewPS##A, SF_Pixel);
VARIATION1(0) VARIATION1(1) VARIATION1(2) VARIATION1(3) VARIATION1(4)
#undef VARIATION1
// @param Quality 0: visualize, 1:low, 2:medium, 3:high, 4:very high
template< uint32 Quality >
static void SetMotionBlurShaderNewTempl(const FRenderingCompositePassContext& Context)
{
TShaderMapRef< FPostProcessVS > VertexShader( Context.GetShaderMap() );
TShaderMapRef< FPostProcessMotionBlurNewPS< Quality > > PixelShader( Context.GetShaderMap() );
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(Context.RHICmdList, Context.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
VertexShader->SetParameters(Context);
PixelShader->SetParameters(Context);
}
FRCPassPostProcessMotionBlurNew::FRCPassPostProcessMotionBlurNew(uint32 InQuality)
: Quality(InQuality)
{
// internal error
check(Quality >= 1 && Quality <= 4);
}
void FRCPassPostProcessMotionBlurNew::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, MotionBlur);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
// we assume the input and output is full resolution
FIntPoint SrcSize = InputDesc->Extent;
FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent;
// e.g. 4 means the input texture is 4x smaller than the buffer size
uint32 ScaleFactor = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY().X / SrcSize.X;
FIntRect SrcRect = View.ViewRect / ScaleFactor;
FIntRect DestRect = SrcRect;
const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);
// Set the view family's render target/viewport.
SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef());
Context.SetViewportAndCallRHI(SrcRect);
// is optimized away if possible (RT size=view size, )
//Context.RHICmdList.Clear(true, FLinearColor::Black, false, 1.0f, false, 0, SrcRect);
// set the state
Context.RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
if(Quality == 1)
{
SetMotionBlurShaderNewTempl<1>(Context);
}
else if(Quality == 2)
{
SetMotionBlurShaderNewTempl<2>(Context);
}
else if(Quality == 3)
{
SetMotionBlurShaderNewTempl<3>(Context);
}
else
{
check(Quality == 4);
SetMotionBlurShaderNewTempl<4>(Context);
}
TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
// Draw a quad mapping scene color to the view's render target
DrawRectangle(
Context.RHICmdList,
0, 0,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Min.X, SrcRect.Min.Y,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Size(),
SrcSize,
*VertexShader,
EDRF_UseTriangleOptimization);
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessMotionBlurNew::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
// we don't need the alpha channel and 32bit is faster and costs less memory
Ret.Format = PF_FloatRGB;
Ret.DebugName = TEXT("MotionBlur");
return Ret;
}
void FRCPassPostProcessVisualizeMotionBlur::Process(FRenderingCompositePassContext& Context)
{
SCOPED_DRAW_EVENT(Context.RHICmdList, VisualizeMotionBlur);
const FPooledRenderTargetDesc* InputDesc = GetInputDesc(ePId_Input0);
if(!InputDesc)
{
// input is not hooked up correctly
return;
}
const FSceneView& View = Context.View;
const FSceneViewFamily& ViewFamily = *(View.Family);
FIntPoint TexSize = InputDesc->Extent;
// we assume the input and output is full resolution
FIntPoint SrcSize = InputDesc->Extent;
FIntPoint DestSize = PassOutputs[0].RenderTargetDesc.Extent;
// e.g. 4 means the input texture is 4x smaller than the buffer size
uint32 ScaleFactor = FSceneRenderTargets::Get(Context.RHICmdList).GetBufferSizeXY().X / SrcSize.X;
FIntRect SrcRect = FIntRect::DivideAndRoundUp(View.ViewRect, ScaleFactor);
FIntRect DestRect = SrcRect;
const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);
// Set the view family's render target/viewport.
SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef());
// is optimized away if possible (RT size=view size, )
Context.RHICmdList.Clear(true, FLinearColor::Black, false, 1.0f, false, 0, SrcRect);
Context.SetViewportAndCallRHI(SrcRect);
// set the state
Context.RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
// Quality 0: visualize
SetMotionBlurShaderTempl<0>(Context);
// Draw a quad mapping scene color to the view's render target
TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
DrawRectangle(
Context.RHICmdList,
0, 0,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Min.X, SrcRect.Min.Y,
SrcRect.Width(), SrcRect.Height(),
SrcRect.Size(),
SrcSize,
*VertexShader,
EDRF_UseTriangleOptimization);
// this is a helper class for FCanvas to be able to get screen size
class FRenderTargetTemp : public FRenderTarget
{
public:
const FSceneView& View;
const FTexture2DRHIRef Texture;
FRenderTargetTemp(const FSceneView& InView, const FTexture2DRHIRef InTexture)
: View(InView), Texture(InTexture)
{
}
virtual FIntPoint GetSizeXY() const
{
return View.ViewRect.Size();
};
virtual const FTexture2DRHIRef& GetRenderTargetTexture() const
{
return Texture;
}
} TempRenderTarget(View, (const FTexture2DRHIRef&)DestRenderTarget.TargetableTexture);
FCanvas Canvas(&TempRenderTarget, NULL, ViewFamily.CurrentRealTime, ViewFamily.CurrentWorldTime, ViewFamily.DeltaWorldTime, Context.GetFeatureLevel());
float X = 20;
float Y = 8;
const float YStep = 14;
const float ColumnWidth = 200;
FString Line;
Line = FString::Printf(TEXT("Visualize MotionBlur"));
Canvas.DrawShadowedString(X, Y += YStep, *Line, GetStatsFont(), FLinearColor(1, 1, 0));
static const auto MotionBlurDebugVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.MotionBlurDebug"));
const int32 MotionBlurDebug = MotionBlurDebugVar ? MotionBlurDebugVar->GetValueOnRenderThread() : 0;
Line = FString::Printf(TEXT("%d, %d"), ViewFamily.FrameNumber, MotionBlurDebug);
Canvas.DrawShadowedString(X, Y += YStep, TEXT("FrameNo, r.MotionBlurDebug:"), GetStatsFont(), FLinearColor(1, 1, 0));
Canvas.DrawShadowedString(X + ColumnWidth, Y, *Line, GetStatsFont(), FLinearColor(1, 1, 0));
static const auto VelocityTestVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.VelocityTest"));
const int32 VelocityTest = VelocityTestVar ? VelocityTestVar->GetValueOnRenderThread() : 0;
extern bool IsParallelVelocity();
Line = FString::Printf(TEXT("%d, %d, %d"), ViewFamily.bWorldIsPaused, VelocityTest, IsParallelVelocity());
Canvas.DrawShadowedString(X, Y += YStep, TEXT("Paused, r.VelocityTest, Parallel:"), GetStatsFont(), FLinearColor(1, 1, 0));
Canvas.DrawShadowedString(X + ColumnWidth, Y, *Line, GetStatsFont(), FLinearColor(1, 1, 0));
const FScene* Scene = (const FScene*)View.Family->Scene;
Canvas.DrawShadowedString(X, Y += YStep, TEXT("MotionBlurInfoData (per object):"), GetStatsFont(), FLinearColor(1, 1, 0));
Canvas.DrawShadowedString(X + ColumnWidth, Y, *Scene->MotionBlurInfoData.GetDebugString(), GetStatsFont(), FLinearColor(1, 1, 0));
const FSceneViewState *SceneViewState = (const FSceneViewState*)View.State;
Line = FString::Printf(TEXT("View=%.4x PrevView=%.4x"),
View.ViewMatrices.ViewMatrix.ComputeHash() & 0xffff,
SceneViewState->PrevViewMatrices.ViewMatrix.ComputeHash() & 0xffff);
Canvas.DrawShadowedString(X, Y += YStep, TEXT("ViewMatrix:"), GetStatsFont(), FLinearColor(1, 1, 0));
Canvas.DrawShadowedString(X + ColumnWidth, Y, *Line, GetStatsFont(), FLinearColor(1, 1, 0));
for(uint32 BufferId = 0; BufferId < 2; ++BufferId)
{
const TCHAR* Usage = TEXT("unused");
if(BufferId == GPrevPerBoneMotionBlur.GetReadBufferIndex())
{
Usage = TEXT("read");
}
else if(BufferId == GPrevPerBoneMotionBlur.GetWriteBufferIndex())
{
Usage = TEXT("write");
}
Line = FString::Printf(TEXT("BoneBuffer %d: %s"), BufferId, Usage);
// LeftTop.y + (LinesPerBuffer + GapBetweenBuffers) * Scale
Canvas.DrawShadowedString(4, 98 + BufferId * (48 + 8) * 3, *Line, GetStatsFont(), FLinearColor(1, 1, 0));
}
Canvas.Flush_RenderThread(Context.RHICmdList);
Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
FPooledRenderTargetDesc FRCPassPostProcessVisualizeMotionBlur::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;
Ret.Reset();
Ret.DebugName = TEXT("MotionBlur");
return Ret;
}
| 35.173174 | 224 | 0.781667 | PopCap |
d18877b4a5906058307b3f59197c735faea752b0 | 2,724 | hpp | C++ | examples/suffix_sorting/construct_bwt.hpp | stevenybw/thrill | a2dc05035f4e24f64af0a22b60155e80843a5ba9 | [
"BSD-2-Clause"
] | 609 | 2015-08-27T11:09:24.000Z | 2022-03-28T21:34:05.000Z | examples/suffix_sorting/construct_bwt.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 109 | 2015-09-10T21:34:42.000Z | 2022-02-15T14:46:26.000Z | examples/suffix_sorting/construct_bwt.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 114 | 2015-08-27T14:54:13.000Z | 2021-12-08T07:28:35.000Z | /*******************************************************************************
* examples/suffix_sorting/construct_bwt.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2016 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_EXAMPLES_SUFFIX_SORTING_CONSTRUCT_BWT_HEADER
#define THRILL_EXAMPLES_SUFFIX_SORTING_CONSTRUCT_BWT_HEADER
#include <thrill/api/collapse.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/max.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sort.hpp>
#include <thrill/api/window.hpp>
#include <thrill/api/zip.hpp>
#include <thrill/api/zip_with_index.hpp>
namespace examples {
namespace suffix_sorting {
template <typename InputDIA, typename SuffixArrayDIA>
InputDIA ConstructBWT(const InputDIA& input, const SuffixArrayDIA& suffix_array,
uint64_t input_size) {
// thrill::Context& ctx = input.ctx();
using Char = typename InputDIA::ValueType;
using Index = typename SuffixArrayDIA::ValueType;
struct IndexRank {
Index index;
Index rank;
} TLX_ATTRIBUTE_PACKED;
struct IndexChar {
Index index;
Char ch;
} TLX_ATTRIBUTE_PACKED;
return suffix_array
.Map([input_size](const Index& i) {
if (i == Index(0))
return Index(input_size - 1);
return i - Index(1);
})
.ZipWithIndex([](const Index& text_pos, const size_t& i) {
return IndexRank { text_pos, Index(i) };
})
// .Zip(Generate(ctx, input_size),
// [](const Index& text_pos, const size_t& idx) {
// return IndexRank { text_pos, Index(idx) };
// })
.Sort([](const IndexRank& a, const IndexRank& b) {
return a.index < b.index;
})
.Zip(input,
[](const IndexRank& text_order, const Char& ch) {
return IndexChar { text_order.rank, ch };
})
.Sort([](const IndexChar& a, const IndexChar& b) {
return a.index < b.index;
})
.Map([](const IndexChar& ic) {
return ic.ch;
})
.Collapse();
}
} // namespace suffix_sorting
} // namespace examples
#endif // !THRILL_EXAMPLES_SUFFIX_SORTING_CONSTRUCT_BWT_HEADER
/******************************************************************************/
| 33.62963 | 80 | 0.532305 | stevenybw |
d18be5e9c92e1867fda619f41295be943f0837a1 | 2,509 | hpp | C++ | include/socks5/request.hpp | xSHAD0Wx/libsocks5 | a578033579ab9b3139e62aa4bf8ee72344ff2a30 | [
"BSD-3-Clause"
] | null | null | null | include/socks5/request.hpp | xSHAD0Wx/libsocks5 | a578033579ab9b3139e62aa4bf8ee72344ff2a30 | [
"BSD-3-Clause"
] | null | null | null | include/socks5/request.hpp | xSHAD0Wx/libsocks5 | a578033579ab9b3139e62aa4bf8ee72344ff2a30 | [
"BSD-3-Clause"
] | null | null | null | #ifndef LIBSOCKS5_REQUEST_HPP
#define LIBSOCKS5_REQUEST_HPP
#include "socks5/detail/type_traits/iterator.hpp"
#include "socks5/message.hpp"
#include <boost/asio/ip/address.hpp>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <string_view>
#include <type_traits>
#include <vector>
namespace socks5 {
namespace detail {
template <typename T,
std::size_t size = sizeof(T),
typename = std::enable_if_t<std::is_unsigned_v<T>>>
inline void append_uint(T num, std::vector<std::uint8_t> &buf) noexcept {
static_assert(size >= 1 && size <= 8 && size <= sizeof(T));
buf.emplace_back((num >> (8 * (size - 1))) & 0xFF);
if constexpr (size - 1 > 0) {
append_uint<T, size - 1>(num, buf);
}
}
} // namespace detail
template <std::uint8_t version>
struct request final : socks5::message<std::vector<std::uint8_t>> {
request() {
put<std::uint8_t>(version);
}
template <typename... Arg>
request(Arg &&... args) : request() {
(put(std::forward<Arg>(args)), ...);
}
template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
inline void put(T num) noexcept {
socks5::detail::append_uint(num, message::buf_);
}
template <typename Iterator,
typename = std::enable_if_t<
socks5::detail::type_traits::is_iterator_v<Iterator>>>
inline void put(const Iterator &begin, const Iterator &end) {
std::copy(begin, end, std::back_inserter(message::buf_));
}
inline void put(std::string_view str) {
assert(str.length() <= 0xFF);
put<std::uint8_t>(str.length());
put(str.cbegin(), str.cend());
}
inline void put(const boost::asio::ip::address_v4 &addr) {
const auto &bytes = addr.to_bytes();
put<std::uint8_t>(1);
put(bytes.cbegin(), bytes.cend());
}
inline void put(const boost::asio::ip::address_v6 &addr) {
const auto &bytes = addr.to_bytes();
put<std::uint8_t>(4);
put(bytes.cbegin(), bytes.cend());
}
inline void put(const boost::asio::ip::address &addr) {
if (addr.is_v4()) {
put(addr.to_v4());
} else {
put(addr.to_v6());
}
}
};
template <std::uint8_t version, typename... T>
inline auto make_request(T &&... args) -> socks5::request<version> {
socks5::request<version> ret {};
(ret.put(std::forward<T>(args)), ...);
return ret;
}
} // namespace socks5
#endif
| 26.410526 | 77 | 0.601435 | xSHAD0Wx |
d18cbd7e834e4b85bf31de8ca1f66a9d868ff72d | 729 | cpp | C++ | Contest/CPBuddySeries/contest2/Longest_prefix.cpp | ganeshbhandarkar/Problem-Solving | f7abc60483571eaf695bb8bc18e487163aef15db | [
"MIT"
] | 1 | 2020-08-06T18:04:47.000Z | 2020-08-06T18:04:47.000Z | Contest/CPBuddySeries/contest2/Longest_prefix.cpp | ganeshbhandarkar/Problem-Solving | f7abc60483571eaf695bb8bc18e487163aef15db | [
"MIT"
] | null | null | null | Contest/CPBuddySeries/contest2/Longest_prefix.cpp | ganeshbhandarkar/Problem-Solving | f7abc60483571eaf695bb8bc18e487163aef15db | [
"MIT"
] | null | null | null | /*
* @Author: ganesh bhandarkar
* @Date: 2020-08-09 21:45:43
* @Last Modified by: ganesh bhandarkar
* @Last Modified time: 2020-08-09 21:45:43
*/
#include <bits/stdc++.h>
using namespace std;
int lps(string s) {
int n = s.length();
int lp[n];
int i=1,j=0;
lp[0]=0;
while (i<n) {
if (s[i]==s[j]) {
j++;
lp[i] = j;
i++;
} else {
if (j != 0)
j = lp[j-1];
else {
lp[i] = 0;
i++;
}
}
}
return lp[n-1];
}
int main() {
int T;
cin >> T;
while (T--) {
string s;
cin >> s;
printf("%d\n",lps(s));
}
return 0;
} | 17.357143 | 44 | 0.378601 | ganeshbhandarkar |
d18e8598c101b05de3fa7e989321df13de520fe7 | 793 | cpp | C++ | tests/test_omp_threads.cpp | buckaroo-upgrade-bot/facebookresearch-faiss | 94464ab00b5bab579ddfbf1b9ee530816888d670 | [
"BSD-3-Clause"
] | 2 | 2019-04-07T05:01:30.000Z | 2019-10-25T02:27:20.000Z | tests/test_omp_threads.cpp | montecarlo1/faiss | 4e8d324922b0a5574579a5771e45aa080983891d | [
"BSD-3-Clause"
] | null | null | null | tests/test_omp_threads.cpp | montecarlo1/faiss | 4e8d324922b0a5574579a5771e45aa080983891d | [
"BSD-3-Clause"
] | 2 | 2022-01-12T12:05:17.000Z | 2022-02-14T07:13:38.000Z | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD+Patents license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <gtest/gtest.h>
#include <omp.h>
TEST(Threading, openmp) {
omp_set_num_threads(10);
EXPECT_EQ(omp_get_max_threads(), 10);
std::vector<int> nt_per_thread(10);
size_t sum = 0;
#pragma omp parallel reduction(+: sum)
{
int nt = omp_get_num_threads ();
int rank = omp_get_thread_num ();
nt_per_thread[rank] = nt;
#pragma omp for
for(int i = 0; i < 1000 * 1000 * 10; i++) {
sum += i;
}
}
EXPECT_EQ (nt_per_thread[0], 10);
EXPECT_GT (sum, 0);
}
| 19.825 | 74 | 0.614124 | buckaroo-upgrade-bot |
d1935945395c81611d54a5935c2822f403fe555a | 545 | cc | C++ | src/ObjectInfo.cc | CS126SP20/3D-Hotdog | 072f1cd3f522a0448f7a2ba4a70912e4fcc924bb | [
"MIT"
] | null | null | null | src/ObjectInfo.cc | CS126SP20/3D-Hotdog | 072f1cd3f522a0448f7a2ba4a70912e4fcc924bb | [
"MIT"
] | null | null | null | src/ObjectInfo.cc | CS126SP20/3D-Hotdog | 072f1cd3f522a0448f7a2ba4a70912e4fcc924bb | [
"MIT"
] | null | null | null | // Copyright (c) 2020 [Your Name]. All rights reserved.
#include <cinder/app/App.h>
#include <mylibrary/ObjectInfo.h>
#include <string>
namespace mylibrary {
ObjectInfo::ObjectInfo(std::string name, cinder::Color color,
cinder::vec3 position, int type) {
mName = name;
mColor = color;
mPosition = position;
mType = type;
}
ObjectInfo::ObjectInfo() {
mName = "random object";
mColor = cinder::Color(0.34f, 0.78f, 1.0f);
mPosition = cinder::vec3(0, 5, 0);
mType = rand() % 2;
}
} // namespace mylibrary | 22.708333 | 61 | 0.645872 | CS126SP20 |
d1967ca07239d426d07f5bad59f6a32e325ad75b | 3,120 | cc | C++ | src/net/http/HttpContext.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | 2 | 2019-07-15T08:34:38.000Z | 2019-08-07T12:27:23.000Z | src/net/http/HttpContext.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | null | null | null | src/net/http/HttpContext.cc | plantree/Slack | 469fff18792a6d4d20c409f0331e3c93117c5ddf | [
"MIT"
] | null | null | null | /*
* @Author: py.wang
* @Date: 2019-07-21 08:21:33
* @Last Modified by: py.wang
* @Last Modified time: 2019-07-22 08:42:22
*/
#include "src/net/Buffer.h"
#include "src/net/http/HttpContext.h"
using namespace slack;
using namespace slack::net;
// 解析请求行
bool HttpContext::processRequestLine(const char *begin, const char *end)
{
bool succeed = false;
const char *start = begin;
const char *space = std::find(start, end, ' ');
// find method
if (space != end && request_.setMethod(start, space))
{
start = space + 1;
space = std::find(start, end, ' ');
// find path
if (space != end)
{
const char *question = std::find(start, space, '?');
// find query
if (question != space)
{
request_.setPath(start, question);
request_.setQuery(question, space);
}
else
{
request_.setPath(start, space);
}
start = space + 1;
succeed = (end - start == 8) && std::equal(start, end-1, "HTTP/1.");
if (succeed)
{
if (*(end-1) == '1')
{
request_.setVersion(HttpRequest::kHttp11);
}
else if (*(end-1) == '0')
{
request_.setVersion(HttpRequest::kHttp10);
}
else
{
succeed = false;
}
}
}
}
return succeed;
}
bool HttpContext::parseRequest(Buffer *buf, Timestamp receiveTime)
{
bool ok = true;
bool hasMore = true;
while (hasMore)
{
if (state_ == kExpectRequestLine)
{
const char *crlf = buf->findCRLF();
if (crlf)
{
// 解析请求行
ok = processRequestLine(buf->peek(), crlf);
if (ok)
{
request_.setReceiveTime(receiveTime);
buf->retrieveUntil(crlf+2);
state_ = kExpectHeaders;
}
else
{
hasMore = false;
}
}
else
{
hasMore = false;
}
}
else if (state_ == kExpectHeaders)
{
const char *crlf = buf->findCRLF();
if (crlf)
{
const char *colon = std::find(buf->peek(), crlf, ':');
if (colon != crlf)
{
request_.addHeader(buf->peek(), colon, crlf);
}
else
{
// empty line, end of header
state_ = kGotAll;
hasMore = false;
}
buf->retrieveUntil(crlf+2);
}
else
{
hasMore = false;
}
}
else if (state_ == kExpectBody)
{
}
}
return ok;
} | 26.440678 | 80 | 0.403526 | plantree |
d1975ccbf5aa8805ea3572aa94dc27bf1c13c00a | 468 | cpp | C++ | Leetcode/1000-2000/1277. Count Square Submatrices with All Ones/1277.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1277. Count Square Submatrices with All Ones/1277.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1277. Count Square Submatrices with All Ones/1277.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int countSquares(vector<vector<int>>& matrix) {
for (int i = 0; i < matrix.size(); ++i)
for (int j = 0; j < matrix[0].size(); ++j)
if (matrix[i][j] == 1 && i > 0 && j > 0)
matrix[i][j] +=
min({matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i][j - 1]});
return accumulate(begin(matrix), end(matrix), 0, [](int a, const auto& A) {
return a + accumulate(begin(A), end(A), 0);
});
}
};
| 33.428571 | 79 | 0.489316 | Next-Gen-UI |
d19d6d8b431259cfd6d59b75185b11f379b835c0 | 845 | cpp | C++ | ChessTree.cpp | pradeepdsmk/chess-tree | 759d4f984aad97cd5429d9e075cf7c6b7d656345 | [
"MIT"
] | 1 | 2022-03-01T21:06:30.000Z | 2022-03-01T21:06:30.000Z | ChessTree.cpp | pradeepdsmk/chess-tree | 759d4f984aad97cd5429d9e075cf7c6b7d656345 | [
"MIT"
] | null | null | null | ChessTree.cpp | pradeepdsmk/chess-tree | 759d4f984aad97cd5429d9e075cf7c6b7d656345 | [
"MIT"
] | null | null | null | // ChessTree.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <chrono>
#include <Windows.h>
#include "Log.h"
#include "Engine.h"
#include "XboardCommand.h"
#ifdef _WIN32
#define CMD_CLEAR_SCREEN "cls"
#elif
#define CMD_CLEAR_SCREEN "clear"
#endif
typedef std::chrono::high_resolution_clock::time_point Timepoint;
void idea3() {
std::string input, output;
chess::Engine engine;
chess::XboardCommand command(engine);
while (1) {
Sleep(200); // for some reason
std::getline(std::cin, input);
Log::add("input: " + input);
if (command.process(input, output) == false) {
break;
}
Log::add("output: " + output);
if (!output.empty()) {
std::cout << output << std::endl;
}
}
}
int main()
{
Log::begin();
idea3();
Log::end();
return 0;
} | 15.648148 | 99 | 0.657988 | pradeepdsmk |
d19da24c6700cce5b5824163766e66024bf817be | 9,308 | cpp | C++ | src/drivers/linux_pwm_out/linux_pwm_out.cpp | SaxionMechatronics/Firmware | 7393d5d7610dc8d2cb64d90a5359b6c561fb642a | [
"BSD-3-Clause"
] | 13 | 2020-10-31T05:09:26.000Z | 2022-03-15T05:41:31.000Z | src/drivers/linux_pwm_out/linux_pwm_out.cpp | SaxionMechatronics/Firmware | 7393d5d7610dc8d2cb64d90a5359b6c561fb642a | [
"BSD-3-Clause"
] | 86 | 2020-11-12T02:38:47.000Z | 2021-04-20T23:25:57.000Z | src/drivers/linux_pwm_out/linux_pwm_out.cpp | SaxionMechatronics/Firmware | 7393d5d7610dc8d2cb64d90a5359b6c561fb642a | [
"BSD-3-Clause"
] | 11 | 2020-10-28T05:38:18.000Z | 2022-01-20T06:18:00.000Z | /****************************************************************************
*
* Copyright (c) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "linux_pwm_out.hpp"
#include <board_pwm_out.h>
#include <drivers/drv_hrt.h>
using namespace pwm_out;
LinuxPWMOut::LinuxPWMOut() :
CDev("/dev/pwm_out"),
OutputModuleInterface(MODULE_NAME, px4::wq_configurations::hp_default),
_cycle_perf(perf_alloc(PC_ELAPSED, MODULE_NAME": cycle")),
_interval_perf(perf_alloc(PC_INTERVAL, MODULE_NAME": interval"))
{
_mixing_output.setAllMinValues(PWM_DEFAULT_MIN);
_mixing_output.setAllMaxValues(PWM_DEFAULT_MAX);
}
LinuxPWMOut::~LinuxPWMOut()
{
/* clean up the alternate device node */
unregister_class_devname(PWM_OUTPUT_BASE_DEVICE_PATH, _class_instance);
perf_free(_cycle_perf);
perf_free(_interval_perf);
delete _pwm_out;
}
int LinuxPWMOut::init()
{
/* do regular cdev init */
int ret = CDev::init();
if (ret != OK) {
return ret;
}
/* try to claim the generic PWM output device node as well - it's OK if we fail at this */
_class_instance = register_class_devname(PWM_OUTPUT_BASE_DEVICE_PATH);
_mixing_output.setDriverInstance(_class_instance);
_pwm_out = new BOARD_PWM_OUT_IMPL(MAX_ACTUATORS);
ret = _pwm_out->init();
if (ret != 0) {
PX4_ERR("PWM output init failed");
delete _pwm_out;
_pwm_out = nullptr;
return ret;
}
update_params();
ScheduleNow();
return ret;
}
int LinuxPWMOut::task_spawn(int argc, char *argv[])
{
LinuxPWMOut *instance = new LinuxPWMOut();
if (instance) {
_object.store(instance);
_task_id = task_id_is_work_queue;
if (instance->init() == PX4_OK) {
return PX4_OK;
}
} else {
PX4_ERR("alloc failed");
}
delete instance;
_object.store(nullptr);
_task_id = -1;
return PX4_ERROR;
}
bool LinuxPWMOut::updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS],
unsigned num_outputs, unsigned num_control_groups_updated)
{
_pwm_out->send_output_pwm(outputs, num_outputs);
return true;
}
void LinuxPWMOut::Run()
{
if (should_exit()) {
ScheduleClear();
_mixing_output.unregister();
exit_and_cleanup();
return;
}
perf_begin(_cycle_perf);
perf_count(_interval_perf);
_mixing_output.update();
// check for parameter updates
if (_parameter_update_sub.updated()) {
// clear update
parameter_update_s pupdate;
_parameter_update_sub.copy(&pupdate);
// update parameters from storage
update_params();
}
_mixing_output.updateSubscriptions(false);
perf_end(_cycle_perf);
}
void LinuxPWMOut::update_params()
{
updateParams();
// skip update when armed
if (_mixing_output.armed().armed) {
return;
}
int32_t pwm_min_default = PWM_DEFAULT_MIN;
int32_t pwm_max_default = PWM_DEFAULT_MAX;
int32_t pwm_disarmed_default = 0;
const char *prefix;
if (_class_instance == CLASS_DEVICE_PRIMARY) {
prefix = "PWM_MAIN";
param_get(param_find("PWM_MAIN_MIN"), &pwm_min_default);
param_get(param_find("PWM_MAIN_MAX"), &pwm_max_default);
param_get(param_find("PWM_MAIN_DISARM"), &pwm_disarmed_default);
} else if (_class_instance == CLASS_DEVICE_SECONDARY) {
prefix = "PWM_AUX";
param_get(param_find("PWM_AUX_MIN"), &pwm_min_default);
param_get(param_find("PWM_AUX_MAX"), &pwm_max_default);
param_get(param_find("PWM_AUX_DISARM"), &pwm_disarmed_default);
} else if (_class_instance == CLASS_DEVICE_TERTIARY) {
prefix = "PWM_EXTRA";
param_get(param_find("PWM_EXTRA_MIN"), &pwm_min_default);
param_get(param_find("PWM_EXTRA_MAX"), &pwm_max_default);
param_get(param_find("PWM_EXTRA_DISARM"), &pwm_disarmed_default);
} else {
PX4_ERR("invalid class instance %d", _class_instance);
return;
}
char str[17];
for (unsigned i = 0; i < MAX_ACTUATORS; i++) {
// PWM_MAIN_MINx
{
sprintf(str, "%s_MIN%u", prefix, i + 1);
int32_t pwm_min = -1;
if (param_get(param_find(str), &pwm_min) == PX4_OK && pwm_min >= 0) {
_mixing_output.minValue(i) = math::constrain(pwm_min, PWM_LOWEST_MIN, PWM_HIGHEST_MIN);
if (pwm_min != _mixing_output.minValue(i)) {
int32_t pwm_min_new = _mixing_output.minValue(i);
param_set(param_find(str), &pwm_min_new);
}
} else {
_mixing_output.minValue(i) = pwm_min_default;
}
}
// PWM_MAIN_MAXx
{
sprintf(str, "%s_MAX%u", prefix, i + 1);
int32_t pwm_max = -1;
if (param_get(param_find(str), &pwm_max) == PX4_OK && pwm_max >= 0) {
_mixing_output.maxValue(i) = math::constrain(pwm_max, PWM_LOWEST_MAX, PWM_HIGHEST_MAX);
if (pwm_max != _mixing_output.maxValue(i)) {
int32_t pwm_max_new = _mixing_output.maxValue(i);
param_set(param_find(str), &pwm_max_new);
}
} else {
_mixing_output.maxValue(i) = pwm_max_default;
}
}
// PWM_MAIN_FAILx
{
sprintf(str, "%s_FAIL%u", prefix, i + 1);
int32_t pwm_failsafe = -1;
if (param_get(param_find(str), &pwm_failsafe) == PX4_OK && pwm_failsafe >= 0) {
_mixing_output.failsafeValue(i) = math::constrain(pwm_failsafe, 0, PWM_HIGHEST_MAX);
if (pwm_failsafe != _mixing_output.failsafeValue(i)) {
int32_t pwm_fail_new = _mixing_output.failsafeValue(i);
param_set(param_find(str), &pwm_fail_new);
}
}
}
// PWM_MAIN_DISx
{
sprintf(str, "%s_DIS%u", prefix, i + 1);
int32_t pwm_dis = -1;
if (param_get(param_find(str), &pwm_dis) == PX4_OK && pwm_dis >= 0) {
_mixing_output.disarmedValue(i) = math::constrain(pwm_dis, 0, PWM_HIGHEST_MAX);
if (pwm_dis != _mixing_output.disarmedValue(i)) {
int32_t pwm_dis_new = _mixing_output.disarmedValue(i);
param_set(param_find(str), &pwm_dis_new);
}
} else {
_mixing_output.disarmedValue(i) = pwm_disarmed_default;
}
}
// PWM_MAIN_REVx
{
sprintf(str, "%s_REV%u", prefix, i + 1);
int32_t pwm_rev = 0;
if (param_get(param_find(str), &pwm_rev) == PX4_OK) {
uint16_t &reverse_pwm_mask = _mixing_output.reverseOutputMask();
if (pwm_rev >= 1) {
reverse_pwm_mask = reverse_pwm_mask | (2 << i);
} else {
reverse_pwm_mask = reverse_pwm_mask & ~(2 << i);
}
}
}
}
if (_mixing_output.mixers()) {
int16_t values[MAX_ACTUATORS] {};
for (unsigned i = 0; i < MAX_ACTUATORS; i++) {
sprintf(str, "%s_TRIM%u", prefix, i + 1);
float pval = 0.0f;
param_get(param_find(str), &pval);
values[i] = roundf(10000 * pval);
}
// copy the trim values to the mixer offsets
_mixing_output.mixers()->set_trims(values, MAX_ACTUATORS);
}
}
int LinuxPWMOut::ioctl(device::file_t *filp, int cmd, unsigned long arg)
{
int ret = OK;
PX4_DEBUG("ioctl cmd: %d, arg: %ld", cmd, arg);
lock();
switch (cmd) {
case MIXERIOCRESET:
_mixing_output.resetMixerThreadSafe();
break;
case MIXERIOCLOADBUF: {
const char *buf = (const char *)arg;
unsigned buflen = strlen(buf);
ret = _mixing_output.loadMixerThreadSafe(buf, buflen);
update_params();
break;
}
default:
ret = -ENOTTY;
break;
}
unlock();
if (ret == -ENOTTY) {
ret = CDev::ioctl(filp, cmd, arg);
}
return ret;
}
int LinuxPWMOut::custom_command(int argc, char *argv[])
{
return print_usage("unknown command");
}
int LinuxPWMOut::print_status()
{
perf_print_counter(_cycle_perf);
perf_print_counter(_interval_perf);
_mixing_output.printStatus();
return 0;
}
int LinuxPWMOut::print_usage(const char *reason)
{
if (reason) {
PX4_WARN("%s\n", reason);
}
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
Linux PWM output driver with board-specific backend implementation.
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("linux_pwm_out", "driver");
PRINT_MODULE_USAGE_COMMAND("start");
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
return 0;
}
extern "C" __EXPORT int linux_pwm_out_main(int argc, char *argv[])
{
return LinuxPWMOut::main(argc, argv);
}
| 25.088949 | 91 | 0.698431 | SaxionMechatronics |
d1a48e71dfcdd1cb0d06f2946bc29c12c489b357 | 1,923 | hpp | C++ | SpelJongEmu/src/Op.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | 17 | 2018-06-23T14:40:56.000Z | 2019-07-02T11:58:55.000Z | SpelJongEmu/src/Op.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | 3 | 2018-06-23T12:35:12.000Z | 2018-06-23T12:38:54.000Z | SpelJongEmu/src/Op.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | null | null | null | /*
MIT License
Copyright(c) 2017 Tomasz R?kawek(Coffee GB)
Copyright(c) 2018 Matt Marchant(Speljongen)
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.
*/
#pragma once
#include <cstdint>
#include <cstddef>
#include <array>
#include <functional>
class AddressSpace;
class Registers;
class InterruptManager;
using OpArgs = std::array<std::uint8_t, 2>;
using OpExecution = std::function<std::uint16_t(Registers&, AddressSpace&, const OpArgs&, std::uint16_t)>;
struct Op final
{
bool readsMemory = false;
bool writesMemory = false;
std::size_t operandLength = 0;
OpExecution execute =
[](Registers&, AddressSpace&, const OpArgs&, std::uint16_t context)
{
return context;
};
std::function<void(InterruptManager& interruptManager)> switchInterrupts = [](InterruptManager&) {};
std::function<bool(Registers& registers)>proceed = [](Registers&) { return true; };
bool forceFinishCycle = false;
}; | 34.339286 | 106 | 0.75767 | fallahn |
d1a543a5924c328cefb16dc22a80cf0542a54145 | 2,947 | cpp | C++ | src/editor/views/MooClock.cpp | XD-chill-bro/ptcollab | 757a7cc099bf28009438471b93d0def483e95dfa | [
"MIT"
] | null | null | null | src/editor/views/MooClock.cpp | XD-chill-bro/ptcollab | 757a7cc099bf28009438471b93d0def483e95dfa | [
"MIT"
] | null | null | null | src/editor/views/MooClock.cpp | XD-chill-bro/ptcollab | 757a7cc099bf28009438471b93d0def483e95dfa | [
"MIT"
] | null | null | null | #include "MooClock.h"
MooClock::MooClock(PxtoneClient *client)
: QObject(client),
m_client(client),
m_prev_clock(0),
m_this_seek(0),
m_this_seek_caught_up(false) {
connect(m_client->controller(), &PxtoneController::seeked, [this](int clock) {
m_this_seek = clock;
m_this_seek_caught_up = false;
});
}
int MooClock::last_clock() const {
const pxtnMaster *master = m_client->pxtn()->master;
return master->get_beat_clock() * master->get_play_meas() *
master->get_beat_num();
}
int MooClock::repeat_clock() const {
const pxtnMaster *master = m_client->pxtn()->master;
return master->get_repeat_meas() * master->get_beat_num() *
master->get_beat_clock();
}
int MooClock::now() {
int clock = m_client->pxtn()->moo_get_now_clock(*m_client->moo());
// Some really hacky magic to get the playhead smoother given that
// there's a ton of buffering that makes it hard to actually tell where the
// playhead is accurately. We do this:
// 1. Subtract the buffer duration.
// 2. Track how long since the last (laggy) clock update and add.
// 3. Works most of the time, but leads to a wrong clock after a seek or at
// the end of a song, because it'll put the playhead before the repeat or
// the seek position.
// 4. To account for this, if we're before the current seek position, clamp
// to seek position. Also track if we've looped and render at the end of
// song instead of before repeat if so.
// 5. The tracking if we've looped or not is also necessary to tell if we've
// actually caught up to a seek.
int bytes_per_second = 4 * 44100; // bytes in sample * bytes per second
if (m_prev_clock != clock) {
m_prev_clock = clock;
timeSinceLastClock.restart();
}
int64_t offset_from_buffer =
m_client->audioState()->bufferSize(); // - m_audio_output->bytesFree()
double estimated_buffer_offset =
-offset_from_buffer / double(bytes_per_second);
if (!m_client->isPlaying())
timeSinceLastClock.restart();
else
estimated_buffer_offset += timeSinceLastClock.elapsed() / 1000.0;
clock += (last_clock() - repeat_clock()) * m_client->moo()->num_loop;
const pxtnMaster *master = m_client->pxtn()->master;
clock += std::min(estimated_buffer_offset, 0.0) * master->get_beat_tempo() *
master->get_beat_clock() / 60;
if (clock >= m_this_seek) m_this_seek_caught_up = true;
if (!m_this_seek_caught_up) clock = m_this_seek;
if (clock >= last_clock())
clock = (clock - repeat_clock()) % (last_clock() - repeat_clock()) +
repeat_clock();
// Because of offsetting it might seem like even though we've repeated the
// clock is before [repeat_clock]. So fix it here.
if (m_client->moo()->num_loop > 0 && clock < repeat_clock())
clock += last_clock() - repeat_clock();
return clock;
}
bool MooClock::has_last() const {
return m_client->pxtn()->master->get_last_meas() > 0;
}
| 35.939024 | 80 | 0.684425 | XD-chill-bro |
d1a5aea2963cedc749bf9be286cf65bb74c85ccc | 44,821 | cc | C++ | xpdf/TileMap.cc | haephrati/SG_PDF2Text | 393ba8b500de6d10ab7c38936c009a5c44fa4189 | [
"Apache-2.0"
] | 1 | 2021-10-30T07:53:44.000Z | 2021-10-30T07:53:44.000Z | xpdf/TileMap.cc | haephrati/SG_PDF2Text | 393ba8b500de6d10ab7c38936c009a5c44fa4189 | [
"Apache-2.0"
] | null | null | null | xpdf/TileMap.cc | haephrati/SG_PDF2Text | 393ba8b500de6d10ab7c38936c009a5c44fa4189 | [
"Apache-2.0"
] | null | null | null | //========================================================================
//
// TileMap.cc
//
// Copyright 2014 Glyph & Cog, LLC
//
//========================================================================
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include "gmem.h"
#include "gmempp.h"
#include "GList.h"
#include "PDFDoc.h"
#include "DisplayState.h"
#include "TileMap.h"
//------------------------------------------------------------------------
// Number of pixels of matte color between pages (above and below each
// other) in continuous mode.
#define continuousPageSpacing 3
// Number of pixels of matte color between facing pages (left and
// right of each other) in side-by-side mode.
#define sideBySidePageSpacing 3
// Number of pixels of matte color between pages (left and right of
// each other) in horizontal continuous mode.
#define horizContinuousPageSpacing 3
//------------------------------------------------------------------------
TileMap::TileMap(DisplayState *stateA) {
state = stateA;
state->setTileMap(this);
pageDPI = NULL;
pageW = pageH = NULL;
tileW = tileH = NULL;
pageBoxW = pageBoxH = NULL;
pageX = pageY = NULL;
tiles = NULL;
}
TileMap::~TileMap() {
clearPageParams();
clearContinuousModeParams();
gfree(pageBoxW);
gfree(pageBoxH);
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
}
}
GList *TileMap::getTileList() {
double pageDPI1, pageDPI2;
int pageW1, pageH1, tileW1, tileH1, pageW2, pageH2, tileW2, tileH2;
int offsetX, offsetY, offsetX2;
int x0, y0, x1, y1, x, y, tx, ty, tw, th, page;
if (tiles) {
return tiles;
}
tiles = new GList();
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return tiles;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
page = state->getScrollPage();
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (pageW1 < state->getWinW()) {
offsetX = (state->getWinW() - pageW1) / 2;
} else {
offsetX = 0;
}
if (pageH1 < state->getWinH()) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = 0;
}
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX) >= pageW1) {
x1 = pageW1 - 1;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY) >= pageH1) {
y1 = pageH1 - 1;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + offsetY));
}
}
break;
case displayContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
page = findContinuousPage(state->getScrollY());
while (page <= state->getDoc()->getNumPages() &&
pageY[page - 1] < state->getScrollY() + state->getWinH()) {
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (maxW < state->getWinW()) {
offsetX = (state->getWinW() - maxW) / 2;
} else {
offsetX = 0;
}
offsetX += (maxW - pageW1) / 2;
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - pageY[page - 1] - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX)
>= pageW1) {
x1 = pageW1 - 1;
}
if ((y1 = state->getScrollY() - pageY[page - 1]
+ state->getWinH() - 1 - offsetY)
>= pageH1) {
y1 = pageH1 - 1;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + pageY[page - 1]
+ offsetY));
}
}
++page;
}
break;
case displaySideBySideSingle:
page = state->getScrollPage();
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (page + 1 <= state->getDoc()->getNumPages()) {
pageDPI2 = pageDPI[page];
pageW2 = pageW[page];
pageH2 = pageH[page];
tileW2 = tileW[page];
tileH2 = tileH[page];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageDPI2 = pageDPI1;
pageW2 = pageW1;
pageH2 = pageH1;
tileW2 = tileW1;
tileH2 = tileH1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (pageH1 < state->getWinH() && pageH2 < state->getWinH()) {
if (pageH1 > pageH2) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = (state->getWinH() - pageH2) / 2;
}
} else {
offsetY = 0;
}
// left page
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX) >= pageW1) {
x1 = pageW1 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY) >= pageH1) {
y1 = pageH1 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(page,
state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + offsetY));
}
}
// right page
if (page + 1 <= state->getDoc()->getNumPages()) {
if ((x0 = state->getScrollX() - offsetX2) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX2)
>= pageW2) {
x1 = pageW2 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY)
>= pageH2) {
y1 = pageH2 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH2; y <= y1 / tileH2; ++y) {
for (x = x0 / tileW2; x <= x1 / tileW2; ++x) {
tx = x * tileW2;
ty = y * tileH2;
tw = tileW2;
if (tx + tw > pageW2) {
tw = pageW2 - tx;
}
th = tileH2;
if (ty + th > pageH2) {
th = pageH2 - ty;
}
tiles->append(new PlacedTileDesc(page + 1,
state->getRotate(), pageDPI2,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX2,
ty - state->getScrollY() + offsetY));
}
}
}
break;
case displaySideBySideContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
page = findSideBySideContinuousPage(state->getScrollY());
while (page <= state->getDoc()->getNumPages() &&
(pageY[page - 1] < state->getScrollY() + state->getWinH() ||
(page + 1 <= state->getDoc()->getNumPages() &&
pageY[page] < state->getScrollY() + state->getWinH()))) {
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (page + 1 <= state->getDoc()->getNumPages()) {
pageDPI2 = pageDPI[page];
pageW2 = pageW[page];
pageH2 = pageH[page];
tileW2 = tileW[page];
tileH2 = tileH[page];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageDPI2 = pageDPI1;
pageW2 = pageW1;
pageH2 = pageH1;
tileW2 = tileW1;
tileH2 = tileH1;
}
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
// left page
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - pageY[page - 1] - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX)
>= pageW1) {
x1 = pageW1 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() - pageY[page - 1]
+ state->getWinH() - 1 - offsetY)
>= pageH1) {
y1 = pageH1 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + pageY[page - 1]
+ offsetY));
}
}
++page;
// right page
if (page <= state->getDoc()->getNumPages()) {
if ((x0 = state->getScrollX() - offsetX2) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - pageY[page - 1] - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX2)
>= pageW2) {
x1 = pageW2 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() - pageY[page - 1]
+ state->getWinH() - 1 - offsetY)
>= pageH2) {
y1 = pageH2 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH2; y <= y1 / tileH2; ++y) {
for (x = x0 / tileW2; x <= x1 / tileW2; ++x) {
tx = x * tileW2;
ty = y * tileH2;
tw = tileW2;
if (tx + tw > pageW2) {
tw = pageW2 - tx;
}
th = tileH2;
if (ty + th > pageH2) {
th = pageH2 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI2,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX2,
ty - state->getScrollY() + pageY[page - 1]
+ offsetY));
}
}
}
++page;
}
break;
case displayHorizontalContinuous:
if (totalW < state->getWinW()) {
offsetX = (state->getWinW() - totalW) / 2;
} else {
offsetX = 0;
}
page = findHorizContinuousPage(state->getScrollX());
while (page <= state->getDoc()->getNumPages() &&
pageX[page - 1] < state->getScrollX() + state->getWinW()) {
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (maxH < state->getWinH()) {
offsetY = (state->getWinH() - maxH) / 2;
} else {
offsetY = 0;
}
if ((x0 = state->getScrollX() - pageX[page - 1] - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() - pageX[page - 1]
+ state->getWinW() - 1 - offsetX)
>= pageW1) {
x1 = pageW1 - 1;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY)
>= pageH1) {
y1 = pageH1 - 1;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + pageX[page - 1]
+ offsetX,
ty - state->getScrollY() + offsetY));
}
}
++page;
}
break;
}
return tiles;
}
void TileMap::getScrollLimits(int *horizMax, int *vertMax) {
int pageW1, pageH1, pageW2, pageH2;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*horizMax = *vertMax = 0;
return;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
*horizMax = pageW[state->getScrollPage() - 1];
*vertMax = pageH[state->getScrollPage() - 1];
break;
case displayContinuous:
*horizMax = maxW;
*vertMax = totalH;
break;
case displaySideBySideSingle:
pageW1 = pageW[state->getScrollPage() - 1];
pageH1 = pageH[state->getScrollPage() - 1];
if (state->getScrollPage() + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[state->getScrollPage()];
pageH2 = pageH[state->getScrollPage()];
} else {
pageW2 = pageW1;
pageH2 = pageH1;
}
*horizMax = pageW1 + sideBySidePageSpacing + pageW2;
*vertMax = pageH1 > pageH2 ? pageH1 : pageH2;
break;
case displaySideBySideContinuous:
*horizMax = maxW + sideBySidePageSpacing + maxW2;
*vertMax = totalH;
break;
case displayHorizontalContinuous:
*horizMax = totalW;
*vertMax = maxH;
break;
default: // should never happen
*horizMax = *vertMax = 0;
break;
}
}
GBool TileMap::cvtWindowToUser(int xw, int yw,
int *pg, double *xu, double *yu) {
GBool ok;
int xd, yd;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*pg = 0;
*xu = *yu = 0;
return gFalse;
}
ok = cvtWindowToDev(xw, yw, pg, &xd, &yd);
cvtDevToUser(*pg, xd, yd, xu, yu);
return ok;
}
GBool TileMap::cvtWindowToDev(int xw, int yw,
int *pg, int *xd, int *yd) {
int pageW1, pageH1, pageW2, pageH2, offsetX, offsetX2, offsetY;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
*pg = state->getScrollPage();
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (pageW1 < state->getWinW()) {
offsetX = (state->getWinW() - pageW1) / 2;
} else {
offsetX = 0;
}
if (pageH1 < state->getWinH()) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = 0;
}
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
case displayContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
*pg = findContinuousPage(yw - offsetY + state->getScrollY());
if (*pg < 1 || *pg > state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (maxW < state->getWinW()) {
offsetX = (state->getWinW() - maxW) / 2;
} else {
offsetX = 0;
}
offsetX += (maxW - pageW1) / 2;
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY - pageY[*pg - 1] + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
case displaySideBySideSingle:
pageW1 = pageW[state->getScrollPage() - 1];
pageH1 = pageH[state->getScrollPage() - 1];
if (state->getScrollPage() + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[state->getScrollPage()];
pageH2 = pageH[state->getScrollPage()];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
pageH2 = pageH1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (pageH1 < state->getWinH() && pageH2 < state->getWinH()) {
if (pageH1 > pageH2) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = (state->getWinH() - pageH2) / 2;
}
} else {
offsetY = 0;
}
if (xw + state->getScrollX() < offsetX2) {
*pg = state->getScrollPage();
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
} else {
if (state->getScrollPage() + 1 > state->getDoc()->getNumPages()) {
*pg = *xd = *yd = 0;
return gFalse;
}
*pg = state->getScrollPage() + 1;
*xd = xw - offsetX2 + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW2 && *yd >= 0 && *yd < pageH2;
}
case displaySideBySideContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
*pg = findSideBySideContinuousPage(yw - offsetY + state->getScrollY());
if (*pg < 1 || *pg > state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (*pg + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[*pg];
pageH2 = pageH[*pg];
} else {
pageW2 = pageH2 = 0;
}
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (xw + state->getScrollX() < offsetX2) {
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY - pageY[*pg - 1] + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
} else {
if (*pg + 1 > state->getDoc()->getNumPages()) {
*pg = *xd = *yd = 0;
return false;
}
++*pg;
*xd = xw - offsetX2 + state->getScrollX();
*yd = yw - offsetY - pageY[*pg - 1] + state->getScrollY();
return *xd >= 0 && *xd < pageW2 && *yd >= 0 && *yd < pageH2;
}
case displayHorizontalContinuous:
if (totalW < state->getWinW()) {
offsetX = (state->getWinW() - totalW) / 2;
} else {
offsetX = 0;
}
*pg = findHorizContinuousPage(xw - offsetX + state->getScrollX());
if (*pg < 1 || *pg > state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (maxH < state->getWinH()) {
offsetY = (state->getWinH() - maxH) / 2;
} else {
offsetY = 0;
}
*xd = xw - offsetX - pageX[*pg - 1] + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
}
return gFalse;
}
GBool TileMap::cvtUserToWindow(int pg, double xu, double yu,
int *xw, int *yw) {
int xd, yd;
cvtUserToDev(pg, xu, yu, &xd, &yd);
return cvtDevToWindow(pg, xd, yd, xw, yw);
}
GBool TileMap::cvtDevToWindow(int pg, int xd, int yd,
int *xw, int *yw) {
int leftPg, pageW1, pageH1, pageW2, pageH2, offsetX, offsetX2, offsetY;
if (!state->getDoc() ||
pg < 1 || pg > state->getDoc()->getNumPages()) {
*xw = *yw = 0;
return gFalse;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
if (pg != state->getScrollPage()) {
*xw = *yw = 0;
return gFalse;
}
pageW1 = pageW[pg - 1];
pageH1 = pageH[pg - 1];
if (pageW1 < state->getWinW()) {
offsetX = (state->getWinW() - pageW1) / 2;
} else {
offsetX = 0;
}
if (pageH1 < state->getWinH()) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = 0;
}
*xw = xd + offsetX - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
break;
case displayContinuous:
pageW1 = pageW[pg - 1];
pageH1 = pageH[pg - 1];
if (maxW < state->getWinW()) {
offsetX = (state->getWinW() - maxW) / 2;
} else {
offsetX = 0;
}
offsetX += (maxW - pageW1) / 2;
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
*xw = xd + offsetX - state->getScrollX();
*yw = pageY[pg - 1] + yd + offsetY - state->getScrollY();
break;
case displaySideBySideSingle:
if (!(pg == state->getScrollPage() ||
(pg == state->getScrollPage() + 1 &&
state->getScrollPage() + 1 <= state->getDoc()->getNumPages()))) {
*xw = *yw = 0;
return gFalse;
}
pageW1 = pageW[state->getScrollPage() - 1];
pageH1 = pageH[state->getScrollPage() - 1];
if (state->getScrollPage() + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[state->getScrollPage()];
pageH2 = pageH[state->getScrollPage()];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
pageH2 = pageH1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (pageH1 < state->getWinH() && pageH2 < state->getWinH()) {
if (pageH1 > pageH2) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = (state->getWinH() - pageH2) / 2;
}
} else {
offsetY = 0;
}
if (pg == state->getScrollPage()) {
*xw = xd + offsetX - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
} else {
*xw = xd + offsetX2 - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
}
break;
case displaySideBySideContinuous:
leftPg = (pg - 1) | 1;
pageW1 = pageW[leftPg - 1];
pageH1 = pageH[leftPg - 1];
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
if (pg == leftPg) {
*xw = xd + offsetX - state->getScrollX();
} else {
*xw = xd + offsetX2 - state->getScrollX();
}
*yw = pageY[pg - 1] + yd + offsetY - state->getScrollY();
break;
case displayHorizontalContinuous:
if (totalW < state->getWinW()) {
offsetX = (state->getWinW() - totalW) / 2;
} else {
offsetX = 0;
}
if (maxH < state->getWinH()) {
offsetY = (state->getWinH() - maxH) / 2;
} else {
offsetY = 0;
}
*xw = pageX[pg - 1] + xd + offsetX - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
break;
}
return gTrue;
}
void TileMap::cvtUserToDev(int pg, double xu, double yu, int *xd, int *yd) {
double m[6];
if (!state->getDoc() ||
pg < 1 || pg > state->getDoc()->getNumPages()) {
*xd = *yd = 0;
return;
}
computePageMatrix(pg, m);
*xd = (int)(xu * m[0] + yu * m[2] + m[4] + 0.5);
*yd = (int)(xu * m[1] + yu * m[3] + m[5] + 0.5);
}
void TileMap::cvtDevToUser(int pg, int xd, int yd, double *xu, double *yu) {
double m[6], im[6];
if (!state->getDoc() ||
pg < 1 || pg > state->getDoc()->getNumPages()) {
*xu = *yu = 0;
return;
}
computePageMatrix(pg, m);
invertMatrix(m, im);
*xu = xd * im[0] + yd * im[2] + im[4];
*yu = xd * im[1] + yd * im[3] + im[5];
}
void TileMap::getWindowPageRange(int x, int y, int w, int h,
int *firstPage, int *lastPage) {
GList *tiles;
PlacedTileDesc *tile;
int i;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*firstPage = *lastPage = 0;
return;
}
*firstPage = state->getDoc()->getNumPages();
*lastPage = 0;
tiles = getTileList();
for (i = 0; i < tiles->getLength(); ++i) {
tile = (PlacedTileDesc *)tiles->get(i);
if (tile->px < x + w &&
tile->px + tile->tw > x &&
tile->py < y + h &&
tile->py + tile->th > y) {
if (tile->page < *firstPage) {
*firstPage = tile->page;
}
if (tile->page > *lastPage) {
*lastPage = tile->page;
}
}
}
}
int TileMap::getPageTopY(int page) {
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
case displaySideBySideSingle:
case displayHorizontalContinuous:
default:
return 0;
case displayContinuous:
case displaySideBySideContinuous:
return pageY[page - 1];
}
}
int TileMap::getPageBottomY(int page) {
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
case displaySideBySideSingle:
case displayHorizontalContinuous:
default:
return pageH[page - 1] - state->getWinH();
case displayContinuous:
case displaySideBySideContinuous:
return pageY[page - 1] + pageH[page - 1] - state->getWinH();
}
}
int TileMap::getPageLeftX(int page) {
int leftPage, rightPage, pageW1, pageW2, offsetX, offsetX2;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return 0;
case displayContinuous:
return (maxW - pageW[page - 1]) / 2;
case displaySideBySideSingle:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (rightPage <= state->getDoc()->getNumPages()) {
pageW2 = pageW[rightPage - 1];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX : offsetX2;
case displaySideBySideContinuous:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX : offsetX2;
case displayHorizontalContinuous:
return pageX[page - 1];
}
}
int TileMap::getPageRightX(int page) {
int leftPage, rightPage, pageW1, pageW2, offsetX, offsetX2;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return pageW[page - 1] - state->getWinW();
case displayContinuous:
return (maxW + pageW[page - 1]) / 2 - state->getWinW();
case displaySideBySideSingle:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (rightPage <= state->getDoc()->getNumPages()) {
pageW2 = pageW[rightPage - 1];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX + pageW1 - state->getWinW()
: offsetX2 + pageW2 - state->getWinW();
case displaySideBySideContinuous:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (rightPage <= state->getDoc()->getNumPages()) {
pageW2 = pageW[rightPage - 1];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
}
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX + pageW1 - state->getWinW()
: offsetX2 + pageW2 - state->getWinW();
case displayHorizontalContinuous:
return pageX[page - 1] + pageW[page - 1] - state->getWinW();
}
}
int TileMap::getFirstPage() {
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return state->getScrollPage();
case displayContinuous:
return findContinuousPage(state->getScrollY());
case displaySideBySideSingle:
return state->getScrollPage();
case displaySideBySideContinuous:
return findSideBySideContinuousPage(state->getScrollY());
case displayHorizontalContinuous:
return findHorizContinuousPage(state->getScrollX());
}
}
int TileMap::getFirstPageTop() {
int page;
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return state->getScrollPage();
case displayContinuous:
page = findContinuousPage(state->getScrollY());
if (page < state->getDoc()->getNumPages() &&
pageY[page - 1] < state->getScrollY()) {
return page + 1;
} else {
return page;
}
case displaySideBySideSingle:
return state->getScrollPage();
case displaySideBySideContinuous:
page = findSideBySideContinuousPage(state->getScrollY());
if (page < state->getDoc()->getNumPages() &&
pageY[page - 1] < state->getScrollY()) {
return page + 1;
} else {
return page;
}
case displayHorizontalContinuous:
page = findHorizContinuousPage(state->getScrollX());
if (page < state->getDoc()->getNumPages() &&
pageX[page - 1] < state->getScrollX()) {
return page + 1;
} else {
return page;
}
}
}
int TileMap::getMidPage() {
int wx, wy, pg, x, y;
wx = state->getWinW() / 2;
wy = state->getWinH() / 2;
if (!cvtWindowToDev(wx, wy, &pg, &x, &y)) {
if (state->getDisplayMode() == displayContinuous) {
wy += continuousPageSpacing;
} else if (state->getDisplayMode() == displaySideBySideContinuous) {
wx += sideBySidePageSpacing;
wy += continuousPageSpacing;
} else if (state->getDisplayMode() == displayHorizontalContinuous) {
wx += horizContinuousPageSpacing;
} else {
return state->getScrollPage();
}
if (!cvtWindowToDev(wx, wy, &pg, &x, &y)) {
return 1;
}
}
return pg;
}
int TileMap::getLastPage() {
int pg, x, y, n;
switch (state->getDisplayMode()) {
case displaySingle:
default:
return state->getScrollPage();
case displayContinuous:
if (!cvtWindowToDev(state->getWinW() / 2, state->getWinH() - 1,
&pg, &x, &y)) {
return state->getDoc()->getNumPages();
}
return pg;
case displaySideBySideSingle:
pg = state->getScrollPage() + 1;
n = state->getDoc()->getNumPages();
if (pg > n) {
pg = n;
}
return pg;
case displaySideBySideContinuous:
if (!cvtWindowToDev(state->getWinW() / 2, state->getWinH() - 1,
&pg, &x, &y)) {
return state->getScrollPage();
}
pg = ((pg - 1) & ~1) + 2;
n = state->getDoc()->getNumPages();
if (pg > n) {
pg = n;
}
return pg;
case displayHorizontalContinuous:
x = state->getWinW() - 1;
y = state->getWinH() / 2;
if (!cvtWindowToDev(state->getWinW() - 1, state->getWinH() / 2,
&pg, &x, &y)) {
return state->getDoc()->getNumPages();
}
return pg;
}
}
double TileMap::getDPI(int page) {
if (page < 1 || page > state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
return pageDPI[page - 1];
}
double TileMap::getPageBoxWidth(int page) {
return pageBoxW[page - 1];
}
double TileMap::getPageBoxHeight(int page) {
return pageBoxH[page - 1];
}
int TileMap::getContinuousPageSpacing() {
return continuousPageSpacing;
}
int TileMap::getSideBySidePageSpacing() {
return sideBySidePageSpacing;
}
int TileMap::getHorizContinuousPageSpacing() {
return horizContinuousPageSpacing;
}
void TileMap::docChanged() {
PDFDoc *doc;
int nPages, pg, rot;
doc = state->getDoc();
if (doc) {
nPages = doc->getNumPages();
} else {
nPages = 0;
}
pageBoxW = (double *)greallocn(pageBoxW, nPages, sizeof(double));
pageBoxH = (double *)greallocn(pageBoxH, nPages, sizeof(double));
for (pg = 1; pg <= nPages; ++pg) {
rot = doc->getPageRotate(pg);
if (rot == 0 || rot == 180) {
pageBoxW[pg - 1] = doc->getPageCropWidth(pg);
pageBoxH[pg - 1] = doc->getPageCropHeight(pg);
} else {
pageBoxW[pg - 1] = doc->getPageCropHeight(pg);
pageBoxH[pg - 1] = doc->getPageCropWidth(pg);
}
}
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::windowSizeChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::displayModeChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::zoomChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::rotateChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::scrollPositionChanged() {
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::forceRedraw() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::clearPageParams() {
gfree(pageDPI);
gfree(pageW);
gfree(pageH);
gfree(tileW);
gfree(tileH);
pageDPI = NULL;
pageW = pageH = NULL;
tileW = tileH = NULL;
}
void TileMap::updatePageParams() {
double rotPageBoxW, rotPageBoxW2, rotPageBoxH, rotPageBoxH2, rotPageBoxHMax;
double hDPI, vDPI, dpi;
int page, otherPage, nxTiles, nyTiles;
//--- check to see if the continuous mode params have already been updated
if (pageDPI) {
return;
}
//--- allocate memory
pageDPI = (double *)gmallocn(state->getDoc()->getNumPages(), sizeof(double));
pageW = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
pageH = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
tileW = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
tileH = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
for (page = 1; page <= state->getDoc()->getNumPages(); ++page) {
//--- special handling for side-by-side modes
if (state->displayModeIsSideBySide()) {
// rotate the page boxes
if (page & 1) {
otherPage = page + 1;
if (otherPage >= state->getDoc()->getNumPages()) {
otherPage = page;
}
} else {
otherPage = page - 1;
if (otherPage < 1) {
otherPage = page;
}
}
if (state->getRotate() == 0 || state->getRotate() == 180) {
rotPageBoxW = pageBoxW[page - 1];
rotPageBoxW2 = pageBoxW[otherPage - 1];
rotPageBoxH = pageBoxH[page - 1];
rotPageBoxH2 = pageBoxH[otherPage - 1];
} else {
rotPageBoxW = pageBoxH[page - 1];
rotPageBoxW2 = pageBoxH[otherPage - 1];
rotPageBoxH = pageBoxW[page - 1];
rotPageBoxH2 = pageBoxW[otherPage - 1];
}
rotPageBoxHMax = (rotPageBoxH > rotPageBoxH2) ? rotPageBoxH
: rotPageBoxH2;
// compute resolution
if (state->getZoom() == zoomPage) {
hDPI = ((state->getWinW() - sideBySidePageSpacing) /
(rotPageBoxW + rotPageBoxW2)) * 72.0;
vDPI = (state->getWinH() / rotPageBoxHMax) * 72.0;
dpi = hDPI < vDPI ? hDPI : vDPI;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomWidth) {
dpi = ((state->getWinW() - sideBySidePageSpacing) /
(rotPageBoxW + rotPageBoxW2)) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomHeight) {
dpi = (state->getWinH() / rotPageBoxHMax) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else {
dpi = 0.01 * state->getZoom() * 72.0;
}
//--- all other (non-side-by-side) modes
} else {
// rotate the page boxes
if (state->getRotate() == 0 || state->getRotate() == 180) {
rotPageBoxW = pageBoxW[page - 1];
rotPageBoxH = pageBoxH[page - 1];
} else {
rotPageBoxW = pageBoxH[page - 1];
rotPageBoxH = pageBoxW[page - 1];
}
// compute resolution
if (state->getZoom() == zoomPage) {
hDPI = (state->getWinW() / rotPageBoxW) * 72.0;
vDPI = (state->getWinH() / rotPageBoxH) * 72.0;
dpi = hDPI < vDPI ? hDPI : vDPI;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomWidth) {
dpi = (state->getWinW() / rotPageBoxW) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomHeight) {
dpi = (state->getWinH() / rotPageBoxH) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else {
dpi = 0.01 * state->getZoom() * 72.0;
}
}
pageDPI[page - 1] = dpi;
// compute bitmap size
pageW[page - 1] = (int)((rotPageBoxW * dpi / 72.0) + 0.5);
if (pageW[page - 1] < 1) {
pageW[page - 1] = 1;
}
pageH[page - 1] = (int)((rotPageBoxH * dpi / 72.0) + 0.5);
if (pageH[page - 1] < 1) {
pageH[page - 1] = 1;
}
// compute tile size
// (tile width and height are rounded up -- the bottom and right
// tiles may be slightly smaller than the computed size)
if (pageW[page - 1] <= state->getMaxTileWidth()) {
nxTiles = 1;
tileW[page - 1] = pageW[page - 1];
} else {
nxTiles = (pageW[page - 1] + state->getMaxTileWidth() - 1)
/ state->getMaxTileWidth();
tileW[page - 1] = (pageW[page - 1] + nxTiles - 1) / nxTiles;
}
if (pageH[page - 1] <= state->getMaxTileHeight()) {
nyTiles = 1;
tileH[page - 1] = pageH[page - 1];
} else {
nyTiles = (pageH[page - 1] + state->getMaxTileHeight() - 1)
/ state->getMaxTileHeight();
tileH[page - 1] = (pageH[page - 1] + nyTiles - 1) / nyTiles;
}
}
}
void TileMap::clearContinuousModeParams() {
gfree(pageX);
pageX = pageY = NULL;
}
void TileMap::updateContinuousModeParams() {
int page, pageW1, pageH1, pageW2, pageH2, x, y;
// check to see if the continuous mode params have already been updated
if (pageX) {
return;
}
updatePageParams();
switch (state->getDisplayMode()) {
case displayContinuous:
if (!pageX) {
pageX = pageY = (int *)gmallocn(state->getDoc()->getNumPages(),
sizeof(int));
}
y = 0;
maxW = 0;
for (page = 1; page <= state->getDoc()->getNumPages(); ++page) {
pageY[page - 1] = y;
y += pageH[page - 1] + continuousPageSpacing;
if (page == 1 || pageW[page - 1] > maxW) {
maxW = pageW[page - 1];
}
}
totalH = y - continuousPageSpacing;
break;
case displaySideBySideContinuous:
if (!pageX) {
pageX = pageY = (int *)gmallocn(state->getDoc()->getNumPages(),
sizeof(int));
}
y = 0;
maxW = maxW2 = 0;
for (page = 1; page <= state->getDoc()->getNumPages(); page += 2) {
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
if (page + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[page];
pageH2 = pageH[page];
} else {
pageW2 = pageW1;
pageH2 = pageH1;
}
pageY[page - 1] = y;
if (page == 1 || pageW1 > maxW) {
maxW = pageW1;
}
if (page + 1 <= state->getDoc()->getNumPages()) {
pageY[page] = y;
}
if (pageW2 > maxW2) {
maxW2 = pageW2;
}
y += (pageH1 > pageH2) ? pageH1 : pageH2;
y += continuousPageSpacing;
}
totalH = y - continuousPageSpacing;
break;
case displayHorizontalContinuous:
if (!pageX) {
pageX = pageY = (int *)gmallocn(state->getDoc()->getNumPages(),
sizeof(int));
}
x = 0;
maxH = 0;
for (page = 1; page <= state->getDoc()->getNumPages(); ++page) {
pageX[page - 1] = x;
x += pageW[page - 1] + horizContinuousPageSpacing;
if (page == 1 || pageH[page - 1] > maxH) {
maxH = pageH[page - 1];
}
}
totalW = x - horizContinuousPageSpacing;
break;
default:
break;
}
}
void TileMap::computePageMatrix(int page, double *m) {
PDFRectangle *cropBox;
double px1, py1, px2, py2, k;
int rotate;
updatePageParams();
cropBox = state->getDoc()->getCatalog()->getPage(page)->getCropBox();
px1 = cropBox->x1;
py1 = cropBox->y1;
px2 = cropBox->x2;
py2 = cropBox->y2;
k = pageDPI[page - 1] / 72.0;
rotate = state->getRotate() +
state->getDoc()->getCatalog()->getPage(page)->getRotate();
if (rotate > 360) {
rotate -= 360;
}
switch (rotate) {
case 0:
default:
m[0] = k;
m[1] = 0;
m[2] = 0;
m[3] = -k;
m[4] = -k * px1;
m[5] = k * py2;
break;
case 90:
m[0] = 0;
m[1] = k;
m[2] = k;
m[3] = 0;
m[4] = -k * py1;
m[5] = -k * px1;
break;
case 180:
m[0] = -k;
m[1] = 0;
m[2] = 0;
m[3] = k;
m[4] = k * px2;
m[5] = -k * py1;
break;
case 270:
m[0] = 0;
m[1] = -k;
m[2] = -k;
m[3] = 0;
m[4] = k * py2;
m[5] = k * px2;
break;
}
}
void TileMap::invertMatrix(double *m, double *im) {
double det;
det = 1 / (m[0] * m[3] - m[1] * m[2]);
im[0] = m[3] * det;
im[1] = -m[1] * det;
im[2] = -m[2] * det;
im[3] = m[0] * det;
im[4] = (m[2] * m[5] - m[3] * m[4]) * det;
im[5] = (m[1] * m[4] - m[0] * m[5]) * det;
}
int TileMap::findContinuousPage(int y) {
int a, b, m;
if (y < pageY[0]) {
return 0;
}
if (y >= totalH) {
return state->getDoc()->getNumPages() + 1;
}
a = -1;
b = state->getDoc()->getNumPages();
// invariant: pageY[a] < y < pageY[b]
while (b - a > 1) {
m = (a + b) / 2;
if (y > pageY[m] - continuousPageSpacing) {
a = m;
} else if (y < pageY[m] - continuousPageSpacing) {
b = m;
} else {
return m + 1;
}
}
return a + 1;
}
int TileMap::findSideBySideContinuousPage(int y) {
int a, b, m;
if (y < pageY[0]) {
return 0;
}
if (y >= totalH) {
return (state->getDoc()->getNumPages() + 2) & ~1;
}
a = -2;
b = (state->getDoc()->getNumPages() + 1) & ~1;
// invariant: pageY[a] < y < pageY[b]
while (b - a > 2) {
m = ((a + b) / 2) & ~1;
if (y > pageY[m] - continuousPageSpacing) {
a = m;
} else if (y < pageY[m] - continuousPageSpacing) {
b = m;
} else {
return m + 1;
}
}
return a + 1;
}
int TileMap::findHorizContinuousPage(int x) {
int a, b, m;
if (x < pageX[0]) {
return 0;
}
if (x >= totalW) {
return state->getDoc()->getNumPages() + 1;
}
a = -1;
b = state->getDoc()->getNumPages();
// invariant: pageX[a] < x < pageX[b]
while (b - a > 1) {
m = (a + b) / 2;
if (x > pageX[m] - horizContinuousPageSpacing) {
a = m;
} else if (x < pageX[m] - horizContinuousPageSpacing) {
b = m;
} else {
return m + 1;
}
}
return a + 1;
}
| 26.505618 | 80 | 0.555142 | haephrati |
d1a98a953358cb46afc8910fa6c15d3b19d71edd | 580 | hpp | C++ | include/LegacyForwardIterator.hpp | jharmer95/cpp_named_concepts | 6cf81562f893b03baf365d5a9dc8b3f0f828fd1a | [
"CC0-1.0"
] | null | null | null | include/LegacyForwardIterator.hpp | jharmer95/cpp_named_concepts | 6cf81562f893b03baf365d5a9dc8b3f0f828fd1a | [
"CC0-1.0"
] | null | null | null | include/LegacyForwardIterator.hpp | jharmer95/cpp_named_concepts | 6cf81562f893b03baf365d5a9dc8b3f0f828fd1a | [
"CC0-1.0"
] | null | null | null | #pragma once
#include "LegacyInputIterator.hpp"
#include "DefaultConstructible.hpp"
#include "LegacyOutputIterator.hpp"
#include <concepts>
#include <iterator>
namespace concepts
{
template<typename It>
concept LegacyForwardIterator = requires(It i)
{
requires !LegacyOutputIterator<It>
|| (LegacyOutputIterator<It> && std::same_as<typename std::iterator_traits<It>::value_type&, typename std::iterator_traits<It>::reference>);
{ i++ } -> std::same_as<It>;
{ *i++ } -> std::same_as<typename std::iterator_traits<It>::reference>;
};
} // namespace concepts
| 26.363636 | 148 | 0.72069 | jharmer95 |
d1ab6844967c92a57828ecdc96a0ea6c0e01df72 | 152 | cpp | C++ | Basics/f_ForLoop/lab/b_latinLetters.cpp | KaPrimov/cpp-courses | c114e46cd570d2e987ee65baf26dd85557f929d3 | [
"MIT"
] | null | null | null | Basics/f_ForLoop/lab/b_latinLetters.cpp | KaPrimov/cpp-courses | c114e46cd570d2e987ee65baf26dd85557f929d3 | [
"MIT"
] | null | null | null | Basics/f_ForLoop/lab/b_latinLetters.cpp | KaPrimov/cpp-courses | c114e46cd570d2e987ee65baf26dd85557f929d3 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
for (char letter = 'a'; letter <= 'z'; letter++) {
cout << letter << " ";
}
return 0;
}
| 11.692308 | 51 | 0.546053 | KaPrimov |
d1ab7935225b9144683e4cc016362bd67187522a | 3,409 | cpp | C++ | src/nec/datamanager.cpp | krikienoid/nectarispcmapeditor | f51cb89c2550a2ec17fa0d75d2741f1106ee5dd9 | [
"MIT"
] | null | null | null | src/nec/datamanager.cpp | krikienoid/nectarispcmapeditor | f51cb89c2550a2ec17fa0d75d2741f1106ee5dd9 | [
"MIT"
] | null | null | null | src/nec/datamanager.cpp | krikienoid/nectarispcmapeditor | f51cb89c2550a2ec17fa0d75d2741f1106ee5dd9 | [
"MIT"
] | null | null | null | #include "datamanager.h"
namespace Nec {
const std::string DataManager::FILENAME_BIGINFO = "biginfo.bin";
const std::string DataManager::FILENAME_BIGUNIT = "bigunit.bin";
const std::string DataManager::FILENAME_BIGMAP = "bigmap.bin";
DataManager::DataManager() {
bigInfo = new BigInfo();
// bigUnit = new BigUnit();
bigMap = new BigMap(bigInfo);
}
DataManager::~DataManager() {
delete bigInfo;
delete bigMap;
}
void DataManager::read(const std::string& filepath) {
// Assume working directory by default
std::string filedir = "";
std::string filename = filepath;
// If directory is given
const auto slashPos = filepath.find_last_of("/\\");
if (slashPos != std::string::npos) {
filedir = filepath.substr(0, slashPos + 1);
filename = filepath.substr(slashPos + 1);
}
// Check file name
std::transform(
filename.begin(),
filename.end(),
filename.begin(),
::tolower
);
if (
filename == FILENAME_BIGINFO ||
filename == FILENAME_BIGUNIT ||
filename == FILENAME_BIGMAP
) {
constexpr auto fileReadMode = std::ios::in | std::ios::binary;
// Open files for reading
std::ifstream bigInfoBin;
std::ifstream bigUnitBin;
std::ifstream bigMapBin;
bigInfoBin.open(filedir + FILENAME_BIGINFO, fileReadMode);
bigUnitBin.open(filedir + FILENAME_BIGUNIT, fileReadMode);
bigMapBin.open(filedir + FILENAME_BIGMAP, fileReadMode);
// Read Data
if (bigInfoBin.good() && bigUnitBin.good() && bigMapBin.good()) {
// biginfo.bin must be read first
bigInfo->read(bigInfoBin);
// bigmap.bin
bigMap->read(bigMapBin);
}
// Close Files
bigInfoBin.close();
bigUnitBin.close();
bigMapBin.close();
}
}
void DataManager::write(const std::string& filepath) {
// Assume working directory by default
std::string filedir = "";
std::string filename = filepath;
// If directory is given
const auto slashPos = filepath.find_last_of("/\\");
if (slashPos != std::string::npos) {
filedir = filepath.substr(0, slashPos + 1);
filename = filepath.substr(slashPos + 1);
}
// Check file name
std::transform(
filename.begin(),
filename.end(),
filename.begin(),
::tolower
);
if (
filename == FILENAME_BIGINFO ||
filename == FILENAME_BIGUNIT ||
filename == FILENAME_BIGMAP
) {
constexpr auto fileWriteMode = std::ios::out | std::ios::binary;
// Open files for writing
std::ofstream bigInfoBin;
std::ofstream bigUnitBin;
std::ofstream bigMapBin;
bigInfoBin.open(filedir + FILENAME_BIGINFO, fileWriteMode);
// bigUnitBin.open(filedir + FILENAME_BIGUNIT, fileWriteMode);
bigMapBin.open(filedir + FILENAME_BIGMAP, fileWriteMode);
if (bigInfoBin.good() && bigUnitBin.good() && bigMapBin.good()) {
// bigmap.bin
bigMap->write(bigMapBin);
// biginfo.bin must be written last
bigInfo->write(bigInfoBin);
}
// Close Files
bigInfoBin.close();
bigUnitBin.close();
bigMapBin.close();
}
}
} // namespace Nec
| 27.055556 | 78 | 0.589909 | krikienoid |
d1b1be7a0cbe54971163e65b9a3ad7144d7a5d50 | 752 | cpp | C++ | contrib/gtm/main/gtm_stat.cpp | wotchin/openGauss-server | ebd92e92b0cfd76b121d98e4c57a22d334573159 | [
"MulanPSL-1.0"
] | 1 | 2020-06-30T15:00:50.000Z | 2020-06-30T15:00:50.000Z | contrib/gtm/main/gtm_stat.cpp | wotchin/openGauss-server | ebd92e92b0cfd76b121d98e4c57a22d334573159 | [
"MulanPSL-1.0"
] | null | null | null | contrib/gtm/main/gtm_stat.cpp | wotchin/openGauss-server | ebd92e92b0cfd76b121d98e4c57a22d334573159 | [
"MulanPSL-1.0"
] | null | null | null | /* -------------------------------------------------------------------------
*
* gtm_stat.c
*
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
* Portions Copyright (c) 2010-2012 Postgres-XC Development Group
*
*
* IDENTIFICATION
* $PostgreSQL$
*
* -------------------------------------------------------------------------
*/
#include "gtm/gtm_c.h"
#include "gtm/gtm.h"
uint32 GTM_Message_Stats[MSG_MAX_MESSAGE_TYPE];
uint32 GTM_Result_Stats[GTM_MAX_RESULT_TYPE];
void gtm_msgstat_increment(int type)
{
GTM_Message_Stats[type]++;
}
void gtm_resultstat_increment(int type)
{
GTM_Result_Stats[type]++;
}
void gtm_print_stats(void)
{}
| 22.787879 | 76 | 0.590426 | wotchin |
d1b1c496a22b266da0710e4fe0d40c67a03c01aa | 5,805 | cpp | C++ | QtKnobs/styles/piestyle.cpp | eyecreate/QtKnobs | 242643bab6c38d8acbee1101edb83bb10f332bb6 | [
"MIT"
] | 68 | 2015-03-15T01:25:22.000Z | 2022-03-25T11:27:55.000Z | QtKnobs/styles/piestyle.cpp | darongE/QtKnobs | 0395e265fdc06bd70debe68e904d2ef6acb90bce | [
"MIT"
] | 9 | 2015-03-12T14:40:28.000Z | 2018-12-10T04:15:30.000Z | QtKnobs/styles/piestyle.cpp | darongE/QtKnobs | 0395e265fdc06bd70debe68e904d2ef6acb90bce | [
"MIT"
] | 23 | 2015-03-16T14:33:46.000Z | 2021-12-22T06:06:53.000Z | /*************************************************************************************
** The MIT License (MIT)
**
** Knobs is a free Qt and QML based widget.
** Copyright (c) 2015 Ashish Dabhade
** Email: ashishd157@gmail.com
**
** 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 "piestyle.h"
#define M_180_D_PI 180/M_PI
#define M_PI_D_180 M_PI/180
PieStyle::PieStyle(QQuickItem *parent) :
QQuickPaintedItem(parent),
m_value(0),
m_minValue(0),
m_maxValue(100),
m_percent(0),
m_readOnly(false),
m_color(QColor(135,206,235)),
m_mode(PieStyle::Normal),
m_style(PieStyle::Flat),
m_multiColor(false),
m_factor(57.6),
m_scale(16 / m_factor),
m_startAngle((m_value * m_factor) + (1440)),
m_spanAngle(0)
{
setAntialiasing(true);
#if defined Q_OS_LINUX || defined Q_OS_MAC
setRenderTarget(QQuickPaintedItem::FramebufferObject);
#endif
}
void PieStyle::paint(QPainter *painter)
{
qreal w = (width()/3.0)-1.0;
static const qreal m = 1.5;
painter->setPen(Qt::NoPen);
if(m_style==PieStyle::Flat) {
if(!m_multiColor) {
painter->setBrush(m_color);
painter->drawPie(boundingRect().marginsRemoved(QMarginsF(m,m,m,m)), m_startAngle, -m_spanAngle);
} else {
qreal parts = m_spanAngle/1440 + 1;
for(int i=0;i<parts;i++)
{
switch(i)
{
case 0:
m_startAngle = 1440;
painter->setBrush(m_chunkColors[i]);
break;
case 1:
case 2:
case 3:
m_startAngle = m_startAngle - 1440;
m_spanAngle = m_spanAngle - 1440;
painter->setBrush(m_chunkColors.at(i));
break;
}
painter->drawPie(boundingRect().marginsRemoved(QMarginsF(m,m,m,m)), m_startAngle, -m_spanAngle);
}
}
} else {
if(m_value==0)
return;
qreal w = width();
qreal h = height();
qreal a = ((m_spanAngle/16.0)-90.0)*M_PI_D_180;
qreal d = qCeil((w-w/1.2)/2.0)+1.0;
qreal x = w/2.0+(w/2.0-d)*qCos(a);
qreal y = h/2.0+(h/2.0-d)*qSin(a);
painter->setBrush(m_color);
painter->drawPie(boundingRect().marginsRemoved(QMarginsF(m,m,m,m)), m_startAngle, -m_spanAngle);
painter->drawEllipse(QPointF(w/2.0,d),d-2.0,d-2.0);
painter->drawEllipse(QPointF(x,y),d-2.0,d-2.0);
}
painter->setBrush(Qt::white);
painter->drawEllipse(boundingRect().center(),w,w);
}
int PieStyle::endValueFromPoint(qreal x, qreal y)
{
qreal theta = qAtan2(x,-y);
qreal angle = fmod((theta * M_180_D_PI) + 360.0,360.0);
int v = qCeil(angle * m_scale) + m_minValue;
return m_mode==PieStyle::Percent ? (v-m_minValue)*100/(m_maxValue-m_minValue) : v;
}
void PieStyle::classBegin()
{}
void PieStyle::componentComplete()
{
m_anim = children().first()->children().first();
}
bool PieStyle::animationRunning()
{
return m_anim->property("running").toBool();
}
void PieStyle::setValue(int arg)
{
if (m_value == arg)
return;
m_value = arg;
if(m_value>m_maxValue)
m_value = m_maxValue;
if(m_value<m_minValue)
m_value = m_minValue;
int diff = (m_value-m_minValue);
m_spanAngle = diff * m_factor;
m_percent = diff*100/(m_maxValue-m_minValue);
if(m_mode == PieStyle::Normal) {
emit percentChanged(m_percent);
emit valueChanged(m_value);
} else {
emit valueChanged(m_value);
emit percentChanged(m_percent);
}
update();
}
void PieStyle::setMinValue(int arg)
{
if (m_minValue == arg)
return;
m_minValue = arg;
m_value = m_minValue;
emit minValueChanged(arg);
}
void PieStyle::setMaxValue(int arg)
{
m_maxValue = arg;
m_factor = (360.0/(m_maxValue-m_minValue)) * 16.0;
m_scale = 16.0 / m_factor;
if (m_maxValue == arg)
return;
emit maxValueChanged(arg);
}
void PieStyle::setPercent(int arg)
{
if (m_percent == arg)
return;
m_percent = arg;
int value = qCeil(m_percent*(m_maxValue-m_minValue)/100.0) + m_minValue;
setValue(value);
}
void PieStyle::setMultiColor(bool arg)
{
if (m_multiColor != arg) {
m_multiColor = arg;
if(m_multiColor)
m_chunkColors << QColor(197,81,134)
<< QColor(232,156,132)
<< QColor(254,197,107)
<< QColor(81,197,212);
emit multiColorChanged(arg);
}
}
| 29.92268 | 112 | 0.591214 | eyecreate |
d1b2f54659528e71a0d59527d28d3c253a0db1eb | 5,018 | cpp | C++ | av/media/libstagefright/WVMExtractor.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | av/media/libstagefright/WVMExtractor.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | av/media/libstagefright/WVMExtractor.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 5 | 2019-12-25T04:05:02.000Z | 2022-01-14T16:57:55.000Z | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "WVMExtractor"
#include <utils/Log.h>
#include "include/WVMExtractor.h"
#include <arpa/inet.h>
#include <utils/String8.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/Utils.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/MediaSource.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/MediaErrors.h>
#include <media/stagefright/MediaBuffer.h>
#include <dlfcn.h>
#include <utils/Errors.h>
/* The extractor lifetime is short - just long enough to get
* the media sources constructed - so the shared lib needs to remain open
* beyond the lifetime of the extractor. So keep the handle as a global
* rather than a member of the extractor
*/
void *gVendorLibHandle = NULL;
namespace android {
static Mutex gWVMutex;
WVMExtractor::WVMExtractor(const sp<DataSource> &source)
: mDataSource(source)
{
Mutex::Autolock autoLock(gWVMutex);
if (!getVendorLibHandle()) {
return;
}
typedef WVMLoadableExtractor *(*GetInstanceFunc)(sp<DataSource>);
GetInstanceFunc getInstanceFunc =
(GetInstanceFunc) dlsym(gVendorLibHandle,
"_ZN7android11GetInstanceENS_2spINS_10DataSourceEEE");
if (getInstanceFunc) {
if (source->DrmInitialization(
MEDIA_MIMETYPE_CONTAINER_WVM) != NULL) {
mImpl = (*getInstanceFunc)(source);
CHECK(mImpl != NULL);
setDrmFlag(true);
} else {
ALOGE("Drm manager failed to initialize.");
}
} else {
ALOGE("Failed to locate GetInstance in libwvm.so");
}
}
static void init_routine()
{
gVendorLibHandle = dlopen("libwvm.so", RTLD_NOW);
if (gVendorLibHandle == NULL) {
ALOGE("Failed to open libwvm.so: %s", dlerror());
}
}
bool WVMExtractor::getVendorLibHandle()
{
static pthread_once_t sOnceControl = PTHREAD_ONCE_INIT;
pthread_once(&sOnceControl, init_routine);
return gVendorLibHandle != NULL;
}
WVMExtractor::~WVMExtractor() {
}
size_t WVMExtractor::countTracks() {
return (mImpl != NULL) ? mImpl->countTracks() : 0;
}
sp<IMediaSource> WVMExtractor::getTrack(size_t index) {
if (mImpl == NULL) {
return NULL;
}
return mImpl->getTrack(index);
}
sp<MetaData> WVMExtractor::getTrackMetaData(size_t index, uint32_t flags) {
if (mImpl == NULL) {
return NULL;
}
return mImpl->getTrackMetaData(index, flags);
}
sp<MetaData> WVMExtractor::getMetaData() {
if (mImpl == NULL) {
return NULL;
}
return mImpl->getMetaData();
}
int64_t WVMExtractor::getCachedDurationUs(status_t *finalStatus) {
if (mImpl == NULL) {
return 0;
}
return mImpl->getCachedDurationUs(finalStatus);
}
status_t WVMExtractor::getEstimatedBandwidthKbps(int32_t *kbps) {
if (mImpl == NULL) {
return UNKNOWN_ERROR;
}
return mImpl->getEstimatedBandwidthKbps(kbps);
}
void WVMExtractor::setAdaptiveStreamingMode(bool adaptive) {
if (mImpl != NULL) {
mImpl->setAdaptiveStreamingMode(adaptive);
}
}
void WVMExtractor::setCryptoPluginMode(bool cryptoPluginMode) {
if (mImpl != NULL) {
mImpl->setCryptoPluginMode(cryptoPluginMode);
}
}
void WVMExtractor::setUID(uid_t uid) {
if (mImpl != NULL) {
mImpl->setUID(uid);
}
}
status_t WVMExtractor::getError() {
if (mImpl == NULL) {
return UNKNOWN_ERROR;
}
return mImpl->getError();
}
void WVMExtractor::setError(status_t err) {
if (mImpl != NULL) {
mImpl->setError(err);
}
}
bool SniffWVM(
const sp<DataSource> &source, String8 *mimeType, float *confidence,
sp<AMessage> *) {
Mutex::Autolock autoLock(gWVMutex);
if (!WVMExtractor::getVendorLibHandle()) {
return false;
}
typedef WVMLoadableExtractor *(*SnifferFunc)(const sp<DataSource>&);
SnifferFunc snifferFunc =
(SnifferFunc) dlsym(gVendorLibHandle,
"_ZN7android15IsWidevineMediaERKNS_2spINS_10DataSourceEEE");
if (snifferFunc) {
if ((*snifferFunc)(source)) {
*mimeType = MEDIA_MIMETYPE_CONTAINER_WVM;
*confidence = 10.0f;
return true;
}
} else {
ALOGE("IsWidevineMedia not found in libwvm.so");
}
return false;
}
} //namespace android
| 25.343434 | 88 | 0.669191 | Keneral |
d1b36490f57fd3b7f85237d450662d9b5fb6add8 | 39,453 | cpp | C++ | qws/src/qtc_x_core.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 42 | 2015-02-16T19:29:16.000Z | 2021-07-25T11:09:03.000Z | qws/src/qtc_x_core.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 1 | 2017-11-23T12:49:25.000Z | 2017-11-23T12:49:25.000Z | qws/src/qtc_x_core.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 5 | 2015-10-15T21:25:30.000Z | 2017-11-22T13:18:24.000Z | /////////////////////////////////////////////////////////////////////////////
//
// File : qtc_x_core.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:01:54
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <wchar.h>
#include <qtc_wrp_core.h>
#include <qtc_subclass.h>
#include <dynamicqobject.h>
#include <QMutex>
extern "C"
{
QTCEXPORT(void*,qtc_QObject)(void *x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
qtc_DynamicQObject*tr = new qtc_DynamicQObject(tx0);
QPointer<qtc_DynamicQObject> * ttr = new QPointer<qtc_DynamicQObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void,qtc_QObject_finalizer)(void* x0) {
delete ((QPointer<qtc_DynamicQObject>*)x0);
}
QTCEXPORT(void*,qtc_QObject_getFinalizer)() {
return (void*)(&qtc_QObject_finalizer);
}
QTCEXPORT(void,qtc_QObject_delete)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
delete ((qtc_DynamicQObject*)tx0);
}
QTCEXPORT(void*,qtc_QObject_parent)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject * tr = ((QObject*)tx0)->parent();
QPointer<QObject> * ttr = new QPointer<QObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void*,qtc_QObject_parentSc)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
QObject * tr = ((QObject*)tx0)->parent();
QPointer<QObject> * ttr = new QPointer<QObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void*,qtc_QObject_parentref)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject * tr = ((QObject*)tx0)->parent();
QPointer<QObject> * ttr = new QPointer<QObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void,qtc_QObject_setParent)(void* x0, void* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx1)->parent());
((QObject*)tx0)->setParent((QObject*)tx1);
}
QTCEXPORT(void*,qtc_QObject_property)(void* x0, wchar_t* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
QVariant*tr = new QVariant(((QObject*)tx0)->property(txa1.data()));
return (void*) tr;
}
QTCEXPORT(int,qtc_QObject_setProperty)(void* x0, wchar_t* x1, void* x2) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int) ((QObject*)tx0)->setProperty(txa1.data(), (const QVariant&)(*(QVariant*)x2));
}
QTCEXPORT(int,qtc_QObject_blockSignals)(void* x0, int x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
bool tb = ((QObject*)tx0)->blockSignals(((bool)x1));
if (((QObject*)tx0)->property(QTC_PROP).isValid()) {
tx0 = (((qtc_DynamicQObject *)tx0)->parent());
tb |= ((QObject*)tx0)->blockSignals(((bool)x1));
}
return (int) tb;
}
QTCEXPORT(int,qtc_QObject_signalsBlocked)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
bool tb = ((QObject*)tx0)->signalsBlocked();
if (((QObject*)tx0)->property(QTC_PROP).isValid()) {
tx0 = (((qtc_DynamicQObject *)tx0)->parent());
tb |= ((QObject*)tx0)->signalsBlocked();
}
return (int) tb;
}
QTCEXPORT(void,qtc_QObject_installEventFilter)(void* x0, void* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx0)->parent());
((QObject*)tx0)->installEventFilter((QObject*)tx1);
}
QTCEXPORT(void,qtc_QObject_removeEventFilter)(void* x0, void* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx0)->parent());
((QObject*)tx0)->removeEventFilter((QObject*)tx1);
}
QTCEXPORT(int,qtc_QObject_isWidgetType)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
return (int) ((QObject*)tx0)->isWidgetType();
}
QTCEXPORT(void,qtc_QObject_killTimer)(void* x0, int x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
((QObject*)tx0)->killTimer(x1);
}
QTCEXPORT(int,qtc_QObject_startTimer)(void* x0, int x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
return ((QObject*)tx0)->startTimer(x1);
}
QTCEXPORT (int,qtc_QObject_pa_eq) (void* x0, void* x1)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
QObject*tx1 = *((QPointer<QObject>*)x1);
bool ltc = tx0 == tx1 ? true : false;
return (int) ltc;
}
QTCEXPORT (int,qtc_QObject_pa_oeq) (void* x0, void* x1)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx1)->parent());
bool ltc = tx0 == tx1 ? true : false;
return (int) ltc;
}
QTCEXPORT (int,qtc_QObject_pa_lt) (void* x0, void* x1)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
QObject*tx1 = *((QPointer<QObject>*)x1);
bool ltc = tx0 < tx1 ? true : false;
return (int) ltc;
}
QTCEXPORT (int,qtc_QObject_children) (void* x0, void* _ref)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QList<QObject *> tql = ((QObject*)tx0)->children();
if (_ref != NULL) {
for (int i = 0; i < tql.size(); i++) {
QPointer<QObject> * ttr = new QPointer<QObject>(tql.at(i));
((void**)_ref)[i] = (void*)ttr;
}
}
return tql.size();
}
QTCEXPORT(int,qtc_QString_GetString)(void* x0, wchar_t* x1) {
if (x1) {
((QString*)x0)->toWCharArray(x1);
}
return ((QByteArray*)x0)->length();
}
QTCEXPORT(void,qtc_QString_Delete)(void* x0) {
delete (QString*)x0;
}
QTCEXPORT(void*,qtc_QByteArray)() {
QByteArray*tba = new QByteArray();
return (void*) tba;
}
QTCEXPORT(int,qtc_QByteArray_isEmpty)(void* x0) {
return (int) ((QByteArray*)x0)->isEmpty();
}
QTCEXPORT(int,qtc_QByteArray_GetByteArray)(void* x0, char* x1) {
if (x1) {
char * tqba_data = ((QByteArray*)x0)->data();
for (int i = 0; i < ((QByteArray*)x0)->length(); i++) {
x1[i] = tqba_data[i];
}
}
return ((QByteArray*)x0)->length();
}
QTCEXPORT(void,qtc_QByteArray_finalizer)(void* x0) {
delete ((QByteArray*)x0);
}
QTCEXPORT(void*,qtc_QByteArray_getFinalizer)() {
return (void*)(&qtc_QByteArray_finalizer);
}
QTCEXPORT(void,qtc_QByteArray_Delete)(void* x0) {
delete (QByteArray*)x0;
}
QTCEXPORT(void*,qtc_QObject_metaObject)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
return (void*) ((QObject*)tx0)->metaObject();
}
QTCEXPORT(int,qtc_QObject_inherits)(void* x0, wchar_t* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int) ((QObject*)tx0)->inherits(txa1.data());
}
QTCEXPORT(void*,qtc_QObject_objectName)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
QString * tq = new QString(((QObject*)tx0)->objectName());
return (void*)(tq);
}
QTCEXPORT(void,qtc_QObject_setObjectName)(void* x0, wchar_t* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
return ((QObject*)tx0)->setObjectName(from_method(x1));
}
QTCEXPORT(void,qtc_connectSlot_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* st_ptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, st_ptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_int_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_int)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_int_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_bool_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_bool)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_bool_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_ptr_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_ptr)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_ptr_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_str_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_str)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_str_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_public_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, NULL, NULL, NULL);
}
QTCEXPORT(void,qtc_connectSlot_public)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ) {
qtc_connectSlot_public_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection);
}
QTCEXPORT(void,qtc_connectSignal_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tsig_obj)->connectDynamicSignal(tqba_sig.data(), (qtc_DynamicQObject *)tslt_obj, tqba_slt.data(), (Qt::ConnectionType)con_typ);
}
QTCEXPORT(void,qtc_connectSignal)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ) {
qtc_connectSignal_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection);
}
QTCEXPORT(void,qtc_emitSignal_nll)(void* sig_obj, wchar_t* sig_typ) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[1];
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(void,qtc_emitSignal_int)(void* sig_obj, wchar_t* sig_typ, int val) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[2];
tvpp[1] = (void*)(&val);
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(void,qtc_emitSignal_bool)(void* sig_obj, wchar_t* sig_typ, int val) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[2];
tvpp[1] = (void*)(&val);
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(void,qtc_emitSignal_str)(void* sig_obj, wchar_t* sig_typ, wchar_t* val) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_val(from_method(val));
QByteArray tqba_val(tq_val.toAscii());
void * tvpp[2];
tvpp[1] = (void*)(&tq_val);
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT (void,qtc_emitSignal_ptr)(void* sig_obj, wchar_t* sig_typ, void* sig_ptr) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[2];
if (!tqba_sig.endsWith("*)")) {
tvpp[1] = sig_ptr;
} else {
tvpp[1] = (void *) (&sig_ptr);
}
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(int,qtc_disconnectSlot_sos)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
return (int) ((qtc_DynamicQObject*)tslt_obj)->disconnectDynamicSlot_sos((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data());
}
QTCEXPORT(int,qtc_disconnectSlot_so)(void* sig_obj, wchar_t* sig_typ, void* slt_obj) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
return (int) ((qtc_DynamicQObject*)tslt_obj)->disconnectDynamicSlot_so((qtc_DynamicQObject*)tsig_obj, tqba_sig.data());
}
QTCEXPORT(int,qtc_disconnectSlot_s)(void* sig_obj, wchar_t* sig_typ) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
return (int) ((qtc_DynamicQObject*)tsig_obj)->disconnectDynamicSlot_s(tqba_sig.data());
}
QTCEXPORT(int,qtc_disconnectSlot)(void* sig_obj) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
return (int) ((qtc_DynamicQObject*)tsig_obj)->disconnectDynamicSlot();
}
QTCEXPORT (void, qtc_freeDynamicSlots)(void * obj) {
((qtc_DynamicQObject *)obj)->freeDynamicSlots();
}
QTCEXPORT(void*,qtc_QResource)() {
return (void*) new QResource();
}
QTCEXPORT(int,qtc_QResource_registerResource)(wchar_t* x1) {
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int)QResource::registerResource(tx1);
}
QTCEXPORT(int,qtc_QResource_unregisterResource)(wchar_t* x1) {
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int)QResource::unregisterResource(tx1);
}
QTCEXPORT(void,qtc_qsrand)(int x1) {
qsrand(x1);
}
QTCEXPORT(int,qtc_QObject_isNull)(void* x1) {
QObject*tx1 = *((QPointer<QObject>*)x1);
if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent()));
return (int) (tx1 == NULL);
}
QTCEXPORT(int,qtc_QDataStream_read_qint8)(void* x0) {
qint8 tqi8;
(*(QDataStream*)x0) >> tqi8;
return (int)tqi8;
}
QTCEXPORT(void,qtc_QDataStream_write_qint8)(void* x0, int x1) {
(*(QDataStream*)x0) << (qint8)x1;
}
QTCEXPORT(int,qtc_QDataStream_read_qint32)(void* x0) {
qint32 tqi32;
(*(QDataStream*)x0) >> tqi32;
return (int)tqi32;
}
QTCEXPORT(void,qtc_QDataStream_write_qint32)(void* x0, int x1) {
qint32 tqi32 = (qint32)x1;
(*(QDataStream*)x0) << tqi32;
}
QTCEXPORT(int,qtc_QDataStream_read_bool)(void* x0) {
bool tb;
(*(QDataStream*)x0) >> tb;
return (int)tb;
}
QTCEXPORT(void,qtc_QDataStream_write_bool)(void* x0, int x1) {
(*(QDataStream*)x0) << (bool)x1;
}
QTCEXPORT(void*,qtc_QDataStream_read_str)(void* x0) {
QString tqs;
(*(QDataStream*)x0) >> tqs;
QString * tqr = new QString(tqs);
return (void*) tqr;
}
QTCEXPORT(void,qtc_QDataStream_write_str)(void* x0, wchar_t* x1) {
QString tqs(from_method(x1));
(*(QDataStream*)x0) << tqs;
}
QTCEXPORT(void*,qtc_QDataStream_readRawData)(void* x0, int x1) {
QByteArray * tqba = new QByteArray(x1, '\0');
((QDataStream*)x0)->readRawData(tqba->data(), x1);
return (void*)(tqba);
}
QTCEXPORT(void*,qtc_QPolygonList)(int _len0, void* x0) {
QVector<QPoint> tqa1;
for (int tqai = 0; tqai < _len0; tqai+=2) {
QPoint tqp(((int*)x0)[tqai], ((int*)x0)[tqai + 1]);
tqa1.append(tqp);
}
QPolygon*tr = new QPolygon(tqa1);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QPolygonFList)(int _len0, void* x0) {
QVector<QPointF> tqa1;
for (int tqai = 0; tqai < _len0; tqai+=2) {
QPointF tqp(((double*)x0)[tqai], ((double*)x0)[tqai + 1]);
tqa1.append(tqp);
}
QPolygonF*tr = new QPolygonF(tqa1);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_GlobalColor)(long x0) {
QVariant*tr = new QVariant((Qt::GlobalColor)x0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_GlobalColor)(void* x0, long x1) {
((QVariant*)x0)->setValue<QColor>((Qt::GlobalColor)x1);
}
QTCEXPORT(void*,qtc_QVariantValue_QColor)(void* x0) {
QColor*tr = new QColor(((QVariant*)x0)->value<QColor>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QDate)(void* x0) {
QVariant*tr = new QVariant((const QDate&)(*(QDate*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QDate)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QDate>((const QDate&)(*(QDate*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QDate)(void* x0) {
QDate*tr = new QDate(((QVariant*)x0)->value<QDate>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toDate)(void* x0) {
QDate*tr = new QDate(((QVariant*)x0)->toDate());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QTime)(void* x0) {
QVariant*tr = new QVariant((const QTime&)(*(QTime*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QTime)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QTime>((const QTime&)(*(QTime*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QTime)(void* x0) {
QTime*tr = new QTime(((QVariant*)x0)->value<QTime>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toTime)(void* x0) {
QTime*tr = new QTime(((QVariant*)x0)->toTime());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QDateTime)(void* x0) {
QVariant*tr = new QVariant((const QDateTime&)(*(QDateTime*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QDateTime)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QDateTime>((const QDateTime&)(*(QDateTime*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QDateTime)(void* x0) {
QDateTime*tr = new QDateTime(((QVariant*)x0)->value<QDateTime>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toDateTime)(void* x0) {
QDateTime*tr = new QDateTime(((QVariant*)x0)->toDateTime());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QSize)(void* x0) {
QVariant*tr = new QVariant((const QSize&)(*(QSize*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSize)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QSize>((const QSize&)(*(QSize*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QSize)(void* x0) {
QSize*tr = new QSize(((QVariant*)x0)->value<QSize>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toSize)(void* x0) {
QSize*tr = new QSize(((QVariant*)x0)->toSize());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QSize_qth)(int x0_w, int x0_h) {
QSize tx0(x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSize_qth)(void* x0, int x1_w, int x1_h) {
QSize tx1(x1_w, x1_h);
((QVariant*)x0)->setValue<QSize>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QSize_qth)(void* x0, int* _ret_w, int* _ret_h) {
QSize tx0 = ((QVariant*)x0)->value<QSize>();
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toSize_qth)(void* x0, int* _ret_w, int* _ret_h) {
QSize tx0 = ((QVariant*)x0)->toSize();
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_QSizeF)(void* x0) {
QVariant*tr = new QVariant((const QSizeF&)(*(QSizeF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSizeF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QSizeF>((const QSizeF&)(*(QSizeF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QSizeF)(void* x0) {
QSizeF*tr = new QSizeF(((QVariant*)x0)->value<QSizeF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toSizeF)(void* x0) {
QSizeF*tr = new QSizeF(((QVariant*)x0)->toSizeF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QSizeF_qth)(double x0_w, double x0_h) {
QSizeF tx0(x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSizeF_qth)(void* x0, double x1_w, double x1_h) {
QSizeF tx1(x1_w, x1_h);
((QVariant*)x0)->setValue<QSizeF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QSizeF_qth)(void* x0, double* _ret_w, double* _ret_h) {
QSizeF tx0 = (((QVariant*)x0)->value<QSizeF>());
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toSizeF_qth)(void* x0, double* _ret_w, double* _ret_h) {
QSizeF tx0 = ((QVariant*)x0)->toSizeF();
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_QPoint)(void* x0) {
QVariant*tr = new QVariant((const QPoint&)(*(QPoint*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPoint)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QPoint>((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QPoint)(void* x0) {
QPoint*tr = new QPoint(((QVariant*)x0)->value<QPoint>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toPoint)(void* x0) {
QPoint*tr = new QPoint(((QVariant*)x0)->toPoint());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QPoint_qth)(int x0_x, int x0_y) {
QPoint tx0(x0_x, x0_y);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPoint_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QVariant*)x0)->setValue<QPoint>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QPoint_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tx0 = (((QVariant*)x0)->value<QPoint>());
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void,qtc_QVariant_toPoint_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tx0 = ((QVariant*)x0)->toPoint();
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void*,qtc_QVariant_QPointF)(void* x0) {
QVariant*tr = new QVariant((const QPointF&)(*(QPointF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPointF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QPointF>((const QPointF&)(*(QPointF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QPointF)(void* x0) {
QPointF*tr = new QPointF(((QVariant*)x0)->value<QPointF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toPointF)(void* x0) {
QPointF*tr = new QPointF(((QVariant*)x0)->toPointF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QPointF_qth)(double x0_x, double x0_y) {
QPointF tx0(x0_x, x0_y);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPointF_qth)(void* x0, double x1_x, double x1_y) {
QPointF tx1(x1_x, x1_y);
((QVariant*)x0)->setValue<QPointF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QPointF_qth)(void* x0, double* _ret_x, double* _ret_y) {
QPointF tx0 = ((QVariant*)x0)->value<QPointF>();
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void,qtc_QVariant_toPointF_qth)(void* x0, double* _ret_x, double* _ret_y) {
QPointF tx0 = ((QVariant*)x0)->toPointF();
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void*,qtc_QVariant_QLine)(void* x0) {
QVariant*tr = new QVariant((const QLine&)(*(QLine*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLine)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QLine>((const QLine&)(*(QLine*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QLine)(void* x0) {
QLine*tr = new QLine(((QVariant*)x0)->value<QLine>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toLine)(void* x0) {
QLine*tr = new QLine(((QVariant*)x0)->toLine());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QLine_qth)(int x0_x1, int x0_y1, int x0_x2, int x0_y2) {
QLine tx0(x0_x1, x0_y1, x0_x2, x0_y2);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLine_qth)(void* x0, int x1_x1, int x1_y1, int x1_x2, int x1_y2) {
QLine tx1(x1_x1, x1_y1, x1_x2, x1_y2);
((QVariant*)x0)->setValue<QLine>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QLine_qth)(void* x0, int* _ret_x1, int* _ret_y1, int* _ret_x2, int* _ret_y2) {
QLine tx0 = ((QVariant*)x0)->value<QLine>();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void,qtc_QVariant_toLine_qth)(void* x0, int* _ret_x1, int* _ret_y1, int* _ret_x2, int* _ret_y2) {
QLine tx0 = ((QVariant*)x0)->toLine();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void*,qtc_QVariant_QLineF)(void* x0) {
QVariant*tr = new QVariant((const QLineF&)(*(QLineF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLineF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QLineF>((const QLineF&)(*(QLineF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QLineF)(void* x0) {
QLineF*tr = new QLineF(((QVariant*)x0)->value<QLineF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toLineF)(void* x0) {
QLineF*tr = new QLineF(((QVariant*)x0)->toLineF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QLineF_qth)(double x0_x1, double x0_y1, double x0_x2, double x0_y2) {
QLineF tx0(x0_x1, x0_y1, x0_x2, x0_y2);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLineF_qth)(void* x0, double x1_x1, double x1_y1, double x1_x2, double x1_y2) {
QLineF tx1(x1_x1, x1_y1, x1_x2, x1_y2);
((QVariant*)x0)->setValue<QLineF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QLineF_qth)(void* x0, double* _ret_x1, double* _ret_y1, double* _ret_x2, double* _ret_y2) {
QLineF tx0 = ((QVariant*)x0)->value<QLineF>();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void,qtc_QVariant_toLineF_qth)(void* x0, double* _ret_x1, double* _ret_y1, double* _ret_x2, double* _ret_y2) {
QLineF tx0 = ((QVariant*)x0)->toLineF();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void*,qtc_QVariant_QRect)(void* x0) {
QVariant*tr = new QVariant((const QRect&)(*(QRect*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRect)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QRect>((const QRect&)(*(QRect*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QRect)(void* x0) {
QRect*tr = new QRect(((QVariant*)x0)->value<QRect>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toRect)(void* x0) {
QRect*tr = new QRect(((QVariant*)x0)->toRect());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QRect_qth)(int x0_x, int x0_y, int x0_w, int x0_h) {
QRect tx0(x0_x, x0_y, x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRect_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
((QVariant*)x0)->setValue<QRect>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QRect_qth)(void* x0, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx0 = ((QVariant*)x0)->value<QRect>();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toRect_qth)(void* x0, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx0 = ((QVariant*)x0)->toRect();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_QRectF)(void* x0) {
QVariant*tr = new QVariant((const QRectF&)(*(QRectF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRectF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QRectF>((const QRectF&)(*(QRectF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QRectF)(void* x0) {
QRectF*tr = new QRectF(((QVariant*)x0)->value<QRectF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toRectF)(void* x0) {
QRectF*tr = new QRectF(((QVariant*)x0)->toRectF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QRectF_qth)(double x0_x, double x0_y, double x0_w, double x0_h) {
QRectF tx0(x0_x, x0_y, x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRectF_qth)(void* x0, double x1_x, double x1_y, double x1_w, double x1_h) {
QRectF tx1(x1_x, x1_y, x1_w, x1_h);
((QVariant*)x0)->setValue<QRectF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QRectF_qth)(void* x0, double* _ret_x, double* _ret_y, double* _ret_w, double* _ret_h) {
QRectF tx0 = ((QVariant*)x0)->value<QRectF>();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toRectF_qth)(void* x0, double* _ret_x, double* _ret_y, double* _ret_w, double* _ret_h) {
QRectF tx0 = ((QVariant*)x0)->toRectF();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_List)(int _len0, void* x0) {
QList<QVariant>tql0;
for (int i = 0; i < _len0; i++) {
tql0.append(*((QVariant*)((void**)x0)[i]));
}
QVariant*tr = new QVariant(tql0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_List)(void* x0, int _len1, void* x1) {
QList<QVariant>tql1;
for (int i = 0; i < _len1; i++) {
tql1.append(*((QVariant*)((void**)x1)[i]));
}
((QVariant*)x0)->setValue<QVariantList>(tql1);
}
QTCEXPORT(int,qtc_QVariantValue_List)(void* x0, void* _ref) {
QList<QVariant> tql = ((QVariant*)x0)->value<QVariantList>();
if (_ref != NULL) {
for (int i = 0; i < tql.size(); i++) {
QVariant * tr = new QVariant(tql.at(i));
((void**)_ref)[i] = (void*)tr;
}
}
return tql.size();
}
QTCEXPORT(int,qtc_QVariant_toList)(void* x0, void* _ref) {
QList<QVariant> tql = ((QVariant*)x0)->toList();
if (_ref != NULL) {
for (int i = 0; i < tql.size(); i++) {
QVariant * tr = new QVariant(tql.at(i));
((void**)_ref)[i] = (void*)tr;
}
}
return tql.size();
}
QTCEXPORT(void*,qtc_QVariant_QStringList)(int _len0, void* x0) {
QStringList tqsl0;
for (int i = 0; i < _len0; i++) {
tqsl0.append(from_method(((wchar_t**)x0)[i]));
}
QVariant*tr = new QVariant(tqsl0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QStringList)(void* x0, int _len1, void* x1) {
QStringList tqsl1;
for (int i = 0; i < _len1; i++) {
tqsl1.append(from_method(((wchar_t**)x1)[i]));
}
((QVariant*)x0)->setValue<QStringList>(tqsl1);
}
QTCEXPORT(int,qtc_QVariantValue_QStringList)(void* x0, void* _ref) {
QStringList tqsl = ((QVariant*)x0)->value<QStringList>();
if (_ref != NULL) {
for (int i = 0; i < tqsl.size(); i++) {
QString * tqs = new QString(tqsl.at(i));
((void**)_ref)[i] = (void*)tqs;
}
}
return tqsl.size();
}
QTCEXPORT(int,qtc_QVariant_toStringList)(void* x0, void* _ref) {
QStringList tqsl = ((QVariant*)x0)->toStringList();
if (_ref != NULL) {
for (int i = 0; i < tqsl.size(); i++) {
QString * tqs = new QString(tqsl.at(i));
((void**)_ref)[i] = (void*)tqs;
}
}
return tqsl.size();
}
QTCEXPORT(void*,qtc_QVariant_Int)(int x0) {
QVariant*tr = new QVariant(x0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_Int)(void* x0, int x1) {
((QVariant*)x0)->setValue<int>(x1);
}
QTCEXPORT(int,qtc_QVariantValue_Int)(void* x0) {
return ((QVariant*)x0)->value<int>();
}
QTCEXPORT(int,qtc_QVariant_toInt)(void* x0) {
return ((QVariant*)x0)->toInt();
}
QTCEXPORT(void*,qtc_QVariant_Bool)(int x0) {
QVariant*tr = new QVariant(((bool)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_Bool)(void* x0, int x1) {
((QVariant*)x0)->setValue<bool>(((bool)x1));
}
QTCEXPORT(int,qtc_QVariantValue_Bool)(void* x0) {
return (int) ((QVariant*)x0)->value<bool>();
}
QTCEXPORT(int,qtc_QVariant_toBool)(void* x0) {
return (int) ((QVariant*)x0)->toBool();
}
QTCEXPORT(void*,qtc_QVariant_Double)(double x0) {
QVariant*tr = new QVariant(x0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_Double)(void* x0, double x1) {
((QVariant*)x0)->setValue<double>(x1);
}
QTCEXPORT(double,qtc_QVariantValue_Double)(void* x0) {
return ((QVariant*)x0)->value<double>();
}
QTCEXPORT(double,qtc_QVariant_toDouble)(void* x0) {
return ((QVariant*)x0)->toDouble();
}
QTCEXPORT(void*,qtc_QVariant_QString)(wchar_t* x0) {
QString tx1(from_method(x0));
QVariant*tr = new QVariant(tx1);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QString)(void* x0, wchar_t* x1) {
QString tx1(from_method(x1));
((QVariant*)x0)->setValue<QString>(tx1);
}
QTCEXPORT(void*,qtc_QVariantValue_QString)(void* x0) {
QString * tq = new QString(((QVariant*)x0)->value<QString>());
return (void*) tq;
}
QTCEXPORT(void*,qtc_QVariant_toString)(void* x0) {
QString * tq = new QString(((QVariant*)x0)->toString());
return (void*) tq;
}
QTCEXPORT(void*,qtc_QVariant_QByteArray)(void* x0) {
QVariant*tr = new QVariant((const QByteArray&)(*(QByteArray*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QByteArray)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QByteArray>((const QByteArray&)(*(QByteArray*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QByteArray)(void* x0) {
QByteArray * tq = new QByteArray(((QVariant*)x0)->value<QByteArray>());
return (void*) tq;
}
QTCEXPORT(void*,qtc_QVariant_toByteArray)(void* x0) {
QByteArray * tq = new QByteArray(((QVariant*)x0)->toByteArray());
return (void*) tq;
}
QTCEXPORT(long,qtc_QVariant_type)(void* x0) {
return (long) ((QVariant*)x0)->type();
}
QTCEXPORT(void*,qtc_QVariant_typeName)(void* x0) {
QString * tq = new QString(((QVariant*)x0)->typeName());
return (void*) tq;
}
QTCEXPORT(long,qtc_QVariant_nameToType)(wchar_t* x1) {
QString tx1(from_method(x1));
return (long) QVariant::nameToType(tx1.toUtf8().constData());
}
QTCEXPORT(void*,qtc_QVariant_typeToName)(long x1) {
QString * tq = new QString(QVariant::typeToName((QVariant::Type)x1));
return (void*) tq;
}
QTCEXPORT(int,qtc_QVariant_canConvert)(void* x0, long x1) {
return (int) ((QVariant*)x0)->canConvert((QVariant::Type)x1);
}
QTCEXPORT(int,qtc_QVariant_convert)(void* x0, long x1) {
return (int) ((QVariant*)x0)->convert((QVariant::Type)x1);
}
QTCEXPORT(void,qtc_QVariant_clear)(void* x0) {
((QVariant*)x0)->clear();
return;
}
QTCEXPORT(int,qtc_QVariant_isNull)(void* x0) {
return (int) ((QVariant*)x0)->isNull();
}
QTCEXPORT(int,qtc_QVariant_isValid)(void* x0) {
return (int) ((QVariant*)x0)->isValid();
}
QTCEXPORT(void*,qtc_QPointer)(void *x0) {
QPointer<QObject> * ttr = new QPointer<QObject>((QObject*)x0);
return (void *) ttr;
}
QTCEXPORT(void*,qtc_QPointer_data)(void *x0) {
QObject *ttr = *((QPointer<QObject>*)x0);
return (void *) ttr;
}
QTCEXPORT(int,qtc_QPolygonF_qpoints)(void *x0, double* _ret) {
int ts = ((QPolygonF*)x0)->size();
if (_ret != NULL) {
for (int i = 0; i < ts; i++) {
_ret[i * 2] = ((QPolygonF*)x0)->at(i).x();
_ret[(i * 2) + 1] = ((QPolygonF*)x0)->at(i).y();
}
}
return ts;
}
QTCEXPORT(int,qtc_QPolygon_qpoints)(void *x0, int* _ret) {
int ts = ((QPolygon*)x0)->size();
if (_ret != NULL) {
for (int i = 0; i < ts; i++) {
_ret[i * 2] = ((QPolygon*)x0)->at(i).x();
_ret[(i * 2) + 1] = ((QPolygon*)x0)->at(i).y();
}
}
return ts;
}
}
| 33.378173 | 182 | 0.676831 | keera-studios |
d1b3d4da3a4bae3d0ae068306d0c8d6e2dc1cfb8 | 1,331 | cpp | C++ | gameserver/test/main.cpp | shockerjue/Gameserver | 78faab152e1cb211d551a794ea4df5738cf99b04 | [
"Unlicense"
] | 31 | 2017-10-18T08:56:43.000Z | 2022-03-22T15:43:10.000Z | gameserver/test/main.cpp | shockerjue/Gameserver | 78faab152e1cb211d551a794ea4df5738cf99b04 | [
"Unlicense"
] | null | null | null | gameserver/test/main.cpp | shockerjue/Gameserver | 78faab152e1cb211d551a794ea4df5738cf99b04 | [
"Unlicense"
] | 14 | 2018-03-15T10:36:53.000Z | 2021-11-11T19:35:39.000Z | #include "./../src/msghandle/gameserver_msgheader.pb.h"
#include "./../../common/util/util.h"
#include "./../../common/msgdefine/msgheader.h"
#include "./../../common/network/network.h"
using namespace util;
using namespace msghandle;
using namespace gameserver_proto;
using namespace engine;
using namespace engine::network;
int main(int argc,const char* argv[]){
NetworkAddress address("127.0.0.1",4);
Network network(network::Protocol::TCP);
bool ret = network.Connect(address,8092);
if(!ret){
Log::Perror(__func__,"Connect fail!");
return -1;
}
LoginRequest login;
login.set_rid(9021);
login.set_key("ABCFARTQYT09879HJGJ^&**&()JKJI890");
string data;
login.SerializeToString(&data);
struct MessageHeader header;
header.msg_type = 10000;
header.msg_size = data.length();
char _data[sizeof(struct MessageHeader) + data.length()];
memcpy(_data,&header,sizeof(struct MessageHeader));
memcpy(_data + sizeof(struct MessageHeader),data.c_str(),data.length());
int len = network.Send(_data,sizeof(_data));
cout<<"Send sccuess len:"<<len<<" B"<<endl;
char buf[100] = {0};
len = network.Recv(buf,100);
string _recv = buf + sizeof(struct MessageHeader);
LoginResponse re_login;
re_login.ParseFromString(_recv);
cout<<"{status:"<<re_login.status()<<", msg:"<<re_login.msg()<<"}"<<endl;
return 0;
}
| 26.098039 | 74 | 0.709241 | shockerjue |
d1b5466adf001f4b32a8c3055cd9bbfb398ce3ca | 5,376 | cpp | C++ | src/wrappers/sockets/client_socket.cpp | ben-turner/s-torrent | f8ff818f2ce9c2bf76d2a108e1f32d3a601390e0 | [
"X11",
"BSD-2-Clause",
"MIT"
] | 20 | 2015-04-15T05:36:05.000Z | 2022-03-21T07:02:55.000Z | src/wrappers/sockets/client_socket.cpp | ben-turner/s-torrent | f8ff818f2ce9c2bf76d2a108e1f32d3a601390e0 | [
"X11",
"BSD-2-Clause",
"MIT"
] | null | null | null | src/wrappers/sockets/client_socket.cpp | ben-turner/s-torrent | f8ff818f2ce9c2bf76d2a108e1f32d3a601390e0 | [
"X11",
"BSD-2-Clause",
"MIT"
] | 6 | 2016-09-20T08:41:22.000Z | 2021-03-10T14:16:59.000Z | #include "client_socket.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include <stdexcept>
namespace sockets
{
Client_socket::Client_socket ( std::string address, int port )
{
struct sockaddr_in server_address;
struct hostent* resolved_server;
// Create a socket on the internet using the tcp
socket_address = socket(AF_INET, SOCK_STREAM, 0);
if ( socket_address < 0 )
error ( "Client_socket : Couldn't open socket" );
// Resolve server
resolved_server = gethostbyname ( address.c_str () );
if ( resolved_server == NULL )
error ( "Client_socket : Host not found: \"" + address + "\"" );
// Empty server_address
bzero ( ( char* ) &server_address, sizeof ( server_address ) );
// Use the internet
server_address.sin_family = AF_INET;
// Use address of resolved server
bcopy ( ( char* ) resolved_server->h_addr, ( char* ) &server_address.sin_addr.s_addr, resolved_server->h_length );
// sin_port has to be in network byte order
server_address.sin_port = htons ( port );
// Enable socket address reuse
int yes = 1;
int success = setsockopt ( socket_address, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof ( int ) );
if ( success < 0 )
error ( "Client_socket : setsockopt failed" );
// server_address has to be converted to sockaddr* from sockadd_in
success = connect ( socket_address, ( struct sockaddr* ) &server_address, sizeof ( server_address ) );
if ( success < 0 )
error ( "Client_socket : Connecting failed");
}
Client_socket::Client_socket ( int socket_address ) :
socket_address ( socket_address )
{}
std::string Client_socket::read_line ( std::string linebreak )
{
// Read until we have at least one line
while ( next_lines.empty () )
{
// This might actually happen ( look at the test for an example )
if ( ends_with ( line_rest, linebreak ) )
{
// Remove the linebreak from the end
next_lines.push_back ( line_rest.substr ( 0, line_rest.find_last_of ( linebreak ) ) );
line_rest = "";
break;
}
char buffer [ 1024 ];
int success = read ( socket_address, buffer, sizeof ( buffer ) - 1 );
if ( success < 0 )
error ( "read_line : Reading from socket failed");
else if ( success == 0 )
error ( "read_line : Connection closed");
buffer [ success ] = '\0';
// Create actual string from vector
std::string data_string ( buffer, strlen ( buffer ) );
std::string line;
// Split lines at delimiter
while ( ( line = get_line ( data_string, linebreak ) ).size () > 0 )
{
// Apply line_rest ( if any )
line = line_rest + line;
line_rest.clear ();
// Save yourself the hassle of dealing with DOS linebreaks
next_lines.push_back ( line );
}
// If buffer_string doesn't end with a linebreak
if ( data_string.size () > 0 )
{
// Create a line_rest
line_rest += data_string;
}
}
// Return next line
while ( !next_lines.empty () && next_lines.front () == "" )
next_lines.pop_front ();
if ( !next_lines.empty () )
{
std::string line = next_lines.front ();
next_lines.pop_front ();
return line;
}
else
return read_line ();
}
void Client_socket::send ( std::string message, std::string linebreak )
{
message += linebreak;
int success = write ( socket_address, message.c_str (), message.size () );
if ( success < 0 )
error ( "send : Sending over socket failed");
}
void Client_socket::shutdown ()
{
int success = close ( socket_address );
if ( success < 0 )
error ( "shutdown : Shutting socket down failed" );
}
void Client_socket::error ( std::string message )
{
if ( errno != 0 )
throw std::runtime_error ( "Error in sockets::Client_socket::" + message + " ( " + strerror ( errno ) + " )" );
else
throw std::runtime_error ( "Error in sockets::Client_socket::" + message );
}
std::string Client_socket::get_line ( std::string& from, const std::string& delimiter )
{
size_t pos = from.find ( delimiter );
if ( pos != std::string::npos )
{
std::string return_string = from.substr ( 0, pos );
from = from.substr ( pos + delimiter.size () );
return return_string;
}
return "";
}
bool Client_socket::ends_with ( const std::string& target, const std::string& ending )
{
if ( target.length () >= ending.length () )
return ( 0 == target.compare ( target.length () - ending.length (), ending.length (), ending ) );
return false;
}
}
| 34.242038 | 123 | 0.549851 | ben-turner |
d1b6b396afc16bb80ba24924854f6d65ad014d1a | 4,144 | cpp | C++ | game/tile_instance.cpp | astrellon/Rouge | 088f55b331284238e807e0562b9cbbed6428c20f | [
"MIT"
] | null | null | null | game/tile_instance.cpp | astrellon/Rouge | 088f55b331284238e807e0562b9cbbed6428c20f | [
"MIT"
] | null | null | null | game/tile_instance.cpp | astrellon/Rouge | 088f55b331284238e807e0562b9cbbed6428c20f | [
"MIT"
] | null | null | null | #include "tile_instance.h"
#include <util/utils.h>
#include "tile.h"
#include "engine.h"
#include <lua/wrappers/lua_id_table.h>
namespace am {
namespace game {
const int TileInstance::LUA_ID = LUA_ID_TILEINSTANCE;
const char *TileInstance::LUA_TABLENAME = LUA_TABLE_TILEINSTANCE;
TileInstance::TileInstance() :
mTile(nullptr),
mBaseVariation(0),
mTransitionVariation(0),
mOrder(-1)
{
for (int i = 0; i < 8; i++)
{
mTileEdgeValues[i] = 0u;
}
}
TileInstance::TileInstance(Tile *tile) :
mTile(tile),
mBaseVariation(0),
mTransitionVariation(0),
mOrder(-1)
{
for (int i = 0; i < 8; i++)
{
mTileEdgeValues[i] = 0u;
}
}
TileInstance::~TileInstance()
{
}
Tile *TileInstance::getTile()
{
if (mTile)
{
return mTile;
}
return Tile::getDefaultTile();
}
const Tile *TileInstance::getTile() const
{
if (mTile)
{
return mTile;
}
return Tile::getDefaultTile();
}
void TileInstance::setTile(Tile *tile)
{
mTile = tile;
}
bool TileInstance::setTileName(const char *tileName)
{
return setTileName(std::string(tileName));
}
bool TileInstance::setTileName(const std::string &tileName)
{
int framePos = static_cast<int>(tileName.find_last_of(":"));
std::string tileNameUse;
int frameValue = 0;
if (framePos >= 0)
{
std::string name = tileName.substr(0, framePos);
std::string frame = tileName.substr(framePos + 1);
tileNameUse = name;
bool parseResult = util::Utils::fromString<int>(frameValue, frame);
if (!parseResult)
{
frameValue = 0;
}
}
else
{
tileNameUse = tileName;
}
Tile *tile = Engine::getEngine()->getTile(tileNameUse.c_str());
if (tile == nullptr)
{
return false;
}
setTile(tile);
setBaseVariation(frameValue);
return true;
}
void TileInstance::setBaseVariation(int frame)
{
mBaseVariation = frame;
}
int TileInstance::getBaseVariation() const
{
return mBaseVariation;
}
void TileInstance::randomiseVaritation()
{
gfx::Asset *asset = mTile ? mTile->getGraphicAsset() : nullptr;
if (!asset)
{
return;
}
if (asset->getFrameRate() <= 0.0f)
{
if (asset->isSubWindowAnimation())
{
setBaseVariation(util::Utils::rand(0, asset->getTotalSubWindows()));
}
else
{
setBaseVariation(util::Utils::rand(0, asset->getTotalTextures()));
}
}
else
{
setBaseVariation(0);
}
}
void TileInstance::setTransitionVariation(int frame)
{
mTransitionVariation = frame;
}
int TileInstance::getTransitionVariation() const
{
return mTransitionVariation;
}
bool TileInstance::hasEdgeValue() const
{
for (int i = 0; i < 8; i++)
{
if (mTileEdgeValues[i] != 0)
{
return true;
}
}
return false;
}
void TileInstance::clearTileEdges()
{
for (int i = 0; i < 8; i++)
{
mTileEdgeValues[i] = 0u;
}
}
void TileInstance::setTileEdgeValue(uint32_t index, uint8_t edgeValue)
{
if (index < 8)
{
mTileEdgeValues[index] = edgeValue;
}
}
uint8_t TileInstance::getTileEdgeValue(uint32_t index) const
{
if (index < 8)
{
return mTileEdgeValues[index];
}
return 0u;
}
void TileInstance::addTileType(TileType *tileType)
{
if (tileType != nullptr)
{
mTileTypes.push_back(tileType);
}
}
void TileInstance::removeTileType(TileType *tileType)
{
if (tileType == nullptr)
{
return;
}
for (size_t i = 0; i < mTileTypes.size(); i++)
{
if (mTileTypes[i].get() == tileType)
{
mTileTypes.erase(mTileTypes.begin() + i);
}
}
}
void TileInstance::removeAllTileTypes()
{
mTileTypes.clear();
}
bool TileInstance::hasTileType(TileType *tileType) const
{
if (tileType == nullptr)
{
return false;
}
for (size_t i = 0; i < mTileTypes.size(); i++)
{
if (mTileTypes[i].get() == tileType)
{
return true;
}
}
return false;
}
TileInstance::TileTypeList &TileInstance::getTileTypes()
{
return mTileTypes;
}
const TileInstance::TileTypeList &TileInstance::getTileTypes() const
{
return mTileTypes;
}
void TileInstance::setOrder(uint32_t order)
{
mOrder = order;
}
uint32_t TileInstance::getOrder() const
{
return mOrder;
}
}
}
| 17.785408 | 72 | 0.649855 | astrellon |
d1b7fff69b9e2870c3e57c6ff996251e31eec4f8 | 4,545 | cpp | C++ | camera/hal/mediatek/mtkcam/main/hal/device3/common/Cam3Device.cpp | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | camera/hal/mediatek/mtkcam/main/hal/device3/common/Cam3Device.cpp | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | camera/hal/mediatek/mtkcam/main/hal/device3/common/Cam3Device.cpp | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | /*
* Copyright (C) 2019 MediaTek 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.
*/
#define LOG_TAG "MtkCam/Cam3Device"
//
#include "MyUtils.h"
#include <mtkcam/main/hal/Cam3Device.h>
//
using NSCam::Cam3Device;
/******************************************************************************
*
******************************************************************************/
static inline Cam3Device* getDevice(camera3_device const* device) {
return Cam3Device::getDevice(device);
}
////////////////////////////////////////////////////////////////////////////////
// Implementation of hw_device_t
////////////////////////////////////////////////////////////////////////////////
static int camera_close_device(hw_device_t* device) {
if (!device) {
return -EINVAL;
}
//
return Cam3Device::getDevice(device)->i_closeDevice();
}
static hw_device_t const gHwDevice = {
/** tag must be initialized to HARDWARE_DEVICE_TAG */
.tag = HARDWARE_DEVICE_TAG,
/** version number for hw_device_t */
.version = CAMERA_DEVICE_API_VERSION_3_3, // chrom only support 3_3 now
/** reference to the module this device belongs to */
.module = NULL,
/** padding reserved for future use */
.reserved = {0},
/** Close this device */
.close = camera_close_device,
};
////////////////////////////////////////////////////////////////////////////////
// Implementation of camera3_device_ops
////////////////////////////////////////////////////////////////////////////////
static int camera_initialize(camera3_device const* device,
camera3_callback_ops_t const* callback_ops) {
MERROR status = -ENODEV;
//
Cam3Device* const pDev = getDevice(device);
if (pDev) {
status = pDev->i_initialize(callback_ops);
}
return status;
}
static int camera_configure_streams(
camera3_device const* device, camera3_stream_configuration_t* stream_list) {
MERROR status = -ENODEV;
//
Cam3Device* const pDev = getDevice(device);
if (pDev) {
status = pDev->i_configure_streams(stream_list);
}
return status;
}
static camera_metadata_t const* camera_construct_default_request_settings(
camera3_device const* device, int type) {
Cam3Device* const pDev = getDevice(device);
if (pDev) {
return pDev->i_construct_default_request_settings(type);
}
return NULL;
}
static int camera_process_capture_request(camera3_device const* device,
camera3_capture_request_t* request) {
MERROR status = -ENODEV;
//
Cam3Device* const pDev = getDevice(device);
if (pDev) {
status = pDev->i_process_capture_request(request);
}
return status;
}
static void camera_dump(camera3_device const* device, int fd) {
Cam3Device* const pDev = getDevice(device);
if (pDev) {
pDev->i_dump(fd);
}
}
static int camera_flush(camera3_device const* device) {
MERROR status = -ENODEV;
//
Cam3Device* const pDev = getDevice(device);
if (pDev) {
status = pDev->i_flush();
}
return status;
}
static camera3_device_ops const gCameraDevOps = {
#define OPS(name) .name = camera_##name
OPS(initialize),
OPS(configure_streams),
.register_stream_buffers = NULL,
OPS(construct_default_request_settings),
OPS(process_capture_request),
.get_metadata_vendor_tag_ops = NULL,
OPS(dump),
OPS(flush),
#undef OPS
.reserved = {0},
};
/******************************************************************************
*
******************************************************************************/
Cam3Device::Cam3Device() : mpModuleCallbacks(NULL) {
MY_LOGD("ctor");
::memset(&mDevice, 0, sizeof(mDevice));
mDevice.priv = this;
mDevice.common = gHwDevice;
mDevice.ops = &mDeviceOps;
mDeviceOps = gCameraDevOps;
//
}
/******************************************************************************
*
******************************************************************************/
void Cam3Device::onLastStrongRef(const void* /*id*/) {
MY_LOGD("");
}
| 30.503356 | 80 | 0.573377 | strassek |
d1be8efd94a39972d7227c84bff91a52e9a5c750 | 629 | cpp | C++ | Project Euler Problems/Problem12.cpp | rishusingh022/My-Journey-of-Data-Structures-and-Algorithms | 28a70fdf10366fc97ddb9f6a69852b3478b564e6 | [
"MIT"
] | null | null | null | Project Euler Problems/Problem12.cpp | rishusingh022/My-Journey-of-Data-Structures-and-Algorithms | 28a70fdf10366fc97ddb9f6a69852b3478b564e6 | [
"MIT"
] | 1 | 2021-10-01T18:26:34.000Z | 2021-10-01T18:26:34.000Z | Project Euler Problems/Problem12.cpp | rishusingh022/My-Journey-of-Data-Structures-and-Algorithms | 28a70fdf10366fc97ddb9f6a69852b3478b564e6 | [
"MIT"
] | 7 | 2021-10-01T16:07:29.000Z | 2021-10-04T13:23:48.000Z | #include<bits/stdc++.h>
using namespace std;
int no_of_divisors(long long int n)
{
int divisors = 1,count =1;
while(n%2==0)
{
n/=2;
count++;
}
//cout<<count;
divisors*=count;
for(int i=3;i<=sqrt(n);i++)
{ count =1;
while(n%i==0)
{
n/=i;
count++;
}
divisors*=count;
}
if(n>2)
divisors*=2;
return divisors;
}
int main()
{
const int divisors_check =500;
long long int sum = 0,i=1;
do{
sum+=i,i++;
}while(no_of_divisors(sum)<divisors_check);
cout<<sum;
return 0;
} | 17 | 47 | 0.475358 | rishusingh022 |
d1bebb1e78b9e0b5e41e4bb8dfa71674e68df33d | 2,194 | hpp | C++ | p5out/src/application/imageio.hpp | tinyalpha/PhysicsSimulation | a13f259862216d809b02aa4739e7692a9d66e2bc | [
"MIT"
] | 25 | 2016-11-14T23:23:53.000Z | 2020-12-17T08:29:41.000Z | p5out/src/application/imageio.hpp | tinyalpha/PhysicsSimulation | a13f259862216d809b02aa4739e7692a9d66e2bc | [
"MIT"
] | 1 | 2018-08-08T00:31:49.000Z | 2018-08-08T00:31:49.000Z | p5out/src/application/imageio.hpp | tinyalpha/PhysicsSimulation | a13f259862216d809b02aa4739e7692a9d66e2bc | [
"MIT"
] | 1 | 2020-03-22T12:04:52.000Z | 2020-03-22T12:04:52.000Z | /* LIBRARY: ImageIO Library v0.13
*
* FILE: imageio.hpp
*
* COPYRIGHT: Copyright (c) 2003-2004 Adrien Treuille
*
* AUTHORS: Adrien Treuille (treuille [AT] cs [DOT] washington [DOT] edu)
* Kristin Siu
*
* LICENSE: The ImageIO Library is supplied "AS IS". The Authors
* disclaim all warranties, expressed or implied,
* including, without limitation, the warranties of
* merchantability and of fitness for any purpose.
* The Authors assume no liability for direct, indirect,
* incidental, special, exemplary, or consequential
* damages, which may result from the use of the ImageIO
* Library, even if advised of the possibility of such
* damage.
*
* Permission is hereby granted to use, copy, modify,
* and distribute this source code, or portions hereof,
* for any purpose, without fee, for non-commercial
* purposes. All rights reserved for commercial uses of
* this source code.
*/
#ifndef _462_APPLICATION_IMAGEIO_HPP_
#define _462_APPLICATION_IMAGEIO_HPP_
#include <cstdlib>
namespace _462 {
// Sets tbe width and height to the appropriate values and mallocs
// a char *buffer loading up the values in row-major, RGBA format.
// The memory associated with the buffer can be deallocated with free().
// If there was an error reading file, then 0 is returned, and
// width = height are set to -1.
unsigned char* imageio_load_image( const char* filename, int *width, int *height );
// Saves image given by buffer with specicified width and height
// to the given file name, returns true on success, false otherwise.
// The image format is RGBA.
bool imageio_save_image( const char* filename, unsigned char* buffer, int width, int height );
// Writes the current opengl frame buffer to a specified file name.
// Returns true on succces, false otherwise.
bool imageio_save_screenshot( const char* filename, int width, int height );
// puts a default filename in name, up to len characters
void imageio_gen_name( char* filename, size_t len );
} /* _462 */
#endif /* _462_APPLICATION_IMAGEIO_HPP_ */
| 39.178571 | 94 | 0.692343 | tinyalpha |
d1c041790d599aa0d1b197136b45adbf63aa7b69 | 4,703 | cpp | C++ | src/pow.cpp | kevacoin-team/kevacoin | 7a6f5024cb8e2f0283c6e57b9f4439dcdf9a09e8 | [
"MIT"
] | null | null | null | src/pow.cpp | kevacoin-team/kevacoin | 7a6f5024cb8e2f0283c6e57b9f4439dcdf9a09e8 | [
"MIT"
] | null | null | null | src/pow.cpp | kevacoin-team/kevacoin | 7a6f5024cb8e2f0283c6e57b9f4439dcdf9a09e8 | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <pow.h>
#include <arith_uint256.h>
#include <chain.h>
#include <primitives/block.h>
#include <uint256.h>
extern void GetRandomXSeedParams(uint64_t& seedHeight, uint256& blockHash);
// Copy and modified from CalculateDogecoinNextWorkRequired (dogecoin.cpp)
unsigned int CalculateDigishieldNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
const int64_t retargetTimespan = params.nPowTargetTimespan;
const int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
int64_t nModulatedTimespan = nActualTimespan;
int64_t nMaxTimespan;
int64_t nMinTimespan;
// amplitude filter - thanks to daft27 for this code
nModulatedTimespan = retargetTimespan + (nModulatedTimespan - retargetTimespan) / 8;
nMinTimespan = retargetTimespan - (retargetTimespan / 4);
nMaxTimespan = retargetTimespan + (retargetTimespan / 2);
// Limit adjustment step
if (nModulatedTimespan < nMinTimespan)
nModulatedTimespan = nMinTimespan;
else if (nModulatedTimespan > nMaxTimespan)
nModulatedTimespan = nMaxTimespan;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nModulatedTimespan;
bnNew /= retargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
assert(pindexLast != nullptr);
// Go back by what we want to be 14 days worth of blocks
// Kevacoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
int blockstogoback = params.DifficultyAdjustmentInterval()-1;
if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
blockstogoback = params.DifficultyAdjustmentInterval();
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
return CalculateDigishieldNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
bool CheckProofOfWork(const CBlock& block, unsigned int nBits, const Consensus::Params& params) {
uint64_t seedHeight = 0;
uint256 blockHash(0);
GetRandomXSeedParams(seedHeight, blockHash);
//return CheckProofOfWork(block.GetPoWHash(seedHeight, blockHash), nBits, params);
return true;
}
bool CheckProofOfWork(const CBlockHeader& block, unsigned int nBits, const Consensus::Params& params) {
uint64_t seedHeight = 0;
uint256 blockHash(0);
GetRandomXSeedParams(seedHeight, blockHash);
//return CheckProofOfWork(block.GetPoWHash(seedHeight, blockHash), nBits, params);
return true;
}
| 35.360902 | 137 | 0.732936 | kevacoin-team |
d1c36c92f9a0a91d8b0c848bee1649f169e3de47 | 3,748 | cpp | C++ | apps/eop1/delighter/MA_v1.0_src/ImageReceiver/ImageReceiver.cpp | gaps-closure/top-level | 11ccdbf753d4093bed1f6537b3fe675e3251076c | [
"BSD-3-Clause"
] | null | null | null | apps/eop1/delighter/MA_v1.0_src/ImageReceiver/ImageReceiver.cpp | gaps-closure/top-level | 11ccdbf753d4093bed1f6537b3fe675e3251076c | [
"BSD-3-Clause"
] | null | null | null | apps/eop1/delighter/MA_v1.0_src/ImageReceiver/ImageReceiver.cpp | gaps-closure/top-level | 11ccdbf753d4093bed1f6537b3fe675e3251076c | [
"BSD-3-Clause"
] | 2 | 2020-03-30T05:47:37.000Z | 2020-04-02T23:10:14.000Z |
#include <stdio.h>
#include <string>
#include <fstream>
#include <amqm/AMQManager.h>
#include <Utils.h>
#include "ImageReceiver.h"
#include <nlohmann/json.hpp>
#include <opencv2/opencv.hpp>
#include <heartbeat/HeartBeat.h>
#include <BlockingQueue.h>
using namespace amqm;
using namespace cms;
using namespace std;
using namespace cv;
#define OVERLAY(text,pos) cv::putText(imageMat,text,pos,ENCLAVE_FONT,FONT_SCALE,ENCLAVE_COLOR,FONT_THICKNESS)
static const string WINDOW_NAME = "CLOSURE Image Receiver";
static const cv::Scalar ENCLAVE_COLOR = CV_RGB(235, 140, 52);
static const cv::HersheyFonts ENCLAVE_FONT = cv::FONT_HERSHEY_DUPLEX;
static const cv::Point NAME_POINT(10, 400);
static const cv::Point SIZE_POINT(10, 440);
static const cv::Point META_POINT(10, 480);
static const double FONT_SCALE = 1.0;
static const int FONT_THICKNESS = 2;
static BlockingQueue<json> messageQueue;
static cv::Mat imageMat;
ImageReceiver::ImageReceiver()
{
amq.listen("receiveImageDetections", std::bind(&ImageReceiver::updateImageDetected, this, _1), true);
json j = Utils::loadDefaultConfig();
processConfigContent(j);
}
void ImageReceiver::processConfigContent(json j)
{
}
ImageReceiver::~ImageReceiver()
{
}
void ImageReceiver::updateImageDetected(const json &j)
{
messageQueue.push(j);
}
void hexToBin(string hexData, char *image_buf, int image_buf_size)
{
int buf_size = hexData.length();
if (image_buf_size < buf_size / 2) {
cout << "ERROR: buffer too small: " << buf_size << " v.s. " << image_buf_size << endl;
buf_size = image_buf_size * 2;
}
int k = 0;
for (int i = 0; i < buf_size; i += 2) {
image_buf[k++] = std::stoul(hexData.substr(i, 2), nullptr, 16);
}
}
void displayImage(const json &j)
{
string name = j["A_name"].get<string>();
int size = j["B_size"];
string pad = j["C_pad"].get<string>();
string meta = j["D_metadata"].get<string>();
string imageData = j["E_imgData"].get<string>();
cout << "Receiver rcvd " << name << " : " << size << " : " << meta << endl;
char img[size];
hexToBin(imageData, img, size);
vector<unsigned char> imVec(img, img + size);
imdecode(imVec, IMREAD_COLOR, &imageMat);
OVERLAY("Name: " + name, NAME_POINT);
OVERLAY("Size: " + to_string(size), SIZE_POINT);
OVERLAY("Meta: " + meta, META_POINT);
imshow(WINDOW_NAME, imageMat);
// GIve enough time for iamge to render, 800ms seems adequate
waitKey(800); // Wait for any keystroke in the window
}
void displaySplash(string pathanme)
{
std::string image_path = samples::findFile(pathanme);
Mat img = imread(image_path, IMREAD_COLOR);
if (img.empty()) {
std::cout << "Could not read the image: " << image_path << std::endl;
return;
}
img.convertTo(imageMat, CV_8U);
imshow(WINDOW_NAME, imageMat);
moveWindow(WINDOW_NAME, 0, 100);
waitKey(1000); // Wait for any keystroke in the window
}
void ImageReceiver::run()
{
displaySplash("config/images/splash-receiver.jpg");
HeartBeat isrm_HB("ImageReceiver");
isrm_HB.startup_Listener("ImageDetector");
json timeout;
timeout["A_name"] = "timeout";
while (true) {
json msg = messageQueue.pop(1, timeout);
string name = msg["A_name"].get<string>();
// imshow will not refresh the window after waitKey returns
// refresh it if no new message is received
if (!name.compare("timeout")) {
imshow(WINDOW_NAME, imageMat);
waitKey(10);
}
else {
displayImage(msg);
}
}
}
| 27.762963 | 111 | 0.636873 | gaps-closure |
d1c7024bfc06fc71c2df0d891bce19a53d10da44 | 3,015 | cpp | C++ | apps/main.cpp | mpohl100/TheChase | 06a3ddd7b2a5dd5102f3b3288706bd6e658d0cd9 | [
"Apache-2.0"
] | null | null | null | apps/main.cpp | mpohl100/TheChase | 06a3ddd7b2a5dd5102f3b3288706bd6e658d0cd9 | [
"Apache-2.0"
] | null | null | null | apps/main.cpp | mpohl100/TheChase | 06a3ddd7b2a5dd5102f3b3288706bd6e658d0cd9 | [
"Apache-2.0"
] | null | null | null | #include <chase/TeamAnalysisPar.h>
#include <clara.hpp>
#include <iostream>
int main(int argc, char** argv)
{
using namespace clara;
std::string name;
bool help = false;
auto cli = Opt(name, "name")["-n"]["--name"]("name to greet") | Help(help);
auto result = cli.parse(Args(argc, argv));
if (!result) {
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
exit(1);
}
if (help) {
std::cout << cli;
exit(0);
}
#if 0
chase::SimpleAnalysisOptions options;
options.dontPlayFinal = true;
options.nbGenerations = 500;
chase::simpleChaseAnalysis(options);
#else
std::vector<std::vector<double>> playerPercentages = {
{0.4, 0.7, 0.4, 0.4},
{0.4, 0.4, 0.7, 0.4},
{0.4, 0.4, 0.4, 0.7},
{0.6, 0.4, 0.4, 0.4},
{0.4, 0.6, 0.4, 0.4},
{0.4, 0.4, 0.6, 0.4},
{0.4, 0.4, 0.4, 0.6},
{0.5, 0.4, 0.4, 0.4},
{0.4, 0.5, 0.4, 0.4},
{0.4, 0.4, 0.5, 0.4},
{0.4, 0.4, 0.4, 0.5},
{0.7, 0.5, 0.5, 0.5},
{0.5, 0.7, 0.5, 0.5},
{0.5, 0.5, 0.7, 0.5},
{0.5, 0.5, 0.5, 0.7},
{0.6, 0.5, 0.5, 0.5},
{0.5, 0.6, 0.5, 0.5},
{0.5, 0.5, 0.6, 0.5},
{0.5, 0.5, 0.5, 0.6},
{0.7, 0.6, 0.6, 0.6},
{0.6, 0.7, 0.6, 0.6},
{0.6, 0.6, 0.7, 0.6},
{0.6, 0.6, 0.6, 0.7}};
for(const auto& playerPercentage : playerPercentages)
{
chase::TeamPlayerAnalysis analysis;
analysis.analysisRange.playerPercentages = playerPercentage;
analysis.analysisRange.chaserFactorParams = {{2.0, 5.0, 1.0}};
chase::teamPlayerAnalysisPar(analysis);
chase::dumpTeamPlayerResults(analysis, std::string("Team" + chase::toStringPath(playerPercentage) + ".csv"));
}
#endif
return 0;
}
| 44.338235 | 117 | 0.305804 | mpohl100 |
d1c74e407d9d4211e94ec4d1bc70ce0ad75489c8 | 2,725 | cpp | C++ | Base/Semaphore.cpp | nondejus/AudioPerfLab | 4289d97d3cd59e9bb2cb5b447d6aaeea8a5fbd12 | [
"MIT"
] | 81 | 2019-11-20T16:19:52.000Z | 2022-03-18T17:14:14.000Z | Base/Semaphore.cpp | nondejus/AudioPerfLab | 4289d97d3cd59e9bb2cb5b447d6aaeea8a5fbd12 | [
"MIT"
] | 4 | 2019-11-23T15:18:12.000Z | 2020-05-04T08:35:04.000Z | Base/Semaphore.cpp | nondejus/AudioPerfLab | 4289d97d3cd59e9bb2cb5b447d6aaeea8a5fbd12 | [
"MIT"
] | 7 | 2019-11-30T09:28:51.000Z | 2021-09-17T20:26:39.000Z | /*
* Copyright (c) 2019 Ableton AG, Berlin
*
* 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 "Base/Semaphore.hpp"
#include <cstdint>
#include <mach/mach_init.h>
#include <mach/semaphore.h>
#include <mach/sync_policy.h>
#include <mach/task.h>
#include <stdexcept>
#if defined(__has_feature) && __has_feature(thread_sanitizer)
#define ANNOTATE_HAPPENS_BEFORE(addr) \
AnnotateHappensBefore(__FILE__, __LINE__, static_cast<void*>(addr))
#define ANNOTATE_HAPPENS_AFTER(addr) \
AnnotateHappensAfter(__FILE__, __LINE__, static_cast<void*>(addr))
extern "C" void AnnotateHappensBefore(const char* f, int l, void* addr);
extern "C" void AnnotateHappensAfter(const char* f, int l, void* addr);
#else
#define ANNOTATE_HAPPENS_BEFORE(addr)
#define ANNOTATE_HAPPENS_AFTER(addr)
#endif
Semaphore::Semaphore(const uint32_t initial)
{
if (semaphore_create(mach_task_self(), &mSemaphore, SYNC_POLICY_FIFO, int(initial)))
{
throw std::runtime_error("Error creating semaphore");
}
}
Semaphore::~Semaphore() { semaphore_destroy(mach_task_self(), mSemaphore); }
Semaphore::Status Semaphore::post()
{
ANNOTATE_HAPPENS_BEFORE(&mSemaphore);
return !semaphore_signal(mSemaphore) ? Status::success : Status::error;
}
Semaphore::Status Semaphore::wait()
{
kern_return_t result;
do
{
result = semaphore_wait(mSemaphore);
} while (result == KERN_ABORTED);
#if defined(__has_feature) && __has_feature(thread_sanitizer)
if (result == KERN_SUCCESS)
{
ANNOTATE_HAPPENS_AFTER(&mSemaphore);
}
#endif
return result == KERN_SUCCESS ? Status::success : Status::error;
}
| 35.38961 | 90 | 0.726606 | nondejus |
d1c913d8c059220d2fe7336a3362addb9f2d2d07 | 850 | cc | C++ | src/developer/debug/zxdb/symbols/identifier.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/developer/debug/zxdb/symbols/identifier.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/developer/debug/zxdb/symbols/identifier.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/debug/zxdb/symbols/identifier.h"
namespace zxdb {
std::string IdentifierComponent::GetName(bool include_debug) const {
if (!include_debug && special_ == SpecialIdentifier::kNone) // Common case.
return name_;
std::string result;
if (include_debug)
result.push_back('"');
if (special_ == SpecialIdentifier::kNone) {
result.append(name_);
} else {
result.append(SpecialIdentifierToString(special_));
if (SpecialIdentifierHasData(special_)) {
result.push_back('(');
result.append(name_);
result.push_back(')');
}
}
if (include_debug)
result.push_back('"');
return result;
}
} // namespace zxdb
| 25 | 78 | 0.688235 | allansrc |
d1ca2ef06b7606a13b1247b19a65bd7d89f4b594 | 2,665 | cpp | C++ | src/gameobject_asteroid.cpp | liamst19/asteroids-study | 809e6573eb45800ba06ec8e03e7103815188a70b | [
"MIT"
] | null | null | null | src/gameobject_asteroid.cpp | liamst19/asteroids-study | 809e6573eb45800ba06ec8e03e7103815188a70b | [
"MIT"
] | null | null | null | src/gameobject_asteroid.cpp | liamst19/asteroids-study | 809e6573eb45800ba06ec8e03e7103815188a70b | [
"MIT"
] | null | null | null | /** gameobject_asteroid.h
*
*
*/
#include <vector>
#include <algorithm>
#include "math.h"
#include "game.h"
#include "gameobject_asteroid.h"
#include "component_physics.h"
#include "component_collision.h"
/** Constructor
*
*/
Asteroid::Asteroid(Game* game,
Vector2d position,
float rotation):
GameObject(game, position, rotation)
{
// Set Velocities
_physics.set_velocity(Vector2d(_game->rand(_rand_forward_velocity_min, _rand_forward_velocity_max),
_game->rand(_rand_forward_velocity_min, _rand_forward_velocity_max)));
_physics.set_angular_velocity(_game->rand(_rand_angular_velocity_min, _rand_angular_velocity_max));
// generate shape
float radius = _game->rand(_rand_radius_min, _rand_radius_max);
_draw.set_shape_active(make_shape_active(radius));
_draw.set_shape_destroyed(make_shape_destroyed(radius));
// prepare collision
_collision.set_radius(radius);
add_component(&_physics);
add_component(&_draw);
add_component(&_collision);
}
/** function: update()
*
*/
void Asteroid::update(double delta_time){
update_components(delta_time);
}
/** function: destroy()
*
*/
void Asteroid::destroy(){
_state = GameObject_State_Code::destroyed;
}
/** function: make_shape()
*
*/
std::vector<Vector2d> Asteroid::make_shape_active(float radius){
std::vector<Vector2d> shape;
int vertices = _game->rand(_rand_vertices_min, _rand_vertices_max);
std::vector<float> angles;
// Fill shape with random angles
for(int i = 0; i < vertices; ++i){
angles.push_back(_game->rand(_rand_angles_min, _rand_angles_max));
}
// Sort angles into shape
std::sort(angles.begin(), angles.end());
Vector2d bounds = _game->get_bounds();
// Draw shape from angles
for(auto angle: angles){
shape.push_back(Vector2d(
radius * Math::Sin(Math::ToRadians(angle)),
-1 * radius * Math::Cos(Math::ToRadians(angle))
));
}
return shape;
}
/** function: draw_shape_destroyed()
*
*/
std::vector<Vector2d> Asteroid::make_shape_destroyed(float radius){
std::vector<Vector2d> shape{
Vector2d(5, -3),
Vector2d(-5, 3),
Vector2d(8, -5),
Vector2d(-8, 5),
Vector2d(3, -1),
Vector2d(-4, 3),
};
return shape;
}
/** function: draw()
*
*/
std::vector<Vector2d> Asteroid::draw(){
return _draw.draw_shape(_physics.position(),
_physics.rotation());
} | 25.380952 | 106 | 0.620263 | liamst19 |
d1cada508aa3d1651678857da0ecddbc19d624fc | 2,104 | hpp | C++ | library/ATF/CNetSocket.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CNetSocket.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CNetSocket.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CNetIndexList.hpp>
#include <CNetSocketVtbl.hpp>
#include <CNetTimer.hpp>
#include <_IP_CHECK_NODE.hpp>
#include <_SOCK_TYPE_PARAM.hpp>
#include <_socket.hpp>
#include <_total_count.hpp>
#include <sockaddr_in.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 8)
struct CNetSocket
{
CNetSocketVtbl *vfptr;
unsigned __int64 m_sAccept;
void *m_AcceptEvent;
_socket *m_Socket;
void **m_Event;
_SOCK_TYPE_PARAM m_SockType;
_total_count m_TotalCount;
bool m_bSetSocket;
unsigned int m_dwSerialCounter;
int m_nIPCheckNodeNum;
_IP_CHECK_NODE *m_ndIPCheck;
unsigned int *m_dwIPCheckBufferList;
CNetIndexList m_listIPCheck;
CNetIndexList m_listIPCheck_Empty;
CNetTimer m_tmrListCheckerIPCheck;
public:
bool Accept_Client(unsigned int dwSocketIndex);
unsigned int Accept_Server();
CNetSocket();
void ctor_CNetSocket();
void CloseAll();
bool CloseSocket(unsigned int n);
int Connect(unsigned int n, struct sockaddr_in* pAddr);
void EmptySocketBuffer(unsigned int n);
unsigned int FindEmptySocket();
struct _socket* GetSocket(unsigned int dwIndex);
unsigned int GetSocketIPAddress(unsigned int dwIndex);
struct _SOCK_TYPE_PARAM* GetSocketType();
struct _total_count* GetTotalCount();
bool InitAcceptSocket(char* pszErrMsg);
void OnLoop();
bool PushIPCheckList(unsigned int dwIP);
bool Recv(unsigned int n, char* pBuf, int nBufMaxSize, int* pnRet);
void Release();
bool Send(unsigned int n, char* pBuf, int nSize, int* pnRet);
bool SetSocket(struct _SOCK_TYPE_PARAM* pType, char* pszErrMsg);
~CNetSocket();
void dtor_CNetSocket();
};
#pragma pack(pop)
static_assert(ATF::checkSize<CNetSocket, 488>(), "CNetSocket");
END_ATF_NAMESPACE
| 34.491803 | 108 | 0.677281 | lemkova |
d1ccd29a5e64983e562a2add75c39af476360f80 | 242 | cpp | C++ | c++11/tests/right_bracket_parse.cpp | queertypes/cplusplus-examples | c4f784cbc9e97220c0e25f7ea9f1121f63d194fe | [
"BSD-3-Clause"
] | null | null | null | c++11/tests/right_bracket_parse.cpp | queertypes/cplusplus-examples | c4f784cbc9e97220c0e25f7ea9f1121f63d194fe | [
"BSD-3-Clause"
] | null | null | null | c++11/tests/right_bracket_parse.cpp | queertypes/cplusplus-examples | c4f784cbc9e97220c0e25f7ea9f1121f63d194fe | [
"BSD-3-Clause"
] | null | null | null | #include <cstdio>
template <class T>
struct X {
};
int main()
{
// can your compiler handle this parse?
X<X<int>> *x{nullptr};
// output for the sake of silencing compiler warnings
printf("%p\n", static_cast<void *>(x));
return 0;
}
| 14.235294 | 54 | 0.652893 | queertypes |
d1d24e4857847c0be5fa20819c17367463c6698e | 21,177 | cpp | C++ | src/data_readers/data_reader_jag.cpp | forsyth2/lbann | 64fc0346f65353c2f7526a019da964914e539fb0 | [
"Apache-2.0"
] | null | null | null | src/data_readers/data_reader_jag.cpp | forsyth2/lbann | 64fc0346f65353c2f7526a019da964914e539fb0 | [
"Apache-2.0"
] | null | null | null | src/data_readers/data_reader_jag.cpp | forsyth2/lbann | 64fc0346f65353c2f7526a019da964914e539fb0 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 "lbann/utils/file_utils.hpp"
#include "lbann/utils/cnpy_utils.hpp"
#include "lbann/utils/image.hpp"
#include "lbann/data_readers/data_reader_jag.hpp"
#include <limits> // numeric_limits
#include <algorithm> // max_element
#include <numeric> // accumulate
#include <functional> // multiplies
#include <type_traits>// is_same
#include <opencv2/core.hpp>
namespace lbann {
data_reader_jag::data_reader_jag(bool shuffle)
: generic_data_reader(shuffle),
m_independent({Undefined}), m_dependent({Undefined}),
m_image_loaded(false), m_scalar_loaded(false),
m_input_loaded(false), m_num_samples(0u),
m_linearized_image_size(0u),
m_linearized_scalar_size(0u),
m_linearized_input_size(0u),
m_image_normalization(0u),
m_image_width(0u), m_image_height(0u),
m_img_min(std::numeric_limits<data_t>::max()),
m_img_max(std::numeric_limits<data_t>::min()) {
}
data_reader_jag::~data_reader_jag() {
}
void data_reader_jag::set_independent_variable_type(
const std::vector< std::vector<data_reader_jag::variable_t> >& independent) {
if (!independent.empty() && !m_independent.empty() && (m_independent[0] == Undefined)) {
m_independent.clear();
}
for (const auto& group: independent) {
for (const auto type: group) {
add_independent_variable_type(type);
}
}
}
void data_reader_jag::add_independent_variable_type(
const data_reader_jag::variable_t independent) {
if (!(independent == JAG_Image || independent == JAG_Scalar ||
independent == JAG_Input || independent == Undefined)) {
throw lbann_exception(std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: unrecognized variable type " + std::to_string(static_cast<int>(independent)));
}
m_independent.push_back(independent);
}
void data_reader_jag::set_dependent_variable_type(
const std::vector < std::vector<data_reader_jag::variable_t> >& dependent) {
if (!dependent.empty() && !m_dependent.empty() && (m_dependent[0] == Undefined)) {
m_dependent.clear();
}
for (const auto& group: dependent) {
for (const auto type: group) {
add_dependent_variable_type(type);
}
}
}
void data_reader_jag::add_dependent_variable_type(
const data_reader_jag::variable_t dependent) {
if (!(dependent == JAG_Image || dependent == JAG_Scalar ||
dependent == JAG_Input || dependent == Undefined)) {
throw lbann_exception(std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: unrecognized variable type " + std::to_string(static_cast<int>(dependent)));
}
m_dependent.push_back(dependent);
}
std::vector<data_reader_jag::variable_t> data_reader_jag::get_independent_variable_type() const {
return m_independent;
}
std::vector<data_reader_jag::variable_t> data_reader_jag::get_dependent_variable_type() const {
return m_dependent;
}
bool data_reader_jag::is_independent(const variable_t t) const {
for(const auto i: m_independent) {
if (i == t) return true;
}
return false;
}
bool data_reader_jag::is_dependent(const variable_t t) const {
for(const auto d: m_dependent) {
if (d == t) return true;
}
return false;
}
bool data_reader_jag::is_used(const variable_t t) const {
return is_independent(t) || is_dependent(t);
}
void data_reader_jag::set_normalization_mode(int mode) {
if ((mode < 0) || (2 < mode)) {
throw lbann_exception("data_reader_jag: invalid normalization mode " +
std::to_string(mode));
}
m_image_normalization = mode;
}
void data_reader_jag::set_image_dims(const int width, const int height) {
if ((width > 0) && (height > 0)) { // set and valid
m_image_width = width;
m_image_height = height;
} else if (!((width == 0) && (height == 0))) { // set but not valid
std::stringstream err;
err << __FILE__<<" "<<__LINE__
<< " :: data_reader_jag::set_image_dims() invalid image dims";
throw lbann_exception(err.str());
}
}
size_t data_reader_jag::get_num_samples() const {
return m_num_samples;
}
size_t data_reader_jag::get_linearized_image_size() const {
return m_linearized_image_size;
}
size_t data_reader_jag::get_linearized_scalar_size() const {
return m_linearized_scalar_size;
}
size_t data_reader_jag::get_linearized_input_size() const {
return m_linearized_input_size;
}
void data_reader_jag::set_linearized_image_size() {
if (!m_image_loaded) {
m_linearized_image_size = 0u;
m_image_width = 0u;
m_image_height = 0u;
} else {
m_linearized_image_size
= std::accumulate(m_images.shape.begin()+1, m_images.shape.end(),
1u, std::multiplies<size_t>());
if (m_linearized_image_size != static_cast<size_t>(m_image_width*m_image_height)) {
if ((m_image_width == 0u) && (m_image_height == 0u)) {
m_image_height = 1;
m_image_width = static_cast<int>(m_linearized_image_size);
} else {
std::stringstream err;
err << __FILE__<<" "<<__LINE__
<< " :: data_reader_jag::set_linearized_image_size() image size mismatch";
throw lbann_exception(err.str());
}
}
}
}
void data_reader_jag::set_linearized_scalar_size() {
if (!m_scalar_loaded) {
m_linearized_scalar_size = 0u;
} else {
m_linearized_scalar_size
= std::accumulate(m_scalars.shape.begin()+1, m_scalars.shape.end(),
1u, std::multiplies<size_t>());
}
}
void data_reader_jag::set_linearized_input_size() {
if (!m_input_loaded) {
m_linearized_input_size = 0u;
} else {
m_linearized_input_size
= std::accumulate(m_inputs.shape.begin()+1, m_inputs.shape.end(),
1u, std::multiplies<size_t>());
}
}
size_t data_reader_jag::get_linearized_size(const data_reader_jag::variable_t t) const {
switch (t) {
case JAG_Image:
return m_linearized_image_size;
case JAG_Scalar:
return m_linearized_scalar_size;
case JAG_Input:
return m_linearized_input_size;
default: { // includes Undefined case
throw lbann_exception(std::string("data_reader_jag::get_linearized_size() : ") +
"unknown or undefined variable type");
}
}
return 0u;
}
int data_reader_jag::get_linearized_data_size() const {
size_t sz = 0u;
for (const auto t: m_independent) {
if (t == Undefined) {
continue;
}
sz += get_linearized_size(t);
}
return static_cast<int>(sz);
}
int data_reader_jag::get_linearized_response_size() const {
size_t sz = 0u;
for (const auto t: m_dependent) {
if (t == Undefined) {
continue;
}
sz += get_linearized_size(t);
}
return static_cast<int>(sz);
}
std::vector<size_t> data_reader_jag::get_linearized_data_sizes() const {
std::vector<size_t> all_dim;
all_dim.reserve(m_independent.size());
for (const auto t: m_independent) {
if (t == Undefined) {
continue;
}
all_dim.push_back(get_linearized_size(t));
}
return all_dim;
}
std::vector<size_t> data_reader_jag::get_linearized_response_sizes() const {
std::vector<size_t> all_dim;
all_dim.reserve(m_dependent.size());
for (const auto t: m_dependent) {
if (t == Undefined) {
continue;
}
all_dim.push_back(get_linearized_size(t));
}
return all_dim;
}
const std::vector<int> data_reader_jag::get_dims(const data_reader_jag::variable_t t) const {
switch (t) {
case JAG_Image:
return {1, m_image_height, m_image_width};
//return {static_cast<int>(m_linearized_image_size)};
case JAG_Scalar:
return {static_cast<int>(m_linearized_scalar_size)};
case JAG_Input:
return {static_cast<int>(m_linearized_input_size)};
default: {
throw lbann_exception(std::string("data_reader_jag::get_dims() : ") +
"unknown or undefined variable type");
}
}
return {};
}
const std::vector<int> data_reader_jag::get_data_dims() const {
std::vector<int> all_dim;
for (const auto t: m_independent) {
if (t == Undefined) {
continue;
}
const std::vector<int> ld = get_dims(t);
all_dim.insert(all_dim.end(), ld.begin(), ld.end());
}
return all_dim;
}
void data_reader_jag::load() {
if (m_gan_labelling) {
m_num_labels=2;
}
if (is_master()) {
std::cout << "JAG load GAN m_gan_labelling : label_value "
<< m_gan_labelling <<" : " << m_gan_label_value << std::endl;
}
const std::string data_dir = add_delimiter(get_file_dir());
const std::string namestr = get_data_filename();
std::vector<std::string> file_names = get_tokens(namestr);
if (file_names.size() != 3u) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: unexpected number of files " + std::to_string(file_names.size()));
}
for(auto& str : file_names) {
str = data_dir + str;
}
load(file_names[0], file_names[1], file_names[2], m_first_n);
size_t num_samples = get_num_samples();
if (m_first_n > 0) {
num_samples = (static_cast<size_t>(m_first_n) <= num_samples)?
static_cast<size_t>(m_first_n) : num_samples;
m_first_n = num_samples;
set_use_percent(1.0);
set_absolute_sample_count(0u);
}
// reset indices
m_shuffled_indices.clear();
m_shuffled_indices.resize(num_samples);
std::iota(m_shuffled_indices.begin(), m_shuffled_indices.end(), 0);
select_subset_of_data();
}
void data_reader_jag::load(const std::string image_file,
const std::string scalar_file,
const std::string input_file,
const size_t first_n) {
if ((m_independent.empty() || (m_independent[0] == Undefined)) &&
!m_dependent.empty() && (m_dependent[0] == Undefined)) {
throw lbann_exception("data_reader_jag: no type of variables to load is defined.");
}
if (is_used(JAG_Image) && !image_file.empty() && !check_if_file_exists(image_file)) {
throw lbann_exception("data_reader_jag: failed to load " + image_file);
}
if (is_used(JAG_Scalar) && !scalar_file.empty() && !check_if_file_exists(scalar_file)) {
throw lbann_exception("data_reader_jag: failed to load " + scalar_file);
}
if (is_used(JAG_Input) && !input_file.empty() && !check_if_file_exists(input_file)) {
throw lbann_exception("data_reader_jag: failed to load " + input_file);
}
m_num_samples = 0u;
// read in only those that will be used
if (is_used(JAG_Image) && !image_file.empty()) {
m_images = cnpy::npy_load(image_file);
if (first_n > 0u) { // to use only first_n samples
cnpy_utils::shrink_to_fit(m_images, first_n);
}
m_image_loaded = true;
set_linearized_image_size();
}
if (is_used(JAG_Scalar) && !scalar_file.empty()) {
m_scalars = cnpy::npy_load(scalar_file);
if (first_n > 0u) { // to use only first_n samples
cnpy_utils::shrink_to_fit(m_scalars, first_n);
}
m_scalar_loaded = true;
set_linearized_scalar_size();
}
if (is_used(JAG_Input) && !input_file.empty()) {
m_inputs = cnpy::npy_load(input_file);
if (first_n > 0u) { // to use only first_n samples
cnpy_utils::shrink_to_fit(m_inputs, first_n);
}
m_input_loaded = true;
set_linearized_input_size();
}
size_t num_samples = 0u;
bool ok = check_data(num_samples);
if (!ok) {
get_description();
throw lbann_exception("data_reader_jag: loaded data format not consistent");
}
m_num_samples = num_samples;
if (m_image_loaded) {
m_img_min = get_image_min();
m_img_max = get_image_max();
if (m_img_min == m_img_max) {
throw lbann_exception("data_reader_jag: no_variation in data");
}
normalize_image();
}
}
bool data_reader_jag::check_data(size_t& num_samples) const {
bool ok = true;
num_samples = 0u;
if (ok && m_image_loaded) {
ok = (m_linearized_image_size > 0u) && (m_images.word_size == sizeof(data_t));
if (!ok) {
std::cerr << "m_images.shape.size() = " << m_images.shape.size() << std::endl
<< "m_linearized_image_size = " << m_linearized_image_size << std::endl
<< "m_images.word_size = " << m_images.word_size << std::endl
<< "sizeof(data_t) = " << sizeof(data_t) << std::endl;
return false;
}
num_samples = m_images.shape[0];
}
if (ok && m_scalar_loaded) {
ok = (m_linearized_scalar_size > 0u) && (m_scalars.word_size == sizeof(scalar_t));
if (!ok) {
std::cerr << "m_scalars.shape.size() = " << m_scalars.shape.size() << std::endl
<< "m_linearized_scalar_size = " << m_linearized_scalar_size << std::endl
<< "m_scalars.word_size = " << m_scalars.word_size << std::endl
<< "sizeof(scalar_t) = " << sizeof(scalar_t) << std::endl;
return false;
}
if (num_samples > 0u) {
ok = ok && (num_samples == m_scalars.shape[0]);
} else {
num_samples = m_scalars.shape[0];
}
}
if (ok && m_input_loaded) {
ok = (m_linearized_input_size > 0u) && (m_inputs.word_size == sizeof(input_t));
if (!ok) {
std::cerr << "m_inputs.shape.size() = " << m_inputs.shape.size() << std::endl
<< "m_linearized_input_size = " << m_linearized_input_size << std::endl
<< "m_inputs.word_size = " << m_inputs.word_size << std::endl
<< "sizeof(input_t) = " << sizeof(input_t) << std::endl;
return false;
}
if (num_samples > 0u) {
ok = ok && (num_samples == m_inputs.shape[0]);
} else {
num_samples = m_inputs.shape[0];
}
}
if (!ok) {
num_samples = 0u;
} else {
if (is_used(JAG_Image)) {
ok = ok && m_image_loaded;
}
if (is_used(JAG_Scalar)) {
ok = ok && m_scalar_loaded;
}
if (is_used(JAG_Input)) {
ok = ok && m_input_loaded;
}
}
return ok;
}
std::string data_reader_jag::get_description() const {
using std::string;
using std::to_string;
string ret = string("data_reader_jag:\n")
+ " - images: " + cnpy_utils::show_shape(m_images) + "\n"
+ " - scalars: " + cnpy_utils::show_shape(m_scalars) + "\n"
+ " - inputs: " + cnpy_utils::show_shape(m_inputs) + "\n";
if (m_image_loaded) {
ret += " - min pixel value: " + to_string(m_img_min) + "\n"
+ " - max pixel value: " + to_string(m_img_max) + "\n"
+ " - image width " + to_string(m_image_width) + "\n"
+ " - image height " + to_string(m_image_height) + "\n"
+ " - image normalization: " + to_string(m_image_normalization) + "\n";
}
return ret;
}
void data_reader_jag::normalize_image() {
if (!m_image_loaded) {
return;
}
const int type_code = CV_MAKETYPE(cv::DataType<data_t>::depth, 1u);
if (m_image_normalization == 1) {
data_t* const ptr = get_image_ptr(0);
// Present the entire image data as a single image
// and normalize it once and for all
cv::Mat img(m_num_samples, m_linearized_image_size,
type_code, reinterpret_cast<void*>(ptr));
cv::normalize(img, img, 0.0, 1.0, cv::NORM_MINMAX);
} else if (m_image_normalization == 2) {
// normalize each image independently
for (size_t i=0u; i < m_num_samples; ++i) {
data_t* const ptr = get_image_ptr(i);
cv::Mat img(1, m_linearized_image_size,
type_code, reinterpret_cast<void*>(ptr));
cv::normalize(img, img, 0.0, 1.0, cv::NORM_MINMAX);
}
} else if (m_image_normalization != 0) {
throw lbann_exception("data_reader_jag: invalid normalization mode " +
std::to_string(m_image_normalization));
}
}
data_reader_jag::data_t* data_reader_jag::get_image_ptr(const size_t i) const {
return (m_image_loaded? cnpy_utils::data_ptr<data_t>(m_images, {i}) : nullptr);
}
data_reader_jag::data_t data_reader_jag::get_image_max() const {
if (!m_image_loaded) {
return std::numeric_limits<data_t>::min();
}
const data_t* ptr = get_image_ptr(0);
const size_t tot_num_pixels = m_images.shape[0]*m_linearized_image_size;
return *std::max_element(ptr, ptr + tot_num_pixels);
}
data_reader_jag::data_t data_reader_jag::get_image_min() const {
if (!m_image_loaded) {
return std::numeric_limits<data_t>::max();
}
const data_t* ptr = get_image_ptr(0);
const size_t tot_num_pixels = m_images.shape[0]*m_linearized_image_size;
return *std::min_element(ptr, ptr + tot_num_pixels);
}
data_reader_jag::scalar_t* data_reader_jag::get_scalar_ptr(const size_t i) const {
return (m_scalar_loaded? cnpy_utils::data_ptr<scalar_t>(m_scalars, {i}) : nullptr);
}
std::vector<DataType> data_reader_jag::get_scalar(const size_t i) const {
const scalar_t* const ptr = get_scalar_ptr(i);
if (ptr == nullptr) {
return {};
}
std::vector<DataType> ret(m_linearized_scalar_size);
for (size_t j = 0u; j < m_linearized_scalar_size; ++j) {
ret[j] = static_cast<DataType>(ptr[j]);
}
return ret;
}
data_reader_jag::input_t* data_reader_jag::get_input_ptr(const size_t i) const {
return (m_input_loaded? cnpy_utils::data_ptr<input_t>(m_inputs, {i}) : nullptr);
}
std::vector<DataType> data_reader_jag::get_input(const size_t i) const {
const input_t* const ptr = get_input_ptr(i);
if (ptr == nullptr) {
return {};
}
std::vector<DataType> ret(m_linearized_input_size);
for (size_t j = 0u; j < m_linearized_input_size; ++j) {
ret[j] = static_cast<DataType>(ptr[j]);
}
return ret;
}
std::vector<CPUMat>
data_reader_jag::create_datum_views(CPUMat& X, const std::vector<size_t>& sizes, const int mb_idx) const {
std::vector<CPUMat> X_v(sizes.size());
El::Int h = 0;
for(size_t i=0u; i < sizes.size(); ++i) {
const El::Int h_end = h + static_cast<El::Int>(sizes[i]);
El::View(X_v[i], X, El::IR(h, h_end), El::IR(mb_idx, mb_idx + 1));
h = h_end;
}
return X_v;
}
bool data_reader_jag::fetch(CPUMat& X, int data_id, int mb_idx,
const data_reader_jag::variable_t vt, const std::string tag) {
switch (vt) {
case JAG_Image: {
const data_t* ptr = get_image_ptr(data_id);
set_minibatch_item<data_t>(X, mb_idx, ptr, m_linearized_image_size);
break;
}
case JAG_Scalar: {
const scalar_t* ptr = get_scalar_ptr(data_id);
set_minibatch_item<scalar_t>(X, mb_idx, ptr, m_linearized_scalar_size);
break;
}
case JAG_Input: {
const input_t* ptr = get_input_ptr(data_id);
set_minibatch_item<input_t>(X, mb_idx, ptr, m_linearized_input_size);
break;
}
default: { // includes Undefined case
throw lbann_exception(std::string("data_reader_jag::fetch_") + tag +
"() : unknown or undefined variable type (" +
std::to_string(static_cast<int>(vt)) + ')');
}
}
return true;
}
bool data_reader_jag::fetch_datum(CPUMat& X, int data_id, int mb_idx) {
std::vector<size_t> sizes = get_linearized_data_sizes();
std::vector<CPUMat> X_v = create_datum_views(X, sizes, mb_idx);
bool ok = true;
for(size_t i = 0u; ok && (i < X_v.size()); ++i) {
ok = fetch(X_v[i], data_id, 0, m_independent[i], "datum");
}
return ok;
}
bool data_reader_jag::fetch_response(CPUMat& X, int data_id, int mb_idx) {
std::vector<size_t> sizes = get_linearized_response_sizes();
std::vector<CPUMat> X_v = create_datum_views(X, sizes, mb_idx);
bool ok = true;
for(size_t i = 0u; ok && (i < X_v.size()); ++i) {
ok = fetch(X_v[i], data_id, 0, m_dependent[i], "response");
}
return ok;
}
bool data_reader_jag::fetch_label(CPUMat& Y, int data_id, int mb_idx) {
if(m_gan_label_value) Y.Set(m_gan_label_value,mb_idx,1); //fake sample is set to 1; adversarial model
else { //fake sample (second half of minibatch is set to 0;discriminator model
//mb_idx < (m_mb_size/2) ? Y.Set(1,mb_idx,1) : Y.Set(m_gan_label_value,mb_idx,1);
mb_idx < (get_current_mini_batch_size()/2) ? Y.Set(1,mb_idx,1) : Y.Set(m_gan_label_value,mb_idx,1);
}
//Y.Set(m_gan_label_value, mb_idx, 1);
return true;
}
} // end of namespace lbann
| 32.88354 | 106 | 0.65727 | forsyth2 |
d1d3766a022f7d18781d9b3036b3993f6c158480 | 966 | cpp | C++ | HPC2/Parralel_bubblesort.cpp | vaibhav-k3/HPC-Assignments | bac3c3f9db813853bab0532c9a9689471c684653 | [
"MIT"
] | 1 | 2020-01-11T17:48:03.000Z | 2020-01-11T17:48:03.000Z | HPC2/Parralel_bubblesort.cpp | Gr3yH4t-H4cK3r/HPC-Assignments | bac3c3f9db813853bab0532c9a9689471c684653 | [
"MIT"
] | null | null | null | HPC2/Parralel_bubblesort.cpp | Gr3yH4t-H4cK3r/HPC-Assignments | bac3c3f9db813853bab0532c9a9689471c684653 | [
"MIT"
] | null | null | null | #include<iostream>
#include<omp.h>
#include<stdlib.h>
#define MAX 50
using namespace std ;
void disp( int* a )
{
for(int i = 0 ; i < MAX ; i++)
{
cout<<a[i]<<" " ;
}
cout<<"\n";
}
void bubblesort( int* a)
{ int temp = 0;
for(int i = 0 ; i < MAX ; i++)
{
for(int j = 0 ; j < MAX -1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j+1] ;
a[j+1] = a[j];
a[j] = temp ;
}
}
}
}
void oddeven_bubblesort(int* a)
{
for(int i = 0 ; i < MAX ; i++)
{
//odd phase
//#pragma omp parallel for
for(int j = 1 ; j < MAX-1 ; j+=2)
{
if(a[j] > a[j+1])
{
swap(a[j] , a[j+1]);
}
}
//even phase
//#pragma omp parallel for
for(int k = 0 ; k < MAX -1 ; k+=2)
{
if(a[k] > a[k+1])
{
swap(a[k] , a[k+1]);
}
}
}
}
int main()
{
int a[50];
for(int i = 0 ; i < MAX ; i++)
{
a[i] = rand()%1000;
}
cout<<" before sorting "<<endl;
disp(a);
oddeven_bubblesort(a);
cout<<"after sorting " <<endl;
disp(a);
}
| 14 | 36 | 0.461698 | vaibhav-k3 |
d1d75874a0bbff96ad77d0a05e702f314095a72d | 482 | cpp | C++ | c/include_guard.cpp | bheckel/code | 98309e8aa145901e49460546643c911eaaff54e6 | [
"Apache-2.0"
] | 1 | 2019-08-11T00:39:34.000Z | 2019-08-11T00:39:34.000Z | c/include_guard.cpp | bheckel/code | 98309e8aa145901e49460546643c911eaaff54e6 | [
"Apache-2.0"
] | null | null | null | c/include_guard.cpp | bheckel/code | 98309e8aa145901e49460546643c911eaaff54e6 | [
"Apache-2.0"
] | 1 | 2020-07-28T05:58:47.000Z | 2020-07-28T05:58:47.000Z | //////////////////////////////////////////////////////////////////////////////
// Name: include_guard.cpp
//
// Summary: Simple inclusion guard header that prevents re-definition
//
// Adapted: Wed 17 Oct 2001 10:24:57 (Bob Heckel -- Thinking in C++)
//////////////////////////////////////////////////////////////////////////////
#ifndef SIMPLE_H
#define SIMPLE_H
struct Simple {
int i,j,k;
initialize() { i = j = k = 0; }
};
#endif // SIMPLE_H
// ...foo...
| 28.352941 | 78 | 0.410788 | bheckel |
d1d954e5d399c4b7106942fb58fed05c74063373 | 4,330 | cpp | C++ | KeepCryingEngine/json_serializer.cpp | KeepCryingEngine/KeepCryingEngine | c2e3f89eb5c3d70916f97b7a04cfbab033553b04 | [
"MIT"
] | 1 | 2018-01-11T20:05:29.000Z | 2018-01-11T20:05:29.000Z | KeepCryingEngine/json_serializer.cpp | KeepCryingEngine/KeepCryingEngine | c2e3f89eb5c3d70916f97b7a04cfbab033553b04 | [
"MIT"
] | 28 | 2018-01-17T21:04:33.000Z | 2018-03-02T13:26:17.000Z | KeepCryingEngine/json_serializer.cpp | PereViader/KeepCryingEngine | c2e3f89eb5c3d70916f97b7a04cfbab033553b04 | [
"MIT"
] | 1 | 2020-01-12T02:28:04.000Z | 2020-01-12T02:28:04.000Z | #include "json_serializer.h"
using nlohmann::json;
using namespace std;
void to_json(nlohmann::json & j, const float2 & v)
{
j = json{ { "x", v.x },{ "y", v.y } };
}
void from_json(const nlohmann::json & j, float2 & v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
}
void to_json(json& j, const float3& v)
{
j = json{ { "x", v.x },{ "y", v.y },{ "z", v.z } };
}
void from_json(const json& j, float3& v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
v.z = j.at("z").get<float>();
}
void to_json(nlohmann::json& j, const float4& v)
{
j = json{ { "x", v.x },{ "y", v.y },{ "z", v.z },{ "w", v.w } };
}
void from_json(const nlohmann::json& j, float4& v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
v.z = j.at("z").get<float>();
v.w = j.at("w").get<float>();
}
void to_json(nlohmann::json& j, const Quat& v)
{
j = json{ { "x", v.x },{ "y", v.y },{ "z", v.z },{ "w", v.w } };
}
void from_json(const nlohmann::json& j, Quat& v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
v.z = j.at("z").get<float>();
v.w = j.at("w").get<float>();
}
void to_json(nlohmann::json& j, const Frustum& v)
{
nlohmann::json jsonPos;
to_json(jsonPos, v.pos);
nlohmann::json jsonUp;
to_json(jsonUp, v.up);
nlohmann::json jsonFront;
to_json(jsonFront, v.front);
j = json
{
{ "pos", jsonPos },
{ "type", v.type },
{ "up", jsonUp },
{ "front", jsonFront },
{ "verticalFov", v.verticalFov },
{ "horizontalFov", v.horizontalFov },
{ "farPlaneDistance", v.farPlaneDistance },
{ "nearPlaneDistance", v.nearPlaneDistance },
{ "orthographicWidth", v.orthographicWidth },
{ "orthographicHeight", v.orthographicHeight }
};
}
void from_json(const nlohmann::json& j, Frustum& v)
{
float3 pos;
from_json(j["pos"], pos);
float3 up;
from_json(j["up"], up);
float3 front;
from_json(j["front"], front);
v.pos = pos;
v.type = j["type"];
v.up = up;
v.front = front;
v.verticalFov = j["verticalFov"];
v.horizontalFov = j["horizontalFov"];
v.farPlaneDistance = j["farPlaneDistance"];
v.nearPlaneDistance = j["nearPlaneDistance"];
v.orthographicWidth = j["orthographicWidth"];
v.orthographicHeight = j["orthographicHeight"];
}
void to_json(nlohmann::json& j, const BASS_DX8_I3DL2REVERB& v)
{
j = json
{
{ "lRoom", v.lRoom },
{ "flRoomRolloffFactor", v.flRoomRolloffFactor },
{ "flDecayTime", v.flDecayTime },
{ "flDecayHFRatio", v.flDecayHFRatio },
{ "lReflections", v.lReflections },
{ "flReflectionsDelay", v.flReflectionsDelay },
{ "lReverb", v.lReverb },
{ "flReverbDelay", v.flReverbDelay },
{ "flDiffusion", v.flDiffusion },
{ "flDensity", v.flDensity },
{ "flHFReference", v.flHFReference }
};
}
void from_json(const nlohmann::json& j, BASS_DX8_I3DL2REVERB& v)
{
v.lRoom = j["lRoom"];
v.flRoomRolloffFactor = j["flRoomRolloffFactor"];
v.flDecayTime = j["flDecayTime"];
v.flDecayHFRatio = j["flDecayHFRatio"];
v.lReflections = j["lReflections"];
v.flReflectionsDelay = j["flReflectionsDelay"];
v.lReverb = j["lReverb"];
v.flReverbDelay = j["flReverbDelay"];
v.flDiffusion = j["flDiffusion"];
v.flDensity = j["flDensity"];
v.flHFReference = j["flHFReference"];
}
void to_json(nlohmann::json & j, const ENGINE_UUID & v)
{
j["id"] = v.id;
}
void from_json(const nlohmann::json & j, ENGINE_UUID & v)
{
v.id = j["id"];
}
void to_json(nlohmann::json & j, const TextureConfiguration & v)
{
j["anisotropicFilter"] = v.anisotropicFilter;
j["magFilterMode"] = v.magFilterMode;
j["minFilterMode"] = v.minFilterMode;
j["mipMap"] = v.mipMap;
j["textureType"] = v.textureType;
j["wrapModeS"] = v.wrapModeS;
j["wrapModeT"] = v.wrapModeT;
}
void from_json(const nlohmann::json & j, TextureConfiguration & v)
{
v.anisotropicFilter = j["anisotropicFilter"];
v.magFilterMode = j["magFilterMode"];
v.minFilterMode = j["minFilterMode"];
v.mipMap = j["mipMap"];
v.textureType = j["textureType"];
v.wrapModeS = j["wrapModeS"];
v.wrapModeT = j["wrapModeT"];
}
void to_json(nlohmann::json & j, const AudioClipIdentifier & v)
{
j["path"] = v.path.string();
j["audioType"] = v.audioType;
j["channelType"] = v.channelType;
}
void from_json(const nlohmann::json & j, AudioClipIdentifier & v)
{
v.path = j["path"].get<string>();
v.audioType = j["audioType"];
v.channelType = j["channelType"];
}
| 23.661202 | 66 | 0.631871 | KeepCryingEngine |
d1d9b8abca81320a7b03a1829f1f27462fe73566 | 13,654 | cpp | C++ | src/solver/conv_ocl_dir2D_bwdWrW_53.cpp | sabreshao/MIOpen | d0ae7a67430e77e30ab10066ff079327e53e1349 | [
"MIT"
] | null | null | null | src/solver/conv_ocl_dir2D_bwdWrW_53.cpp | sabreshao/MIOpen | d0ae7a67430e77e30ab10066ff079327e53e1349 | [
"MIT"
] | null | null | null | src/solver/conv_ocl_dir2D_bwdWrW_53.cpp | sabreshao/MIOpen | d0ae7a67430e77e30ab10066ff079327e53e1349 | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* 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 "miopen/solver.hpp"
#include <miopen/env.hpp>
MIOPEN_DECLARE_ENV_VAR(MIOPEN_WORKAROUND_ISSUE_1007)
namespace miopen {
namespace solver {
bool ConvOclBwdWrW53::IsApplicable(const ConvolutionContext& params) const
{
// Cases when dy has negative padding are not supported (issue 918)
if(params.GetBackwardPad0() < 0 || params.GetBackwardPad1() < 0)
return false;
/// \todo Workaround for issue 1007, seems related to the next ones.
if(!miopen::IsDisabled(MIOPEN_WORKAROUND_ISSUE_1007{}) && params.kernel_size0 == 3 &&
(static_cast<double>(params.batch_sz) * params.out_height * params.out_width *
params.n_outputs * params.n_inputs) > 700000000)
return false;
/// \todo Workaround for some issues. Excludes some configs which covered by
/// the ConvOclBwdWrW2 solver. Found experimentally. Technically, this is a hack.
/// The kernel needs to be well understood and fixed.
if((params.kernel_size0 > 5) || (params.kernel_size0 == 5 && params.in_width >= 64))
return false;
/// \todo Workaround for issue #791. Found experimentally. Technically, this is a hack.
/// The kernel needs to be well understood and fixed.
if((params.kernel_size0 == 3 && params.pad0 == 0 && params.out_width >= 32))
return false;
return ((params.kernel_size0 >= 2 || params.kernel_size1 >= 2) &&
(params.kernel_stride1 == 1 && params.kernel_stride0 == 1));
}
ConvSolution ConvOclBwdWrW53::GetSolution(const ConvolutionContext& params) const
{
ConvSolution result;
size_t localMemSize = 64 * 1024;
const auto hw_wave_sz = 64;
const auto dev_local_mem_sz = localMemSize; // in bytes
// major parameters
// inpout are outputs
int wei_cstride = params.kernel_size0 * params.kernel_size1;
int wei_bstride = params.n_outputs * wei_cstride;
// number of batch iterations
result.n_stacks = 1;
result.n_stacks = std::min(params.batch_sz, result.n_stacks);
// defines how to proceed : 1 grouop per batch or with a loop over all batches
// loop over al batches make sense in 2 cases: a lot of small inputs/outputs or few batches
// param
int N_BATCH_LOOPS = (params.n_inputs * params.n_outputs <= 8 * 1024)
? 1
: (params.batch_sz <= 16 || params.in_width <= 32)
? (params.batch_sz / result.n_stacks)
: 4;
int n_batch_blks =
(params.batch_sz + N_BATCH_LOOPS * result.n_stacks - 1) / (N_BATCH_LOOPS * result.n_stacks);
result.out_pix_tile0 = params.kernel_size0;
result.out_pix_tile1 = params.kernel_size1;
result.in_tile1 = 1;
// span size
// param
result.in_tile0 = (params.in_width % 4 == 0) ? 4 : (params.in_width % 3 == 0)
? 3
: (params.in_width % 2 == 0) ? 2 : 1;
int n_spans = (params.in_width + result.in_tile0 - 1) / result.in_tile0;
// n of wavefronts per group
// param
int n_waves = ((result.out_pix_tile0 * result.out_pix_tile1) <= 16 && (params.in_width > 8))
? 4
: (params.in_width <= 16) ? 1 : 2;
int GRP_SZ = hw_wave_sz * n_waves;
result.n_out_pix_tiles = 1;
int n_out_stacks = std::min(params.n_inputs, std::max(1, GRP_SZ / n_spans));
// number of input maps per group
result.n_in_data_tiles =
(params.in_width <= 32 && (result.out_pix_tile0 * result.out_pix_tile1) <= 16) ? 4 : 1;
result.n_in_data_tiles = std::min(result.n_in_data_tiles, params.n_outputs);
static const int read_unit =
(params.out_width % 4 == 0) ? 4 : (params.out_width % 3 == 0)
? 3
: (params.out_width % 2 == 0) ? 2 : 1;
static const std::string READ_TYPE =
(read_unit == 1) ? "_FLOAT" : "_FLOAT" + std::to_string((read_unit));
// calculate number of input scans in the input block
// max LDS size is 8K
int in_lcl_width =
((params.in_width + read_unit - 1) / read_unit) * read_unit + 2 * params.pad0;
// number of input map blocks being process at once
// param
int in_n_vert_reads = (params.out_height > 32 && params.out_width <= 64 &&
(result.out_pix_tile0 * result.out_pix_tile1) <= 16)
? (params.out_height + 1) / 2
: params.out_height;
while(in_lcl_width * in_n_vert_reads * result.n_in_data_tiles >
(dev_local_mem_sz / (2 * ((params.in_data_type == "FP32") ? 4 : 2))))
{
in_n_vert_reads = (in_n_vert_reads + 1) / 2;
if(in_n_vert_reads < 2 && result.n_in_data_tiles >= 2)
{
in_n_vert_reads = params.in_height;
result.n_in_data_tiles /= 2;
}
else if(in_n_vert_reads < 2)
{
MIOPEN_LOG_E("Not enough local memory to run direct algorithm");
return ConvSolution(miopenStatusUnknownError);
}
}
int in_n_vert_read_loops = (params.in_height + in_n_vert_reads - 1) / in_n_vert_reads;
int ALIGNED_OUT_SCAN_LN = ((params.in_width + read_unit - 1) / read_unit); // image aligned scan
// select output mapping
int total_out_maps = result.n_out_pix_tiles * n_out_stacks;
total_out_maps = (total_out_maps > params.n_inputs) ? params.n_inputs : total_out_maps;
result.grp_tile0 = GRP_SZ;
result.grp_tile1 = 1;
int grp_tile2 = 1;
// utility parameters
int n_ut_waves = 4;
int UT_GRP_SZ0 = hw_wave_sz * n_ut_waves;
int ut_read_unit =
((wei_cstride / 4) * 4 == wei_cstride) ? 4 : ((wei_cstride / 2) * 2 == wei_cstride) ? 2 : 1;
std::string UT_READ_TYPE =
(ut_read_unit == 1) ? "_FLOAT" : "_FLOAT" + std::to_string((ut_read_unit));
if(!params.direction.IsBackwardWrW())
MIOPEN_THROW("!params.direction.IsBackwardWrW()");
// it's backward - inputs are outputs and vs versa
const auto comp_options =
std::string(" -DMLO_DIR_FORWARD=0") + std::string(" -DMLO_GRP_SZ=") +
std::to_string(GRP_SZ) + std::string(" -DMLO_GRP_SZ0=") + std::to_string(result.grp_tile0) +
std::string(" -DMLO_GRP_SZ1=") + std::to_string(result.grp_tile1) +
std::string(" -DMLO_GRP_SZ2=") + std::to_string(grp_tile2) +
std::string(" -DMLO_FILTER_SIZE0=") + std::to_string(params.kernel_size0) +
std::string(" -DMLO_FILTER_SIZE1=") + std::to_string(params.kernel_size1) +
std::string(" -DMLO_FILTER_PAD0=") + std::to_string(params.pad0) +
std::string(" -DMLO_FILTER_PAD1=") + std::to_string(params.pad1) +
std::string(" -DMLO_FILTER_STRIDE0=") + std::to_string(params.kernel_stride0) +
std::string(" -DMLO_FILTER_STRIDE1=") + std::to_string(params.kernel_stride1) +
std::string(" -DSTRIDE_W=") + std::to_string(params.kernel_stride0) +
std::string(" -DSTRIDE_H=") + std::to_string(params.kernel_stride1) +
std::string(" -DMLO_N_OUTPUTS=") + std::to_string(params.n_inputs) +
std::string(" -DMLO_N_INPUTS=") + std::to_string(params.n_outputs) +
std::string(" -DMLO_BATCH_SZ=") + std::to_string(params.batch_sz) +
std::string(" -DMLO_N_BATCH_LOOPS=") + std::to_string(N_BATCH_LOOPS) +
std::string(" -DMLO_OUT_BATCH_STRIDE=") + std::to_string(params.in_batch_stride) +
std::string(" -DMLO_OUT_CHANNEL_STRIDE=") + std::to_string(params.in_channel_stride) +
std::string(" -DMLO_OUT_STRIDE=") + std::to_string(params.in_stride) +
std::string(" -DMLO_IN_BATCH_STRIDE=") + std::to_string(params.out_batch_stride) +
std::string(" -DMLO_IN_CHANNEL_STRIDE=") + std::to_string(params.out_channel_stride) +
std::string(" -DMLO_IN_STRIDE=") + std::to_string(params.out_stride) +
std::string(" -DMLO_WEI_BATCH_STRIDE=") + std::to_string(wei_bstride) +
std::string(" -DMLO_WEI_CHANNEL_STRIDE=") + std::to_string(wei_cstride) +
std::string(" -DMLO_IN_WIDTH=") + std::to_string(params.out_width) +
std::string(" -DMLO_IN_HEIGHT=") + std::to_string(params.out_height) +
std::string(" -DMLO_OUT_WIDTH=") + std::to_string(params.in_width) +
std::string(" -DMLO_OUT_HEIGHT=") + std::to_string(params.in_height) +
std::string(" -DMLO_IN_TILE1=") + std::to_string(result.in_tile1) +
std::string(" -DMLO_IN_TILE0=") + std::to_string(result.in_tile0) +
std::string(" -DMLO_N_LCL_BATCHS=") +
std::to_string(result.n_stacks) // # of diff stacks (part of batch).
+ std::string(" -DMLO_N_LCL_OUT_MAPS=") +
std::to_string(result.n_out_pix_tiles) // # output pixel tiles per wk-item (ALU)
+ std::string(" -DMLO_N_LCL_IN_MAPS=") +
std::to_string(result.n_in_data_tiles) // total # of blocks of different inputs in LDS
+ std::string(" -DMLO_OUT_TILE0=") +
std::to_string(result.out_pix_tile0) // size of ouptput tile per wk-item (ALU)
+ std::string(" -DMLO_OUT_TILE1=") + std::to_string(result.out_pix_tile1) //
+ std::string(" -DMLO_OUT_STACKS=") + std::to_string(n_out_stacks) +
std::string(" -DMLO_N_WAVES=") + std::to_string(n_waves) +
std::string(" -DMLO_READ_TYPE=") + READ_TYPE + std::string(" -DMLO_READ_UNIT=") +
std::to_string(read_unit) + std::string(" -DMLO_ALIGNED_OUT_SCAN_LN=") +
std::to_string(ALIGNED_OUT_SCAN_LN) // image aligned scan
+ std::string(" -DMLO_HW_WAVE_SZ=") + std::to_string(hw_wave_sz) +
std::string(" -DMLO_LG2_PHYS_WAVE_SZ=") + std::to_string(mloLg2(hw_wave_sz)) +
std::string(" -DMLO_IN_EXTENT1=") + std::to_string(in_n_vert_reads) +
std::string(" -DMLO_IN_N_VERT_LOOPS=") + std::to_string(in_n_vert_read_loops)
+ std::string(" -DMLO_CONV_BIAS=") + std::to_string(params.bias)
+ std::string(" -DMLO_UT_READ_TYPE=") + UT_READ_TYPE + std::string(" -DMLO_UT_READ_UNIT=") +
std::to_string(ut_read_unit)
+ std::string(" -DMLO_UT_GRP_SZ0=") + std::to_string(UT_GRP_SZ0)
// + std::string(" -limit-vector-registers=64 ")
+ params.general_compile_options;
// wrt to W
{
KernelInfo kernel;
kernel.l_wk.push_back(result.grp_tile0);
kernel.l_wk.push_back(result.grp_tile1);
kernel.l_wk.push_back(grp_tile2);
// input is output
size_t gbl_wk0 =
GRP_SZ * ((params.n_outputs + result.n_in_data_tiles - 1) / result.n_in_data_tiles);
size_t gbl_wk1 = ((params.n_inputs + total_out_maps - 1) / total_out_maps);
size_t gbl_wk2 = n_batch_blks;
kernel.g_wk.push_back(gbl_wk0);
kernel.g_wk.push_back(gbl_wk1);
kernel.g_wk.push_back(gbl_wk2);
kernel.kernel_file =
(params.kernel_size0 == 5 && params.kernel_size1 == 5 && in_n_vert_read_loops == 1)
? "MIOpenConvBwdWrW_LxG_5x5.cl"
: "MIOpenConvBwdWrW_LxG_P53.cl";
kernel.kernel_name = "MIOpenCvBwdWrW";
kernel.comp_options = comp_options;
result.construction_params.push_back(kernel);
result.workspce_sz = 0;
}
// sum over batch
if(n_batch_blks > 1)
{
KernelInfo kernel;
kernel.kernel_file =
(params.kernel_size0 == 5 && params.kernel_size1 == 5 && in_n_vert_read_loops == 1)
? "MIOpenConvBwdWrW_LxG_5x5.cl"
: "MIOpenConvBwdWrW_LxG_P53.cl";
kernel.kernel_name = "MIOpenCvBwdWrW_rdc";
kernel.comp_options = comp_options;
kernel.l_wk.push_back(UT_GRP_SZ0);
kernel.l_wk.push_back(1);
kernel.l_wk.push_back(1);
int gbl_ut_wk0 = wei_bstride * params.n_inputs / ut_read_unit;
kernel.g_wk.push_back(gbl_ut_wk0);
kernel.g_wk.push_back(1);
kernel.g_wk.push_back(1);
int data_len = (params.out_data_type == "FP32" ? 4 : 8);
result.construction_params.push_back(kernel);
result.workspce_sz = wei_bstride * params.n_inputs * n_batch_blks * data_len;
}
return result;
}
} // namespace solver
} // namespace miopen
| 47.245675 | 100 | 0.625238 | sabreshao |
d1da05ee7e084297f3097ff61f2628df6ff5b06e | 9,616 | cpp | C++ | WebKit/Source/WebCore/storage/SQLTransactionSync.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/WebCore/storage/SQLTransactionSync.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/WebCore/storage/SQLTransactionSync.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "SQLTransactionSync.h"
#if ENABLE(SQL_DATABASE)
#include "DatabaseAuthorizer.h"
#include "DatabaseSync.h"
#include "PlatformString.h"
#include "SQLException.h"
#include "SQLResultSet.h"
#include "SQLStatementSync.h"
#include "SQLTransactionClient.h"
#include "SQLTransactionSyncCallback.h"
#include "SQLValue.h"
#include "SQLiteTransaction.h"
#include "ScriptExecutionContext.h"
#include <wtf/PassRefPtr.h>
#include <wtf/RefPtr.h>
namespace WebCore {
PassRefPtr<SQLTransactionSync> SQLTransactionSync::create(DatabaseSync* db, PassRefPtr<SQLTransactionSyncCallback> callback, bool readOnly)
{
return adoptRef(new SQLTransactionSync(db, callback, readOnly));
}
SQLTransactionSync::SQLTransactionSync(DatabaseSync* db, PassRefPtr<SQLTransactionSyncCallback> callback, bool readOnly)
: m_database(db)
, m_callback(callback)
, m_readOnly(readOnly)
, m_hasVersionMismatch(false)
, m_modifiedDatabase(false)
, m_transactionClient(adoptPtr(new SQLTransactionClient()))
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
}
SQLTransactionSync::~SQLTransactionSync()
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
if (m_sqliteTransaction && m_sqliteTransaction->inProgress())
rollback();
}
PassRefPtr<SQLResultSet> SQLTransactionSync::executeSQL(const String& sqlStatement, const Vector<SQLValue>& arguments, ExceptionCode& ec)
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
m_database->setLastErrorMessage("");
if (!m_database->opened()) {
m_database->setLastErrorMessage("cannot executeSQL because the database is not open");
ec = SQLException::UNKNOWN_ERR;
return 0;
}
if (m_hasVersionMismatch) {
m_database->setLastErrorMessage("cannot executeSQL because there is a version mismatch");
ec = SQLException::VERSION_ERR;
return 0;
}
if (sqlStatement.isEmpty())
return 0;
int permissions = DatabaseAuthorizer::ReadWriteMask;
if (!m_database->scriptExecutionContext()->allowDatabaseAccess())
permissions |= DatabaseAuthorizer::NoAccessMask;
else if (m_readOnly)
permissions |= DatabaseAuthorizer::ReadOnlyMask;
SQLStatementSync statement(sqlStatement, arguments, permissions);
m_database->resetAuthorizer();
bool retryStatement = true;
RefPtr<SQLResultSet> resultSet;
while (retryStatement) {
retryStatement = false;
resultSet = statement.execute(m_database.get(), ec);
if (!resultSet) {
if (m_sqliteTransaction->wasRolledBackBySqlite())
return 0;
if (ec == SQLException::QUOTA_ERR) {
if (m_transactionClient->didExceedQuota(database())) {
ec = 0;
retryStatement = true;
} else {
m_database->setLastErrorMessage("there was not enough remaining storage space");
return 0;
}
}
}
}
if (m_database->lastActionChangedDatabase()) {
m_modifiedDatabase = true;
m_transactionClient->didExecuteStatement(database());
}
return resultSet.release();
}
ExceptionCode SQLTransactionSync::begin()
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
if (!m_database->opened()) {
m_database->reportStartTransactionResult(1, SQLException::UNKNOWN_ERR, 0);
m_database->setLastErrorMessage("cannot begin transaction because the database is not open");
return SQLException::UNKNOWN_ERR;
}
ASSERT(!m_database->sqliteDatabase().transactionInProgress());
// Set the maximum usage for this transaction if this transactions is not read-only.
if (!m_readOnly)
m_database->sqliteDatabase().setMaximumSize(m_database->maximumSize());
ASSERT(!m_sqliteTransaction);
m_sqliteTransaction = adoptPtr(new SQLiteTransaction(m_database->sqliteDatabase(), m_readOnly));
m_database->resetDeletes();
m_database->disableAuthorizer();
m_sqliteTransaction->begin();
m_database->enableAuthorizer();
// Check if begin() succeeded.
if (!m_sqliteTransaction->inProgress()) {
ASSERT(!m_database->sqliteDatabase().transactionInProgress());
m_database->reportStartTransactionResult(2, SQLException::DATABASE_ERR, m_database->sqliteDatabase().lastError());
m_database->setLastErrorMessage("unable to begin transaction",
m_database->sqliteDatabase().lastError(), m_database->sqliteDatabase().lastErrorMsg());
m_sqliteTransaction.clear();
return SQLException::DATABASE_ERR;
}
// Note: We intentionally retrieve the actual version even with an empty expected version.
// In multi-process browsers, we take this opportinutiy to update the cached value for
// the actual version. In single-process browsers, this is just a map lookup.
String actualVersion;
if (!m_database->getActualVersionForTransaction(actualVersion)) {
m_database->reportStartTransactionResult(3, SQLException::DATABASE_ERR, m_database->sqliteDatabase().lastError());
m_database->setLastErrorMessage("unable to read version",
m_database->sqliteDatabase().lastError(), m_database->sqliteDatabase().lastErrorMsg());
rollback();
return SQLException::DATABASE_ERR;
}
m_hasVersionMismatch = !m_database->expectedVersion().isEmpty()
&& (m_database->expectedVersion() != actualVersion);
m_database->reportStartTransactionResult(0, -1, 0); // OK
return 0;
}
ExceptionCode SQLTransactionSync::execute()
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
if (!m_database->opened() || (m_callback && !m_callback->handleEvent(this))) {
if (m_database->lastErrorMessage().isEmpty())
m_database->setLastErrorMessage("failed to execute transaction callback");
m_callback = 0;
return SQLException::UNKNOWN_ERR;
}
m_callback = 0;
return 0;
}
ExceptionCode SQLTransactionSync::commit()
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
if (!m_database->opened()) {
m_database->reportCommitTransactionResult(1, SQLException::UNKNOWN_ERR, 0);
m_database->setLastErrorMessage("unable to commit transaction because the database is not open.");
return SQLException::UNKNOWN_ERR;
}
ASSERT(m_sqliteTransaction);
m_database->disableAuthorizer();
m_sqliteTransaction->commit();
m_database->enableAuthorizer();
// If the commit failed, the transaction will still be marked as "in progress"
if (m_sqliteTransaction->inProgress()) {
m_database->reportCommitTransactionResult(2, SQLException::DATABASE_ERR, m_database->sqliteDatabase().lastError());
m_database->setLastErrorMessage("unable to commit transaction",
m_database->sqliteDatabase().lastError(), m_database->sqliteDatabase().lastErrorMsg());
return SQLException::DATABASE_ERR;
}
m_sqliteTransaction.clear();
// Vacuum the database if anything was deleted.
if (m_database->hadDeletes())
m_database->incrementalVacuumIfNeeded();
// The commit was successful. If the transaction modified this database, notify the delegates.
if (m_modifiedDatabase)
m_transactionClient->didCommitWriteTransaction(database());
m_database->reportCommitTransactionResult(0, -1, 0); // OK
return 0;
}
void SQLTransactionSync::rollback()
{
ASSERT(m_database->scriptExecutionContext()->isContextThread());
m_database->disableAuthorizer();
if (m_sqliteTransaction) {
m_sqliteTransaction->rollback();
m_sqliteTransaction.clear();
}
m_database->enableAuthorizer();
ASSERT(!m_database->sqliteDatabase().transactionInProgress());
}
} // namespace WebCore
#endif // ENABLE(SQL_DATABASE)
| 38.310757 | 139 | 0.706323 | JavaScriptTesting |
d1dda8f4e8bc51f6221a6e325d70ddc354df2279 | 416 | cpp | C++ | serialisation/src/SampleEnvironmentEventDouble.cpp | ess-dmsc/NeXus-Streamer | daa222dceb11974a05a5ef3c0ee8a0697f340335 | [
"BSD-2-Clause"
] | null | null | null | serialisation/src/SampleEnvironmentEventDouble.cpp | ess-dmsc/NeXus-Streamer | daa222dceb11974a05a5ef3c0ee8a0697f340335 | [
"BSD-2-Clause"
] | 100 | 2018-04-11T16:45:19.000Z | 2021-05-05T07:35:55.000Z | serialisation/src/SampleEnvironmentEventDouble.cpp | ess-dmsc/NeXus-Streamer | daa222dceb11974a05a5ef3c0ee8a0697f340335 | [
"BSD-2-Clause"
] | null | null | null | #include "SampleEnvironmentEventDouble.h"
flatbuffers::Offset<LogData> SampleEnvironmentEventDouble::getSEEvent(
flatbuffers::FlatBufferBuilder &builder) {
auto nameOffset = builder.CreateString(m_name);
auto valueOffset = CreateDouble(builder, m_value);
auto timestamp = getTimestamp();
return CreateLogData(builder, nameOffset, Value::Double, valueOffset.Union(),
timestamp);
}
| 37.818182 | 79 | 0.745192 | ess-dmsc |
d1de3c9d15e584f0c2aaab8cbe10cb7f0c9eb496 | 536 | cpp | C++ | filip/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | filip/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | filip/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int a, b, tmpmod, tmpnum = 0;
cin >> a >> b;
for(int i = 0; i < 3; i++){
tmpmod = a%10;
a/=10;
tmpnum += tmpmod;
if(i < 2){
tmpnum*=10;}}
a = tmpnum; tmpnum = 0;
for(int i = 0; i < 3; i++){
tmpmod = b%10;
b/=10;
tmpnum += tmpmod;
if(i < 2){
tmpnum*=10;}}
b = tmpnum;
if(b>a){
cout << b << endl;
} else{
cout << a << endl;
}
return 0;
} | 18.482759 | 33 | 0.391791 | KalawelaLo |
d1e2c89b22dcdf969880423e8b18d25890fc146f | 7,454 | cpp | C++ | samples/Hello/third-party/fuzzylite/fuzzylite/src/term/Aggregated.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | samples/Hello/third-party/fuzzylite/fuzzylite/src/term/Aggregated.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | samples/Hello/third-party/fuzzylite/fuzzylite/src/term/Aggregated.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | /*
fuzzylite (R), a fuzzy logic control library in C++.
Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved.
Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com>
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the FuzzyLite License included with the software.
You should have received a copy of the FuzzyLite License along with
fuzzylite. If not, see <http://www.fuzzylite.com/license/>.
fuzzylite is a registered trademark of FuzzyLite Limited.
*/
#include "fl/term/Aggregated.h"
#include "fl/imex/FllExporter.h"
#include "fl/norm/s/Maximum.h"
namespace fl {
Aggregated::Aggregated(const std::string& name, scalar minimum, scalar maximum,
SNorm* aggregation)
: Term(name), _minimum(minimum), _maximum(maximum), _aggregation(aggregation) { }
Aggregated::Aggregated(const Aggregated& other) : Term(other) {
copyFrom(other);
}
Aggregated& Aggregated::operator=(const Aggregated& other) {
if (this != &other) {
clear();
_aggregation.reset(fl::null);
Term::operator=(other);
copyFrom(other);
}
return *this;
}
Aggregated::~Aggregated() { }
void Aggregated::copyFrom(const Aggregated& source) {
_minimum = source._minimum;
_maximum = source._maximum;
if (source._aggregation.get())
_aggregation.reset(source._aggregation->clone());
for (std::size_t i = 0; i < source._terms.size(); ++i) {
_terms.push_back(source._terms.at(i));
}
}
std::string Aggregated::className() const {
return "Aggregated";
}
Complexity Aggregated::complexity() const {
return complexityOfMembership();
}
Complexity Aggregated::complexityOfMembership() const {
Complexity result;
result.comparison(3);
if (_aggregation.get()) {
result += _aggregation->complexity().multiply(scalar(_terms.size()));
}
for (std::size_t i = 0; i < _terms.size(); ++i) {
result += _terms.at(i).complexity();
}
return result;
}
scalar Aggregated::membership(scalar x) const {
if (Op::isNaN(x)) return fl::nan;
if (not (_terms.empty() or _aggregation.get())) { //Exception for IntegralDefuzzifiers
throw Exception("[aggregation error] "
"aggregation operator needed to aggregate variable "
"<" + getName() + ">", FL_AT);
}
scalar mu = 0.0;
for (std::size_t i = 0; i < _terms.size(); ++i) {
mu = _aggregation->compute(mu, _terms.at(i).membership(x));
}
return mu;
}
Complexity Aggregated::complexityOfActivationDegree() const {
Complexity result;
result.comparison(2);
if (_aggregation.get()) {
result += _aggregation->complexity();
} else result.arithmetic(1);
result.multiply(scalar(_terms.size()));
return result;
}
scalar Aggregated::activationDegree(const Term* forTerm) const {
scalar result = 0.0;
for (std::size_t i = 0; i < _terms.size(); ++i) {
const Activated& activatedTerm = _terms.at(i);
if (activatedTerm.getTerm() == forTerm) {
if (_aggregation.get())
result = _aggregation->compute(result, activatedTerm.getDegree());
else
result += activatedTerm.getDegree(); //Default for WeightDefuzzifier
}
}
return result;
}
const Activated* Aggregated::highestActivatedTerm() const {
const Activated* maximumTerm = fl::null;
scalar maximumActivation = -fl::inf;
for (std::size_t i = 0; i < _terms.size(); ++i) {
const Activated& activated = _terms.at(i);
if (Op::isGt(activated.getDegree(), maximumActivation)) {
maximumActivation = activated.getDegree();
maximumTerm = &activated;
}
}
return maximumTerm;
}
std::string Aggregated::parameters() const {
FllExporter exporter;
std::ostringstream ss;
ss << exporter.toString(getAggregation());
ss << " " << Op::str(getMinimum()) << " " << Op::str(getMaximum()) << " ";
for (std::size_t i = 0; i < terms().size(); ++i) {
ss << " " << exporter.toString(&terms().at(i));
}
return ss.str();
}
void Aggregated::configure(const std::string& parameters) {
FL_IUNUSED(parameters);
}
Aggregated* Aggregated::clone() const {
return new Aggregated(*this);
}
std::string Aggregated::toString() const {
std::vector<std::string> aggregate;
for (std::size_t i = 0; i < terms().size(); ++i) {
aggregate.push_back(terms().at(i).toString());
}
FllExporter exporter;
std::ostringstream ss;
if (getAggregation()) {
ss << getName() << ": " << className() << " "
<< exporter.toString(getAggregation()) << "["
<< Op::join(aggregate, ",") << "]";
} else {
ss << getName() << ": " << className() << " " << "["
<< Op::join(aggregate, "+") << "]"; //\u2295: (+)
}
return ss.str();
}
void Aggregated::setMinimum(scalar minimum) {
this->_minimum = minimum;
}
scalar Aggregated::getMinimum() const {
return this->_minimum;
}
void Aggregated::setMaximum(scalar maximum) {
this->_maximum = maximum;
}
scalar Aggregated::getMaximum() const {
return this->_maximum;
}
void Aggregated::setRange(scalar minimum, scalar maximum) {
setMinimum(minimum);
setMaximum(maximum);
}
scalar Aggregated::range() const {
return getMaximum() - getMinimum();
}
void Aggregated::setAggregation(SNorm* aggregation) {
this->_aggregation.reset(aggregation);
}
SNorm* Aggregated::getAggregation() const {
return this->_aggregation.get();
}
/**
* Operations for std::vector _terms
*/
void Aggregated::addTerm(const Term* term, scalar degree, const TNorm* implication) {
_terms.push_back(Activated(term, degree, implication));
FL_DBG("Aggregating " << _terms.back().toString());
}
void Aggregated::addTerm(const Activated& term) {
_terms.push_back(term);
FL_DBG("Aggregating " << _terms.back().toString());
}
const Activated& Aggregated::removeTerm(std::size_t index) {
const Activated& term = _terms.at(index);
_terms.erase(_terms.begin() + index);
return term;
}
void Aggregated::clear() {
_terms.clear();
}
const Activated& Aggregated::getTerm(std::size_t index) const {
return _terms.at(index);
}
void Aggregated::setTerms(const std::vector<Activated>& terms) {
this->_terms = terms;
}
const std::vector<Activated>& Aggregated::terms() const {
return this->_terms;
}
std::vector<Activated>& Aggregated::terms() {
return this->_terms;
}
std::size_t Aggregated::numberOfTerms() const {
return _terms.size();
}
bool Aggregated::isEmpty() const {
return _terms.empty();
}
}
| 30.056452 | 94 | 0.57553 | okocsis |
d1e3f64fb002a9e33d28d841de937e2f73e025ad | 6,317 | cpp | C++ | src/dialog.cpp | nekoshota/teippi_PronogoMod | 590b59384118b4dc99800260356accf9d484eb63 | [
"MIT"
] | null | null | null | src/dialog.cpp | nekoshota/teippi_PronogoMod | 590b59384118b4dc99800260356accf9d484eb63 | [
"MIT"
] | null | null | null | src/dialog.cpp | nekoshota/teippi_PronogoMod | 590b59384118b4dc99800260356accf9d484eb63 | [
"MIT"
] | null | null | null | #include "dialog.h"
#include "offsets.h"
#include "unit.h"
#include "patchmanager.h"
#include "strings.h"
#include <stdio.h>
#include <vector>
Unit *ui_transported_units[8] = {0, 0, 0, 0, 0, 0, 0, 0};
void TransportStatus_UpdateDrawnValues()
{
Unit *transport = *bw::primary_selected;
int i = 0;
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded, i++)
{
ui_transported_units[i] = unit;
bw::ui_transported_unit_hps[i] = unit->hitpoints;
}
*bw::redraw_transport_ui = Ui_NeedsRedraw_Unk(); // ???
*bw::ui_hitpoints = transport->hitpoints;
*bw::ui_shields = transport->shields >> 8;
*bw::ui_energy = transport->energy;
}
int TransportStatus_DoesNeedRedraw()
{
Unit *transport = *bw::primary_selected;
if (*bw::redraw_transport_ui)
return true;
if (!*bw::is_replay && transport->player != *bw::local_player_id)
return GenericStatus_DoesNeedRedraw();
int i = 0;
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded, i++)
{
if (ui_transported_units[i] != unit)
return true;
if (bw::ui_transported_unit_hps[i] != unit->hitpoints)
return true;
}
return GenericStatus_DoesNeedRedraw();
}
void DrawStatusScreen_LoadedUnits()
{
REG_EAX(Dialog *, dlg);
Unit *transport = *bw::primary_selected;
Control *first_button = dlg->FindChild(StatusScreen::TransportLargeUnit);
Control *large_unit_button, *medium_unit_button, *small_unit_button;
int remaining_space = units_dat_space_provided[transport->unit_id];
if (remaining_space < 8)
{
large_unit_button = dlg->FindChild(StatusScreen::TransportLargeUnit4, first_button);
medium_unit_button = dlg->FindChild(StatusScreen::TransportMediumUnit4, large_unit_button);
small_unit_button = dlg->FindChild(StatusScreen::TransportSmallUnit4, medium_unit_button);
}
else
{
remaining_space = 8;
large_unit_button = first_button;
medium_unit_button = dlg->FindChild(StatusScreen::TransportMediumUnit, large_unit_button);
small_unit_button = dlg->FindChild(StatusScreen::TransportSmallUnit, medium_unit_button);
}
for (Control *ctrl = first_button; ctrl->id != StatusScreen::TransportSmallUnit + 8; ctrl = ctrl->next)
{
ctrl->val = 0;
}
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded)
{
int space = units_dat_space_required[unit->unit_id];
remaining_space -= space;
if (remaining_space < 0)
break;
Control *current_button;
switch (space)
{
case 1:
current_button = small_unit_button;
small_unit_button = small_unit_button->next;
break;
case 2:
current_button = medium_unit_button;
medium_unit_button = medium_unit_button->next;
small_unit_button = small_unit_button->next->next;
break;
case 4:
current_button = large_unit_button;
large_unit_button = large_unit_button->next;
medium_unit_button = medium_unit_button->next->next;
small_unit_button = small_unit_button->next->next->next->next;
break;
default:
current_button = 0;
break;
}
current_button->val = unit;
int border_id;
if (unit->flags & UnitStatus::Hallucination)
border_id = StatusScreen::SmallUnitBorderHallucination + ((space >> 1) * 2);
else if (units_dat_flags[unit->unit_id] & UnitFlags::Hero)
border_id = StatusScreen::SmallUnitBorderHero + ((space >> 1) * 2);
else if (unit->parasites)
border_id = StatusScreen::SmallUnitBorderParasite + ((space >> 1) * 2);
else
border_id = StatusScreen::SmallUnitBorder + ((space >> 1) * 2);
current_button->button_icon = border_id;
current_button->Show();
current_button->MarkDirty();
}
for (Control *ctrl = first_button; ctrl->id != StatusScreen::TransportSmallUnit + 8; ctrl = ctrl->next)
{
if (!ctrl->val)
ctrl->Hide();
}
}
static char ss_kills[0x20];
void StatusScreen_DrawKills()
{
REG_EBX(Dialog *, dlg);
Unit *unit = *bw::primary_selected;
int unit_id = unit->unit_id;
if (unit_id == Unit::Scourge || unit_id == Unit::InfestedTerran || unit->IsKnownHallucination() || (!unit->HasWayOfAttacking() && !unit->kills))
{
dlg->FindChild(StatusScreen::Kills)->Hide();
}
else
{
snprintf(ss_kills, sizeof ss_kills, "%s %d", (*bw::stat_txt_tbl)->GetTblString(String::Kills), unit->kills);
SetLabel(dlg, ss_kills, StatusScreen::Kills);
}
}
void Control::MarkDirty()
{
if (~flags & 0x1)
{
flags |= 0x1;
MarkControlDirty(this);
}
}
void Control::Show()
{
if (flags & 0x8)
return;
flags |= 0x8;
Event event;
event.ext_type = 0xd;
event.type = 0xe;
event.x = *bw::mouse_clickpos_x;
event.y = *bw::mouse_clickpos_y;
event.unk4 = 0;
if ((*EventHandler)(this, &event))
MarkDirty();
}
void Control::Hide()
{
if (~flags & 0x8)
return;
Event event;
event.ext_type = 0xe;
event.type = 0xe;
event.x = *bw::mouse_clickpos_x;
event.y = *bw::mouse_clickpos_y;
event.unk4 = 0;
if ((*EventHandler)(this, &event))
{
event.ext_type = 0x6;
(*EventHandler)(this, &event);
MarkDirty();
}
}
Control *Control::FindChild(int id, Control *search_beg) const
{
if (type == 0)
{
Dialog *dlg = (Dialog *)this;
return dlg->FindChild(id, search_beg);
}
else
return parent->FindChild(id, search_beg);
}
Control *Dialog::FindChild(int id, Control *search_beg) const
{
if (search_beg)
{
for (Control *ctrl = search_beg; ctrl; ctrl = ctrl->next)
{
if (ctrl->id == id)
return ctrl;
}
}
else
{
for (Control *ctrl = dialog.first_child; ctrl; ctrl = ctrl->next)
{
if (ctrl->id == id)
return ctrl;
}
}
return 0;
}
| 29.110599 | 148 | 0.602026 | nekoshota |
d1e4e0970858615269cefb0c00b85547e910b601 | 14,905 | cpp | C++ | src/ui/src/setup/simtab.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/ui/src/setup/simtab.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/ui/src/setup/simtab.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | #include "falclib.h"
#include "chandler.h"
#include "userids.h"
#include "PlayerOp.h"
#include "sim/include/stdhdr.h"
#include "ui_setup.h"
#include "f4find.h"
//define presets for skill level list box (first set is ace, then veteran, etc...)
Preset Presets[] =
{
{FMAccurate, ATRealisticAV, WEAccurate, APNormal, ARRealistic, PDRealistic, 0},
{FMAccurate, ATRealistic, WEAccurate, APNormal, ARModerated, PDRealistic, SIM_UNLIMITED_CHAFF},
{FMAccurate, ATSimplified, WEEnhanced, APEnhanced, ARModerated, PDEnhanced, SIM_NO_BLACKOUT bitor SIM_UNLIMITED_CHAFF bitor SIM_NAMETAGS},
{FMSimplified, ATEasy, WEExaggerated, APEnhanced, ARSimplistic, PDEnhanced, SIM_NO_BLACKOUT bitor SIM_UNLIMITED_CHAFF bitor SIM_NAMETAGS bitor SIM_UNLIMITED_FUEL}, //need to put SIM_UNLIMITED_FUEL
{FMSimplified, ATEasy, WEExaggerated, APIntelligent, ARSimplistic, PDEnhanced, SIM_NO_BLACKOUT bitor SIM_UNLIMITED_AMMO bitor SIM_UNLIMITED_CHAFF bitor SIM_NAMETAGS bitor SIM_UNLIMITED_FUEL bitor SIM_NO_COLLISIONS},
//{FMSimplified,ATEasy,WEExaggerated,APIntelligent,ARSimplistic, PDSuper,SIM_NO_BLACKOUT|SIM_UNLIMITED_AMMO|SIM_UNLIMITED_CHAFF|SIM_NAMETAGS|SIM_UNLIMITED_FUEL|SIM_NO_COLLISIONS}, //back into these two after DEMO
};
extern C_Handler *gMainHandler;
/////////////
// Sim Tab
/////////////
int GetRealism(C_Window *win)
{
C_ListBox *listbox;
C_Button *button;
int realism = 100, maxrealism = 100;
if (win == NULL)
return 0;
listbox = (C_ListBox *)win->FindControl(SET_FLTMOD);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_RADAR);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_WEAPEFF);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_AUTOPILOT);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_PADLOCK);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_REFUELING);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_FUEL);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_CHAFFLARES);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_COLLISIONS);
if (button not_eq NULL)
{
if (button->GetState())
{
// Cobra - 03-08-05 Temp disabled due to unknown cause mid-air collisions
// realism -= button->GetUserNumber(0);
// if(maxrealism > button->GetUserNumber(1))
// maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_BLACKOUT);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_IDTAGS);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_WEATHER);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_BULLSEYE_CALLS);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_INVULNERABILITY);
if (button not_eq NULL)
{
if (button->GetState())
{
//realism = 0;
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
//realism *= 0.5f;
}
}
if (realism > maxrealism)
realism = maxrealism ;
if (realism < 0)
realism = 0;
return realism;
}//GetRealism
int SetRealism(C_Window *win)
{
C_Button *button;
C_EditBox *ebox;
C_ListBox *listbox;
int realism = 100, maxrealism = 100;
if (win == NULL)
return 0;
realism = GetRealism(win);
ebox = (C_EditBox *)win->FindControl(REALISM_READOUT);
if (ebox not_eq NULL)
{
if (realism > maxrealism)
realism = maxrealism ;
if (realism < 0)
realism = 0;
ebox->SetInteger(realism);
}
listbox = (C_ListBox *)win->FindControl(SET_SKILL);
if (listbox)
{
listbox->SetValue(RECRUIT_LEVEL);
for (int i = 0; i < NUM_LEVELS; i++)
{
button = (C_Button *)listbox->GetItem(ACE_LEVEL + i);
if (button)
{
if (realism > button->GetUserNumber(0))
{
listbox->SetValue(ACE_LEVEL + i);
break;
}
}
}
}
win->RefreshWindow();
return realism;
}//SetRealism
void SimControlCB(long, short hittype, C_Base *control)
{
if ((hittype not_eq C_TYPE_LMOUSEUP) and (hittype not_eq C_TYPE_SELECT))
return;
SetRealism(control->Parent_);
}
void SetSkillCB(long, short hittype, C_Base *control)
{
if (hittype not_eq C_TYPE_SELECT)
return;
int Index;
C_Button *button;
C_Window *win;
C_ListBox *lbox;
win = (C_Window *)control->Parent_;
Index = ((C_ListBox *)control)->GetTextID() - ACE_LEVEL;
lbox = (C_ListBox *)win->FindControl(SET_FLTMOD);
if (lbox not_eq NULL)
{
if (Presets[Index].FlightModel == FMAccurate)
lbox->SetValue(SET_FLTMOD_1);
else
lbox->SetValue(SET_FLTMOD_2);
}
lbox = (C_ListBox *)win->FindControl(SET_RADAR);
if (lbox not_eq NULL)
{
switch (Presets[Index].RadarMode)
{
// M.N. full realism mode added
case ATRealisticAV:
lbox->SetValue(SET_RADAR_0);
break;
case ATRealistic:
lbox->SetValue(SET_RADAR_1);
break;
case ATSimplified:
lbox->SetValue(SET_RADAR_2);
break;
case ATEasy:
lbox->SetValue(SET_RADAR_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_WEAPEFF);
if (lbox not_eq NULL)
{
switch (Presets[Index].WeapEffects)
{
case WEAccurate:
lbox->SetValue(SET_WEAPEFF_1);
break;
case WEEnhanced:
lbox->SetValue(SET_WEAPEFF_2);
break;
case WEExaggerated:
lbox->SetValue(SET_WEAPEFF_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_AUTOPILOT);
if (lbox not_eq NULL)
{
switch (Presets[Index].Autopilot)
{
case APNormal:
lbox->SetValue(SET_AUTO_1);
break;
case APEnhanced:
lbox->SetValue(SET_AUTO_2);
break;
case APIntelligent:
lbox->SetValue(SET_AUTO_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_REFUELING);
if (lbox not_eq NULL)
{
switch (Presets[Index].RefuelingMode)
{
case ARRealistic:
lbox->SetValue(SET_REFUEL_1);
break;
case ARModerated:
lbox->SetValue(SET_REFUEL_2);
break;
case ARSimplistic:
lbox->SetValue(SET_REFUEL_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_PADLOCK);
if (lbox not_eq NULL)
{
switch (Presets[Index].PadlockMode)
{
case PDDisabled:
lbox->SetValue(SET_PADLOCK_4);
break;
case PDRealistic:
lbox->SetValue(SET_PADLOCK_1);
break;
case PDEnhanced:
lbox->SetValue(SET_PADLOCK_2);
break;
//case PDSuper:
// lbox->SetValue(SET_PADLOCK_3);
// break;
}
}
button = (C_Button *)win->FindControl(SET_ORDNANCE);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_UNLIMITED_AMMO)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_FUEL);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_UNLIMITED_FUEL)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_CHAFFLARES);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_UNLIMITED_CHAFF)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_COLLISIONS);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_NO_COLLISIONS)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_BLACKOUT);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_NO_BLACKOUT)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_IDTAGS);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_NAMETAGS)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_INVULNERABILITY); //should be SET_INVULNERABLITY
if (button not_eq NULL)
{
button->SetState(C_STATE_0);
button->Refresh();
}
SetRealism(win);
}//SetSkillCB
/*****************************************************************************/
// Retro 25Dec2003
//
// Callback for the radiosubtitle button. Constructs/Destroys the radiolabel
// object. This object is already constructed at startup when the corresponding
// playeroptions variable (subTitles) is set to true.
/*****************************************************************************/
#include "RadioSubTitle.h"
extern int g_nSubTitleTTL;
extern int g_nNumberOfSubTitles;
extern char g_strRadioflightCol[0x40]; // Retro 27Dec2003
extern char g_strRadiotoPackageCol[0x40]; // Retro 27Dec2003
extern char g_strRadioToFromPackageCol[0x40]; // Retro 27Dec2003
extern char g_strRadioTeamCol[0x40]; // Retro 27Dec2003
extern char g_strRadioProximityCol[0x40]; // Retro 27Dec2003
extern char g_strRadioWorldCol[0x40]; // Retro 27Dec2003
extern char g_strRadioTowerCol[0x40]; // Retro 27Dec2003
extern char g_strRadioStandardCol[0x40]; // Retro 27Dec2003
void SubTitleCB(long ID, short hittype, C_Base *control)
{
if (hittype not_eq C_TYPE_LMOUSEUP)
return;
if ((PlayerOptions.getSubtitles() == false) and ( not radioLabel)) // need to create a new object..
{
try
{
radioLabel = new RadioSubTitle(g_nNumberOfSubTitles, g_nSubTitleTTL);
radioLabel->SetChannelColours(g_strRadioflightCol, g_strRadiotoPackageCol, g_strRadioToFromPackageCol,
g_strRadioTeamCol, g_strRadioProximityCol, g_strRadioWorldCol,
g_strRadioTowerCol, g_strRadioStandardCol);
PlayerOptions.SetSubtitles(true);
control->SetState(C_STATE_1);
}
catch (RadioSubTitle::Init_Error)
{
delete(radioLabel);
radioLabel = 0;
PlayerOptions.SetSubtitles(false);
control->SetState(C_STATE_0);
};
}
else // need to delete the object..
{
delete(radioLabel);
radioLabel = 0;
PlayerOptions.SetSubtitles(false);
control->SetState(C_STATE_0);
}
}
// Retro 25Dec2003 ends..
| 25.478632 | 219 | 0.563033 | Terebinth |
d1e81c5d78f2dbf62a8d342b7ac492d9baeb9c1d | 743 | cc | C++ | examples/csv_example.cc | KaiminLai/tiny-machine-learning-system | e29625dfb513032b40712663b63f874e2ae6f924 | [
"MIT"
] | 1 | 2019-01-09T16:03:50.000Z | 2019-01-09T16:03:50.000Z | examples/csv_example.cc | KaiminLai/tiny-machine-learning-system | e29625dfb513032b40712663b63f874e2ae6f924 | [
"MIT"
] | null | null | null | examples/csv_example.cc | KaiminLai/tiny-machine-learning-system | e29625dfb513032b40712663b63f874e2ae6f924 | [
"MIT"
] | null | null | null | #include<iostream>
#include "../src/csv.h"
using namespace std;
using namespace Eigen;
using namespace csv;
int main(){
CSVReader csv("a.csv");
cout<<"rows:"<<csv.rows()<<endl;
cout<<"columns:"<<csv.cols()<<endl;
cout<<"size:"<<csv.size()[0]<<"*"<<csv.size()[1]<<endl;
cout<<"element mat(0,1):"<<csv.get_element(0,1)<<endl;
VectorXd r1 = csv.get_row(1);
VectorXd c1 = csv.get_col(1);
MatrixXd mat = csv.get_mat();
cout<<"row1:\n";
cout<<r1[0]<<" "<<r1[1]<<" "<<r1[2]<<endl;
cout<<"column1:\n";
cout<<c1[0]<<" "<<c1[1]<<endl;
cout<<"mat(0,0):"<<mat(0,0)<<endl;
CSVWriter csv1(mat);
csv1.write("b.csv");
CSVWriter csv2(c1);
csv2.write("c.csv");
CSVWriter csv3(r1);
csv3.write("d.csv");
return 0;
} | 26.535714 | 57 | 0.585464 | KaiminLai |
d1e83f652bf4efb0799fea2bcb282f8a1785db7b | 1,065 | cpp | C++ | tests/memPSGRand_bug57/src_pers/PersTest00_src.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | tests/memPSGRand_bug57/src_pers/PersTest00_src.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | tests/memPSGRand_bug57/src_pers/PersTest00_src.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | #include "Ht.h"
#include "PersTest00.h"
void CPersTest00::PersTest00() {
if (PR2_htValid) {
switch (PR2_htInst) {
case TEST00_ENTRY: {
HtContinue(TEST00_WR);
break;
}
case TEST00_WR: {
GW2_test00_0_src_u0_data[0][1].write_addr(10, 3);
GW2_test00_0_src_u0_data[0][1].test00_0_src_v4_data = ((int32_t)0x001fe79ea30a33c0LL);
HtContinue(TEST00_ST0);
break;
}
case TEST00_ST0: {
if (WriteMemBusy()) {
HtRetry();
break;
}
WriteMem_test00_0_src_v4_data(PR2_memAddr + 0, 10, 3, 0, 1, 1);
WriteMemPause(TEST00_LD0);
break;
}
case TEST00_LD0: {
if (ReadMemBusy()) {
HtRetry();
break;
}
ReadMem_test00_0_dst_v0_data(PR2_memAddr + 0);
ReadMemPause(TEST00_CHK);
break;
}
case TEST00_CHK: {
if ((int32_t)SR_test00_0_dst_v0_data != ((int32_t)0x001fe79ea30a33c0LL)) {
HtAssert(0, 0);
}
HtContinue(TEST00_RTN);
break;
}
case TEST00_RTN: {
if (SendReturnBusy_test00()) {
HtRetry();
break;
}
SendReturn_test00();
break;
}
default:
assert(0);
}
}
}
| 19.363636 | 89 | 0.644131 | TonyBrewer |
d1ec155f32cfc05fb1942da2297411ad0d977f28 | 9,744 | cpp | C++ | oop/cards.cpp | mdatsev/elsys_homeworks | 11c170ae215c6d731092d6147331837a3f306134 | [
"Unlicense"
] | null | null | null | oop/cards.cpp | mdatsev/elsys_homeworks | 11c170ae215c6d731092d6147331837a3f306134 | [
"Unlicense"
] | 45 | 2020-02-25T23:36:11.000Z | 2022-03-30T23:19:18.000Z | oop/cards.cpp | mdatsev/elsys_homeworks | 11c170ae215c6d731092d6147331837a3f306134 | [
"Unlicense"
] | null | null | null | #include <deque>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <unordered_map>
#include <functional>
#include <exception>
#include <unordered_set>
template <class C, class T>
inline int findIn(const C &container, const T &value)
{
auto found = std::find(container.begin(), container.end(), value);
return found != container.end()
? std::distance(container.begin(), found)
: -1;
}
class CardGameError : public std::logic_error
{
public:
CardGameError(const std::string string)
: logic_error(string) {}
};
class Card
{
public:
Card(std::string suit, std::string rank)
: suit_(suit), rank_(rank) {}
std::string get_rank() const
{
return rank_;
}
std::string get_suit() const
{
return suit_;
}
bool operator==(const Card &other) const
{
return rank_ == other.rank_ &&
suit_ == other.suit_;
}
friend std::ostream &operator<<(std::ostream &stream, const Card &card)
{
stream << card.suit_ << card.rank_;
return stream;
}
class CardComparator
{
public:
CardComparator(const std::vector<std::string> &rank_order, const std::vector<std::string> &suit_order)
: rank_order_(rank_order), suit_order_(suit_order) {}
bool operator()(const Card &a, const Card &b)
{
auto aSuitPos = findIn(suit_order_, a.suit_);
auto bSuitPos = findIn(suit_order_, b.suit_);
auto aRankPos = findIn(rank_order_, a.rank_);
auto bRankPos = findIn(rank_order_, b.rank_);
return aSuitPos != bSuitPos
? aSuitPos > bSuitPos
: aRankPos > bRankPos;
}
private:
const std::vector<std::string> rank_order_;
const std::vector<std::string> suit_order_;
};
private:
std::string rank_;
std::string suit_;
};
class Deck
{
public:
size_t size() const
{
return cards_.size();
}
void print_size() const
{
std::cout << size();
}
void draw_top_card()
{
print_top_card();
cards_.pop_front();
}
void draw_bottom_card()
{
print_bottom_card();
cards_.pop_back();
}
void print_top_card() const
{
std::cout << cards_.front();
}
void print_bottom_card() const
{
std::cout << cards_.back();
}
void shuffle()
{
std::random_shuffle(cards_.begin(), cards_.end());
std::cout << *this;
}
void sort(const std::vector<std::string> &rank_order, const std::vector<std::string> &suit_order)
{
std::sort(cards_.begin(), cards_.end(), Card::CardComparator(rank_order, suit_order));
std::cout << *this;
}
void deal(int count)
{
if (cards_.size() < count)
throw CardGameError("ERROR: Not enough cards in deck");
for (int i = 0; i < count; i++)
{
draw_top_card();
std::cout << " ";
}
}
void insert_valid_cards(const Deck &deck, const std::vector<std::string> &allowed_ranks, const std::vector<std::string> &allowed_suits)
{
std::copy_if(deck.cards_.begin(), deck.cards_.end(),
std::back_inserter(cards_),
[&](const Card &card) {
return findIn(allowed_ranks, card.get_rank()) != -1 &&
findIn(allowed_suits, card.get_suit()) != -1;
});
}
friend std::istream &operator>>(std::istream &stream, Deck &deck)
{
std::string line;
std::getline(stream, line);
std::istringstream cards_stream(line);
std::string card_string;
for (int i = 0; std::getline(cards_stream, card_string, ' '); i++)
{
std::string suit(1, card_string[0]);
std::string rank = card_string.substr(1);
deck.cards_.emplace_back(suit, rank);
}
return stream;
}
friend std::ostream &operator<<(std::ostream &stream, const Deck &deck)
{
for (int i = 0; i < deck.cards_.size(); i++)
{
stream << deck.cards_[i] << " ";
}
return stream;
}
private:
std::deque<Card> cards_;
};
class CardGame
{
public:
CardGame(const std::string &name,
const Deck &deck,
unsigned int deck_size,
unsigned int cards_per_hand,
const std::vector<std::string> &rank_order,
const std::vector<std::string> &suit_order = {"C", "D", "H", "S"})
: name_(name), deck_size_(deck_size), cards_per_hand_(cards_per_hand), rank_order_(rank_order), suit_order_(suit_order)
{
if (deck.size() < deck_size)
throw CardGameError("ERROR: Not enough cards for " + name_);
deck_.insert_valid_cards(deck, rank_order, suit_order);
}
CardGame()
: deck_size_(0), cards_per_hand_(0)
{
}
virtual void print_deck_size()
{
deck_.print_size();
}
virtual void draw_top_card()
{
deck_.draw_top_card();
}
virtual void draw_bottom_card()
{
deck_.draw_bottom_card();
}
virtual void print_top_card()
{
deck_.print_top_card();
}
virtual void print_bottom_card()
{
deck_.print_bottom_card();
}
virtual void shuffle_deck()
{
deck_.shuffle();
}
virtual void sort_deck()
{
deck_.sort(rank_order_, suit_order_);
}
virtual void deal()
{
deck_.deal(cards_per_hand_);
}
private:
const std::string name_;
Deck deck_;
const std::vector<std::string> rank_order_;
const std::vector<std::string> suit_order_;
const unsigned int deck_size_;
const unsigned int cards_per_hand_;
};
class CardGameEngine
{
public:
CardGameEngine() : game_(nullptr) {}
~CardGameEngine() { delete game_; }
CardGameEngine &run()
{
setEngineCommands();
keepRunning = true;
std::cout << "> ";
std::cin >> initialDeck_;
for (std::string command; keepRunning;)
{
std::cout << "> ";
std::cin >> command;
try
{
if (engine_commands_.find(command) != engine_commands_.end())
engine_commands_.at(command)();
else if (game_commands_.find(command) != game_commands_.end())
{
if (game_ == nullptr)
throw CardGameError("ERROR: No deck");
game_commands_.at(command)(game_);
}
else
throw CardGameError("ERROR: Unknown operation");
if (findIn(output_commands_, command) != -1)
std::cout << std::endl;
}
catch (CardGameError e)
{
std::cout << e.what() << std::endl;
}
}
return *this;
}
CardGameEngine &stop()
{
quit();
return *this;
}
template <typename Game>
CardGameEngine &addGame(std::string command)
{
auto a = std::bind(&CardGameEngine::setGame<Game>, this);
engine_commands_[command] = a;
return *this;
}
template <typename Game>
CardGameEngine &addCommand(std::string command, void (Game::*function)(), bool has_output = true)
{
game_commands_[command] = std::function<void(Game *)>(function);
if (has_output)
output_commands_.emplace(command);
return *this;
}
template <class Game>
CardGameEngine &setGame()
{
delete game_;
game_ = new Game(initialDeck_);
return *this;
}
private:
void quit()
{
keepRunning = false;
}
bool keepRunning;
CardGame *game_;
Deck initialDeck_;
std::unordered_map<std::string, std::function<void(CardGame *)>> game_commands_;
std::unordered_map<std::string, std::function<void()>> engine_commands_;
std::unordered_set<std::string> output_commands_;
void setEngineCommands()
{
engine_commands_["quit"] = std::bind(&CardGameEngine::quit, this);
}
};
class War;
class Belote;
class Santase;
int main()
{
CardGameEngine()
.addGame<War>("War")
.addGame<Belote>("Belote")
.addGame<Santase>("Santase")
.addCommand("size", &CardGame::print_deck_size)
.addCommand("draw_top_card", &CardGame::draw_top_card)
.addCommand("draw_bottom_card", &CardGame::draw_bottom_card)
.addCommand("top_card", &CardGame::print_top_card)
.addCommand("bottom_card", &CardGame::print_bottom_card)
.addCommand("shuffle", &CardGame::shuffle_deck)
.addCommand("sort", &CardGame::sort_deck)
.addCommand("deal", &CardGame::deal)
.run();
}
class War : public CardGame
{
public:
War(const Deck &deck)
: CardGame(
"War",
deck,
52,
26,
{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"})
{
}
};
class Belote : public CardGame
{
public:
Belote(const Deck &deck)
: CardGame(
"Belote",
deck,
32,
8,
{"7", "8", "9", "J", "Q", "K", "K", "10", "A"})
{
}
};
class Santase : public CardGame
{
public:
Santase(const Deck &deck)
: CardGame(
"Santase",
deck,
24,
6,
{"9", "J", "Q", "K", "10", "A"})
{
}
}; | 26.478261 | 139 | 0.541359 | mdatsev |
d1ee5a73707b1026aac20ab13aa7d49ea028856d | 11,818 | cpp | C++ | Localization/LocalAlign/src/ipc.cpp | wangarcher/examine | e04c923f0db397558ea765d7fbf1050fe4aec3dd | [
"MIT"
] | null | null | null | Localization/LocalAlign/src/ipc.cpp | wangarcher/examine | e04c923f0db397558ea765d7fbf1050fe4aec3dd | [
"MIT"
] | null | null | null | Localization/LocalAlign/src/ipc.cpp | wangarcher/examine | e04c923f0db397558ea765d7fbf1050fe4aec3dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <dbus/dbus.h>
#include <stdbool.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <errno.h>
#include "../include/ipc.h"
/*********************************** 组合导航定位模块进程间通信 ****************************/
/*************** 定位模块的IPC信号量 ***********************/
int INPosSemKey = 2463;
int INPosSemId;
/*************** 定位模块的IPC信号量 ***********************/
/*************** 定位模块的消息队列通信 ***********************/
int INPosMsgKey = 2464; //消息键
int INPosMsgId; //定义位置消息Id, 进程间消息队列共享
/*************** 定位模块的消息队列通信 ***********************/
/*************** 定位模块的共享内存通信 ***********************/
int INPosShmKey = 2465;
int INPosShmId; //获取共享内存(Odom Imu Gps + Pos)句柄
/*************** 定位模块的共享内存通信 ***********************/
/*********************************** 组合导航定位模块进程间通信 ******************************/
/*********************************** SLAM定位模块进程间通信 ****************************/
/*************** 定位模块的IPC信号量 ***********************/
int LocalizationPosSemKey = 2466;
int LocalizationPosSemId;
/*************** 定位模块的IPC信号量 ***********************/
/*************** 定位模块的消息队列通信 ***********************/
int LocalizationPosMsgId; //定义位置消息Id, 进程间消息队列共享
int LocalizationPosMsgKey = 2467; //消息键
/*************** 定位模块的消息队列通信 ***********************/
/*************** 定位模块的共享内存通信 ***********************/
int LocalizationPosShmKey = 2468;
int LocalizationPosShmId;
/*************** 定位模块的共享内存通信 ***********************/
/*********************************** SLAM定位模块进程间通信 ******************************/
/*********************************** 视觉模块进程间通信 ******************************/
/*************** 视觉模块的IPC信号量 ***********************/
int VisualOccPosSemKey = 2469;
int VisualOccPosSemId;
/*************** 视觉模块的IPC信号量 ***********************/
/*************** 视觉模块的消息队列通信 ***********************/
int VisualOccPosMsgKey = 2470; //消息键
int VisualOccPosMsgId; //定义位置消息Id, 进程间消息队列共享
/*************** 视觉模块的消息队列通信 ***********************/
/*************** 视觉模块的共享内存通信 ***********************/
int VisualOccPosShmKey = 2471;
int VisualOccPosShmId;
/*************** 视觉模块的共享内存通信 ***********************/
/*********************************** 视觉模块进程间通信 *****************************/
/*********************************** 雷达模块进程间通信 ******************************/
/*************** 雷达模块的IPC信号量 ***********************/
int LidarOccPosSemKey = 2472;
int LidarOccPosSemId;
/*************** 雷达模块的IPC信号量 ***********************/
/*************** 雷达模块的消息队列通信 ***********************/
int LidarOccPosMsgKey = 2473; //消息键
int LidarOccPosMsgId; //定义位置消息Id, 进程间消息队列共享
/*************** 雷达模块的消息队列通信 ***********************/
/*************** 雷达模块的共享内存通信 ***********************/
int LidarOccPosShmKey = 2474;
int LidarOccPosShmId;
/*************** 雷达模块的共享内存通信 ***********************/
/*********************************** 雷达模块进程间通信 *****************************/
void InitIPC()
{
InitSem(INPosSemId, INPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(INPosMsgId, INPosMsgKey, IPC_CREAT|0777);
InitShareMemory(INPosShmId, INPosShmKey,4096, IPC_CREAT|0777);
InitSem(LocalizationPosSemId, LocalizationPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(LocalizationPosMsgId, LocalizationPosMsgKey, IPC_CREAT|0777);
InitShareMemory(LocalizationPosShmId, LocalizationPosShmKey,4096, IPC_CREAT|0777);
InitSem(VisualOccPosSemId, VisualOccPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(VisualOccPosMsgId, VisualOccPosMsgKey, IPC_CREAT|0777);
InitShareMemory(VisualOccPosShmId, VisualOccPosShmKey,4096, IPC_CREAT|0777);
InitSem(LidarOccPosSemId, LidarOccPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(LidarOccPosMsgId, LidarOccPosMsgKey, IPC_CREAT|0777);
InitShareMemory(LidarOccPosShmId, LidarOccPosShmKey,4096, IPC_CREAT|0777);
}
/*************************************************************** 进程间的信号量通信 ***************************************************/
//(1)第一个参数key是长整型(唯一非零),系统建立IPC通讯 ( 消息队列、 信号量和 共享内存) 时必须指定一个ID值。
//通常情况下,该id值通过ftok函数得到,由内核变成标识符,要想让两个进程看到同一个信号集,只需设置key值不变就可以。
//(2)第二个参数nsem指定信号量集中需要的信号量数目
//(3)第三个参数flag是一组标志,当想要当信号量不存在时创建一个新的信号量,可以将flag设置为IPC_CREAT与文件权限做按位或操作。
//设置了IPC_CREAT标志后,即使给出的key是一个已有信号量的key,也不会产生错误。而IPC_CREAT | IPC_EXCL则可以创建一个新的,唯一的信号量,如果信号量已存在,返回一个错误。一般我们会还或上一个文件权限
int InitSem(int &semId, int key, int num, int cmd)
{
semun sem_union;
sem_union.val = 0;
semId = semget(key_t(key), num, cmd);//创建并打开 或者创建 打开拆开 用时打开
if(semId < 0)
{
perror("InitSem failed");
return -1;
}
//信号量存在则获取
else
{
std::cout << "InitSem Success" << std::endl;
return 0;
}
if (semctl(semId, 0, SETVAL, sem_union) == -1) //设置信号量的计数值为0
{
printf("error to open semaphore!\n");
return -1;
}
//设置信号量集合中的信号量(元素)的计数值
SetSem(semId,1);
return 0;
}
int CreatSem(int &semId, int key, int num, int cmd)
{
semId = semget(key_t(key), num, cmd);
if(semId < 0)
{
std::cout << "Creat Sem failed" << std::endl;
return -1;
}
else
{
std::cout << "Creat Sem failed" << std::endl;
return 0;
}
}
//设置信号量集合里面的信号量的计数值val
int SetSem(int semId,int val)
{
int ret = 0;
if(semId < 0)
{
return -1;
}
semun su;
su.val = val;
ret = semctl(semId,0,SETVAL,su);
return ret;
}
//获取信号量集合里面的信号量的计数值
int GetSem(int semId, int& val)
{
int ret = 0;
semun sem_union;
sem_union.val = 0;
if(semId < 0)
{
return -1;
}
ret = semctl(semId,0,GETVAL,sem_union);
val = sem_union.val;
return ret;
}
//struct sembuf{
// short sem_num; // 除非使用一组信号量,否则它为0
// short sem_op; // 信号量在一次操作中需要改变的数据,通常是两个数,
// 一个是-1,即P(等待)操作,
// 一个是+1,即V(发送信号)操作。
// short sem_flg; // 通常为SEM_UNDO,使操作系统跟踪信号,
// // 并在进程没有释放该信号量而终止时,操作系统释放信号量
//};
int P_sem(int semId, int semIndex)
{
struct sembuf s;
s.sem_num = semIndex;
s.sem_op = -1;
s.sem_flg = SEM_UNDO;
if(semop(semId,&s,1) < 0)
{
printf("op errno,%d: %s\n", errno, strerror(errno));
return -1;
}
}
int V_sem(int semId, int semIndex)
{
struct sembuf s;
s.sem_num = semIndex;
s.sem_op = 1;
s.sem_flg = SEM_UNDO;
if(semop(semId,&s,1) < 0)
{
printf("ov error,%d:%s\n",errno,strerror(errno));
return -1;
}
}
// union semun {
// int val;
// struct semid_ds *buf;
// unsigned short *arry;
// };
// SETVAL:用来把信号量初始化为一个已知的值。
// p 这个值通过union semun中的val成员设置,其作用是在信号量第一次使用前对它进行设置。
// IPC_RMID:用于删除一个已经无需继续使用的信号量标识符。
int DestorySem(int semId)
{
semun sem_union;
if (semctl(semId, 0, IPC_RMID, sem_union) == -1)
{
printf("err to delete semaphore!\n");
return -1;
}
}
/*************************************************************** 进程间的信号量通信 ***************************************************/
/*************************************************************** 进程间的消息队列通信 ***************************************************/
//msgflag:有两个选项IPC_CREAT和IPC_EXCL,
//单独使用IPC_CREAT,如果消息队列不存在则创建之,
//如果存在则打开返回;单独使用IPC_EXCL是没有意义的;
//两个同时使用,如果消息队列不存在则创建之,如果存在则出错返回。
int MessageQueueInit(int &msgId, int msgKey, int cmd)
{
//先检查消息队列是否存在
msgId = msgget(msgKey, cmd);
//不存在则创建
if(msgId < 0)
{
std::cout << "InitMsg failed" << std::endl;
return -1;
}
else
{
std::cout << "InitMsg Success(GetMsg)" << std::endl;
return 0;
}
}
int CreatMessageQueue(int &msgId, int msgKey, int cmd)
{
msgId = msgget(msgKey, cmd);
if(msgId < 0)
{
fprintf(stderr, "CreatMsg failed with error:%d\n", errno);
return -1;
}
else
{
std::cout << "CreatMsg successful" << std::endl;
return 0;
}
}
//msgid:由msgget函数返回的消息队列标识码
//msgp:指针指向准备发送的消息
//msgze:msgp指向的消息的长度(不包括消息类型的long int长整型)
//msgflg: 0:当消息队列满时,msgsnd将会阻塞,直到消息能写进消息队列
// IPC_NOWAIT:当消息队列已满的时候,msgsnd函数不等待立即返回
// IPC_NOERROR:若发送的消息大于size字节,则把该消息截断,截断部分将被丢弃,且不通知发送进程。
int SendMessageQueue(int msgId, void* dataAdress, int msgSize, int cmd)
{
if(-1 == msgsnd(msgId, dataAdress, msgSize, cmd)) //理解: 将数据地址(dataAdress)大小(msgSize)发送到消息队列
{
fprintf(stderr, "msgsnd failed: %d\n", errno);
return -1;
}
else
{
std::cout << "msgsnd successful" << std::endl;
return 0;
}
}
//int msgrcv(int msqid, void *ptr, size_t length, long type, int flag);
//type: 决定从队列中返回哪条消息:
// =0 返回消息队列中第一条消息
// >0 返回消息队列中等于mtype 类型的第一条消息。
// <0 返回mtype<=type 绝对值最小值的第一条消息。
//msgflg为0表示阻塞方式,设置 IPC_NOWAIT 表示非阻塞方式
int RcvMessageQueue(int msgId, void* dataAdress, int msgSize, int cmd)
{
if(-1 == msgrcv(msgId, dataAdress, msgSize, 0, cmd))
{
fprintf(stderr, "msgrcv failed with errno: %d", errno);
return -1;
}
else
{
std::cout << "msgrcv successful" << std::endl;
return 0;
}
}
//msqid:由msgget函数返回的消息队列标识码
//cmd:有三个可选的值,在此我们使用IPC_RMID
// IPC_STAT 把msqid_ds结构中的数据设置为消息队列的当前关联值
// IPC_SET 在进程有足够权限的前提下,把消息队列的当前关联值设置为msqid_ds数据结构中给出的值
// IPC_RMID 删除消息队列
int DestoryMessageQueue(int msgId)
{
if(msgctl(msgId, IPC_RMID, NULL) < 0)
{
perror("msgctl");
return -1;
}
return 0;
}
/*************************************************************** 进程间的消息队列通信 ***************************************************/
/*************************************************************** 进程间的内存共享通信 ***************************************************/
//key:共享内存名字,确保不同进程看到同一份IPC资源;
//其中key值的又由ftok函数创建。
//size:共享内存的大小,共享内存的创建是以页为单位的;
//页的大小是4096k(4kb)
//共享内存分别存放Odom Imu Gps Robot数据 请按照此顺序进行读取以及写入
int InitShareMemory(int &shmid, int key, int size, int cmd)
{
int pageSize = getpagesize();//获取系统页面的大小
if(size <= 0)
{
std::cout << "共享内存创建非法,请检查!" << std::endl;
return -1;
}
else if(size > pageSize)
{
std::cout << "创建共享内存段的大小超过页面的大小!" << std::endl;
return -1;
}
else
{
shmid = shmget(key, size, cmd);
if(shmid < 0)
{
std::cout << "InitShm failed" << std::endl;
return -1;
}
else
{
std::cout << "InitShm success" << std::endl;
return 0;
}
return 0;
}
}
int CreatShareMemory(int &shmid, key_t key, int size, int cmd)
{
shmid = shmget(key, size, IPC_CREAT | 0666);
if( shmid < 0)
{
perror("CreatShm failed");
return -1;
}
else
{
std::cout << "CreatShm successful" << std::endl;
return 0;
}
}
void* AttachShareMemory(int shmid)
{
void* shmaddr;
return shmaddr = (void *) shmat(shmid, NULL, 0);
}
void* WriteShareMemory(void* shmaddr, void* source, int size)
{
return memcpy(shmaddr, source, size);
}
void* ReadShareMemory(void* destion, void* shmaddr, int size)
{
return memcpy(destion, shmaddr, size);
}
int DisattachShareMemory(void* shmaddr)
{
return shmdt(shmaddr);
}
int DestoryShareMemory(int shmid)
{
return shmctl(shmid, IPC_RMID, NULL);
}
/*************************************************************** 进程间的内存共享通信 ***************************************************/
| 26.146018 | 129 | 0.519123 | wangarcher |
d1ef0404149d103b8989ec04bb16369ccc95c262 | 9,714 | cxx | C++ | main/writerfilter/source/doctok/WW8PropertySetImpl.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/writerfilter/source/doctok/WW8PropertySetImpl.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/writerfilter/source/doctok/WW8PropertySetImpl.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "WW8DocumentImpl.hxx"
#include "WW8ResourceModelImpl.hxx"
#include <doctok/resourceids.hxx>
#include <resourcemodel/QNameToString.hxx>
namespace writerfilter {
namespace doctok
{
bool operator != (const WW8PropertySetIterator & rA,
const WW8PropertySetIterator & rB)
{
return ! (rA.equal(rB));
}
WW8Property::~WW8Property()
{
}
WW8PropertySet::~WW8PropertySet()
{
}
WW8PropertySetIterator::~WW8PropertySetIterator()
{
}
WW8PropertyImpl::WW8PropertyImpl(WW8Stream & rStream,
sal_uInt32 nOffset, sal_uInt32 nCount)
: WW8StructBase(rStream, nOffset, nCount)
{
}
WW8PropertyImpl::WW8PropertyImpl(const WW8StructBase & rBase,
sal_uInt32 nOffset,
sal_uInt32 nCount)
: WW8StructBase(rBase, nOffset, nCount)
{
}
WW8PropertyImpl::WW8PropertyImpl(WW8StructBase * pBase,
sal_uInt32 nOffset,
sal_uInt32 nCount)
: WW8StructBase(pBase, nOffset, nCount)
{
}
WW8PropertyImpl::~WW8PropertyImpl()
{
}
sal_uInt32 WW8PropertyImpl::getParam() const
{
sal_uInt32 nResult = 0;
switch (get_spra())
{
case 0:
case 1:
nResult = getU8(2);
break;
case 2:
case 4:
case 5:
nResult = getU16(2);
break;
case 3:
nResult = getU32(2);
break;
case 7:
nResult = getU16(2) + (getU8(4) << 16);
break;
default:
break;
}
return nResult;
}
WW8Stream::Sequence WW8PropertyImpl::getParams() const
{
return WW8Stream::Sequence(mSequence, 2, getCount() - 2);
}
sal_uInt32 WW8PropertyImpl::getByteLength() const
{
sal_uInt32 nParamSize = 0;
switch (get_spra())
{
case 0:
case 1:
nParamSize = 1;
break;
case 2:
case 4:
case 5:
nParamSize = 2;
break;
case 3:
nParamSize = 4;
break;
case 7:
nParamSize = 3;
break;
default:
switch (getId())
{
case 0xd608:
nParamSize = getU16(2) + 1;
break;
default:
nParamSize = getU8(2) + 1;
break;
}
break;
}
return nParamSize + 2;
}
sal_uInt32 WW8PropertyImpl::getParamOffset() const
{
sal_uInt32 nReturn = 0;
if (get_spra() == 6)
nReturn = 1;
switch (getId())
{
case 0xd608:
case 0xd609:
nReturn = 3;
break;
default:
break;
}
return nReturn;
}
void WW8PropertyImpl::dump(OutputWithDepth<string> & o) const
{
o.addItem(toString());
}
string WW8PropertyImpl::toString() const
{
string aResult;
aResult += "<sprmcommon";
char sBuffer[256];
snprintf(sBuffer, sizeof(sBuffer), " id=\"%" SAL_PRIuUINT32 "\"", getId());
aResult += sBuffer;
aResult += " name=\"";
aResult += (*SprmIdToString::Instance())(getId());
aResult += "\"";
snprintf(sBuffer, sizeof(sBuffer), " sgc=\"%x\"", get_sgc());
aResult += sBuffer;
snprintf(sBuffer, sizeof(sBuffer), " spra=\"%x\"", get_spra());
aResult += sBuffer;
snprintf(sBuffer, sizeof(sBuffer), " size=\"%" SAL_PRIxUINT32 "\"", getByteLength());
aResult += sBuffer;
snprintf(sBuffer, sizeof(sBuffer), " param=\"%" SAL_PRIxUINT32 "\"", getParam());
aResult += sBuffer;
aResult += ">\n";
aResult += mSequence.toString();
aResult += "</sprmcommon>";
return aResult;
}
WW8PropertySetImpl::WW8PropertySetImpl(WW8Stream & rStream,
sal_uInt32 nOffset,
sal_uInt32 nCount,
bool bPap)
: WW8StructBase(rStream, nOffset, nCount), mbPap(bPap)
{
}
WW8PropertySetImpl::WW8PropertySetImpl(const WW8StructBase & rBase,
sal_uInt32 nOffset,
sal_uInt32 nCount,
bool bPap)
: WW8StructBase(rBase, nOffset, nCount), mbPap(bPap)
{
}
WW8PropertySetImpl::~WW8PropertySetImpl()
{
}
bool WW8PropertySetImpl::isPap() const
{
return mbPap;
}
sal_uInt32 WW8PropertySetImpl::get_istd() const
{
sal_uInt32 nResult = 0;
if (mbPap)
nResult = getU16(0);
return nResult;
}
WW8PropertySetIterator::Pointer_t WW8PropertySetImpl::begin()
{
return WW8PropertySetIterator::Pointer_t
(new WW8PropertySetIteratorImpl(this, mbPap ? 2 : 0));
}
WW8PropertySetIterator::Pointer_t WW8PropertySetImpl::end()
{
return WW8PropertySetIterator::Pointer_t
(new WW8PropertySetIteratorImpl(this, getCount()));
}
WW8PropertySetIteratorImpl::~WW8PropertySetIteratorImpl()
{
}
WW8Property::Pointer_t
WW8PropertySetImpl::getAttribute(sal_uInt32 nOffset) const
{
WW8PropertyImpl aTmpAttr(*this, nOffset, 3);
sal_uInt32 nLength = aTmpAttr.getByteLength();
if (nOffset + nLength > getCount())
nLength = getCount() - nOffset;
return WW8Property::Pointer_t
(new WW8PropertyImpl(*this, nOffset, nLength));
}
void WW8PropertySetImpl::dump(OutputWithDepth<string> & o) const
{
WW8StructBase::dump(o);
WW8PropertySetIterator::Pointer_t pIt =
const_cast<WW8PropertySetImpl *>(this)->begin();
WW8PropertySetIterator::Pointer_t pItEnd =
const_cast<WW8PropertySetImpl *>(this)->end();
while((*pIt) != (*pItEnd))
{
WW8Property::Pointer_t pAttr = pIt->get();
pAttr->dump(o);
++(*pIt);
}
}
void WW8PropertySetImpl::dots(ostream & o)
{
WW8PropertySetIterator::Pointer_t pIt = begin();
WW8PropertySetIterator::Pointer_t pItEnd = end();
while((*pIt) != (*pItEnd))
{
WW8Property::Pointer_t pAttr = pIt->get();
o << "." << endl;
++(*pIt);
}
}
string WW8PropertySetImpl::getType() const
{
return "WW8PropertySetImpl";
}
void WW8PropertySetImpl::resolveLocal(Sprm & sprm, Properties & rHandler)
{
switch (sprm.getId())
{
case 0x6a03:
{
Value::Pointer_t pValue = sprm.getValue();
getDocument()->setPicLocation(pValue->getInt());
getDocument()->setPicIsData(false);
}
break;
case 0x806:
{
getDocument()->setPicIsData(true);
}
break;
case 0x6646:
{
WW8Stream::Pointer_t pStream = getDocument()->getDataStream();
if (pStream.get() != NULL)
{
Value::Pointer_t pValue = sprm.getValue();
sal_uInt32 nOffset = pValue->getInt();
WW8StructBase aStruct(*pStream, nOffset, 2);
sal_uInt16 nCount = aStruct.getU16(0);
{
WW8PropertySetImpl * pPropSet =
new WW8PropertySetImpl(*pStream, nOffset + 2, nCount);
pPropSet->resolve(rHandler);
}
}
}
break;
default:
break;
}
}
void WW8PropertySetImpl::resolve(Properties & rHandler)
{
if (getCount() >= (isPap() ? 5U : 3U))
{
WW8PropertySetIterator::Pointer_t pIt = begin();
WW8PropertySetIterator::Pointer_t pItEnd = end();
if (isPap())
{
WW8Value::Pointer_t pValue = createValue(getU16(0));
rHandler.attribute(NS_rtf::LN_ISTD, *pValue);
}
while((*pIt) != (*pItEnd))
{
WW8Sprm aSprm(pIt->get());
rHandler.sprm(aSprm);
resolveLocal(aSprm, rHandler);
++(*pIt);
}
}
}
WW8PropertySetIterator & WW8PropertySetIteratorImpl::operator++ ()
{
WW8Property::Pointer_t pTmpAttr = mpAttrSet->getAttribute(mnOffset);
mnOffset += dynamic_cast<WW8PropertyImpl *>(pTmpAttr.get())->
getByteLength();
if (mnOffset > mpAttrSet->getCount() ||
mpAttrSet->getCount() - mnOffset < 3)
mnOffset = mpAttrSet->getCount();
return *this;
}
WW8Property::Pointer_t WW8PropertySetIteratorImpl::get() const
{
return mpAttrSet->getAttribute(mnOffset);
}
bool WW8PropertySetIteratorImpl::equal
(const WW8PropertySetIterator & rIt) const
{
const WW8PropertySetIteratorImpl & rMyIt =
dynamic_cast<const WW8PropertySetIteratorImpl &>(rIt);
return mpAttrSet == rMyIt.mpAttrSet && mnOffset == rMyIt.mnOffset;
}
string WW8PropertySetIteratorImpl::toString() const
{
string sResult = "";
char sBuffer[256];
snprintf(sBuffer, sizeof(sBuffer), "(%" SAL_PRIuUINT32 ")", mnOffset);
sResult += sBuffer;
return sResult;
}
}}
| 22.643357 | 89 | 0.583282 | Grosskopf |
d1f277c362894330ad3b5b1c075802b4579ecd49 | 2,338 | cc | C++ | MassRecoCompare/src/Common.cc | NTUHEP-Tstar/TstarAnalysis | d3bcdf6f0fd19b9a34bbacb1052143856917bea7 | [
"MIT"
] | null | null | null | MassRecoCompare/src/Common.cc | NTUHEP-Tstar/TstarAnalysis | d3bcdf6f0fd19b9a34bbacb1052143856917bea7 | [
"MIT"
] | null | null | null | MassRecoCompare/src/Common.cc | NTUHEP-Tstar/TstarAnalysis | d3bcdf6f0fd19b9a34bbacb1052143856917bea7 | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* Filename : Common.cc
* Description : Declaration of common global variables and functions
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
* Additional comments
*
*******************************************************************************/
#include "TstarAnalysis/MassRecoCompare/interface/Common.hpp"
#include <boost/algorithm/string.hpp>
using namespace std;
/*******************************************************************************
* Declaring global objects
*******************************************************************************/
TstarNamer reconamer( "MassRecoCompare" );
const Color_t Color_Sequence[5] = {
kBlue,
kRed,
kGreen,
kBlack,
kCyan
};
/*******************************************************************************
* Module naming functions
*******************************************************************************/
std::string
ProcessName(){ return "HitFitCompare"; }
/******************************************************************************/
std::string
LabelName( const std::string& modulename )
{
return boost::starts_with( modulename, "ChiSq" ) ?
"ChiSquareResult" : "HitFitResult";
}
/*******************************************************************************
* Common functions
*******************************************************************************/
const vector<tstar::Particle_Label> fitlabellist = {
tstar::lepb_label,
tstar::lepg_label,
tstar::hadw1_label,
tstar::hadw2_label,
tstar::hadb_label,
tstar::hadg_label
};
const vector<tstar::Particle_Label> truthlabellist = {
tstar::lepb_label,
tstar::lepg_label,
tstar::hadw1_label,
tstar::hadw2_label,
tstar::hadb_label,
tstar::hadg_label,
tstar::unknown_label
};
/******************************************************************************/
unsigned
NumCorrectAssign( const RecoResult& results )
{
unsigned ans = 0;
for( const auto x : fitlabellist ){
const auto y = results.GetParticle( x ).TypeFromTruth();
if( x == y ){ ans++; continue; }
if( x == tstar::hadw1_label && y == tstar::hadw2_label ){ ans++; continue; }
if( x == tstar::hadw2_label && y == tstar::hadw1_label ){ ans++; continue; }
}
return ans;
}
| 28.864198 | 80 | 0.44953 | NTUHEP-Tstar |
d1f359753752617b84bcfb358e508e6f557c25b5 | 1,475 | cpp | C++ | compiler/angkor/src/ADT/feature/HWCLayout.test.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/angkor/src/ADT/feature/HWCLayout.test.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/angkor/src/ADT/feature/HWCLayout.test.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. 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.
* 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 "nncc/core/ADT/feature/HWCLayout.h"
#include <gtest/gtest.h>
using namespace nncc::core::ADT::feature;
TEST(ADT_FEATURE_HWC_LAYOUT, C_increase)
{
const uint32_t C = 4;
const uint32_t H = 3;
const uint32_t W = 6;
const Shape shape{C, H, W};
const HWCLayout l;
ASSERT_EQ(l.offset(shape, 1, 1, 1) + 1, l.offset(shape, 2, 1, 1));
}
TEST(ADT_FEATURE_HWC_LAYOUT, W_increase)
{
const uint32_t C = 4;
const uint32_t H = 3;
const uint32_t W = 6;
const Shape shape{C, H, W};
const HWCLayout l;
ASSERT_EQ(l.offset(shape, 1, 2, 1) + C, l.offset(shape, 1, 2, 2));
}
TEST(ADT_FEATURE_HWC_LAYOUT, H_increase)
{
const uint32_t C = 4;
const uint32_t H = 3;
const uint32_t W = 6;
const Shape shape{C, H, W};
const HWCLayout l;
ASSERT_EQ(l.offset(shape, 1, 1, 1) + W * C, l.offset(shape, 1, 2, 1));
}
| 25.431034 | 75 | 0.690169 | wateret |
d1f371a9310b72a8c33d0c46ebd1c10d15beecf9 | 4,291 | cc | C++ | pik/ac_predictions_test.cc | EwoutH/pik | e4b2c7ac71da9b35a9e45a107077f9d33a228012 | [
"MIT"
] | null | null | null | pik/ac_predictions_test.cc | EwoutH/pik | e4b2c7ac71da9b35a9e45a107077f9d33a228012 | [
"MIT"
] | null | null | null | pik/ac_predictions_test.cc | EwoutH/pik | e4b2c7ac71da9b35a9e45a107077f9d33a228012 | [
"MIT"
] | null | null | null | // Copyright 2019 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#include "pik/ac_predictions.h"
#include "gtest/gtest.h"
#include "pik/codec.h"
#include "pik/common.h"
#include "pik/pik.h"
#include "pik/status.h"
#include "pik/testdata_path.h"
namespace pik {
namespace {
struct AcPredictionsTestParams {
explicit AcPredictionsTestParams(const double butteraugli_distance,
const bool fast_mode = false,
const bool shrink8 = false)
: butteraugli_distance(butteraugli_distance),
fast_mode(fast_mode),
shrink8(shrink8) {}
double butteraugli_distance;
bool fast_mode;
bool shrink8;
};
std::ostream& operator<<(std::ostream& os, AcPredictionsTestParams params) {
auto previous_flags = os.flags();
os << std::boolalpha;
os << "AcPredictionsTestParams{/*butteraugli_distance=*/"
<< params.butteraugli_distance << ", /*fast_mode=*/" << params.fast_mode
<< ", /*shrink8=*/" << params.shrink8 << "}";
os.flags(previous_flags);
return os;
}
class AcPredictionsTest
: public testing::TestWithParam<AcPredictionsTestParams> {
protected:
// Returns compressed size [bytes].
static void Roundtrip(CodecInOut* io, const CompressParams& cparams,
const DecompressParams& dparams, ThreadPool* pool) {
PaddedBytes compressed;
const size_t xsize_blocks = DivCeil(io->xsize(), kBlockDim);
const size_t ysize_blocks = DivCeil(io->ysize(), kBlockDim);
Image3F encoding_ac_prediction(xsize_blocks * kDCTBlockSize, ysize_blocks);
PikInfo encoding_info;
encoding_info.testing_aux.ac_prediction = &encoding_ac_prediction;
EXPECT_TRUE(PixelsToPik(cparams, io, &compressed, &encoding_info, pool));
Image3F decoding_ac_prediction;
PikInfo decoding_info;
// WARNING: the code that fills this is not thread-safe, and will only
// work for a single group, which is OK for the current test image.
decoding_info.testing_aux.ac_prediction = &decoding_ac_prediction;
EXPECT_TRUE(PikToPixels(dparams, compressed, io, &decoding_info, pool));
const float kErrorThreshold = 1e-6;
EXPECT_LE(
VerifyRelativeError(decoding_ac_prediction, encoding_ac_prediction,
kErrorThreshold, kErrorThreshold),
kErrorThreshold);
}
};
INSTANTIATE_TEST_SUITE_P(
AcPredictionsTestInstantiation, AcPredictionsTest,
testing::Values(AcPredictionsTestParams{/*butteraugli_distance=*/1.0,
/*fast_mode=*/false,
/*shrink8=*/true},
// No noise, no gradient
AcPredictionsTestParams{/*butteraugli_distance=*/1.0},
// Noise, no gradient
AcPredictionsTestParams{/*butteraugli_distance=*/1.5},
// Noise, gradient
AcPredictionsTestParams{/*butteraugli_distance=*/2.0},
// No noise, no gradient
AcPredictionsTestParams{/*butteraugli_distance=*/1.0,
/*fast_mode=*/true},
// Noise, no gradient
AcPredictionsTestParams{/*butteraugli_distance=*/1.5,
/*fast_mode=*/true},
// Noise, gradient
AcPredictionsTestParams{/*butteraugli_distance=*/2.0,
/*fast_mode=*/true}));
TEST_P(AcPredictionsTest, Roundtrip) {
const std::string pathname =
GetTestDataPath("wesaturate/500px/u76c0g_bliznaca_srgb8.png");
CodecContext codec_context;
CodecInOut io(&codec_context);
ThreadPool pool(8);
ASSERT_TRUE(io.SetFromFile(pathname, &pool));
const AcPredictionsTestParams& params = GetParam();
if (params.shrink8) {
io.ShrinkTo(io.xsize() / 8, io.ysize() / 8);
}
CompressParams cparams;
cparams.butteraugli_distance = params.butteraugli_distance;
cparams.fast_mode = params.fast_mode;
DecompressParams dparams;
Roundtrip(&io, cparams, dparams, &pool);
}
} // namespace
} // namespace pik
| 35.758333 | 79 | 0.639012 | EwoutH |
d1f46989a9fba26159145429767fad72259179d2 | 1,184 | cpp | C++ | testkuplayer/tst_kuplayertest.cpp | listener/mikuplayer | 06b3fb9ffc13184086c5098cd50224c6c60d162f | [
"Unlicense"
] | 17 | 2015-09-13T02:06:27.000Z | 2017-09-22T06:39:26.000Z | testkuplayer/tst_kuplayertest.cpp | xiaosumay/kuplayer | 06b3fb9ffc13184086c5098cd50224c6c60d162f | [
"Unlicense"
] | null | null | null | testkuplayer/tst_kuplayertest.cpp | xiaosumay/kuplayer | 06b3fb9ffc13184086c5098cd50224c6c60d162f | [
"Unlicense"
] | 2 | 2015-10-26T01:54:54.000Z | 2016-01-16T08:24:45.000Z | /*
Copyright (C) 2015 MeiZhaorui(Mason) <listener_mei@163.com>
The File is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The File is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the Library; if not, see
<http://www.gnu.org/licenses/>.
*/
#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include "../src/pyscript.h"
USR_NAMESPACE_KUPLAYER
class kuplayerTest : public QObject
{
Q_OBJECT
public:
kuplayerTest();
private Q_SLOTS:
void testgetShowList();
};
kuplayerTest::kuplayerTest()
{
}
void kuplayerTest::testgetShowList()
{
PyScript p;
QCOMPARE(true,p.getShowList());
}
QTEST_MAIN(kuplayerTest)
#include "tst_kuplayertest.moc"
| 24.163265 | 69 | 0.725507 | listener |
d1f63cd1080601f902d65f7eecdb178a63bb2fae | 11,599 | cpp | C++ | src/Scenario/DIALOGS/CustTree.cpp | privatosan/RayStorm | 17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa | [
"MIT"
] | 2 | 2016-04-03T23:57:54.000Z | 2019-12-05T17:50:37.000Z | src/Scenario/DIALOGS/CustTree.cpp | privatosan/RayStorm | 17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa | [
"MIT"
] | null | null | null | src/Scenario/DIALOGS/CustTree.cpp | privatosan/RayStorm | 17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa | [
"MIT"
] | 2 | 2015-06-20T19:22:47.000Z | 2021-11-15T15:22:14.000Z | // OwnrTree.cpp : implementation file
//
#include "typedefs.h"
#include "CustTree.h"
#include "object.h"
#include "sci.h"
#include "resource.h"
#include "BrowserView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define INSERT_TEXT ""
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Construction
CCustomTreeCtrl::CCustomTreeCtrl()
{
m_bNoPaint = FALSE;
m_bLockPropertySelchanged = FALSE;
}
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Public Interfaces
BOOL CCustomTreeCtrl::SetItemText(HTREEITEM hItem, LPCTSTR lpszItem)
{
CString cstr;
CRect crect;
cstr = lpszItem;
AddTextItem(hItem, cstr);
GetItemRect(hItem, &crect, FALSE);
InvalidateRect(&crect);
return TRUE;
}
CString CCustomTreeCtrl::GetItemText(HTREEITEM hItem)
{
CString cstr;
GetTextFromItem(hItem, cstr);
return cstr;
}
HTREEITEM CCustomTreeCtrl::InsertItem(LPTV_INSERTSTRUCT lpInsertStruct)
{
HTREEITEM hItem;
CString cstr;
cstr = lpInsertStruct->item.pszText;
lpInsertStruct->item.pszText = INSERT_TEXT;
hItem = CTreeCtrl::InsertItem(lpInsertStruct);
if (!hItem)
return NULL;
AddTextItem(hItem, cstr);
return hItem;
}
HTREEITEM CCustomTreeCtrl::InsertItem(UINT nMask, LPCTSTR lpszItem,
int nImage,
int nSelectedImage,
UINT nState,UINT nStateMask,
LPARAM lParam,
HTREEITEM hParent,
HTREEITEM hInsertAfter)
{
CString cstr;
HTREEITEM hItem;
hItem = CTreeCtrl::InsertItem(nMask, INSERT_TEXT, nImage,
nSelectedImage, nState,
nStateMask, lParam, hParent,
hInsertAfter);
if (!hItem)
return NULL;
cstr = lpszItem;
AddTextItem(hItem, cstr);
return hItem;
}
HTREEITEM CCustomTreeCtrl::InsertItem(LPCTSTR lpszItem, HTREEITEM hParent, HTREEITEM hInsertAfter)
{
CString cstr;
HTREEITEM hItem;
cstr = lpszItem;
hItem = CTreeCtrl::InsertItem(INSERT_TEXT, hParent,
hInsertAfter);
if (!hItem)
return NULL;
AddTextItem(hItem, cstr);
return hItem;
}
HTREEITEM CCustomTreeCtrl::InsertItem(LPCTSTR lpszItem, int nImage,
int nSelectedImage,
HTREEITEM hParent,
HTREEITEM hInsertAfter)
{
CString cstr;
HTREEITEM hItem;
cstr = lpszItem;
hItem = CTreeCtrl::InsertItem(INSERT_TEXT, nImage,nSelectedImage,
hParent, hInsertAfter);
if (!hItem)
return NULL;
AddTextItem(hItem, cstr);
return hItem;
}
BOOL CCustomTreeCtrl::GetItem(TV_ITEM* pItem)
{
BOOL bRet;
CString cstr;
bRet = CTreeCtrl::GetItem(pItem);
if (bRet)
{
GetTextFromItem(pItem->hItem, cstr);
strncpy(pItem->pszText, cstr, pItem->cchTextMax);
}
return bRet;
}
BOOL CCustomTreeCtrl::SetItem(TV_ITEM* pItem)
{
BOOL bRet;
CString cstr;
cstr = pItem->pszText;
pItem->pszText = INSERT_TEXT;
bRet = CTreeCtrl::SetItem(pItem);
if (bRet)
{
AddTextItem(pItem->hItem, cstr);
}
return bRet;
}
BOOL CCustomTreeCtrl::SetItem(HTREEITEM hItem, UINT nMask,
LPCTSTR lpszItem, int nImage,
int nSelectedImage, UINT nState,
UINT nStateMask, LPARAM lParam)
{
BOOL bRet;
bRet = CTreeCtrl::SetItem(hItem, nMask, INSERT_TEXT, nImage,
nSelectedImage, nState, nStateMask,
lParam);
if (bRet)
{
CString cstr;
cstr = lpszItem;
AddTextItem(hItem, cstr);
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Implementation Methods
HTREEITEM CCustomTreeCtrl::PtInField(POINT pt)
{
CRect crect;
HTREEITEM htreeitem;
htreeitem = GetFirstVisibleItem();
while (htreeitem)
{
GetItemRect(htreeitem, &crect, TRUE);
if (crect.PtInRect(pt))
break;
htreeitem = GetNextVisibleItem(htreeitem);
}
return htreeitem;
}
void CCustomTreeCtrl::AddTextItem(HTREEITEM hItem, CString &cstr)
{
m_cmapTextItems.SetAt(hItem, cstr);
}
void CCustomTreeCtrl::RemoveTextItem(HTREEITEM hItem)
{
m_cmapTextItems.RemoveKey(hItem);
}
BOOL CCustomTreeCtrl::GetTextFromItem(HTREEITEM hItem, CString &cstr)
{
return m_cmapTextItems.Lookup(hItem, cstr);
}
void CCustomTreeCtrl::SetItemWidth(HTREEITEM htreeitem, CDC &cdc,
DWORD dwWidth)
{
int nSpaceWidth, nSpaces;
CString cstr;
cdc.GetCharWidth(' ', ' ', &nSpaceWidth);
// I don't know when a space wouldn't have width, but I would
// hate to see a divide by zero error.
if (!nSpaceWidth)
return;
nSpaces = dwWidth / nSpaceWidth + ((dwWidth % nSpaceWidth)?1:0);
cstr = CTreeCtrl::GetItemText(htreeitem);
if (cstr.GetLength() != nSpaces)
{
CTreeCtrl::SetItemText(htreeitem, CString(' ', nSpaces));
}
}
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Overidables
// This function should normally be overridden, however it is always
// nice to have a default implementation to fall back on
DWORD CCustomTreeCtrl::DrawItem(HTREEITEM htreeitem, CDC &cdc, CRect &rect, UINT nState)
{
CFont *oldFont;
CRect rectBack;
COLORREF oldCol;
OBJECT *object;
char *name;
rectBack = rect;
rectBack.right += 4;
cdc.FillSolidRect(&rectBack, GetSysColor(COLOR_WINDOW));
oldFont = cdc.SelectObject(GetFont());
object = (OBJECT*)(GetItemData(htreeitem));
if (object)
{
name = object->GetName();
if (object->selected)
oldCol = cdc.SetTextColor(RGB(255,0,0));
else
oldCol = cdc.SetTextColor(RGB(0,0,0));
cdc.DrawText(name, &rect, DT_VCENTER | DT_SINGLELINE);
cdc.SelectObject(oldFont);
cdc.SetTextColor(oldCol);
return cdc.GetTextExtent(name, strlen(name)).cx;
}
return 0;
}
BEGIN_MESSAGE_MAP(CCustomTreeCtrl, CTreeCtrl)
//{{AFX_MSG_MAP(CCustomTreeCtrl)
ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnPropertySelchanged)
ON_NOTIFY_REFLECT(TVN_ITEMEXPANDED, OnItemExpanded)
ON_WM_PAINT()
ON_WM_RBUTTONDOWN()
ON_WM_ERASEBKGND()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl message handlers
// To prevent flickering when using non default bkcolor
BOOL CCustomTreeCtrl::OnEraseBkgnd(CDC *)
{
return TRUE;
}
// Disable Tooltips
BOOL CCustomTreeCtrl::OnNotify(WPARAM wParam, LPARAM lParam,
LRESULT* pResult)
{
return TRUE;
}
/*************
* DESCRIPTION: set which to current selected object
* INPUT: system
* OUTPUT: -
*************/
void CCustomTreeCtrl::OnPropertySelchanged(LPNMHDR pNMHDR, LRESULT *lParam)
{
NM_TREEVIEW *pnmtv;
if (m_bLockPropertySelchanged)
return;
pnmtv = (NM_TREEVIEW*)pNMHDR;
OBJECT *which = (OBJECT*)GetItemData(pnmtv->itemNew.hItem);
if (which)
{
if (!(GetKeyState(VK_SHIFT) & 0xf000))
DeselectAll();
which->SelectObject();
// lock us to prevent recursive call
m_bLockPropertySelchanged = TRUE;
sciBrowserBuild();
m_bLockPropertySelchanged = FALSE;
sciRedraw();
}
}
void CCustomTreeCtrl::OnPaint()
{
HTREEITEM hTreeItem;
CRect rect, rectClip, rectClient, rectTemp;
CFont *pcfont, *pcfontOld;
CBitmap bitmap;
CDC memDC;
CRgn rgn;
CPaintDC dc(this);
UINT nState;
BOOL bFocus;
DWORD dwWidth;
// If we are flagged to ignore this pain message,
// then validate rect and return
if (m_bNoPaint)
{
m_bNoPaint = FALSE;
ValidateRect(NULL);
return;
}
// Create a memory DC compatible with the paint DC
memDC.CreateCompatibleDC(&dc);
dc.GetClipBox(&rectClip);
GetClientRect(&rectClient);
// Select a compatible bitmap into the memory DC
bitmap.CreateCompatibleBitmap(&dc, rectClient.Width(), rectClient.Height());
memDC.SelectObject(&bitmap);
// Set clip region to be same as that in paint DC
rgn.CreateRectRgnIndirect(&rectClip);
memDC.SelectClipRgn(&rgn);
rgn.DeleteObject();
// First let the control do its default drawing.
// Retrieve Invalid Rect for use throughout paint handler
ValidateRect(NULL);
// If we have focus, store this fact, but then turn it off
if (bFocus = GetFocus() == this)
{
// Make sure any paint message generated by
// SetFocus() does nothing
m_bNoPaint = TRUE;
::SetFocus(NULL);
// Make sure that or Invalid rect is the same as it
// was upon entering the paint handler
ValidateRect(NULL);
InvalidateRect(&rectClient);
// Set Paint Flag so that future paint handling will occur
m_bNoPaint = FALSE;
}
// Get that default drawing done... without a focus rect or
// selected area
CWnd::DefWindowProc(WM_PAINT, (WPARAM)memDC.m_hDC, 0);
// If we did have focus we will restore it now
if (bFocus)
{
m_bNoPaint = TRUE;
SetFocus();
m_bNoPaint = FALSE;
}
// We want a valid window rect now... SetFocus() may have
// invalidated some portion of the client
ValidateRect(NULL);
// As control we need to make sure we do our drawing in
// our parents font
pcfont = GetParent()->GetFont();
pcfontOld = memDC.SelectObject(pcfont);
// Now we will enumerate the visible items in the control
hTreeItem = GetFirstVisibleItem();
while (hTreeItem)
{
// Where is this item in the client
GetItemRect(hTreeItem, &rect, TRUE);
// Get the state of the current item to pass to the
// DrawItem() Function
nState = GetItemState(hTreeItem, ~0);
// Expand / limit the area of the item to the right
// edge of the client
rect.right = rectClient.right;
// If the item falls inside of our original
// invalid rect then redraw it
// by calling the overidable virtual function DrawItem()
if (rectTemp.IntersectRect(&rect, &rectClient))
{
dwWidth = DrawItem(hTreeItem, memDC, rect, nState);
SetItemWidth(hTreeItem, memDC, dwWidth);
}
// Continue through visible items
hTreeItem = GetNextVisibleItem(hTreeItem);
}
// We do this, because SetItemWidth actually changes
// the text of the items in the control and it
// may have flagged a repaint which we don't want to happen
ValidateRect(NULL);
dc.BitBlt(rectClip.left, rectClip.top, rectClip.Width(), rectClip.Height(), &memDC, rectClip.left, rectClip.top,SRCCOPY);
}
/*************
* DESCRIPTION: called if tree item is expanded or collapsed
* INPUT: system
* OUTPUT: -
*************/
void CCustomTreeCtrl::OnItemExpanded(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
OBJECT *object;
object = (OBJECT *)GetItemData(pNMTreeView->itemNew.hItem);
if (object)
{
if (pNMTreeView->action & TVE_COLLAPSE)
object->flags &= ~OBJECT_NODEOPEN;
if (pNMTreeView->action & TVE_EXPAND)
object->flags |= OBJECT_NODEOPEN;
}
*pResult = 0;
}
/*************
* DESCRIPTION: ON_WM_RBUTTONDOWN
* handles right mouse button click
* display pop up menu in browser menu
* INPUT: nFlags Specifies if various flags are set
* point coordinates of mouse cursor
* OUTPUT: -
*************/
void CCustomTreeCtrl::OnRButtonDown(UINT nFlags, CPoint point)
{
CMenu menu;
int resource;
HTREEITEM hItem;
UINT flags;
OBJECT *object;
hItem = HitTest(point, &flags);
if (hItem)
{
object = (OBJECT*)GetItemData(hItem);
resource = object->GetResourceID();
ClientToScreen(&point);
if (menu.LoadMenu(resource))
{
CMenu* pSubMenu = menu.GetSubMenu(0);
if (pSubMenu != NULL)
{
if (resource == IDR_POPUP_OBJECT)
{
if (object->external != EXTERNAL_NONE)
pSubMenu->EnableMenuItem(IDM_TOSCENE, MF_ENABLED);
else
pSubMenu->EnableMenuItem(IDM_TOSCENE, MF_GRAYED);
}
pSubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, ((CBrowserView*)GetParent())->pCamView);
}
}
}
}
| 22.435203 | 122 | 0.677903 | privatosan |
d1f7ac7c8728744bc1f2ac220a3d5b44936bdc4c | 1,556 | cpp | C++ | hello.cpp | wuyudi/-Computer-Graphics | 228ef5e5db24c2af78ea8b5f68def47675895fd3 | [
"MIT"
] | null | null | null | hello.cpp | wuyudi/-Computer-Graphics | 228ef5e5db24c2af78ea8b5f68def47675895fd3 | [
"MIT"
] | null | null | null | hello.cpp | wuyudi/-Computer-Graphics | 228ef5e5db24c2af78ea8b5f68def47675895fd3 | [
"MIT"
] | null | null | null | //g++ -o hello -Wall hello.cpp -mwindows glut32.lib -lopengl32 -lglu32
#include <windows.h>
#include <gl/glut.h>
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT); /* clear all pixels */
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_POLYGON); /* draw white polygon with corners at(0.25, 0.25, 0.0) and (0.75, 0.75, 0.0)*/
glVertex3f(0.25, 0.25, 0.0);
glVertex3f(0.75, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0);
glVertex3f(0.25, 0.75, 0.0);
glEnd();
glFlush(); /* start processing buffered OpenGL routines */
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0); /* select clearing color */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); /* initialize viewing values */
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); /*Declare initial display mode(single buffer and RGBA).*/
glutInitWindowSize(250, 250); /*Declare initial window size.*/
glutInitWindowPosition(100, 100); /*Declare initial window position.*/
glutCreateWindow("hello"); /*Open window with "hello"in its title bar.*/
init(); /*Call initialization routines.*/
glutDisplayFunc(display); /*Register callback function to display graphics.*/
glutMainLoop(); /*Enter main loop and process events.*/
return 0; /* ANSI C requires main to return int. */
}
| 40.947368 | 106 | 0.587404 | wuyudi |
060013ca6684d72925a5ed796ecf040827993dca | 20,470 | cpp | C++ | tools/OdometryViewer/main.cpp | jackiecx/rtabmap | e12b10b860a85872568180e11f5babd78bf266b0 | [
"BSD-3-Clause"
] | 1 | 2019-06-14T15:21:42.000Z | 2019-06-14T15:21:42.000Z | tools/OdometryViewer/main.cpp | jackiecx/rtabmap | e12b10b860a85872568180e11f5babd78bf266b0 | [
"BSD-3-Clause"
] | null | null | null | tools/OdometryViewer/main.cpp | jackiecx/rtabmap | e12b10b860a85872568180e11f5babd78bf266b0 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke 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 <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UEventsManager.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/core/Odometry.h>
#include <rtabmap/core/OdometryThread.h>
#include <rtabmap/gui/OdometryViewer.h>
#include <rtabmap/core/CameraThread.h>
#include <rtabmap/core/CameraRGBD.h>
#include <rtabmap/core/CameraStereo.h>
#include <rtabmap/core/DBReader.h>
#include <rtabmap/core/VWDictionary.h>
#include <QApplication>
#include <QPushButton>
#include <pcl/console/print.h>
void showUsage()
{
printf("\nUsage:\n"
"odometryViewer [options]\n"
"Options:\n"
" -driver # Driver number to use: 0=OpenNI-PCL, 1=OpenNI2, 2=Freenect, 3=OpenNI-CV, 4=OpenNI-CV-ASUS, 5=Freenect2, 6=dc1394, 7=FlyCapture2\n"
" -o # Odometry type (default 6): 0=SURF, 1=SIFT, 2=ORB, 3=FAST/FREAK, 4=FAST/BRIEF, 5=GFTT/FREAK, 6=GFTT/BRIEF, 7=BRISK\n"
" -nn # Nearest neighbor strategy (default 3): kNNFlannNaive=0, kNNFlannKdTree=1, kNNFlannLSH=2, kNNBruteForce=3, kNNBruteForceGPU=4\n"
" -nndr # Nearest neighbor distance ratio (default 0.7)\n"
" -flow Use optical flow odometry.\n"
" -icp Use ICP odometry\n"
" -mono Use Mono odometry\n"
"\n"
" -hz #.# Camera rate (default 0, 0 means as fast as the camera can)\n"
" -db \"input.db\" Use database instead of camera (recorded with rtabmap-dataRecorder)\n"
" -clouds # Maximum clouds shown (default 10, zero means inf)\n"
" -sec #.# Delay (seconds) before reading the database (if set)\n"
"\n"
" -in #.# Inliers maximum distance, features/ICP (default 0.01 m)\n"
" -max # Max features used for matching (default 0=inf)\n"
" -min # Minimum inliers to accept the transform (default 20)\n"
" -depth #.# Maximum features depth (default 5.0 m)\n"
" -i # RANSAC/ICP iterations (default 30)\n"
" -reset # Reset countdown (default 0 = disabled)\n"
" -gpu Use GPU\n"
" -lh # Local history (default 1000)\n"
"\n"
" -brief_bytes # BRIEF bytes (default 32)\n"
" -fast_thr # FAST threshold (default 30)\n"
"\n"
" -d # ICP decimation (default 4)\n"
" -v # ICP voxel size (default 0.005)\n"
" -s # ICP samples (default 0, not used if voxel is set.)\n"
" -cr #.# ICP correspondence ratio (default 0.7)\n"
" -p2p ICP point to point (default point to plane)"
"\n"
" -debug Log debug messages\n"
"\n"
"Examples:\n"
" odometryViewer -odom 0 -lh 5000 SURF example\n"
" odometryViewer -odom 1 -lh 10000 SIFT example\n"
" odometryViewer -odom 4 -nn 2 -lh 1000 FAST/BRIEF example\n"
" odometryViewer -odom 3 -nn 2 -lh 1000 FAST/FREAK example\n"
" odometryViewer -icp -in 0.05 -i 30 ICP example\n"
" odometryViewer -flow -in 0.02 Optical flow example\n");
exit(1);
}
int main (int argc, char * argv[])
{
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kInfo);
ULogger::setPrintTime(false);
ULogger::setPrintWhere(false);
// parse arguments
float rate = 0.0;
std::string inputDatabase;
int driver = 0;
int odomType = rtabmap::Parameters::defaultOdomFeatureType();
bool icp = false;
bool flow = false;
bool mono = false;
int nnType = rtabmap::Parameters::defaultOdomBowNNType();
float nndr = rtabmap::Parameters::defaultOdomBowNNDR();
float distance = rtabmap::Parameters::defaultOdomInlierDistance();
int maxWords = rtabmap::Parameters::defaultOdomMaxFeatures();
int minInliers = rtabmap::Parameters::defaultOdomMinInliers();
float maxDepth = rtabmap::Parameters::defaultOdomMaxDepth();
int iterations = rtabmap::Parameters::defaultOdomIterations();
int resetCountdown = rtabmap::Parameters::defaultOdomResetCountdown();
int decimation = 4;
float voxel = 0.005;
int samples = 10000;
float ratio = 0.7f;
int maxClouds = 10;
int briefBytes = rtabmap::Parameters::defaultBRIEFBytes();
int fastThr = rtabmap::Parameters::defaultFASTThreshold();
float sec = 0.0f;
bool gpu = false;
int localHistory = rtabmap::Parameters::defaultOdomBowLocalHistorySize();
bool p2p = false;
for(int i=1; i<argc; ++i)
{
if(strcmp(argv[i], "-driver") == 0)
{
++i;
if(i < argc)
{
driver = std::atoi(argv[i]);
if(driver < 0 || driver > 7)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-o") == 0)
{
++i;
if(i < argc)
{
odomType = std::atoi(argv[i]);
if(odomType < 0 || odomType > 6)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-nn") == 0)
{
++i;
if(i < argc)
{
nnType = std::atoi(argv[i]);
if(nnType < 0 || nnType > 4)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-nndr") == 0)
{
++i;
if(i < argc)
{
nndr = uStr2Float(argv[i]);
if(nndr < 0.0f)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-hz") == 0)
{
++i;
if(i < argc)
{
rate = uStr2Float(argv[i]);
if(rate < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-db") == 0)
{
++i;
if(i < argc)
{
inputDatabase = argv[i];
if(UFile::getExtension(inputDatabase).compare("db") != 0)
{
printf("Database path (%s) should end with \"db\" \n", inputDatabase.c_str());
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-clouds") == 0)
{
++i;
if(i < argc)
{
maxClouds = std::atoi(argv[i]);
if(maxClouds < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-sec") == 0)
{
++i;
if(i < argc)
{
sec = uStr2Float(argv[i]);
if(sec < 0.0f)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-in") == 0)
{
++i;
if(i < argc)
{
distance = uStr2Float(argv[i]);
if(distance <= 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-max") == 0)
{
++i;
if(i < argc)
{
maxWords = std::atoi(argv[i]);
if(maxWords < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-min") == 0)
{
++i;
if(i < argc)
{
minInliers = std::atoi(argv[i]);
if(minInliers < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-depth") == 0)
{
++i;
if(i < argc)
{
maxDepth = uStr2Float(argv[i]);
if(maxDepth < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-i") == 0)
{
++i;
if(i < argc)
{
iterations = std::atoi(argv[i]);
if(iterations <= 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-reset") == 0)
{
++i;
if(i < argc)
{
resetCountdown = std::atoi(argv[i]);
if(resetCountdown < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-d") == 0)
{
++i;
if(i < argc)
{
decimation = std::atoi(argv[i]);
if(decimation < 1)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-v") == 0)
{
++i;
if(i < argc)
{
voxel = uStr2Float(argv[i]);
if(voxel < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-s") == 0)
{
++i;
if(i < argc)
{
samples = std::atoi(argv[i]);
if(samples < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-cr") == 0)
{
++i;
if(i < argc)
{
ratio = uStr2Float(argv[i]);
if(ratio < 0.0f)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-gpu") == 0)
{
gpu = true;
continue;
}
if(strcmp(argv[i], "-lh") == 0)
{
++i;
if(i < argc)
{
localHistory = std::atoi(argv[i]);
if(localHistory < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-brief_bytes") == 0)
{
++i;
if(i < argc)
{
briefBytes = std::atoi(argv[i]);
if(briefBytes < 1)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-fast_thr") == 0)
{
++i;
if(i < argc)
{
fastThr = std::atoi(argv[i]);
if(fastThr < 1)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-icp") == 0)
{
icp = true;
continue;
}
if(strcmp(argv[i], "-flow") == 0)
{
flow = true;
continue;
}
if(strcmp(argv[i], "-mono") == 0)
{
mono = true;
continue;
}
if(strcmp(argv[i], "-p2p") == 0)
{
p2p = true;
continue;
}
if(strcmp(argv[i], "-debug") == 0)
{
ULogger::setLevel(ULogger::kDebug);
ULogger::setPrintTime(true);
ULogger::setPrintWhere(true);
continue;
}
printf("Unrecognized option : %s\n", argv[i]);
showUsage();
}
if(odomType > 1 && nnType == rtabmap::VWDictionary::kNNFlannKdTree)
{
UERROR("You set \"-o %d\" (binary descriptor), you must use \"-nn 2\" (any \"-nn\" other than kNNFlannKdTree)", odomType);
showUsage();
}
else if(odomType <= 1 && nnType == rtabmap::VWDictionary::kNNFlannLSH)
{
UERROR("You set \"-o %d\" (float descriptor), you must use \"-nn 1\" (any \"-nn\" other than kNNFlannLSH)", odomType);
showUsage();
}
if(inputDatabase.size())
{
UINFO("Using database input \"%s\"", inputDatabase.c_str());
}
else
{
UINFO("Using OpenNI camera");
}
std::string odomName;
if(odomType == 0)
{
odomName = "SURF";
}
else if(odomType == 1)
{
odomName = "SIFT";
}
else if(odomType == 2)
{
odomName = "ORB";
}
else if(odomType == 3)
{
odomName = "FAST+FREAK";
}
else if(odomType == 4)
{
odomName = "FAST+BRIEF";
}
else if(odomType == 5)
{
odomName = "GFTT+FREAK";
}
else if(odomType == 6)
{
odomName = "GFTT+BRIEF";
}
else if(odomType == 7)
{
odomName = "BRISK";
}
if(icp)
{
odomName= "ICP";
}
if(flow)
{
odomName= "Optical Flow";
}
std::string nnName;
if(nnType == 0)
{
nnName = "kNNFlannLinear";
}
else if(nnType == 1)
{
nnName = "kNNFlannKdTree";
}
else if(nnType == 2)
{
nnName= "kNNFlannLSH";
}
else if(nnType == 3)
{
nnName= "kNNBruteForce";
}
else if(nnType == 4)
{
nnName= "kNNBruteForceGPU";
}
UINFO("Odometry used = %s", odomName.c_str());
UINFO("Camera rate = %f Hz", rate);
UINFO("Maximum clouds shown = %d", maxClouds);
UINFO("Delay = %f s", sec);
UINFO("Max depth = %f", maxDepth);
UINFO("Reset odometry coutdown = %d", resetCountdown);
QApplication app(argc, argv);
rtabmap::Odometry * odom = 0;
rtabmap::ParametersMap parameters;
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomMaxDepth(), uNumber2Str(maxDepth)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomResetCountdown(), uNumber2Str(resetCountdown)));
if(!icp)
{
UINFO("Min inliers = %d", minInliers);
UINFO("Inlier maximum correspondences distance = %f", distance);
UINFO("RANSAC iterations = %d", iterations);
UINFO("Max features = %d", maxWords);
UINFO("GPU = %s", gpu?"true":"false");
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomInlierDistance(), uNumber2Str(distance)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomMinInliers(), uNumber2Str(minInliers)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomIterations(), uNumber2Str(iterations)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomMaxFeatures(), uNumber2Str(maxWords)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomFeatureType(), uNumber2Str(odomType)));
if(odomType == 0)
{
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kSURFGpuVersion(), uBool2Str(gpu)));
}
if(odomType == 2)
{
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kORBGpu(), uBool2Str(gpu)));
}
if(odomType == 3 || odomType == 4)
{
UINFO("FAST threshold = %d", fastThr);
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kFASTThreshold(), uNumber2Str(fastThr)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kFASTGpu(), uBool2Str(gpu)));
}
if(odomType == 4 || odomType == 6)
{
UINFO("BRIEF bytes = %d", briefBytes);
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kBRIEFBytes(), uNumber2Str(briefBytes)));
}
if(flow)
{
// Optical Flow
odom = new rtabmap::OdometryOpticalFlow(parameters);
}
else
{
//BOW
UINFO("Nearest neighbor = %s", nnName.c_str());
UINFO("Nearest neighbor ratio = %f", nndr);
UINFO("Local history = %d", localHistory);
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomBowNNType(), uNumber2Str(nnType)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomBowNNDR(), uNumber2Str(nndr)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomBowLocalHistorySize(), uNumber2Str(localHistory)));
if(mono)
{
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomPnPFlags(), uNumber2Str(0))); //CV_ITERATIVE
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomPnPReprojError(), "4.0"));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomIterations(), "100"));
odom = new rtabmap::OdometryMono(parameters);
}
else
{
odom = new rtabmap::OdometryBOW(parameters);
}
}
}
else if(icp) // ICP
{
UINFO("ICP maximum correspondences distance = %f", distance);
UINFO("ICP iterations = %d", iterations);
UINFO("Cloud decimation = %d", decimation);
UINFO("Cloud voxel size = %f", voxel);
UINFO("Cloud samples = %d", samples);
UINFO("Cloud correspondence ratio = %f", ratio);
UINFO("Cloud point to plane = %s", p2p?"false":"true");
odom = new rtabmap::OdometryICP(decimation, voxel, samples, distance, iterations, ratio, !p2p);
}
rtabmap::OdometryThread odomThread(odom);
rtabmap::OdometryViewer odomViewer(maxClouds, 2, 0.0, 50);
UEventsManager::addHandler(&odomThread);
UEventsManager::addHandler(&odomViewer);
odomViewer.setWindowTitle("Odometry view");
odomViewer.resize(1280, 480+QPushButton().minimumHeight());
if(inputDatabase.size())
{
rtabmap::DBReader camera(inputDatabase, rate, true);
if(camera.init())
{
odomThread.start();
if(sec > 0)
{
uSleep(sec*1000);
}
camera.start();
app.exec();
camera.join(true);
odomThread.join(true);
}
}
else
{
rtabmap::Camera * camera = 0;
rtabmap::Transform t=rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0);
if(driver == 0)
{
camera = new rtabmap::CameraOpenni("", rate, t);
}
else if(driver == 1)
{
if(!rtabmap::CameraOpenNI2::available())
{
UERROR("Not built with OpenNI2 support...");
exit(-1);
}
camera = new rtabmap::CameraOpenNI2("", rate, t);
}
else if(driver == 2)
{
if(!rtabmap::CameraFreenect::available())
{
UERROR("Not built with Freenect support...");
exit(-1);
}
camera = new rtabmap::CameraFreenect(0, rate, t);
}
else if(driver == 3)
{
if(!rtabmap::CameraOpenNICV::available())
{
UERROR("Not built with OpenNI from OpenCV support...");
exit(-1);
}
camera = new rtabmap::CameraOpenNICV(false, rate, t);
}
else if(driver == 4)
{
if(!rtabmap::CameraOpenNICV::available())
{
UERROR("Not built with OpenNI from OpenCV support...");
exit(-1);
}
camera = new rtabmap::CameraOpenNICV(true, rate, t);
}
else if(driver == 5)
{
if(!rtabmap::CameraFreenect2::available())
{
UERROR("Not built with Freenect2 support...");
exit(-1);
}
camera = new rtabmap::CameraFreenect2(0, rtabmap::CameraFreenect2::kTypeRGBDepthSD, rate, t);
}
else if(driver == 6)
{
if(!rtabmap::CameraStereoDC1394::available())
{
UERROR("Not built with dc1394 support...");
exit(-1);
}
camera = new rtabmap::CameraStereoDC1394(rate, t);
}
else if(driver == 7)
{
if(!rtabmap::CameraStereoFlyCapture2::available())
{
UERROR("Not built with FlyCapture2/Triclops support...");
exit(-1);
}
camera = new rtabmap::CameraStereoFlyCapture2(rate, t);
}
else
{
UFATAL("Camera driver (%d) not found!", driver);
}
//pcl::console::setVerbosityLevel(pcl::console::L_DEBUG);
if(camera->init())
{
if(camera->isCalibrated())
{
rtabmap::CameraThread cameraThread(camera);
cameraThread.setColorOnly(true);
odomThread.start();
cameraThread.start();
odomViewer.exec();
cameraThread.join(true);
odomThread.join(true);
}
else
{
printf("The camera is not calibrated! You should calibrate the camera first.\n");
delete camera;
}
}
else
{
printf("Failed to initialize the camera! Please select another driver (see \"--help\").\n");
delete camera;
}
}
return 0;
}
| 24.51497 | 162 | 0.566097 | jackiecx |
06007cf5ea31140d74a080ecadaee399d74c1b7d | 418 | cpp | C++ | src/ganon-classify/main.cpp | mdehollander/ganon | 3a0b87fcda1f47455b4eefc6c47989b0c601f16f | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/ganon-classify/main.cpp | mdehollander/ganon | 3a0b87fcda1f47455b4eefc6c47989b0c601f16f | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/ganon-classify/main.cpp | mdehollander/ganon | 3a0b87fcda1f47455b4eefc6c47989b0c601f16f | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include <ganon-classify/CommandLineParser.hpp>
#include <ganon-classify/GanonClassify.hpp>
#include <cstdlib>
#include <utility>
int main( int argc, char** argv )
{
if ( auto config = GanonClassify::CommandLineParser::parse( argc, argv ); config.has_value() )
{
return GanonClassify::run( std::move( config.value() ) ) ? EXIT_SUCCESS : EXIT_FAILURE;
}
return EXIT_FAILURE;
}
| 26.125 | 99 | 0.665072 | mdehollander |
0602d1109739d313e8640dfec91565a021e50a31 | 4,363 | cpp | C++ | Server/Shared/Database/src/MySQLReplDriver.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | 4 | 2015-08-17T20:12:22.000Z | 2020-05-30T19:53:26.000Z | Server/Shared/Database/src/MySQLReplDriver.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | null | null | null | Server/Shared/Database/src/MySQLReplDriver.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd 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 "MySQLReplDriver.h"
#include "StringUtility.h"
MySQLReplDriver::MySQLReplDriver(const char* host,
const char* database,
const char* user,
const char* password) :
MySQLDriver(host, database, user, password)
{
// split m_host into m_hosts
char* hostp;
char* hostCopy = StringUtility::newStrDup(m_host); // is const char
char* hostList = hostCopy;
while ((hostp = strchr(hostList, ','))) {
mc2dbg8 << "[MySQLReplDriver] found ',' points at: " << hostList << endl;
hostp[0] = '\0';
mc2dbg8 << "[MySQLReplDriver] fixup, points at: " << hostList << endl;
m_hosts.push_back(StringUtility::newStrDup(hostList));
hostList = hostp + 1;
}
m_hosts.push_back(StringUtility::newStrDup(hostList));
mc2dbg4 << "[MySQLReplDriver] " << m_hosts.size() << " DB hosts" << endl;
if (m_hosts.size() == 1) {
mc2log << warn << "[MySQLReplDriver] Only one DB host specified! "
"Continuing anyway." << endl;
}
delete [] hostCopy;
m_hostIter = m_hosts.begin();
m_host = *m_hostIter;
}
MySQLReplDriver::~MySQLReplDriver()
{
mc2dbg8 << "[MySQLReplDriver] Shutting down" << endl;
for (m_hostIter = m_hosts.begin(); m_hostIter != m_hosts.end(); m_hostIter++)
delete *m_hostIter;
m_hosts.erase(m_hosts.begin(), m_hosts.end());
}
bool
MySQLReplDriver::connect()
{
// try to connect to the current host first, then try the others,
// do any wrap-around
vector<const char*>::iterator start = m_hostIter;
bool allFailed = false;
mc2dbg8 << "[MySQLReplDriver] connecting, starting with: " << m_host << endl;
while (!MySQLDriver::connect() && !allFailed) {
++m_hostIter;
if (m_hostIter == m_hosts.end())
m_hostIter = m_hosts.begin();
if (m_hostIter == start) {
allFailed = true;
} else {
m_host = *m_hostIter;
mc2dbg8 << "[MySQLReplDriver] connect failed, trying next: "
<< m_host << endl;
}
}
if (allFailed) {
mc2log << error << "[MySQLReplDriver] Couldn't connect to any of the hosts! "
<< endl;
return false;
}
return true;
}
bool
MySQLReplDriver::ping()
{
if(MySQLDriver::ping()) {
return true;
} else {
// for now: if ping() fails, do a panic!!!
mc2log << fatal << "[MySQLReplDriver] Server gone!" << endl;
PANIC("[MySQLReplDriver] Emergency abort!", "");
return false;
}
}
int
MySQLReplDriver::getError(const void* result)
{
// we probably want to do driver specific checks here later
return MySQLDriver::getError(result);
}
const char*
MySQLReplDriver::getErrorString(const void* result)
{
// we probably want to do driver specific checks here later
return MySQLDriver::getErrorString(result);
}
| 40.027523 | 755 | 0.685079 | wayfinder |
06030ea4d9f1cf7b3c1d3dece9058db58eea34b4 | 930 | cpp | C++ | tests/sha3.cpp | calccrypto/Hashes | 4764d88bc71b4905141a208ab38f475cdc547f13 | [
"MIT"
] | 20 | 2016-01-10T13:53:41.000Z | 2022-01-28T02:09:07.000Z | tests/sha3.cpp | m0n0ph1/Hashes | 4764d88bc71b4905141a208ab38f475cdc547f13 | [
"MIT"
] | 1 | 2020-07-13T17:48:10.000Z | 2020-07-18T21:03:41.000Z | tests/sha3.cpp | m0n0ph1/Hashes | 4764d88bc71b4905141a208ab38f475cdc547f13 | [
"MIT"
] | 10 | 2017-05-15T16:25:59.000Z | 2022-02-03T15:31:11.000Z | #include <gtest/gtest.h>
#include "Hashes/SHA3.h"
#include "testvectors/sha/sha3.h"
TEST(SHA3, 224) {
EXPECT_EQ(SHA3 <224> ().blocksize(), (std::size_t) (1600 - 2 * 224));
EXPECT_EQ(SHA3 <224> ().digestsize(), (std::size_t) 224);
hash_test <SHA3 <224> > (SHA3_224_TEST_VECTORS);
}
TEST(SHA3, 256) {
EXPECT_EQ(SHA3 <256> ().blocksize(), (std::size_t) (1600 - 2 * 256));
EXPECT_EQ(SHA3 <256> ().digestsize(), (std::size_t) 256);
hash_test <SHA3 <256> > (SHA3_256_TEST_VECTORS);
}
TEST(SHA3, 384) {
EXPECT_EQ(SHA3 <384> ().blocksize(), (std::size_t) (1600 - 2 * 384));
EXPECT_EQ(SHA3 <384> ().digestsize(), (std::size_t) 384);
hash_test <SHA3 <384> > (SHA3_384_TEST_VECTORS);
}
TEST(SHA3, 512) {
EXPECT_EQ(SHA3 <512> ().blocksize(), (std::size_t) (1600 - 2 * 512));
EXPECT_EQ(SHA3 <512> ().digestsize(), (std::size_t) 512);
hash_test <SHA3 <512> > (SHA3_512_TEST_VECTORS);
}
| 31 | 74 | 0.617204 | calccrypto |
06031ab3f7243c4b39fc73cef0753cbe41dcea31 | 5,756 | cpp | C++ | test/timer/timer2/main.cpp | 6923403/C | d365021759e6d9078254b4b7b6455e0408e4b691 | [
"MIT"
] | 1 | 2020-10-01T14:52:45.000Z | 2020-10-01T14:52:45.000Z | test/timer/timer2/main.cpp | 6923403/C | d365021759e6d9078254b4b7b6455e0408e4b691 | [
"MIT"
] | 3 | 2020-06-19T01:24:51.000Z | 2020-07-16T14:00:30.000Z | test/timer/timer2/main.cpp | 6923403/C | d365021759e6d9078254b4b7b6455e0408e4b691 | [
"MIT"
] | null | null | null | #include <pthread.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include "lst_timer.h"
const int FD_LIMIT = 65535;
const int MAX_EVENT_NUM = 1024;
const int TIMESLOT = 5;
static int pipefd[2];
static lst_timer timer_lst;
static int epollfd = 0;
void setnoblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd)
{
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET;
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &evnt);
setnoblocking(fd);
}
void addsig(int sig)
{
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = sighandler;
sa.sa_flags |= SA_RESTART;
sigfillset(&sa.sa_mask);
assert(sigaction(sig, &sa, nullptr) != -1);
}
void timer_handler()
{
timer_lst.tick();
alarm(TIMESLOT);
}
void cb_func(client_data *user_data)
{
epoll_ctl(epollfd, EPOLL_CTL_DEL, user_data->sockfd, 0);
assert(user_data);
close(user_data->sockfd);
std::cout << "close fd = " << user_data->sockfd << std::endl;
}
int main(int argc, char **argv)
{
int port = 20999;
int ret = 0;
struct sockaddr_in address;
memset(&address, 0, sizeof(s_addr));
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
int ret = 0;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd >= 0);
ret = bind(sockfd, (struct sockaddr_in*) &address, sizeof(address));
assert(ret != -1);
ret = listen(sockfd, 5);
assert(ret != -1);
epoll_event events[MAX_EVENT_NUM];
int epollfd = epoll_create(5);
assert(epollfd != -1);
addfd(epollfd, sockfd);
ret = socketpair(AF_UNIX, SOCK_STREAM, 0, pipefd);
assert(ret != -1);
setnoblocking(pipefd[1]);
addfd(epollfd, pipefd[0]);
addsig(SIGALRM);
addsig(SIGTERM);
bool stop_server = false;
client_data *users = new client_data[FD_LIMIT];
bool timeout = false;
alarm(TIMESLOT);
while(!stop_server)
{
int number = epoll_wait(epollfd, events, MAX_EVENT_NUM - 1);
if((number < 0) && (errno != EINTR))
{
std::cout << "epoll failure" << std::endl;
break;
}
for(int i = 0; i < number; i++)
{
int m_sockfd = events[i].data.fd;
if(m_sockfd == sockfd)
{
/*
* 新用户请求
*/
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int connfd = accept(sockfd, (struct sockaddr*) &client_addr, &client_addr_len);
addfd(epollfd, connfd);
users[connfd].address = client_addr;
users[connfd].sockfd = connfd;
util_timer *timer = new util_timer;
timer->user_data = &users[connfd];
timer->cb_func = cb_func;
time_t cur = time(NULL);
timer->expire = cur + 3 * TIMESLOT;
users[connfd].timer = timer;
timer_lst.add_timer(timer);
}
/*
* 处理信号
*/
else if((m_sockfd == pipefd[0]) && (events.events & EPOLLIN))
{
int sig;
char signals[1024];
ret = recv(pipefd[0], signals, sizeof(signals), 0);
if(ret == -1)
{
continue;
}
else if(ret == 0)
{
continue;
}
else
{
for(int i = 0; i < ret; i++)
{
switch (signals[i])
{
case SIGALRM:
timeout = true;
break;
case SIGTERM:
stop_server = true;
}
}
}
}
else if(events[i].events & EPOLLIN) {
memset(users[m_sockfd].buf, '\0', BUF_SIZE);
ret = recv(m_sockfd, users[m_sockfd].buf, BUF_SIZE - 1, 0);
std::cout << "get " << ret << " bytes if client data " << users[m_sockfd].buf << " from " << m_sockfd
<< std::endl;
util_timer *timer = users[m_sockfd].timer;
if (ret < 0) {
//发生读错误 关闭连接 移除定时器
if (errno != EAGAIN) {
cb_func(&users[sockfd]);
if (timer) {
timer_lst.del_timer(timer);
}
}
} else if (ret == 0) {
//关闭连接 移除定时器
cb_func(&users[sockfd]);
if (timer) {
timer_lst.del_timer(timer);
}
} else {
if (timer) {
time_t cur = time(nullptr);
timer->expire = cur + 3 + TIMESLOT;
std::cout << "addjust_timer once " << std::endl;
timer_lst.adjust_tiimer(timer);
}
}
}
else
{
continue;
}
}
if(timeout)
{
tiimer_handler();
timeout = false;
}
}
return 0;
} | 28.49505 | 117 | 0.465775 | 6923403 |
0605dd3228416c3c48a47a7a8707d3c5cb88e37f | 997 | cpp | C++ | dataset/test/modification/1466_all/24/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1466_all/24/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1466_all/24/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void iev_mv()
;
int main()
;
void r() {
int ky_fzo;
cin >> ky_fzo;
int kxt[ky_fzo];
map<int, int> keo;
{
int ow = 0;
if (5 > 3) cout << "new code";for ( ; ow < ky_fzo; )
/* 'for' inside */
{
cin >> kxt[ow];
ow++;
}}
sort(kxt, kxt + ky_fzo);
{
int xev = 1;
if (5 > 3) cout << "new code";for ( ; xev < ky_fzo; )
/* 'for' inside */
{
/* 'if' begin */
if (kxt[xev] <= kxt[xev - 1])
/* 'if' inside */
kxt[xev]++;
xev++;
}}
{
int vr_o = 0;
if (5 > 3) cout << "new code";for ( ; vr_o < ky_fzo; )
/* 'for' inside */
{
keo[kxt[vr_o]]++;
vr_o++;
}}
cout << keo.size() << endl;
}
int main() {
int wew = 1;
cin >> wew;
if (5 > 3) cout << "new code";for ( ; wew--; )
/* 'for' inside */
{
r();
}
return 0;
}
| 15.338462 | 59 | 0.408225 | Karina5005 |
060b83e07c1257e5b4098b32de1b9fe5ccf76a36 | 1,010 | cpp | C++ | modules/gin_metadata/gin_metadata.cpp | peterrudenko/Gin | 449c4c6b83fbec91070dc87d124c60a7d1f8c0a5 | [
"BSD-3-Clause"
] | null | null | null | modules/gin_metadata/gin_metadata.cpp | peterrudenko/Gin | 449c4c6b83fbec91070dc87d124c60a7d1f8c0a5 | [
"BSD-3-Clause"
] | null | null | null | modules/gin_metadata/gin_metadata.cpp | peterrudenko/Gin | 449c4c6b83fbec91070dc87d124c60a7d1f8c0a5 | [
"BSD-3-Clause"
] | null | null | null | /*==============================================================================
Copyright 2018 by Roland Rabien
For more information visit www.rabiensoftware.com
==============================================================================*/
// Your project must contain an AppConfig.h file with your project-specific settings in it,
// and your header search path must make it accessible to the module's files.
#include "AppConfig.h"
#ifdef _WIN32
#include <Windows.h>
#include <ctime>
#endif
//==============================================================================
#include "gin_metadata.h"
//==============================================================================
namespace gin
{
using namespace juce;
using juce::Rectangle;
using juce::MemoryBlock;
#include "metadata/libjpegpng.cpp"
#include "metadata/commentmetadata.cpp"
#include "metadata/exifmetadata.cpp"
#include "metadata/imagemetadata.cpp"
#include "metadata/iptcmetadata.cpp"
#include "metadata/xmpmetadata.cpp"
}
| 26.578947 | 91 | 0.526733 | peterrudenko |
060c5679378209dd375f26dfcd5fb005acb9cdb0 | 622 | cpp | C++ | CodeChef/Practice/GDOG.cpp | ysumit99/Compi-Coding | d0e96c4f024328b0bfb799fab927919dae367f7a | [
"MIT"
] | 1 | 2019-04-19T13:06:33.000Z | 2019-04-19T13:06:33.000Z | CodeChef/Practice/GDOG.cpp | ysumit99/Compi-Coding | d0e96c4f024328b0bfb799fab927919dae367f7a | [
"MIT"
] | null | null | null | CodeChef/Practice/GDOG.cpp | ysumit99/Compi-Coding | d0e96c4f024328b0bfb799fab927919dae367f7a | [
"MIT"
] | null | null | null | //https://www.codechef.com/problems/GDOG
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
#ifdef DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base ::sync_with_stdio(false);
cin.tie(0);
int t, n, k;
cin >> t;
while (t--)
{
cin >> n >> k;
int max = INT_MIN, temp;
for (int i = 1; i <= k; i++)
{
temp = n - (n / i) * i;
if (temp > max)
{
max = temp;
}
}
cout << max << endl;
}
return 0;
} | 16.368421 | 40 | 0.442122 | ysumit99 |
060d7013508e95574467d57a0846b6e1430e8552 | 282 | cc | C++ | Part-III/Ch13/13.1.1/13.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | 1 | 2021-09-23T13:13:12.000Z | 2021-09-23T13:13:12.000Z | Part-III/Ch13/13.1.1/13.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | Part-III/Ch13/13.1.1/13.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | #include <string>
class HasPtr
{
public:
HasPtr(const std::string &s = std::string())
: ps(new std::string(s)), i(0)
{}
HasPtr(const HasPtr &has_ptr)
: ps(new std::string(*(has_ptr.ps))), i(has_ptr.i)
{}
private:
std::string *ps;
int i;
}; | 16.588235 | 58 | 0.549645 | RingZEROtlf |
06117e726c94d35380790a0ef0f9360a84eef171 | 692 | cpp | C++ | q11727.cpp | abraxaslee/ACM-ICPC | d8db31a4a2a36258bfba42a806b02bbf3eceaf2b | [
"MIT"
] | 1 | 2018-03-19T05:18:49.000Z | 2018-03-19T05:18:49.000Z | q11727.cpp | abraxaslee/ACM-ICPC | d8db31a4a2a36258bfba42a806b02bbf3eceaf2b | [
"MIT"
] | null | null | null | q11727.cpp | abraxaslee/ACM-ICPC | d8db31a4a2a36258bfba42a806b02bbf3eceaf2b | [
"MIT"
] | null | null | null | //q11727.cpp - 2011/10/11
//accepted at 2011/10/11
//run time = 0.000
#include <stdio.h>
using namespace std;
int salary[3] = {};
int top = 0;
void sort(int inputNum){
int i;
for(i = top-1; i >= 0 && salary[i] > inputNum; i--){
salary[i+1] = salary[i];
}
i += 1;
salary[i] = inputNum;
top += 1;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("q11727.in", "r", stdin);
freopen("q11727.out", "w", stdout);
#endif
int caseNum, currentCase = 0, tmp;
scanf("%d", &caseNum);
while(caseNum-- > 0){
top = 0;
for(int j=0;j<3;j++){
scanf("%d", &tmp);
sort(tmp);
}
printf("Case %d: %d\n", ++currentCase, salary[1]);
}
return 0;
}
| 17.3 | 54 | 0.537572 | abraxaslee |
061295877e030725b0c744e3b0f7f87cf9c89944 | 2,133 | cpp | C++ | C++/Data Structure/Tree.cpp | tanisha-bhadani/hacktoberfest2021-1 | faa1a0fe6b20459162cf9f6cb207f898a58aa54f | [
"MIT"
] | 380 | 2021-10-01T10:22:20.000Z | 2022-03-06T14:34:22.000Z | C++/Data Structure/Tree.cpp | tanisha-bhadani/hacktoberfest2021-1 | faa1a0fe6b20459162cf9f6cb207f898a58aa54f | [
"MIT"
] | 146 | 2021-10-01T09:49:54.000Z | 2022-01-20T14:40:52.000Z | C++/Data Structure/Tree.cpp | tanisha-bhadani/hacktoberfest2021-1 | faa1a0fe6b20459162cf9f6cb207f898a58aa54f | [
"MIT"
] | 1,335 | 2021-10-01T10:00:18.000Z | 2022-03-03T20:07:35.000Z | #include<iostream>
#include<queue>
using namespace std;
class SinglyLinkedListNode {
public:
char key;
SinglyLinkedListNode * left;
SinglyLinkedListNode * right;
SinglyLinkedListNode(char node_data) {
this -> key = node_data;
this -> left = NULL;
this -> right = NULL;
}
};
class SinglyLinkedList {
public:
SinglyLinkedListNode * root;
queue q;
SinglyLinkedList() {
this -> root = NULL;
}
void insert_node_left(char node_data, SinglyLinkedListNode * ptr ) {
/*code to insert new node at the end in linked list having node_data*/
this -> tail -> next = ptr1;
this -> tail = ptr1;
}
};
void print_singly_linked_list(SinglyLinkedListNode * node) {
/*code to print linked list separated by single space*/
SinglyLinkedListNode * walker = node;
while (walker != NULL) {
cout << walker -> data << " ";
walker = walker -> next;
}
cout<<endl;
}
SinglyLinkedListNode * removeDuplicates(SinglyLinkedListNode * head) {
/*code to remove duplicates*/
SinglyLinkedListNode * w1 = head;
SinglyLinkedListNode * w2 = head -> next;
while (w2 != NULL) {
if (w1 -> data == w2 -> data) {
SinglyLinkedListNode * temp = w2;
w2 = w2 -> next;
w1 -> next = w2;
delete temp;
} else {
w1 = w1 -> next;
w2 = w2 -> next;
}
}
return head;
}
int main() {
int test_cases;
cin >> test_cases;
SinglyLinkedListNode * listfinal[test_cases];
for (int i = 0; i < test_cases; i++) {
SinglyLinkedList * LS = new SinglyLinkedList();
/*code to read input and insert node in linked list*/
int num_node;
cin >> num_node;
for (int a = 0; a < num_node; a++) {
int value;
cin >> value;
if (a == 0) {
SinglyLinkedListNode * ptr = new SinglyLinkedListNode(value);
LS -> head = ptr;
LS -> tail = ptr;
} else {
LS -> insert_node(value);
}
}
LS -> head = removeDuplicates(LS -> head);
listfinal[i] = LS -> head;
}
for (int i = 0; i < test_cases; i++) {
print_singly_linked_list(listfinal[i]);
cout << endl;
}
return 0;
}
| 22.935484 | 74 | 0.601969 | tanisha-bhadani |
061303968b4bb3db66ec033910e2e33fc93fb898 | 73,441 | cpp | C++ | Core/burn/drv/dataeast/d_rohga.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 17 | 2018-05-24T05:20:45.000Z | 2021-12-24T07:27:22.000Z | Core/burn/drv/dataeast/d_rohga.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 6 | 2016-10-20T02:36:07.000Z | 2017-03-08T15:23:06.000Z | Core/burn/drv/dataeast/d_rohga.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 5 | 2019-01-21T00:45:00.000Z | 2021-07-20T08:34:22.000Z | // FB Alpha Rohga Armor Force / Wizard Fire / Nitro Ball / Schmeiser Robo driver module
// Based on MAME driver by Bryan McPhail
#include "tiles_generic.h"
#include "m68000_intf.h"
#include "h6280_intf.h"
#include "deco16ic.h"
#include "msm6295.h"
#include "burn_ym2151.h"
static UINT8 *AllMem;
static UINT8 *MemEnd;
static UINT8 *AllRam;
static UINT8 *RamEnd;
static UINT8 *Drv68KROM;
static UINT8 *DrvHucROM;
static UINT8 *DrvGfxROM0;
static UINT8 *DrvGfxROM1;
static UINT8 *DrvGfxROM2;
static UINT8 *DrvGfxROM3;
static UINT8 *DrvGfxROM4;
static UINT8 *DrvSndROM0;
static UINT8 *DrvSndROM1;
static UINT8 *Drv68KRAM;
static UINT8 *DrvHucRAM;
static UINT8 *DrvPalRAM;
static UINT8 *DrvPalBuf;
static UINT8 *DrvSprRAM;
static UINT8 *DrvSprRAM2;
static UINT8 *DrvSprBuf;
static UINT8 *DrvSprBuf2;
static UINT8 *DrvPrtRAM;
static UINT32 *DrvPalette;
static UINT8 DrvRecalc;
static UINT8 *flipscreen;
static UINT8 DrvJoy1[16];
static UINT8 DrvJoy2[16];
static UINT8 DrvJoy3[16];
static UINT8 DrvDips[3];
static UINT8 DrvReset;
static UINT16 DrvInputs[4];
static UINT16 *tempdraw[2];
static INT32 DrvOkiBank;
static struct BurnInputInfo RohgaInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3" },
{"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" },
{"P2 Button 3", BIT_DIGITAL, DrvJoy1 + 14, "p2 fire 3" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
{"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" },
};
STDINPUTINFO(Rohga)
static struct BurnInputInfo WizdfireInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
};
STDINPUTINFO(Wizdfire)
static struct BurnInputInfo NitrobalInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" },
{"P3 Coin", BIT_DIGITAL, DrvJoy3 + 7, "p3 coin" },
{"P3 Up", BIT_DIGITAL, DrvJoy3 + 0, "p3 up" },
{"P3 Down", BIT_DIGITAL, DrvJoy3 + 1, "p3 down" },
{"P3 Left", BIT_DIGITAL, DrvJoy3 + 2, "p3 left" },
{"P3 Right", BIT_DIGITAL, DrvJoy3 + 3, "p3 right" },
{"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p3 fire 1" },
{"P3 Button 2", BIT_DIGITAL, DrvJoy3 + 5, "p3 fire 2" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
};
STDINPUTINFO(Nitrobal)
static struct BurnDIPInfo RohgaDIPList[]=
{
{0x14, 0xff, 0xff, 0xff, NULL },
{0x15, 0xff, 0xff, 0x7f, NULL },
{0x16, 0xff, 0xff, 0xff, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x14, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x14, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x14, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x14, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x14, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x14, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x14, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x14, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x14, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x14, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x14, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x14, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x14, 0x01, 0x40, 0x40, "Off" },
{0x14, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" },
{0x14, 0x01, 0x80, 0x80, "Off" },
{0x14, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Player's Vitality" },
{0x15, 0x01, 0x30, 0x30, "Normal" },
{0x15, 0x01, 0x30, 0x20, "Low" },
{0x15, 0x01, 0x30, 0x10, "Lowest" },
{0x15, 0x01, 0x30, 0x00, "High" },
{0 , 0xfe, 0 , 2, "Allow Continue" },
{0x15, 0x01, 0x40, 0x40, "Off" },
{0x15, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x15, 0x01, 0x80, 0x80, "Off" },
{0x15, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Stage Clear Bonus" },
{0x16, 0x01, 0x01, 0x01, "Off" },
{0x16, 0x01, 0x01, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Enemy's Vitality" },
{0x16, 0x01, 0x0c, 0x08, "Low" },
{0x16, 0x01, 0x0c, 0x0c, "Normal" },
{0x16, 0x01, 0x0c, 0x04, "High" },
{0x16, 0x01, 0x0c, 0x00, "Highest" },
{0 , 0xfe, 0 , 4, "Enemy Encounter Rate" },
{0x16, 0x01, 0x30, 0x20, "Low" },
{0x16, 0x01, 0x30, 0x30, "Normal" },
{0x16, 0x01, 0x30, 0x10, "High" },
{0x16, 0x01, 0x30, 0x00, "Highest" },
{0 , 0xfe, 0 , 4, "Enemy's Weapon Speed" },
{0x16, 0x01, 0xc0, 0x80, "Slow" },
{0x16, 0x01, 0xc0, 0xc0, "Normal" },
{0x16, 0x01, 0xc0, 0x40, "Fast" },
{0x16, 0x01, 0xc0, 0x00, "Fastest" },
};
STDDIPINFO(Rohga)
static struct BurnDIPInfo SchmeisrDIPList[]=
{
{0x14, 0xff, 0xff, 0xff, NULL },
{0x15, 0xff, 0xff, 0xff, NULL },
{0x16, 0xff, 0xff, 0xff, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x14, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x14, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x14, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x14, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x14, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x14, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x14, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x14, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x14, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x14, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x14, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x14, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x14, 0x01, 0x40, 0x40, "Off" },
{0x14, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Service Mode" },
{0x14, 0x01, 0x80, 0x80, "Off" },
{0x14, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x15, 0x01, 0x04, 0x00, "Off" },
{0x15, 0x01, 0x04, 0x04, "On" },
{0 , 0xfe, 0 , 2, "Freeze Screen" },
{0x16, 0x01, 0x20, 0x20, "Off" },
{0x16, 0x01, 0x20, 0x00, "On" },
};
STDDIPINFO(Schmeisr)
static struct BurnDIPInfo WizdfireDIPList[]=
{
{0x12, 0xff, 0xff, 0xff, NULL },
{0x13, 0xff, 0xff, 0x7f, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x12, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x12, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x12, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x12, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x12, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x12, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x12, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x12, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x12, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x12, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x12, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x12, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x12, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x12, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x12, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x12, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x12, 0x01, 0x40, 0x40, "Off" },
{0x12, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" },
{0x12, 0x01, 0x80, 0x80, "Off" },
{0x12, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x13, 0x01, 0x03, 0x00, "2" },
{0x13, 0x01, 0x03, 0x01, "3" },
{0x13, 0x01, 0x03, 0x03, "4" },
{0x13, 0x01, 0x03, 0x02, "5" },
{0 , 0xfe, 0 , 4, "Difficulty" },
{0x13, 0x01, 0x0c, 0x08, "Easy" },
{0x13, 0x01, 0x0c, 0x0c, "Normal" },
{0x13, 0x01, 0x0c, 0x04, "Hard" },
{0x13, 0x01, 0x0c, 0x00, "Hardest" },
{0 , 0xfe, 0 , 4, "Magic Gauge Speed" },
{0x13, 0x01, 0x30, 0x00, "Very Slow" },
{0x13, 0x01, 0x30, 0x10, "Slow" },
{0x13, 0x01, 0x30, 0x30, "Normal" },
{0x13, 0x01, 0x30, 0x20, "Fast" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x13, 0x01, 0x80, 0x80, "Off" },
{0x13, 0x01, 0x80, 0x00, "On" },
};
STDDIPINFO(Wizdfire)
static struct BurnDIPInfo NitrobalDIPList[]=
{
{0x19, 0xff, 0xff, 0xff, NULL },
{0x1a, 0xff, 0xff, 0x7f, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x19, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x19, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x19, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x19, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x19, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x19, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x19, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x19, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x19, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x19, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x19, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x19, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x19, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x19, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x19, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x19, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x19, 0x01, 0x40, 0x40, "Off" },
{0x19, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" },
{0x19, 0x01, 0x80, 0x80, "Off" },
{0x19, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x1a, 0x01, 0x03, 0x01, "1" },
{0x1a, 0x01, 0x03, 0x00, "2" },
{0x1a, 0x01, 0x03, 0x03, "3" },
{0x1a, 0x01, 0x03, 0x02, "4" },
{0 , 0xfe, 0 , 4, "Difficulty?" },
{0x1a, 0x01, 0x0c, 0x08, "Easy" },
{0x1a, 0x01, 0x0c, 0x0c, "Normal" },
{0x1a, 0x01, 0x0c, 0x04, "Hard" },
{0x1a, 0x01, 0x0c, 0x00, "Hardest" },
{0 , 0xfe, 0 , 2, "Split Coin Chutes" },
{0x1a, 0x01, 0x10, 0x10, "Off" },
{0x1a, 0x01, 0x10, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Players" },
{0x1a, 0x01, 0x20, 0x20, "2" },
{0x1a, 0x01, 0x20, 0x00, "3" },
{0 , 0xfe, 0 , 2, "Shot Button to Start" },
{0x1a, 0x01, 0x40, 0x40, "Off" },
{0x1a, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x1a, 0x01, 0x80, 0x80, "Off" },
{0x1a, 0x01, 0x80, 0x00, "On" },
};
STDDIPINFO(Nitrobal)
void __fastcall rohga_main_write_word(UINT32 address, UINT16 data)
{
deco16_write_control_word(0, address, 0x200000, data)
deco16_write_control_word(1, address, 0x240000, data)
switch (address)
{
case 0x2800a8:
deco16_soundlatch = data & 0xff;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
case 0x300000:
memcpy (DrvSprBuf2, DrvSprBuf, 0x800);
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x31000a:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x321100: // schmeisr
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0x322000:
deco16_priority = data;
return;
}
if ((address & 0xffff000) == 0x280000) {
deco16_104_rohga_prot_w(address, data, 0xffff);
return;
}
}
void __fastcall rohga_main_write_byte(UINT32 address, UINT8 data)
{
switch (address)
{
case 0x2800a9:
deco16_soundlatch = data;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
case 0x300000:
case 0x300001:
memcpy (DrvSprBuf2, DrvSprBuf, 0x800);
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x31000a:
case 0x31000b:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x321100: // schmeisr
case 0x321101:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0x322000:
case 0x322001:
deco16_priority = data;
return;
}
if ((address & 0xffff000) == 0x280000) {
deco16_104_rohga_prot_w(address, data, 0x00ff << ((address & 1) << 3));
return;
}
}
UINT16 __fastcall rohga_main_read_word(UINT32 address)
{
switch (address)
{
case 0x2c0000:
case 0x300000: // schmeisr
return DrvDips[2];
case 0x310002: // schmeisr
return (DrvInputs[1] & 0x07) | (deco16_vblank & 0x08);
case 0x321100:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return 0;
}
if ((address & 0xffff000) == 0x280000) {
return deco16_104_rohga_prot_r(address);
}
return 0;
}
UINT8 __fastcall rohga_main_read_byte(UINT32 address)
{
switch (address)
{
case 0x2c0000:
case 0x2c0001:
case 0x300000: // schmeisr
case 0x300001:
return DrvDips[2];
case 0x310002: // schmeisr
case 0x310003:
return (DrvInputs[1] & 0x07) | (deco16_vblank & 0x08);
case 0x321100:
case 0x321101:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return 0;
}
if ((address & 0xffff000) == 0x280000) {
return deco16_104_rohga_prot_r(address) >> ((~address & 1) << 3);
}
return 0;
}
void __fastcall wizdfire_main_write_word(UINT32 address, UINT16 data)
{
deco16_write_control_word(0, address, 0x300000, data)
deco16_write_control_word(1, address, 0x310000, data)
switch (address)
{
case 0x350000:
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x370000:
memcpy (DrvSprBuf2, DrvSprRAM2, 0x800);
return;
case 0x380008:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x320000:
deco16_priority = data;
return;
case 0x320004:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0xfe4150:
case 0xff4260: // nitrobal
case 0xff4a60:
deco16_soundlatch = data & 0xff;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
}
if ((address & 0xffff000) == 0xfe4000) {
deco16_prot_ram[(address & 0x7ff)/2] = data;
return;
}
if ((address & 0xffff000) == 0xff4000) {
deco16_146_nitroball_prot_w(address, data, 0xffff);
return;
}
}
void __fastcall wizdfire_main_write_byte(UINT32 address, UINT8 data)
{
switch (address)
{
case 0x350000:
case 0x350001:
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x370000:
case 0x370001:
memcpy (DrvSprBuf2, DrvSprRAM2, 0x800);
return;
case 0x380008:
case 0x380009:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x320000:
case 0x320001:
deco16_priority = data;
return;
case 0x320004:
case 0x320005:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0xfe4151:
case 0xff4261: // nitrobal
case 0xff4a61:
deco16_soundlatch = data;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
}
if ((address & 0xffff000) == 0xfe4000) {
DrvPrtRAM[(address & 0x7ff)^1] = data;
return;
}
if ((address & 0xffff000) == 0xff4000) {
deco16_146_nitroball_prot_w(address, data, 0x00ff << ((address & 1) << 3));
return;
}
}
UINT16 __fastcall wizdfire_main_read_word(UINT32 address)
{
if (address == 0x320000) return DrvInputs[2];
if ((address & 0xffff800) == 0xfe4000) {
return deco16_104_prot_r(address);
}
if ((address & 0xffff000) == 0xff4000) {
return deco16_146_nitroball_prot_r(address);
}
return 0;
}
UINT8 __fastcall wizdfire_main_read_byte(UINT32 address)
{
if (address == 0x320000 || address == 0x320001) return DrvInputs[2] >> ((~address & 1) << 3);
if ((address & 0xffff800) == 0xfe4000) {
return deco16_104_prot_r(address) >> ((~address & 1) << 3);
}
if ((address & 0xffff000) == 0xff4000) {
return deco16_146_nitroball_prot_r(address) >> ((~address & 1) << 3);
}
return 0;
}
static void DrvYM2151WritePort(UINT32, UINT32 data)
{
if ((data & 0x01) != (UINT32)(DrvOkiBank & 0x01)) {
memcpy (DrvSndROM0, DrvSndROM0 + 0x40000 + ((data & 0x01) >> 0) * 0x40000, 0x40000);
}
if ((data & 0x02) != (UINT32)(DrvOkiBank & 0x02)) {
memcpy (DrvSndROM1, DrvSndROM1 + 0x40000 + ((data & 0x02) >> 1) * 0x40000, 0x40000);
}
DrvOkiBank = data;
}
static INT32 rohga_bank_callback( const INT32 bank )
{
return ((bank >> 4) & 0x3) << 12;
}
static INT32 DrvDoReset()
{
memset (AllRam, 0, RamEnd - AllRam);
SekOpen(0);
SekReset();
SekClose();
deco16SoundReset();
deco16Reset();
DrvOkiBank = -1;
DrvYM2151WritePort(0, 3);
return 0;
}
static INT32 MemIndex()
{
UINT8 *Next; Next = AllMem;
Drv68KROM = Next; Next += 0x200000;
DrvHucROM = Next; Next += 0x010000;
DrvGfxROM0 = Next; Next += 0x080000;
DrvGfxROM1 = Next; Next += 0x400000;
DrvGfxROM2 = Next; Next += 0x400000;
DrvGfxROM3 = Next; Next += 0x800000;
DrvGfxROM4 = Next; Next += 0x100000;
MSM6295ROM = Next;
DrvSndROM0 = Next; Next += 0x100000;
DrvSndROM1 = Next; Next += 0x0c0000;
tempdraw[0] = (UINT16*)Next; Next += 320 * 240 * sizeof(UINT16);
tempdraw[1] = (UINT16*)Next; Next += 320 * 240 * sizeof(UINT16);
DrvPalette = (UINT32*)Next; Next += 0x0800 * sizeof(UINT32);
AllRam = Next;
Drv68KRAM = Next; Next += 0x024000;
DrvHucRAM = Next; Next += 0x002000;
DrvSprRAM2 = Next; Next += 0x000800;
DrvSprRAM = Next; Next += 0x000800;
DrvSprBuf2 = Next; Next += 0x000800;
DrvSprBuf = Next; Next += 0x000800;
deco16_prot_ram = (UINT16*)Next;
DrvPrtRAM = Next; Next += 0x000800;
deco16_buffer_ram = (UINT16*)Next; Next += 0x000800;
DrvPalRAM = Next; Next += 0x002000;
DrvPalBuf = Next; Next += 0x002000;
flipscreen = Next; Next += 0x000001;
RamEnd = Next;
MemEnd = Next;
return 0;
}
static INT32 DrvSpriteDecode()
{
INT32 Plane[6] = { 0x400000*8+8, 0x400000*8, 0x200000*8+8, 0x200000*8, 8, 0 };
INT32 XOffs[16] = { 7,6,5,4,3,2,1,0, 32*8+7, 32*8+6, 32*8+5, 32*8+4, 32*8+3, 32*8+2, 32*8+1, 32*8+0 };
INT32 YOffs[16] = { 15*16, 14*16, 13*16, 12*16, 11*16, 10*16, 9*16, 8*16, 7*16, 6*16, 5*16, 4*16, 3*16, 2*16, 1*16, 0*16};
UINT8 *tmp = (UINT8*)BurnMalloc(0x600000);
if (tmp == NULL) {
return 1;
}
memcpy (tmp, DrvGfxROM3, 0x600000);
GfxDecode(0x8000, 6, 16, 16, Plane, XOffs, YOffs, 0x200, tmp, DrvGfxROM3);
BurnFree (tmp);
return 0;
}
static INT32 RohgaInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x100001, 2, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x100000, 3, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 4, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 5, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 6, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 7, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 8, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x100000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 11, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x100000, 12, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 13, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x300000, 14, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x400000, 15, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x500000, 16, 1)) return 1;
if (BurnLoadRom(DrvSndROM0 + 0x040000, 17, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 18, 1)) return 1;
deco56_decrypt_gfx(DrvGfxROM0, 0x020000);
deco56_decrypt_gfx(DrvGfxROM1, 0x100000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0);
DrvSpriteDecode();
}
deco16Init(0, 0, 1);
deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_base(3, 768);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x3c0000, 0x3c1fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x3c2000, 0x3c2fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x3c4000, 0x3c4fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x3c6000, 0x3c6fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c8000, 0x3c8fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c9000, 0x3c9fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3ca000, 0x3cafff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3cb000, 0x3cbfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cc000, 0x3ccfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cd000, 0x3cdfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3ce000, 0x3cefff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3cf000, 0x3cffff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x3d0000, 0x3d07ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x3e0000, 0x3e1fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0x3f0000, 0x3f3fff, SM_RAM);
SekSetWriteWordHandler(0, rohga_main_write_word);
SekSetWriteByteHandler(0, rohga_main_write_byte);
SekSetReadWordHandler(0, rohga_main_read_word);
SekSetReadByteHandler(0, rohga_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.78, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.78, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.78, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 WizdfireInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040001, 2, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040000, 3, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080001, 4, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080000, 5, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 6, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 7, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 8, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x100000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 11, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x080000, 12, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 13, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000001, 14, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 15, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200001, 16, 2)) return 1;
if (BurnLoadRom(DrvGfxROM4 + 0x000000, 17, 2)) return 1;
if (BurnLoadRom(DrvGfxROM4 + 0x000001, 18, 2)) return 1;
if (BurnLoadRom(DrvSndROM0 + 0x040000, 19, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 20, 1)) return 1;
deco74_decrypt_gfx(DrvGfxROM0, 0x020000);
deco74_decrypt_gfx(DrvGfxROM1, 0x200000);
deco74_decrypt_gfx(DrvGfxROM2, 0x100000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x200000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x100000, 0);
deco16_sprite_decode(DrvGfxROM3, 0x400000);
deco16_sprite_decode(DrvGfxROM4, 0x100000);
}
deco16Init(0, 0, 1);
deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x200000 * 2, DrvGfxROM2, 0x100000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_base(3, 768);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x200000, 0x200fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x202000, 0x202fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x208000, 0x208fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x20a000, 0x20afff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x20c000, 0x20c7ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x20e000, 0x20e7ff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x340000, 0x3407ff, SM_RAM);
SekMapMemory(DrvSprRAM2, 0x360000, 0x3607ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x380000, 0x381fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0xfdc000, 0xfe3fff, SM_RAM);
SekMapMemory(Drv68KRAM + 0x8000, 0xfe4800, 0xffffff, SM_RAM);
SekSetWriteWordHandler(0, wizdfire_main_write_word);
SekSetWriteByteHandler(0, wizdfire_main_write_byte);
SekSetReadWordHandler(0, wizdfire_main_read_word);
SekSetReadByteHandler(0, wizdfire_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 SchmeisrInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 2, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 3, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 4, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 5, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x100000, 6, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 7, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x100000, 8, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x300000, 10, 1)) return 1;
if (BurnLoadRom(DrvSndROM0 + 0x040000, 11, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 12, 1)) return 1;
deco74_decrypt_gfx(DrvGfxROM1, 0x100000);
memcpy (DrvGfxROM0 + 0x000000, DrvGfxROM1 + 0x000000, 0x020000);
memcpy (DrvGfxROM0 + 0x020000, DrvGfxROM1 + 0x080000, 0x020000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x040000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0);
DrvSpriteDecode();
}
deco16Init(0, 0, 1);
deco16_set_graphics(DrvGfxROM0, 0x40000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_base(3, 768);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x3c0000, 0x3c1fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x3c2000, 0x3c2fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x3c4000, 0x3c4fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x3c6000, 0x3c6fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c8000, 0x3c8fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c9000, 0x3c9fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3ca000, 0x3cafff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3cb000, 0x3cbfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cc000, 0x3ccfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cd000, 0x3cdfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3ce000, 0x3cefff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3cf000, 0x3cffff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x3d0000, 0x3d07ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x3e0000, 0x3e1fff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x3e2000, 0x3e3fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0xff0000, 0xff7fff, SM_RAM);
SekSetWriteWordHandler(0, rohga_main_write_word);
SekSetWriteByteHandler(0, rohga_main_write_byte);
SekSetReadWordHandler(0, rohga_main_read_word);
SekSetReadByteHandler(0, rohga_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 NitrobalInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040001, 2, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040000, 3, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080001, 4, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080000, 5, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 6, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 7, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 8, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 11, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x100000, 12, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 13, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000001, 14, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 15, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200001, 16, 2)) return 1;
BurnByteswap(DrvGfxROM3, 0x400000);
if (BurnLoadRom(DrvGfxROM4 + 0x000000, 17, 2)) return 1;
if (BurnLoadRom(DrvGfxROM4 + 0x000001, 18, 2)) return 1;
BurnByteswap(DrvGfxROM4, 0x080000);
if (BurnLoadRom(DrvSndROM0 + 0x040000, 19, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 20, 1)) return 1;
deco56_decrypt_gfx(DrvGfxROM0, 0x020000);
deco56_decrypt_gfx(DrvGfxROM1, 0x100000);
deco74_decrypt_gfx(DrvGfxROM2, 0x200000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0);
deco16_sprite_decode(DrvGfxROM3, 0x400000);
deco16_sprite_decode(DrvGfxROM4, 0x080000);
}
deco16Init(0, 0, 0);
deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_mask(2, 0);
deco16_set_color_base(3, 512);
deco16_set_color_mask(3, 0);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x200000, 0x200fff, SM_RAM);
SekMapMemory(deco16_pf_ram[0], 0x201000, 0x201fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x202000, 0x2027ff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x202800, 0x202fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x208000, 0x2087ff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x208800, 0x208fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x20a000, 0x20a7ff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x20a800, 0x20afff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x204000, 0x2047ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x206000, 0x2067ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x20c000, 0x20c7ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x20e000, 0x20e7ff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x340000, 0x3407ff, SM_RAM);
SekMapMemory(DrvSprRAM2, 0x360000, 0x3607ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x380000, 0x381fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0xfec000, 0xff3fff, SM_RAM);
SekMapMemory(Drv68KRAM + 0x8000, 0xff8000, 0xffffff, SM_RAM);
SekSetWriteWordHandler(0, wizdfire_main_write_word);
SekSetWriteByteHandler(0, wizdfire_main_write_byte);
SekSetReadWordHandler(0, wizdfire_main_read_word);
SekSetReadByteHandler(0, wizdfire_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 DrvExit()
{
GenericTilesExit();
deco16Exit();
SekExit();
deco16SoundExit();
BurnFree (AllMem);
return 0;
}
static void rohga_draw_sprites(UINT8 *ram, INT32 is_schmeisr)
{
UINT16 *spriteptr = (UINT16*)ram;
for (INT32 offs = 0x400 - 4; offs >= 0; offs -= 4)
{
INT32 inc, mult, pri = 0;
INT32 sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]);
if (!sprite) continue;
INT32 x = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]);
switch (x & 0x6000)
{
case 0x0000: pri = 0; break;
case 0x4000: pri = 0xf0; break;
case 0x6000: pri = 0xf0 | 0xcc; break;
case 0x2000: pri = 0; break;
}
INT32 y = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]);
if ((y & 0x1000) && (nCurrentFrame & 1)) continue; // flash
INT32 colour = (((x >> 9) & 0xf) << 6);
if (is_schmeisr) colour += ((x & 0x8000) >> 15) << 4;
INT32 fx = y & 0x2000;
INT32 fy = y & 0x4000;
INT32 multi = (1 << ((y & 0x0600) >> 9)) - 1;
x = x & 0x01ff;
y = y & 0x01ff;
if (x >= 320) x -= 512;
if (y >= 256) y -= 512;
sprite &= ~multi;
if (fy)
inc = -1;
else
{
sprite += multi;
inc = 1;
}
if (*flipscreen)
{
x = 304 - x;
y = 240 - y;
if (fx) fx = 0; else fx = 1;
if (fy) fy = 0; else fy = 1;
mult = -16;
}
else
mult = +16;
while (multi >= 0)
{
deco16_draw_prio_sprite(pTransDraw, DrvGfxROM3, (sprite - multi * inc) & 0x7fff, colour + 0x400, x, y + mult * multi, fx, fy, pri);
multi--;
}
}
}
static void wizdfire_draw_sprites(UINT8 *ram, UINT8 *gfx, INT32 coloff, INT32 mode, INT32 bank)
{
UINT16 *spriteptr = (UINT16*)ram;
for (INT32 offs = 0; offs < 0x400; offs += 4)
{
INT32 inc, mult, prio = 0, alpha = 0xff;
INT32 sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]);
if (!sprite) continue;
INT32 x = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]);
switch (mode)
{
case 4:
if ((x & 0xc000) != 0xc000)
continue;
prio = 0x08;
break;
case 3:
if ((x & 0xc000) != 0x8000)
continue;
prio = 0x10;
break;
case 2:
if ((x & 0x8000) != 0x8000)
continue;
prio = 0x20;
break;
case 1:
case 0:
default:
if ((x & 0x8000) != 0)
continue;
prio = 0x40;
break;
}
INT32 y = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]);
if ((y & 0x1000) && (nCurrentFrame & 1)) continue; // flash
INT32 colour = (x >> 9) & 0x1f;
if (bank == 4 && colour & 0x10)
{
alpha = 0x80;
colour &= 0xf;
}
INT32 fx = y & 0x2000;
INT32 fy = y & 0x4000;
INT32 multi = (1 << ((y & 0x0600) >> 9)) - 1;
x = x & 0x01ff;
y = y & 0x01ff;
if (x >= 320) x -= 512;
if (y >= 256) y -= 512;
sprite &= ~multi;
if (fy)
inc = -1;
else
{
sprite += multi;
inc = 1;
}
if (*flipscreen)
{
x = 304 - x;
y = 240 - y;
mult = -16;
} else {
mult = +16;
fx = !fx;
fy = !fy;
}
if (bank == 3) {
sprite &= 0x7fff;
} else {
sprite &= 0x0fff;
}
while (multi >= 0)
{
deco16_draw_prio_sprite(pTransDraw, gfx, sprite - multi * inc, (colour << 4) + coloff, x, y + mult * multi, fx, fy, -1);
#if 0
drawgfx_alpha(bitmap,cliprect,machine->gfx[bank],
sprite - multi * inc,
colour,
fx,fy,
x,y + mult * multi,
0,alpha);
#endif
multi--;
}
}
}
static void nitrobal_draw_sprites(UINT8 *ram, INT32 gfxbank, INT32 /*bpp*/)
{
// if (bpp != (nBurnBpp & 0x04)) return;
UINT16 *spriteptr = (UINT16*)ram;
INT32 offs = 0x3fc;
INT32 end = -4;
INT32 inc = -4;
UINT8 *gfx;
while (offs != end)
{
INT32 x, y, sprite, colour, fx, fy, w, h, sx, sy, x_mult, y_mult, tilemap_pri, sprite_pri, coloff;
INT32 alpha = 0xff;
sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 3]);
if (!sprite)
{
offs += inc;
continue;
}
sx = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]);
h = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0xf000) >> 12;
w = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0x0f00) >> 8;
sy = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]);
if ((sy & 0x2000) && (nCurrentFrame & 1))
{
offs += inc;
continue;
}
colour = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) >> 0) & 0x1f;
if (gfxbank == 3)
{
switch (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0xe0)
{
case 0xc0: tilemap_pri = 8; break;
case 0x80: tilemap_pri = 32; break;
case 0x20: tilemap_pri = 32; break;
case 0x40: tilemap_pri = 8; break;
case 0xa0: tilemap_pri = 32; break;
case 0x00: tilemap_pri = 128; break;
default: tilemap_pri = 128; break;
}
sprite_pri = 1;
gfx = DrvGfxROM3;
coloff = 0x400;
}
else
{
if (deco16_priority)
tilemap_pri = 8;
else
tilemap_pri = 64;
sprite_pri = 2;
gfx = DrvGfxROM4;
coloff = 0x600;
if (colour & 0x10) {
alpha = 0x80;
colour &= 0x0f;
}
}
fx = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 0]) & 0x4000);
fy = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 0]) & 0x8000);
if (!*flipscreen)
{
if (fx) fx = 0; else fx = 1;
if (fy) fy = 0; else fy = 1;
sx = sx & 0x01ff;
sy = sy & 0x01ff;
if (sx > 0x180) sx = -(0x200 - sx);
if (sy > 0x180) sy = -(0x200 - sy);
if (fx) { x_mult = -16; sx += 16 * w; } else { x_mult = 16; sx -= 16; }
if (fy) { y_mult = -16; sy += 16 * h; } else { y_mult = 16; sy -= 16; }
}
else
{
sx = sx & 0x01ff;
sy = sy & 0x01ff;
if (sx & 0x100) sx = -(0x100 - (sx & 0xff));
if (sy & 0x100) sy = -(0x100 - (sy & 0xff));
sx = 304 - sx;
sy = 240 - sy;
if (sx >= 432) sx -= 512;
if (sy >= 384) sy -= 512;
if (fx) { x_mult = -16; sx += 16; } else { x_mult = 16; sx -= 16 * w; }
if (fy) { y_mult = -16; sy += 16; } else { y_mult = 16; sy -= 16 * h; }
}
if (gfxbank == 3) {
sprite &= 0x7fff;
} else {
sprite &= 0x0fff;
}
for (x = 0; x < w; x++)
{
for (y = 0; y < h; y++)
{
//if (!bpp) {
deco16_draw_prio_sprite(pTransDraw, gfx, sprite + y + h * x, (colour << 4) + coloff, sx + x_mult * (w-x), sy + y_mult * (h-y), fx, fy, tilemap_pri, sprite_pri);
//} else {
// deco16_draw_alphaprio_sprite(DrvPalette, gfx, sprite + y + h * x, (colour << 4) + coloff, sx + x_mult * (w-x), sy + y_mult * (h-y), fx, fy, tilemap_pri, sprite_pri, alpha);
//}
}
}
offs += inc;
}
}
static void draw_combined_playfield_step1()
{
UINT8 *tptr = deco16_pf_rowscroll[3];
deco16_pf_rowscroll[3] = deco16_pf_rowscroll[2];
deco16_draw_layer(2, tempdraw[0], 0x10000);
deco16_draw_layer(3, tempdraw[1], 0x10000);
deco16_pf_rowscroll[3] = tptr;
}
static void draw_combined_playfield(INT32 color, INT32 priority) // opaque
{
UINT16 *src0 = tempdraw[0];
UINT16 *src1 = tempdraw[1];
UINT16 *dest = pTransDraw;
UINT8 *prio = deco16_prio_map;
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = 0; x < nScreenWidth; x++) {
dest[x] = color | (src0[x] & 0x0f) | ((src1[x] & 0x0f) << 4);
prio[x] = priority;
}
src0 += nScreenWidth;
src1 += nScreenWidth;
dest += nScreenWidth;
prio += 512;
}
}
static void update_rohga(INT32 is_schmeisr)
{
// if (DrvRecalc) {
deco16_palette_recalculate(DrvPalette, DrvPalRAM);
DrvRecalc = 0;
// }
deco16_pf12_update();
deco16_pf34_update();
for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {
pTransDraw[i] = 0x300;
}
if ((deco16_priority & 0x03) == 0) {
draw_combined_playfield_step1();
}
deco16_clear_prio_map();
switch (deco16_priority & 3)
{
case 0:
if (deco16_priority & 4)
{
draw_combined_playfield(0x300, DECO16_LAYER_PRIORITY(3));
}
else
{
deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01));
deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x02));
}
deco16_draw_layer(1, pTransDraw, DECO16_LAYER_PRIORITY(0x04));
break;
case 1:
deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01));
deco16_draw_layer(1, pTransDraw, DECO16_LAYER_PRIORITY(0x02));
deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x04));
break;
case 2:
deco16_draw_layer(1, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01));
deco16_draw_layer(3, pTransDraw, DECO16_LAYER_PRIORITY(0x02));
deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x04));
break;
}
if (nSpriteEnable & 1) rohga_draw_sprites(DrvSprBuf2, is_schmeisr);
deco16_draw_layer(0, pTransDraw, 0);
BurnTransferCopy(DrvPalette);
}
static INT32 RohgaDraw()
{
update_rohga(0);
return 0;
}
static INT32 SchmeisrDraw()
{
update_rohga(1);
return 0;
}
static INT32 WizdfireDraw()
{
// if (DrvRecalc) {
deco16_palette_recalculate(DrvPalette, DrvPalRAM);
DrvRecalc = 0;
// }
deco16_pf12_update();
deco16_pf34_update();
for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {
pTransDraw[i] = 0x200;
}
if (nBurnLayer & 1) deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE);
if (nSpriteEnable & 1) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 4, 3);
if (nBurnLayer & 2) deco16_draw_layer(1, pTransDraw, 0);
if (nSpriteEnable & 2) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 3, 3);
if ((deco16_priority & 0x1f) == 0x1f) {
if (nBurnLayer & 4) deco16_draw_layer(2, pTransDraw, 0); // tilemap draw alpha 0x80...
} else {
if (nBurnLayer & 4) deco16_draw_layer(2, pTransDraw, 0);
}
if (nSpriteEnable & 4) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 0, 3);
if (nSpriteEnable & 8) wizdfire_draw_sprites(DrvSprBuf2, DrvGfxROM4, 0x600, 2, 4);
if (nSpriteEnable & 16) wizdfire_draw_sprites(DrvSprBuf2, DrvGfxROM4, 0x600, 1, 4);
if (nBurnLayer & 8) deco16_draw_layer(0, pTransDraw, 0);
BurnTransferCopy(DrvPalette);
return 0;
}
static INT32 NitrobalDraw()
{
// if (DrvRecalc) {
deco16_palette_recalculate(DrvPalette, DrvPalRAM);
DrvRecalc = 0;
// }
deco16_pf12_update();
deco16_pf34_update();
for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {
pTransDraw[i] = 0x200;
}
draw_combined_playfield_step1();
deco16_clear_prio_map();
draw_combined_playfield(0x200, 0);
if (nBurnLayer & 1)deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE);
deco16_draw_layer(1, pTransDraw, 16);
nitrobal_draw_sprites(DrvSprBuf , 3, 0);
nitrobal_draw_sprites(DrvSprBuf2, 4, 0);
deco16_draw_layer(0, pTransDraw, DECO16_LAYER_PRIORITY(0xff));
BurnTransferCopy(DrvPalette);
// nitrobal_draw_sprites(DrvSprBuf , 3, 4);
// nitrobal_draw_sprites(DrvSprBuf2, 4, 4);
return 0;
}
static INT32 DrvFrame()
{
if (DrvReset) {
DrvDoReset();
}
{
deco16_prot_inputs = DrvInputs;
memset (DrvInputs, 0xff, 4 * sizeof(UINT16));
for (INT32 i = 0; i < 16; i++) {
DrvInputs[0] ^= (DrvJoy1[i] & 1) << i;
DrvInputs[1] ^= (DrvJoy2[i] & 1) << i;
DrvInputs[3] ^= (DrvJoy3[i] & 1) << i;
}
DrvInputs[2] = (DrvDips[1] << 8) | (DrvDips[0] << 0);
}
INT32 nInterleave = 256;
INT32 nSoundBufferPos = 0;
INT32 nCyclesTotal[2] = { 14000000 / 58, 2685000 / 58 };
INT32 nCyclesDone[2] = { 0, 0 };
h6280NewFrame();
SekOpen(0);
h6280Open(0);
deco16_vblank = 0;
for (INT32 i = 0; i < nInterleave; i++)
{
nCyclesDone[0] += SekRun(nCyclesTotal[0] / nInterleave);
nCyclesDone[1] += h6280Run(nCyclesTotal[1] / nInterleave);
if (i == 240) deco16_vblank = 0x08;
if (pBurnSoundOut) {
INT32 nSegmentLength = nBurnSoundLen / nInterleave;
INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
deco16SoundUpdate(pSoundBuf, nSegmentLength);
nSoundBufferPos += nSegmentLength;
}
}
SekSetIRQLine(6, SEK_IRQSTATUS_ACK);
if (pBurnSoundOut) {
INT32 nSegmentLength = nBurnSoundLen - nSoundBufferPos;
INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
if (nSegmentLength) {
deco16SoundUpdate(pSoundBuf, nSegmentLength);
}
}
h6280Close();
SekClose();
if (pBurnDraw) {
BurnDrvRedraw();
}
return 0;
}
static INT32 DrvScan(INT32 nAction, INT32 *pnMin)
{
struct BurnArea ba;
if (pnMin != NULL) {
*pnMin = 0x029722;
}
if (nAction & ACB_MEMORY_RAM) {
memset(&ba, 0, sizeof(ba));
ba.Data = AllRam;
ba.nLen = RamEnd-AllRam;
ba.szName = "All Ram";
BurnAcb(&ba);
}
if (nAction & ACB_DRIVER_DATA) {
SekScan(nAction);
deco16SoundScan(nAction, pnMin);
deco16Scan();
SCAN_VAR(DrvOkiBank);
INT32 bank = DrvOkiBank;
DrvOkiBank = -1;
DrvYM2151WritePort(0, bank);
}
return 0;
}
// Rohga Armor Force (Asia/Europe v5.0)
static struct BurnRomInfo rohgaRomDesc[] = {
{ "ht-00-1.2a", 0x040000, 0x1ed84a67, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "ht-03-1.2d", 0x040000, 0x84e7ebf6, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohga)
STD_ROM_FN(rohga)
struct BurnDriver BurnDrvRohga = {
"rohga", NULL, NULL, NULL, "1991",
"Rohga Armor Force (Asia/Europe v5.0)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohgaRomInfo, rohgaRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (Asia/Europe v3.0 Set 1)
static struct BurnRomInfo rohga1RomDesc[] = {
{ "jd00.bin", 0x040000, 0xe046c77a, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jd03.bin", 0x040000, 0x2c5120b8, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohga1)
STD_ROM_FN(rohga1)
struct BurnDriver BurnDrvRohga1 = {
"rohga1", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (Asia/Europe v3.0 Set 1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohga1RomInfo, rohga1RomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (Asia/Europe v3.0 Set 2)
static struct BurnRomInfo rohga2RomDesc[] = {
{ "hts-00-3.2a", 0x040000, 0x154f02ec, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "hts-03-3.2d", 0x040000, 0x5e69d3d8, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohga2)
STD_ROM_FN(rohga2)
struct BurnDriver BurnDrvRohga2 = {
"rohga2", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (Asia/Europe v3.0 Set 2)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohga2RomInfo, rohga2RomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (Hong Kong v3.0)
static struct BurnRomInfo rohgahRomDesc[] = {
{ "jd00-2.2a", 0x040000, 0xec70646a, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jd03-2.2d", 0x040000, 0x11d4c9a2, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohgah)
STD_ROM_FN(rohgah)
struct BurnDriver BurnDrvRohgah = {
"rohgah", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (Hong Kong v3.0)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohgahRomInfo, rohgahRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (US v1.0)
static struct BurnRomInfo rohgauRomDesc[] = {
{ "ha00.2a", 0x040000, 0xd8d13052, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "ha03.2d", 0x040000, 0x5f683bbf, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohgau)
STD_ROM_FN(rohgau)
struct BurnDriver BurnDrvRohgau = {
"rohgau", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (US v1.0)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohgauRomInfo, rohgauRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Wolf Fang -Kuhga 2001- (Japan)
static struct BurnRomInfo wolffangRomDesc[] = {
{ "hw_00-1.2a", 0x040000, 0x69dc611e, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "hw_03-1.2d", 0x040000, 0xb66d9680, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "hw_04-.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "hw_01-.13a", 0x010000, 0xd9810ca4, 3 | BRF_GRA }, // 5 Characters
{ "hw_02-.14a", 0x010000, 0x2a27ac8e, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(wolffang)
STD_ROM_FN(wolffang)
struct BurnDriver BurnDrvWolffang = {
"wolffang", "rohga", NULL, NULL, "1991",
"Wolf Fang -Kuhga 2001- (Japan)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, wolffangRomInfo, wolffangRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Wizard Fire (Over Sea v2.1)
static struct BurnRomInfo wizdfireRomDesc[] = {
{ "je-01.3d", 0x020000, 0xb6d62367, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "je-00.3a", 0x020000, 0xf33de278, 1 | BRF_PRG | BRF_ESS }, // 1
{ "je-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2
{ "je-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3
{ "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4
{ "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5
{ "je-06.20r", 0x010000, 0x79042546, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "je-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters
{ "je-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8
{ "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10
{ "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles
{ "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12
{ "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14
{ "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15
{ "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16
{ "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18
{ "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(wizdfire)
STD_ROM_FN(wizdfire)
struct BurnDriver BurnDrvWizdfire = {
"wizdfire", NULL, NULL, NULL, "1992",
"Wizard Fire (Over Sea v2.1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0,
NULL, wizdfireRomInfo, wizdfireRomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo,
WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Wizard Fire (US v1.1)
static struct BurnRomInfo wizdfireuRomDesc[] = {
{ "jf-01.3d", 0x020000, 0xbde42a41, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jf-00.3a", 0x020000, 0xbca3c995, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jf-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jf-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3
{ "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4
{ "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jf-06.20r", 0x010000, 0x79042546, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jf-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters
{ "jf-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8
{ "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10
{ "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles
{ "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12
{ "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14
{ "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15
{ "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16
{ "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18
{ "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(wizdfireu)
STD_ROM_FN(wizdfireu)
struct BurnDriver BurnDrvWizdfireu = {
"wizdfireu", "wizdfire", NULL, NULL, "1992",
"Wizard Fire (US v1.1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0,
NULL, wizdfireuRomInfo, wizdfireuRomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo,
WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Dark Seal 2 (Japan v2.1)
static struct BurnRomInfo darkseal2RomDesc[] = {
{ "jb-01-3.3d", 0x020000, 0x82308c01, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jb-00-3.3a", 0x020000, 0x1d38113a, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jb-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jb-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3
{ "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4
{ "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jb-06.20r", 0x010000, 0x2066a1dd, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jb-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters
{ "jb-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8
{ "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10
{ "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles
{ "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12
{ "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14
{ "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15
{ "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16
{ "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18
{ "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(darkseal2)
STD_ROM_FN(darkseal2)
struct BurnDriver BurnDrvDarkseal2 = {
"darkseal2", "wizdfire", NULL, NULL, "1992",
"Dark Seal 2 (Japan v2.1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0,
NULL, darkseal2RomInfo, darkseal2RomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo,
WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Schmeiser Robo (Japan)
static struct BurnRomInfo schmeisrRomDesc[] = {
{ "sr001j.8a", 0x080000, 0xed31f3ff, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "sr006j.8d", 0x080000, 0x9e9cfa5d, 1 | BRF_PRG | BRF_ESS }, // 1
{ "sr013.18p", 0x010000, 0x4ac00cbb, 2 | BRF_PRG | BRF_ESS }, // 2 Huc6280 Code
{ "sr002-74.9a", 0x080000, 0x97e15c7b, 3 | BRF_GRA }, // 3 Foreground Tiles
{ "sr003-74.11a", 0x080000, 0xea367971, 3 | BRF_GRA }, // 4
{ "sr007.17d", 0x100000, 0x886f80c7, 4 | BRF_GRA }, // 5 Background Tiles
{ "sr008.18d", 0x100000, 0xa74cbc90, 4 | BRF_GRA }, // 6
{ "sr004.19a", 0x100000, 0xe25434a1, 5 | BRF_GRA }, // 7 Sprites
{ "sr005.20a", 0x100000, 0x1630033b, 5 | BRF_GRA }, // 8
{ "sr009.19d", 0x100000, 0x7b9d982f, 5 | BRF_GRA }, // 9
{ "sr010.20d", 0x100000, 0x6e9e5352, 5 | BRF_GRA }, // 10
{ "sr012.15p", 0x080000, 0x38843d4d, 7 | BRF_SND }, // 12 OKI M6295 Samples 0
{ "sr011.14p", 0x080000, 0x81805616, 6 | BRF_SND }, // 11 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 13 Unused PROMs
};
STD_ROM_PICK(schmeisr)
STD_ROM_FN(schmeisr)
struct BurnDriver BurnDrvSchmeisr = {
"schmeisr", NULL, NULL, NULL, "1993",
"Schmeiser Robo (Japan)\0",NULL, "Hot B", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_VSFIGHT, 0,
NULL, schmeisrRomInfo, schmeisrRomName, NULL, NULL, RohgaInputInfo, SchmeisrDIPInfo,
SchmeisrInit, DrvExit, DrvFrame, SchmeisrDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Nitro Ball (US)
static struct BurnRomInfo nitrobalRomDesc[] = {
{ "jl01-4.d3", 0x020000, 0x0414e409, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jl00-4.b3", 0x020000, 0xdd9e2bcc, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jl03-4.d5", 0x020000, 0xea264ac5, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jl02-4.b5", 0x020000, 0x74047997, 1 | BRF_PRG | BRF_ESS }, // 3
{ "jl05-2.d6", 0x040000, 0xb820fa20, 1 | BRF_PRG | BRF_ESS }, // 4
{ "jl04-2.b6", 0x040000, 0x1fd8995b, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jl08.r20", 0x010000, 0x93d93fe1, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jl06.d10", 0x010000, 0x91cf668e, 3 | BRF_GRA }, // 7 Characters
{ "jl07.d12", 0x010000, 0xe61d0e42, 3 | BRF_GRA }, // 8
{ "mav00.b10", 0x080000, 0x34785d97, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mav01.b12", 0x080000, 0x8b531b16, 4 | BRF_GRA }, // 10
{ "mav02.b16", 0x100000, 0x20723bf7, 5 | BRF_GRA }, // 11 Background Tiles
{ "mav03.e16", 0x100000, 0xef6195f0, 5 | BRF_GRA }, // 12
{ "mav05.e19", 0x100000, 0xd92d769c, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mav04.b19", 0x100000, 0x8ba48385, 6 | BRF_GRA }, // 14
{ "mav07.e20", 0x080000, 0x5fc10ccd, 6 | BRF_GRA }, // 15
{ "mav06.b20", 0x080000, 0xae6201a5, 6 | BRF_GRA }, // 16
{ "mav09.e23", 0x040000, 0x1ce7b51a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mav08.b23", 0x040000, 0x64966576, 7 | BRF_GRA }, // 18
{ "mav10.r17", 0x080000, 0x8ad734b0, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mav11.r19", 0x080000, 0xef513908, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "jn-00.17l", 0x000400, 0x6ac77b84, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(nitrobal)
STD_ROM_FN(nitrobal)
struct BurnDriver BurnDrvNitrobal = {
"nitrobal", NULL, NULL, NULL, "1992",
"Nitro Ball (US)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 3, HARDWARE_PREFIX_DATAEAST, GBF_SHOOT, 0,
NULL, nitrobalRomInfo, nitrobalRomName, NULL, NULL, NitrobalInputInfo, NitrobalDIPInfo,
NitrobalInit, DrvExit, DrvFrame, NitrobalDraw, DrvScan, &DrvRecalc, 0x800,
240, 320, 3, 4
};
// Gun Ball (Japan)
static struct BurnRomInfo gunballRomDesc[] = {
{ "jc01.3d", 0x020000, 0x61bfa998, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jc00.3b", 0x020000, 0x73ba8f74, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jc03.5d", 0x020000, 0x19231612, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jc02.5b", 0x020000, 0xa254f34c, 1 | BRF_PRG | BRF_ESS }, // 3
{ "jc05-3.6d", 0x040000, 0xf750a709, 1 | BRF_PRG | BRF_ESS }, // 4
{ "jc04-3.6b", 0x040000, 0xad711767, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jl08.r20", 0x010000, 0x93d93fe1, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jl06.d10", 0x010000, 0x91cf668e, 3 | BRF_GRA }, // 7 Characters
{ "jl07.d12", 0x010000, 0xe61d0e42, 3 | BRF_GRA }, // 8
{ "mav00.b10", 0x080000, 0x34785d97, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mav01.b12", 0x080000, 0x8b531b16, 4 | BRF_GRA }, // 10
{ "mav02.b16", 0x100000, 0x20723bf7, 5 | BRF_GRA }, // 11 Background Tiles
{ "mav03.e16", 0x100000, 0xef6195f0, 5 | BRF_GRA }, // 12
{ "mav05.e19", 0x100000, 0xd92d769c, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mav04.b19", 0x100000, 0x8ba48385, 6 | BRF_GRA }, // 14
{ "mav07.e20", 0x080000, 0x5fc10ccd, 6 | BRF_GRA }, // 15
{ "mav06.b20", 0x080000, 0xae6201a5, 6 | BRF_GRA }, // 16
{ "mav09.e23", 0x040000, 0x1ce7b51a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mav08.b23", 0x040000, 0x64966576, 7 | BRF_GRA }, // 18
{ "mav10.r17", 0x080000, 0x8ad734b0, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mav11.r19", 0x080000, 0xef513908, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "jn-00.17l", 0x000400, 0x6ac77b84, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(gunball)
STD_ROM_FN(gunball)
struct BurnDriver BurnDrvGunball = {
"gunball", "nitrobal", NULL, NULL, "1992",
"Gun Ball (Japan)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL, 3, HARDWARE_PREFIX_DATAEAST, GBF_SHOOT, 0,
NULL, gunballRomInfo, gunballRomName, NULL, NULL, NitrobalInputInfo, NitrobalDIPInfo,
NitrobalInit, DrvExit, DrvFrame, NitrobalDraw, DrvScan, &DrvRecalc, 0x800,
240, 320, 3, 4
};
| 32.424283 | 179 | 0.634223 | atship |
0613d2a5cb672ce0c734d4551bf53d5225e8b18a | 7,057 | cpp | C++ | aws-cpp-sdk-connect/source/model/VocabularyLanguageCode.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-connect/source/model/VocabularyLanguageCode.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-connect/source/model/VocabularyLanguageCode.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/connect/model/VocabularyLanguageCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace Connect
{
namespace Model
{
namespace VocabularyLanguageCodeMapper
{
static const int ar_AE_HASH = HashingUtils::HashString("ar-AE");
static const int de_CH_HASH = HashingUtils::HashString("de-CH");
static const int de_DE_HASH = HashingUtils::HashString("de-DE");
static const int en_AB_HASH = HashingUtils::HashString("en-AB");
static const int en_AU_HASH = HashingUtils::HashString("en-AU");
static const int en_GB_HASH = HashingUtils::HashString("en-GB");
static const int en_IE_HASH = HashingUtils::HashString("en-IE");
static const int en_IN_HASH = HashingUtils::HashString("en-IN");
static const int en_US_HASH = HashingUtils::HashString("en-US");
static const int en_WL_HASH = HashingUtils::HashString("en-WL");
static const int es_ES_HASH = HashingUtils::HashString("es-ES");
static const int es_US_HASH = HashingUtils::HashString("es-US");
static const int fr_CA_HASH = HashingUtils::HashString("fr-CA");
static const int fr_FR_HASH = HashingUtils::HashString("fr-FR");
static const int hi_IN_HASH = HashingUtils::HashString("hi-IN");
static const int it_IT_HASH = HashingUtils::HashString("it-IT");
static const int ja_JP_HASH = HashingUtils::HashString("ja-JP");
static const int ko_KR_HASH = HashingUtils::HashString("ko-KR");
static const int pt_BR_HASH = HashingUtils::HashString("pt-BR");
static const int pt_PT_HASH = HashingUtils::HashString("pt-PT");
static const int zh_CN_HASH = HashingUtils::HashString("zh-CN");
VocabularyLanguageCode GetVocabularyLanguageCodeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == ar_AE_HASH)
{
return VocabularyLanguageCode::ar_AE;
}
else if (hashCode == de_CH_HASH)
{
return VocabularyLanguageCode::de_CH;
}
else if (hashCode == de_DE_HASH)
{
return VocabularyLanguageCode::de_DE;
}
else if (hashCode == en_AB_HASH)
{
return VocabularyLanguageCode::en_AB;
}
else if (hashCode == en_AU_HASH)
{
return VocabularyLanguageCode::en_AU;
}
else if (hashCode == en_GB_HASH)
{
return VocabularyLanguageCode::en_GB;
}
else if (hashCode == en_IE_HASH)
{
return VocabularyLanguageCode::en_IE;
}
else if (hashCode == en_IN_HASH)
{
return VocabularyLanguageCode::en_IN;
}
else if (hashCode == en_US_HASH)
{
return VocabularyLanguageCode::en_US;
}
else if (hashCode == en_WL_HASH)
{
return VocabularyLanguageCode::en_WL;
}
else if (hashCode == es_ES_HASH)
{
return VocabularyLanguageCode::es_ES;
}
else if (hashCode == es_US_HASH)
{
return VocabularyLanguageCode::es_US;
}
else if (hashCode == fr_CA_HASH)
{
return VocabularyLanguageCode::fr_CA;
}
else if (hashCode == fr_FR_HASH)
{
return VocabularyLanguageCode::fr_FR;
}
else if (hashCode == hi_IN_HASH)
{
return VocabularyLanguageCode::hi_IN;
}
else if (hashCode == it_IT_HASH)
{
return VocabularyLanguageCode::it_IT;
}
else if (hashCode == ja_JP_HASH)
{
return VocabularyLanguageCode::ja_JP;
}
else if (hashCode == ko_KR_HASH)
{
return VocabularyLanguageCode::ko_KR;
}
else if (hashCode == pt_BR_HASH)
{
return VocabularyLanguageCode::pt_BR;
}
else if (hashCode == pt_PT_HASH)
{
return VocabularyLanguageCode::pt_PT;
}
else if (hashCode == zh_CN_HASH)
{
return VocabularyLanguageCode::zh_CN;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<VocabularyLanguageCode>(hashCode);
}
return VocabularyLanguageCode::NOT_SET;
}
Aws::String GetNameForVocabularyLanguageCode(VocabularyLanguageCode enumValue)
{
switch(enumValue)
{
case VocabularyLanguageCode::ar_AE:
return "ar-AE";
case VocabularyLanguageCode::de_CH:
return "de-CH";
case VocabularyLanguageCode::de_DE:
return "de-DE";
case VocabularyLanguageCode::en_AB:
return "en-AB";
case VocabularyLanguageCode::en_AU:
return "en-AU";
case VocabularyLanguageCode::en_GB:
return "en-GB";
case VocabularyLanguageCode::en_IE:
return "en-IE";
case VocabularyLanguageCode::en_IN:
return "en-IN";
case VocabularyLanguageCode::en_US:
return "en-US";
case VocabularyLanguageCode::en_WL:
return "en-WL";
case VocabularyLanguageCode::es_ES:
return "es-ES";
case VocabularyLanguageCode::es_US:
return "es-US";
case VocabularyLanguageCode::fr_CA:
return "fr-CA";
case VocabularyLanguageCode::fr_FR:
return "fr-FR";
case VocabularyLanguageCode::hi_IN:
return "hi-IN";
case VocabularyLanguageCode::it_IT:
return "it-IT";
case VocabularyLanguageCode::ja_JP:
return "ja-JP";
case VocabularyLanguageCode::ko_KR:
return "ko-KR";
case VocabularyLanguageCode::pt_BR:
return "pt-BR";
case VocabularyLanguageCode::pt_PT:
return "pt-PT";
case VocabularyLanguageCode::zh_CN:
return "zh-CN";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace VocabularyLanguageCodeMapper
} // namespace Model
} // namespace Connect
} // namespace Aws
| 34.593137 | 92 | 0.579425 | truthiswill |
061539070b92ba6ecf691a18d97789d12f62c4f4 | 2,868 | cpp | C++ | src/database/overlay/ftgl/src/FTGlyphContainer.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/database/overlay/ftgl/src/FTGlyphContainer.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/database/overlay/ftgl/src/FTGlyphContainer.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
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.
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 "FTGlyphContainer.h"
#include "FTGlyph.h"
#include "FTFace.h"
#include "FTCharmap.h"
FTGlyphContainer::FTGlyphContainer( FTFace* f)
: face(f),
err(0)
{
glyphs.push_back( NULL);
charMap = new FTCharmap( face);
}
FTGlyphContainer::~FTGlyphContainer()
{
GlyphVector::iterator glyphIterator;
for( glyphIterator = glyphs.begin(); glyphIterator != glyphs.end(); ++glyphIterator)
{
delete *glyphIterator;
}
glyphs.clear();
delete charMap;
}
bool FTGlyphContainer::CharMap( FT_Encoding encoding)
{
bool result = charMap->CharMap( encoding);
err = charMap->Error();
return result;
}
unsigned int FTGlyphContainer::FontIndex( const unsigned int characterCode) const
{
return charMap->FontIndex( characterCode);
}
void FTGlyphContainer::Add( FTGlyph* tempGlyph, const unsigned int characterCode)
{
charMap->InsertIndex( characterCode, glyphs.size());
glyphs.push_back( tempGlyph);
}
const FTGlyph* const FTGlyphContainer::Glyph( const unsigned int characterCode) const
{
signed int index = charMap->GlyphListIndex( characterCode);
return glyphs[index];
}
FTBBox FTGlyphContainer::BBox( const unsigned int characterCode) const
{
return glyphs[charMap->GlyphListIndex( characterCode)]->BBox();
}
float FTGlyphContainer::Advance( const unsigned int characterCode, const unsigned int nextCharacterCode)
{
unsigned int left = charMap->FontIndex( characterCode);
unsigned int right = charMap->FontIndex( nextCharacterCode);
float width = face->KernAdvance( left, right).X();
width += glyphs[charMap->GlyphListIndex( characterCode)]->Advance().X();
return width;
}
FTPoint FTGlyphContainer::Render( const unsigned int characterCode, const unsigned int nextCharacterCode, FTPoint penPosition)
{
FTPoint kernAdvance, advance;
unsigned int left = charMap->FontIndex( characterCode);
unsigned int right = charMap->FontIndex( nextCharacterCode);
kernAdvance = face->KernAdvance( left, right);
if( !face->Error())
{
advance = glyphs[charMap->GlyphListIndex( characterCode)]->Render( penPosition);
}
kernAdvance += advance;
return kernAdvance;
}
| 26.803738 | 126 | 0.722803 | OpenXIP |
061907f0002b965d21ad5abff7eb6c93ca3606da | 4,065 | hpp | C++ | Supermicro/benchmarks/dlrm/implementations/hugectr_J_2/HugeCTR/include/resource_manager.hpp | CaoZhongZ/training_results_v1.0 | 8200377f425ae24b6ed6c2816b9273aab0996d43 | [
"Apache-2.0"
] | 27 | 2021-07-01T00:34:52.000Z | 2022-03-29T08:49:53.000Z | Supermicro/benchmarks/dlrm/implementations/hugectr_J_2/HugeCTR/include/resource_manager.hpp | CaoZhongZ/training_results_v1.0 | 8200377f425ae24b6ed6c2816b9273aab0996d43 | [
"Apache-2.0"
] | 21 | 2021-08-31T08:34:50.000Z | 2022-03-17T11:42:10.000Z | Supermicro/benchmarks/dlrm/implementations/hugectr_J_2/HugeCTR/include/resource_manager.hpp | CaoZhongZ/training_results_v1.0 | 8200377f425ae24b6ed6c2816b9273aab0996d43 | [
"Apache-2.0"
] | 39 | 2021-07-02T00:46:14.000Z | 2022-03-13T16:59:55.000Z | /*
* Copyright (c) 2020, 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.
*/
#pragma once
#include <cpu_resource.hpp>
#include <device_map.hpp>
#include <gpu_resource.hpp>
#include <rmm/mr/device/device_memory_resource.hpp>
#include <collectives/ib_comm.hpp>
#include <collectives/all_reduce_comm.hpp>
namespace HugeCTR {
/**
* @brief GPU resources container.
*
* A GPU resource container in one node. An instant includes:
* GPU resource vector, thread pool for training, nccl communicators.
*/
class ResourceManager {
int num_process_;
int process_id_;
DeviceMap device_map_;
DeviceMap::Layout device_layout_;
std::shared_ptr<CPUResource> cpu_resource_;
std::vector<std::shared_ptr<GPUResource>> gpu_resources_; /**< GPU resource vector */
std::vector<std::vector<bool>> p2p_matrix_;
std::vector<std::shared_ptr<rmm::mr::device_memory_resource>> base_cuda_mr_;
std::vector<std::shared_ptr<rmm::mr::device_memory_resource>> memory_resource_;
#ifdef ENABLE_MPI
std::unique_ptr<IbComm> ib_comm_ = NULL;
#endif
std::shared_ptr<AllReduceInPlaceComm> ar_comm_ = NULL;
void enable_all_peer_accesses();
public:
ResourceManager(int num_process, int process_id, DeviceMap&& device_map, unsigned long long seed);
static std::shared_ptr<ResourceManager> create(
const std::vector<std::vector<int>>& visible_devices, unsigned long long seed,
DeviceMap::Layout dist = DeviceMap::LOCAL_FIRST);
ResourceManager(const ResourceManager&) = delete;
ResourceManager& operator=(const ResourceManager&) = delete;
int get_num_process() const { return num_process_; }
int get_process_id() const { return process_id_; }
int get_master_process_id() const { return 0; }
bool is_master_process() const { return process_id_ == 0; }
#ifdef ENABLE_MPI
IbComm* get_ib_comm() const { return ib_comm_.get(); }
void set_ready_to_transfer() { if (ib_comm_) ib_comm_->set_ready_to_transfer(); }
#endif
void set_ar_comm(AllReduceAlgo algo, bool use_mixed_precision);
AllReduceInPlaceComm* get_ar_comm() const { return ar_comm_.get(); }
DeviceMap::Layout get_device_layout() const { return device_map_.get_device_layout(); }
const std::shared_ptr<CPUResource>& get_local_cpu() const { return cpu_resource_; }
const std::shared_ptr<GPUResource>& get_local_gpu(size_t local_gpu_id) const {
return gpu_resources_[local_gpu_id];
}
const std::vector<int>& get_local_gpu_device_id_list() const {
return device_map_.get_device_list();
}
size_t get_local_gpu_count() const { return device_map_.get_device_list().size(); }
size_t get_global_gpu_count() const { return device_map_.size(); }
int get_process_id_from_gpu_global_id(size_t global_gpu_id) const {
return device_map_.get_pid(global_gpu_id);
}
size_t get_gpu_local_id_from_global_id(size_t global_gpu_id) const { // sequential GPU indices
return device_map_.get_local_id(global_gpu_id);
}
size_t get_gpu_global_id_from_local_id(size_t local_gpu_id) const { // sequential GPU indices
return device_map_.get_global_id(local_gpu_id);
}
bool p2p_enabled(int src_dev, int dst_dev) const;
bool all_p2p_enabled() const;
const std::shared_ptr<rmm::mr::device_memory_resource>& get_device_rmm_device_memory_resource(
int local_gpu_id) const {
auto dev_list = device_map_.get_device_list();
auto it = std::find(dev_list.begin(), dev_list.end(), local_gpu_id);
auto index = std::distance(dev_list.begin(), it);
return memory_resource_[index];
}
};
} // namespace HugeCTR
| 37.638889 | 100 | 0.755228 | CaoZhongZ |
061b2f826f8ba52116578496e732aa5f013a35fa | 3,008 | cpp | C++ | Engine/PostFX/_fragment/BlitImage.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 47 | 2018-04-27T02:16:26.000Z | 2022-02-28T05:21:24.000Z | Engine/PostFX/_fragment/BlitImage.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 2 | 2018-11-13T18:46:41.000Z | 2022-03-12T00:04:44.000Z | Engine/PostFX/_fragment/BlitImage.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 6 | 2019-08-10T21:56:23.000Z | 2020-10-21T11:18:29.000Z | /****************************************************************************
// Usagi Engine, Copyright © Vitei, Inc. 2013
****************************************************************************/
#include "Engine/Common/Common.h"
#include "Engine/PostFX/PostFXSys.h"
#include "Engine/Graphics/Device/GFXDevice.h"
#include "Engine/Resource/ResourceMgr.h"
#include "Engine/Graphics/StandardVertDecl.h"
#include "Engine/Scene/SceneConstantSets.h"
#include "Engine/Graphics/Device/GFXContext.h"
#include "Engine/Layout/Global2D.h"
#include "BlitImage.h"
namespace usg {
static const DescriptorDeclaration g_descriptorDecl[] =
{
DESCRIPTOR_ELEMENT(0, DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, SHADER_FLAG_PIXEL),
DESCRIPTOR_END()
};
BlitImage::BlitImage()
{
}
BlitImage::~BlitImage()
{
}
void BlitImage::Init(GFXDevice* pDevice, ResourceMgr* pResource, const RenderPassHndl& pass)
{
PipelineStateDecl pipelineDecl;
pipelineDecl.inputBindings[0].Init(usg::GetVertexDeclaration(usg::VT_POSITION));
pipelineDecl.uInputBindingCount = 1;
pipelineDecl.ePrimType = PT_TRIANGLES;
pipelineDecl.pEffect = pResource->GetEffect(pDevice, "PostProcess.Copy");
pipelineDecl.alphaState.SetColor0Only();
usg::DescriptorSetLayoutHndl matDescriptors = pDevice->GetDescriptorSetLayout(g_descriptorDecl);
SamplerDecl pointDecl(SF_LINEAR, SC_CLAMP);
m_sampler = pDevice->GetSampler(pointDecl);
pipelineDecl.layout.descriptorSets[0] = pDevice->GetDescriptorSetLayout(g_sGlobalDescriptors2D );
pipelineDecl.layout.descriptorSets[1] = matDescriptors;
pipelineDecl.layout.uDescriptorSetCount = 2;
pipelineDecl.rasterizerState.eCullFace = CULL_FACE_NONE;
m_material.Init(pDevice, pDevice->GetPipelineState(pass, pipelineDecl), matDescriptors);
// Shared vertex data
PositionVertex verts[4] =
{
{ -1.f, 1.f, 0.5f }, // 0 - TL
{ 1.f, 1.f, 0.5f }, // 1 - TR
{ -1.f, -1.f, 0.5f }, // 2 - BL
{ 1.f, -1.f, 0.5f }, // 3 - BR
};
uint16 iIndices[6] =
{
2, 1, 0, 2, 3, 1,
};
m_fullScreenVB.Init(pDevice, verts, sizeof(PositionVertex), 4, "FullScreenVB");
m_fullScreenIB.Init(pDevice, iIndices, 6, PT_TRIANGLES);
}
void BlitImage::CleanUp(GFXDevice* pDevice)
{
m_fullScreenIB.CleanUp(pDevice);
m_fullScreenVB.CleanUp(pDevice);
m_material.Cleanup(pDevice);
}
void BlitImage::ChangeRenderPass(GFXDevice* pDevice, const RenderPassHndl& pass)
{
PipelineStateDecl decl;
RenderPassHndl hndlTmp;
pDevice->GetPipelineDeclaration(m_material.GetPipelineStateHndl(), decl, hndlTmp);
m_material.SetPipelineState(pDevice->GetPipelineState(pass, decl));
}
void BlitImage::SetSourceTexture(GFXDevice* pDevice, const TextureHndl& tex)
{
m_material.SetTexture(0, tex, m_sampler);
m_material.UpdateDescriptors(pDevice);
}
bool BlitImage::Draw(GFXContext* pContext)
{
pContext->BeginGPUTag("BlitImage", Color::Green);
m_material.Apply(pContext);
pContext->SetVertexBuffer(&m_fullScreenVB);
pContext->DrawIndexed(&m_fullScreenIB);
pContext->EndGPUTag();
return true;
}
}
| 25.931034 | 98 | 0.71875 | vitei |
0620730f122eab6b1b96661bd5476e8c17504dc0 | 8,112 | hpp | C++ | src/ngraph/frontend/onnx_import/core/value_info.hpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | src/ngraph/frontend/onnx_import/core/value_info.hpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | src/ngraph/frontend/onnx_import/core/value_info.hpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/op/constant.hpp"
#include "ngraph/op/parameter_vector.hpp"
#include "ngraph/shape.hpp"
#include "ngraph/type/element_type.hpp"
#include <onnx/onnx.pb.h>
#include "node.hpp"
#include "tensor.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace error
{
namespace value_info
{
struct unspecified_element_type : ngraph_error
{
unspecified_element_type()
: ngraph_error{"value info has no element type specified"}
{
}
};
struct unsupported_element_type : ngraph_error
{
explicit unsupported_element_type(onnx::TensorProto_DataType type)
: ngraph_error{"unsupported value info element type: " +
onnx::TensorProto_DataType_Name(type)}
{
}
};
}
}
class ValueInfo
{
public:
ValueInfo(ValueInfo&&) = default;
ValueInfo(const ValueInfo&) = default;
ValueInfo() = delete;
explicit ValueInfo(const onnx::ValueInfoProto& value_info_proto)
: m_value_info_proto{&value_info_proto}
{
if (value_info_proto.type().has_tensor_type())
{
for (const auto& dim : value_info_proto.type().tensor_type().shape().dim())
{
m_shape.emplace_back(static_cast<Shape::value_type>(dim.dim_value()));
}
}
}
ValueInfo& operator=(const ValueInfo&) = delete;
ValueInfo& operator=(ValueInfo&&) = delete;
const std::string& get_name() const { return m_value_info_proto->name(); }
const Shape& get_shape() const { return m_shape; }
const element::Type& get_element_type() const
{
if (!m_value_info_proto->type().tensor_type().has_elem_type())
{
throw error::value_info::unspecified_element_type{};
}
switch (m_value_info_proto->type().tensor_type().elem_type())
{
case onnx::TensorProto_DataType::TensorProto_DataType_BOOL: return element::boolean;
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT:
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT16: return element::f32;
case onnx::TensorProto_DataType::TensorProto_DataType_DOUBLE: return element::f64;
case onnx::TensorProto_DataType::TensorProto_DataType_INT8: return element::i8;
case onnx::TensorProto_DataType::TensorProto_DataType_INT16: return element::i16;
case onnx::TensorProto_DataType::TensorProto_DataType_INT32: return element::i32;
case onnx::TensorProto_DataType::TensorProto_DataType_INT64: return element::i64;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT8: return element::u8;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT16: return element::u16;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT32: return element::u32;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT64: return element::u64;
default:
throw error::value_info::unsupported_element_type{
m_value_info_proto->type().tensor_type().elem_type()};
}
}
std::shared_ptr<ngraph::Node>
get_ng_node(op::ParameterVector& parameters,
const std::map<std::string, Tensor>& initializers) const
{
const auto it = initializers.find(get_name());
if (it != std::end(initializers))
{
return get_ng_constant(it->second);
}
else
{
parameters.push_back(get_ng_parameter());
return parameters.back();
}
}
protected:
std::shared_ptr<op::Parameter> get_ng_parameter() const
{
return std::make_shared<op::Parameter>(get_element_type(), get_shape());
}
std::shared_ptr<op::Constant> get_ng_constant(const Tensor& tensor) const
{
switch (m_value_info_proto->type().tensor_type().elem_type())
{
case onnx::TensorProto_DataType::TensorProto_DataType_BOOL:
return make_ng_constant<bool>(element::boolean, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT:
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT16:
return make_ng_constant<float>(element::f32, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_DOUBLE:
return make_ng_constant<double>(element::f64, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT8:
return make_ng_constant<int8_t>(element::i8, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT16:
return make_ng_constant<int16_t>(element::i16, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT32:
return make_ng_constant<int32_t>(element::i32, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT64:
return make_ng_constant<int64_t>(element::i64, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT8:
return make_ng_constant<uint8_t>(element::u8, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT16:
return make_ng_constant<uint16_t>(element::u16, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT32:
return make_ng_constant<uint32_t>(element::u32, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT64:
return make_ng_constant<uint64_t>(element::u64, tensor);
default:
throw error::value_info::unsupported_element_type{
m_value_info_proto->type().tensor_type().elem_type()};
}
}
template <typename T>
std::shared_ptr<op::Constant> make_ng_constant(const element::Type& type,
const Tensor& tensor) const
{
return std::make_shared<op::Constant>(type, m_shape, tensor.get_data<T>());
}
private:
const onnx::ValueInfoProto* m_value_info_proto;
Shape m_shape;
};
inline std::ostream& operator<<(std::ostream& outs, const ValueInfo& info)
{
return (outs << "<ValueInfo: " << info.get_name() << ">");
}
} // namespace onnx_import
} // namespace ngraph
| 45.066667 | 100 | 0.568047 | bergtholdt |
0620bd7b0f9c0b556ffb8af1fdee66019a3353cc | 9,794 | cpp | C++ | vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_lim_code.cpp | qtwre/Open-Vehicle-Monitoring-System-3 | 0ebd21bdff06190c0909c29b215ab63f5792e7d6 | [
"MIT"
] | 322 | 2017-06-12T16:56:49.000Z | 2022-03-27T15:46:38.000Z | vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_lim_code.cpp | qtwre/Open-Vehicle-Monitoring-System-3 | 0ebd21bdff06190c0909c29b215ab63f5792e7d6 | [
"MIT"
] | 426 | 2017-08-30T04:47:34.000Z | 2022-03-25T21:01:11.000Z | vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_lim_code.cpp | qtwre/Open-Vehicle-Monitoring-System-3 | 0ebd21bdff06190c0909c29b215ab63f5792e7d6 | [
"MIT"
] | 194 | 2017-07-03T23:34:08.000Z | 2022-03-16T09:09:22.000Z |
//
// Warning: don't edit - generated by generate_ecu_code.pl processing ../dev/lim_i1.json: LIM 14: Charging interface module
// This generated code makes it easier to process CANBUS messages from the LIM ecu in a BMW i3
//
case I3_PID_LIM_STATUS_CALCVN: { // 0x2541
if (datalen < 20) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_STATUS_CALCVN", 20);
break;
}
unsigned long STAT_CVN_WERT = (RXBUF_UINT32(16));
// Read out CVN (here the CVN must be output as in mode $ 09 (PID $ 06)) / CVN auslesen (hier muss die CVN wie
// bei Mode $09 (PID $06) ausgegeben werden)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%lu%s\n", "LIM", "STATUS_CALCVN", "STAT_CVN_WERT", STAT_CVN_WERT, "\"HEX\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_LADESTECKDOSE_TEMPERATUR: { // 0xDB0F
if (datalen < 2) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADESTECKDOSE_TEMPERATUR", 2);
break;
}
float STAT_LADESTECKDOSE_TEMP_WERT = (RXBUF_UINT(0)/10.0f-40.0);
// Temperature of the DC charging connection in ° C (China) / Temperatur der DC-Ladeanschluss in °C (China)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "LIM", "LADESTECKDOSE_TEMPERATUR", "STAT_LADESTECKDOSE_TEMP_WERT", STAT_LADESTECKDOSE_TEMP_WERT, "\"°C\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_LADEBEREITSCHAFT_LIM: { // 0xDEF2
if (datalen < 1) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADEBEREITSCHAFT_LIM", 1);
break;
}
unsigned char STAT_LADEBEREITSCHAFT_LIM = (RXBUF_UCHAR(0));
// Ready to charge (HW line), (1 = yes, 0 = no) sent from LIM to SLE / Ladebereitschaft (HW-Leitung), (1 = ja, 0
// = nein) vom LIM an SLE gesendet
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADEBEREITSCHAFT_LIM", "STAT_LADEBEREITSCHAFT_LIM", STAT_LADEBEREITSCHAFT_LIM, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_PROXIMITY: { // 0xDEF5
if (datalen < 2) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_PROXIMITY", 2);
break;
}
unsigned char STAT_STECKER_NR = (RXBUF_UCHAR(0));
// Condition of the plug / Zustand des Steckers
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PROXIMITY", "STAT_STECKER_NR", STAT_STECKER_NR, "\"0-n\"");
unsigned char STAT_STROMTRAGFAEHIGKEIT_WERT = (RXBUF_UCHAR(1));
// Current carrying capacity of the connected cable / Stromtragfähigkeit des angeschlossenen Kabels
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PROXIMITY", "STAT_STROMTRAGFAEHIGKEIT_WERT", STAT_STROMTRAGFAEHIGKEIT_WERT, "\"A\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_PILOTSIGNAL: { // 0xDEF6
if (datalen < 7) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_PILOTSIGNAL", 7);
break;
}
unsigned char STAT_PILOT_AKTIV = (RXBUF_UCHAR(0));
// State of the pilot signal (0 = not active, 1 = active) / Zustand des Pilotsignals (0 = nicht aktiv, 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_AKTIV", STAT_PILOT_AKTIV, "\"0/1\"");
unsigned char STAT_PILOT_PWM_DUTYCYCLE_WERT = (RXBUF_UCHAR(1));
// Pulse duty factor PWM pilot signal / Tastverhältnis PWM Pilotsignal
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_PWM_DUTYCYCLE_WERT", STAT_PILOT_PWM_DUTYCYCLE_WERT, "\"%\"");
unsigned char STAT_PILOT_CURRENT_WERT = (RXBUF_UCHAR(2));
// Current value calculated from the pilot signal / Errechneter Stromwert aus Pilotsignal
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_CURRENT_WERT", STAT_PILOT_CURRENT_WERT, "\"A\"");
unsigned char STAT_PILOT_LADEBEREIT = (RXBUF_UCHAR(3));
// Vehicle ready to charge state (0 = not ready to charge, 1 = ready to charge) / Zustand Ladebereitschaft
// Fahrzeug (0 = nicht ladebereit, 1 = ladebereit)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_LADEBEREIT", STAT_PILOT_LADEBEREIT, "\"0/1\"");
unsigned short STAT_PILOT_FREQUENZ_WERT = (RXBUF_UINT(4));
// Frequency of the pilot signal / Frequenz des Pilotsignals
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_FREQUENZ_WERT", STAT_PILOT_FREQUENZ_WERT, "\"Hz\"");
float STAT_PILOT_PEGEL_WERT = (RXBUF_UCHAR(6)/10.0f);
// Pilot signal level / Pegel des Pilotsignals
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_PEGEL_WERT", STAT_PILOT_PEGEL_WERT, "\"V\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_LADESCHNITTSTELLE_DC_TEPCO: { // 0xDEF7
if (datalen < 4) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADESCHNITTSTELLE_DC_TEPCO", 4);
break;
}
unsigned char STAT_CHARGE_CONTROL_1 = (RXBUF_UCHAR(0));
// Charge control status 1 line (0 = not active, 1 = active) / Zustand Charge control 1 Leitung (0 = nicht aktiv,
// 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_CONTROL_1", STAT_CHARGE_CONTROL_1, "\"0/1\"");
unsigned char STAT_CHARGE_CONTROL_2 = (RXBUF_UCHAR(1));
// Charge control status 2 line (0 = not active, 1 = active) / Zustand Charge control 2 Leitung (0 = nicht aktiv,
// 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_CONTROL_2", STAT_CHARGE_CONTROL_2, "\"0/1\"");
unsigned char STAT_CHARGE_PERMISSION = (RXBUF_UCHAR(2));
// Charge permission line status (0 = not active, 1 = active) / Zustand Charge Permission Leitung (0 = nicht
// aktiv, 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_PERMISSION", STAT_CHARGE_PERMISSION, "\"0/1\"");
unsigned char STAT_LADESTECKER = (RXBUF_UCHAR(3));
// State of charging plug (0 = not plugged in, 1 = plugged in) / Zustand Ladestecker (0 = nicht gesteckt, 1 =
// gesteckt)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_LADESTECKER", STAT_LADESTECKER, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_DC_SCHUETZ_SCHALTER: { // 0xDEF8
if (datalen < 1) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_SCHUETZ_SCHALTER", 1);
break;
}
unsigned char STAT_DC_SCHUETZ_SCHALTER = (RXBUF_UCHAR(0));
// Contactor switch status (DC charging) / Status Schützschalter (DC-Laden)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_SCHUETZ_SCHALTER", "STAT_DC_SCHUETZ_SCHALTER", STAT_DC_SCHUETZ_SCHALTER, "\"0-n\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_DC_SCHUETZ_SPANNUNG_EINGANG: { // 0xDEF9
if (datalen < 3) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_SCHUETZ_SPANNUNG_EINGANG", 3);
break;
}
unsigned short STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT = (RXBUF_UINT(0));
// Voltage at the input of the relay box (contactors) for DC charging / Spannung am Eingang der Relaisbox
// (Schaltschütze) für DC-Laden
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "LIM", "DC_SCHUETZ_SPANNUNG_EINGANG", "STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT", STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT, "\"V\"");
unsigned char STAT_DC_SCHUETZ_SPANNUNG_NEGATIV = (RXBUF_UCHAR(2));
// Detection of a negative voltage (0 = no or positive voltage / 1 = negative voltage) / Erkennung einer
// negativen Spannung (0 = keine oder positive Spannung / 1 = negative Spannung)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_SCHUETZ_SPANNUNG_EINGANG", "STAT_DC_SCHUETZ_SPANNUNG_NEGATIV", STAT_DC_SCHUETZ_SPANNUNG_NEGATIV, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_DC_PINABDECKUNG_COMBO: { // 0xDEFA
if (datalen < 1) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_PINABDECKUNG_COMBO", 1);
break;
}
unsigned char STAT_DC_PINABDECKUNG = (RXBUF_UCHAR(0));
// State of the DC pin cover for combo socket (0 = closed, 1 = open) / Zustand der DC Pinabdeckung bei
// Combo-Steckdose (0 = geschlossen, 1 = geöffnet)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_PINABDECKUNG_COMBO", "STAT_DC_PINABDECKUNG", STAT_DC_PINABDECKUNG, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
| 48.97 | 183 | 0.620584 | qtwre |
0621aa73a23d5b4465d601edd464d7b63fdd5a36 | 3,494 | cpp | C++ | Code/Projects/Eldritch/src/Components/wbcompeldlight.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Projects/Eldritch/src/Components/wbcompeldlight.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Projects/Eldritch/src/Components/wbcompeldlight.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | #include "core.h"
#include "wbcompeldlight.h"
#include "wbcompeldtransform.h"
#include "wbevent.h"
#include "eldritchworld.h"
#include "idatastream.h"
#include "configmanager.h"
WBCompEldLight::WBCompEldLight()
: m_Radius(0.0f),
m_Color(),
m_HasAddedLight(false),
m_LightLocation(),
m_DeferAddLight(false) {}
WBCompEldLight::~WBCompEldLight() { RemoveLight(); }
/*virtual*/ void WBCompEldLight::InitializeFromDefinition(
const SimpleString& DefinitionName) {
Super::InitializeFromDefinition(DefinitionName);
MAKEHASH(DefinitionName);
STATICHASH(Radius);
m_Radius = ConfigManager::GetInheritedFloat(sRadius, 0.0f, sDefinitionName);
STATICHASH(ColorR);
m_Color.r = ConfigManager::GetInheritedFloat(sColorR, 0.0f, sDefinitionName);
STATICHASH(ColorG);
m_Color.g = ConfigManager::GetInheritedFloat(sColorG, 0.0f, sDefinitionName);
STATICHASH(ColorB);
m_Color.b = ConfigManager::GetInheritedFloat(sColorB, 0.0f, sDefinitionName);
m_Color.a = 1.0f;
STATICHASH(DeferAddLight);
m_DeferAddLight =
ConfigManager::GetInheritedBool(sDeferAddLight, false, sDefinitionName);
}
/*virtual*/ void WBCompEldLight::HandleEvent(const WBEvent& Event) {
XTRACE_FUNCTION;
Super::HandleEvent(Event);
STATIC_HASHED_STRING(OnMoved);
STATIC_HASHED_STRING(OnDestroyed);
STATIC_HASHED_STRING(AddLight);
STATIC_HASHED_STRING(RemoveLight);
const HashedString EventName = Event.GetEventName();
if (EventName == sOnMoved) {
if (m_DeferAddLight) {
// Do nothing
} else {
AddLight();
}
} else if (EventName == sAddLight) {
AddLight();
} else if (EventName == sOnDestroyed || EventName == sRemoveLight) {
RemoveLight();
}
}
void WBCompEldLight::AddLight() {
// I don't currently want to support dynamic light-emitting entities.
// So this event handles the first time a static entity's location is set.
// But if it moves again, that's a problem!
if (m_HasAddedLight) {
return;
}
WBCompEldTransform* pTransform =
GetEntity()->GetTransformComponent<WBCompEldTransform>();
DEVASSERT(pTransform);
m_LightLocation = pTransform->GetLocation();
m_HasAddedLight = GetWorld()->AddLightAt(m_LightLocation, m_Radius, m_Color);
}
void WBCompEldLight::RemoveLight() {
if (m_HasAddedLight) {
m_HasAddedLight = false;
if (GetWorld()) {
GetWorld()->RemoveLightAt(m_LightLocation);
}
}
}
#define VERSION_EMPTY 0
#define VERSION_LIGHT 1
#define VERSION_CURRENT 1
uint WBCompEldLight::GetSerializationSize() {
uint Size = 0;
Size += 4; // Version
Size += sizeof(bool); // m_HasAddedLight
Size += sizeof(Vector); // m_LightLocation
return Size;
}
void WBCompEldLight::Save(const IDataStream& Stream) {
Stream.WriteUInt32(VERSION_CURRENT);
Stream.WriteBool(m_HasAddedLight);
#ifdef __amigaos4__
Vector tmp(m_LightLocation);
littleBigEndian(&tmp.x);
littleBigEndian(&tmp.y);
littleBigEndian(&tmp.z);
Stream.Write(sizeof(Vector), &tmp);
#else
Stream.Write(sizeof(Vector), &m_LightLocation);
#endif
}
void WBCompEldLight::Load(const IDataStream& Stream) {
XTRACE_FUNCTION;
const uint Version = Stream.ReadUInt32();
if (Version >= VERSION_LIGHT) {
m_HasAddedLight = Stream.ReadBool();
Stream.Read(sizeof(Vector), &m_LightLocation);
#ifdef __amigaos4__
littleBigEndian(&m_LightLocation.x);
littleBigEndian(&m_LightLocation.y);
littleBigEndian(&m_LightLocation.z);
#endif
}
} | 25.881481 | 79 | 0.716943 | kas1e |
0621e82627b5480d55556f399fe6b36adde14df9 | 3,670 | cpp | C++ | Engine/Plugins/Runtime/Steam/SteamVR/Source/SteamVR/Private/SteamVRSpectatorScreen.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Runtime/Steam/SteamVR/Source/SteamVR/Private/SteamVRSpectatorScreen.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Runtime/Steam/SteamVR/Source/SteamVR/Private/SteamVRSpectatorScreen.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
//
#include "CoreMinimal.h"
#include "SteamVRPrivate.h"
#if STEAMVR_SUPPORTED_PLATFORMS
#include "SteamVRHMD.h"
#include "RendererPrivate.h"
#include "ScenePrivate.h"
#include "PostProcess/PostProcessHMD.h"
#include "PipelineStateCache.h"
#include "ClearQuad.h"
#include "DefaultSpectatorScreenController.h"
#if PLATFORM_LINUX
#include "VulkanRHIPrivate.h"
#include "ScreenRendering.h"
#include "VulkanPendingState.h"
#include "VulkanContext.h"
#endif
void FSteamVRHMD::CreateSpectatorScreenController()
{
SpectatorScreenController = MakeUnique<FDefaultSpectatorScreenController>(this);
}
FIntRect FSteamVRHMD::GetFullFlatEyeRect_RenderThread(FTexture2DRHIRef EyeTexture) const
{
static FVector2D SrcNormRectMin(0.05f, 0.2f);
static FVector2D SrcNormRectMax(0.45f, 0.8f);
return FIntRect(EyeTexture->GetSizeX() * SrcNormRectMin.X, EyeTexture->GetSizeY() * SrcNormRectMin.Y, EyeTexture->GetSizeX() * SrcNormRectMax.X, EyeTexture->GetSizeY() * SrcNormRectMax.Y);
}
void FSteamVRHMD::CopyTexture_RenderThread(FRHICommandListImmediate& RHICmdList, FTexture2DRHIParamRef SrcTexture, FIntRect SrcRect, FTexture2DRHIParamRef DstTexture, FIntRect DstRect, bool bClearBlack) const
{
check(IsInRenderingThread());
const uint32 ViewportWidth = DstRect.Width();
const uint32 ViewportHeight = DstRect.Height();
const FIntPoint TargetSize(ViewportWidth, ViewportHeight);
const float SrcTextureWidth = SrcTexture->GetSizeX();
const float SrcTextureHeight = SrcTexture->GetSizeY();
float U = 0.f, V = 0.f, USize = 1.f, VSize = 1.f;
if (!SrcRect.IsEmpty())
{
U = SrcRect.Min.X / SrcTextureWidth;
V = SrcRect.Min.Y / SrcTextureHeight;
USize = SrcRect.Width() / SrcTextureWidth;
VSize = SrcRect.Height() / SrcTextureHeight;
}
SetRenderTarget(RHICmdList, DstTexture, FTextureRHIRef());
if (bClearBlack)
{
const FIntRect ClearRect(0, 0, DstTexture->GetSizeX(), DstTexture->GetSizeY());
RHICmdList.SetViewport(ClearRect.Min.X, ClearRect.Min.Y, 0, ClearRect.Max.X, ClearRect.Max.Y, 1.0f);
DrawClearQuad(RHICmdList, FLinearColor::Black);
}
RHICmdList.SetViewport(DstRect.Min.X, DstRect.Min.Y, 0, DstRect.Max.X, DstRect.Max.Y, 1.0f);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
const auto FeatureLevel = GMaxRHIFeatureLevel;
auto ShaderMap = GetGlobalShaderMap(FeatureLevel);
TShaderMapRef<FScreenVS> VertexShader(ShaderMap);
TShaderMapRef<FScreenPS> PixelShader(ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = RendererModule->GetFilterVertexDeclaration().VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
const bool bSameSize = DstRect.Size() == SrcRect.Size();
if (bSameSize)
{
PixelShader->SetParameters(RHICmdList, TStaticSamplerState<SF_Point>::GetRHI(), SrcTexture);
}
else
{
PixelShader->SetParameters(RHICmdList, TStaticSamplerState<SF_Bilinear>::GetRHI(), SrcTexture);
}
RendererModule->DrawRectangle(
RHICmdList,
0, 0,
ViewportWidth, ViewportHeight,
U, V,
USize, VSize,
TargetSize,
FIntPoint(1, 1),
*VertexShader,
EDRF_Default);
}
#endif // STEAMVR_SUPPORTED_PLATFORMS
| 33.363636 | 208 | 0.788011 | windystrife |
1646804752e4aa8d221bb3f28fc88fc8709acbb9 | 12,586 | cpp | C++ | main.cpp | erlog/laughing-couscous | ef5f3ec1e83d524ebad04fd6d62e5b39d95ec413 | [
"MIT",
"Ruby",
"Unlicense"
] | null | null | null | main.cpp | erlog/laughing-couscous | ef5f3ec1e83d524ebad04fd6d62e5b39d95ec413 | [
"MIT",
"Ruby",
"Unlicense"
] | null | null | null | main.cpp | erlog/laughing-couscous | ef5f3ec1e83d524ebad04fd6d62e5b39d95ec413 | [
"MIT",
"Ruby",
"Unlicense"
] | null | null | null | //Compile-time Flags
//#define MAC_COMPILE 0
//#define LINUX_COMPILE 1
#define MEMORY_LOGGING 0
#define DEBUG 1
#include "main.h"
int main() {
//INITIALIZATION- Failures here cause a hard exit
//Start Ruby
ruby_setup_environment(); //VALUE rb_update_func = rb_intern("ruby_update");
//Initialize State & Debug Memory Manager
Memory_Info mem_info = {0}; Global_State = &mem_info;
State* state = (State*)walloc(sizeof(State));
//Load global strings
String_DB _string_db;
state->Strings = &_string_db;
load_strings(state->Strings, "english");
wfree_string_db(state->Strings);
//Initialize game input
state->Input = (Game_Input*)walloc(sizeof(Game_Input));
clear_input(state->Input);
//Load global settings file
load_settings(state);
state->IsRunning = true; //Set this to false to exit after one frame
state->IsPaused = true; //Pause will be toggled when our window gains focus
//DEBUG: Initialize rand()
//TODO: remove this
time_t t;
srand((unsigned) time(&t));
//Initialize screen struct and buffer for taking screenshots
state->Screen = (Texture*)walloc(sizeof(Texture));
state->Screen->asset_path = str_lit("Flamerokz");
state->Screen->width = state->Settings.horizontal_resolution;
state->Screen->height = state->Settings.vertical_resolution;
state->Screen->bytes_per_pixel = 3;
state->Screen->pitch = state->Screen->width * state->Screen->bytes_per_pixel;
state->Screen->buffer_size = state->Screen->pitch * state->Screen->height;
state->Screen->buffer = (uint8_t*)walloc(state->Screen->buffer_size);
//Initialize SDL and OpenGL
SDL_Event event;
int error = SDL_Init(SDL_INIT_VIDEO); if(error != 0) {
message_log("SDL Init Error, Code", error); return 0;
}
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); //Use OpenGL 3.1
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
//TODO: implement fullscreen
SDL_Window* window = SDL_CreateWindow( state->Screen->asset_path,
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, state->Screen->width,
state->Screen->height, SDL_WINDOW_OPENGL);
if(window == NULL) {
message_log("Couldn't initialize-", "SDL OpenGL window"); return 0;
}
state->Window = window;
SDL_GLContext context = SDL_GL_CreateContext( window );
if(context == NULL) {
message_log("Couldn't get-", "OpenGL Context for window"); return 0;
}
if(state->Settings.vsync) { if(SDL_GL_SetSwapInterval(1) != 0) {
//late-swap tearing if the vsync call fails
SDL_GL_SetSwapInterval(-1);
} }
const uint8_t* SDL_KeyState = SDL_GetKeyboardState(NULL);
//GLEW
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK) {
message_log("Couldn't initialize-", "GLEW"); return 0;
}
if(!GLEW_VERSION_2_1) {
message_log("OpenGL 2.1 not supported by GLEW", ""); return 0;
}
//Set up simple OpenGL environment for rendering
glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glMatrixMode( GL_PROJECTION ); glLoadIdentity();
glMatrixMode( GL_MODELVIEW ); glLoadIdentity();
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE);
//glFrontFace(GL_CCW); //Default is CCW, counter-clockwise
//glDepthRange(1.0, -1.0); //change the handedness of the z axis
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//GAME INIT- Failures here may cause a proper smooth exit when necessary
//Construct Camera
state->Camera = (Scene_Camera*)walloc(sizeof(Scene_Camera));
state->Camera->physics = (Physics_Object*)walloc(sizeof(Physics_Object));
load_physics(state->Camera->physics);
state->Camera->projection = glm::perspective(glm::radians(45.0f),
(float)state->Screen->width/state->Screen->height, 0.1f, 100.0f);
//Construct screen-space camera for HUD elements
Scene_Camera screen_camera;
screen_camera.physics = (Physics_Object*)walloc(sizeof(Physics_Object));
load_physics(screen_camera.physics);
//TODO: figure out how to make this in semi-normalized coords that
//can be somewhat resolution-independent
screen_camera.projection = glm::ortho(0.0f, (float)state->Screen->width,
0.0f, (float)state->Screen->height);
//Load Objects
state->Debug_Cube = (Object*)walloc(sizeof(Object));
load_object(state->Debug_Cube, "cube", "blank", "blank_nm",
"blank_spec", "shader");
state->Debug_Sphere = (Object*)walloc(sizeof(Object));
load_object(state->Debug_Sphere, "sphere", "blank", "blank_nm",
"blank_spec", "flat_shaded");
state->Player = (Object*)walloc(sizeof(Object));
load_object(state->Player, "wedge", "cheese", "blank_nm_512",
"cheese_spec", "shader");
state->Player->model->color = rgb_to_vector(0xE7, 0xE0, 0x8B);
state->Player->physics->position = glm::vec3(0.0f, -1.0f, 0.0f);
glm::vec3 light_direction = glm::vec3(0.0f, -1.0f, -1.0f);
normalize(&light_direction);
//TODO: break this out into level loading code
state->ObjectCount = 3;
state->Objects = (Object*)walloc(sizeof(Object)*state->ObjectCount);
load_object(&state->Objects[0], "cube", "blank", "blank_nm",
"blank_spec", "flat");
state->Objects[0].physics->position = glm::vec3(-10.5f, 0.0f, 0.0f);
state->Objects[0].physics->rotation_vector = glm::vec3(1.0f, 1.0f, 0.0f);
state->Objects[0].light_direction = light_direction;
state->Objects[0].model->color = rgb_to_vector(0xE3, 0x1F, 0x1F);
load_object(&state->Objects[1], "african_head", "african_head", "african_head",
"african_head", "flat_shaded");
state->Objects[1].physics->position = glm::vec3(10.5f, 0.0f, 0.0f);
state->Objects[1].physics->rotation_vector = glm::vec3(0.0f, 1.0f, 0.0f);
state->Objects[1].light_direction = light_direction;
state->Objects[1].model->color = rgb_to_vector(0xE3, 0x78, 0x1F);
state->Objects[1].model->scale = glm::vec3(5.0f, 5.0f, 5.0f);
load_object(&state->Objects[2], "cone", "blank", "blank_nm",
"blank_spec", "flat_shaded");
state->Objects[2].physics->position = glm::vec3(-15.5f, 0.0f, 0.0f);
state->Objects[2].physics->rotation_vector = glm::vec3(0.0f, 0.0f, 1.0f);
state->Objects[2].light_direction = light_direction;
state->Objects[2].model->color = rgb_to_vector(0x19, 0xB5, 0x19);
state->Level = (Game_Level*)walloc(sizeof(Game_Level));
load_level(state->Level, "test_level");
//octree_print(&state->Level->octree->root);
Font test_font;
UChar* test_text = UChar_convert("#testing, unicode, 微研");
load_font(&test_font, "DroidSans");
//MAIN LOOP- Failures here may cause a proper smooth exit when necessary
message_log("Starting update loop.");
//TODO: figure out how to start my clock without eating the first frame
state->TimeDifference = 0;
state->LastUpdateTime = 0;
state->PauseStartTime = 0;
int passed_frames = 0;
while(state->IsRunning) {
update_time(state);
//Process keydown events
while(SDL_PollEvent(&event)) { switch(event.type) {
case SDL_WINDOWEVENT:
if(event.window.event == SDL_WINDOWEVENT_SHOWN) {
SDL_SetRelativeMouseMode(SDL_TRUE);
//eat first input to avoid movement jitter
SDL_GetRelativeMouseState(NULL, NULL);
toggle_pause(state);
} else if(event.window.event == SDL_WINDOWEVENT_HIDDEN) {
SDL_SetRelativeMouseMode(SDL_FALSE);
toggle_pause(state);
}
break;
case SDL_KEYDOWN:
handle_keyboard(state, event);
break;
case SDL_QUIT:
state->IsRunning = false;
break;
} }
if(state->IsPaused) { continue; }
poll_input(state, SDL_KeyState);
//TODO: is there a better way to control our framerate?
if( state->DeltaTimeMS > 30 ) {
process_input(state);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//TODO: unified camera system
//first person camera
#if 0
state->Camera->direction = glm::normalize(
glm::vec3(0.0f, 0.0f, -1.0f) * state->Camera->physics->quaternion);
state->Camera->view = glm::lookAt(state->Camera->physics->position,
state->Camera->direction + state->Camera->physics->position,
glm::vec3(0.0f, 1.0f, 0.0f));
state->Camera->physics->quaternion =
glm::quat_cast(state->Camera->view);
#endif
//3rd-person camera
#if 1
state->Camera->physics->position = state->Player->physics->position +
(glm::vec3(0.0f, 6.0f, 6.0f) * state->Camera->physics->quaternion);
state->Camera->view = glm::lookAt(state->Camera->physics->position,
state->Player->physics->position,
glm::vec3(0.0f, 1.0f, 0.0f));
#endif
//draw dynamic objects
for(int i = 0; i < state->ObjectCount; i++) {
//state->Objects[i].physics->angular_velocity = 30.0f;
//update_physics_object(state->Objects[i].physics, state->DeltaTimeS);
gl_draw_object(state->Camera, &state->Objects[i]);
}
//draw level
gl_draw_object(state->Camera, state->Level->geometry);
//octree_debug_draw(state->Level->octree, state);
//do player movement relative to the camera
state->Player->physics->quaternion = state->Camera->physics->quaternion;
state->Player->physics->time_remaining = state->DeltaTimeS;
physics_process_movement(state->Player->physics);
//TODO: make our collision detection not require this sanity check
if(state->Player->physics->moved) {
for(int reps = 0; reps < 25; reps ++) {
if(!process_collision(state->Level, state->Player->physics)) {
break;
}
}
}
//face model in direction of movement
physics_face_movement_direction(state->Player);
gl_draw_object(state->Camera, state->Player);
//draw bounding box
#if 1
state->Debug_Sphere->physics->position = state->Player->physics->position;
state->Debug_Sphere->model->scale = state->Player->physics->radii;
//state->Debug_Sphere->model->rotation = state->Player->model->rotation;
gl_toggle_wireframe(true);
gl_draw_object(state->Camera, state->Debug_Sphere);
gl_toggle_wireframe(false);
#endif
//draw test text
//TODO: make this an FPS counter
test_font.quad->physics->position = glm::vec3(0.0f, 8.0f, 0.0f);
gl_draw_text(&screen_camera, &test_font, test_text, 32.0f);
SDL_GL_SwapWindow(window);
state->LastUpdateTime = state->GameTime;
state->FrameCounter += 1;
//Spit out debug info
if(state->FrameCounter > 100) {
float fps = (float)state->FrameCounter;
fps /= (state->WallTime - state->LastFPSUpdateTime);
message_log("FPS-", fps*1000);
fps = (float)passed_frames;
fps /= (state->WallTime - state->LastFPSUpdateTime);
message_log("Loops spent idling per second-", fps*1000);
message_log("Memory in use-", mem_info.MemoryAllocated -
mem_info.MemoryFreed);
passed_frames = 0;
state->FrameCounter = 0;
state->LastFPSUpdateTime = state->WallTime;
}
clear_input(state->Input);
}
else { passed_frames++; }
}
take_screenshot(state);
wfree_font(&test_font);
wfree_camera(&screen_camera);
wfree(test_text);
wfree_state(state);
wfree(state);
ruby_cleanup(0);
printf("Leaked- %lu Bytes", mem_info.MemoryAllocated - mem_info.MemoryFreed);
SDL_Quit();
return 0;
}
| 39.454545 | 86 | 0.622199 | erlog |
164bf7629950c384ca4357f1bb52a8375321f6bd | 2,112 | cpp | C++ | Javelin/Tools/jasm/CodeSegmentSource.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | 10 | 2016-04-06T01:24:00.000Z | 2021-11-16T10:16:51.000Z | Javelin/Tools/jasm/CodeSegmentSource.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | 1 | 2016-05-06T05:38:58.000Z | 2016-05-09T16:42:43.000Z | Javelin/Tools/jasm/CodeSegmentSource.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | null | null | null | //============================================================================
#include "Javelin/Tools/jasm/CodeSegmentSource.h"
//============================================================================
using namespace Javelin::Assembler;
//============================================================================
CodeSegmentSource::CodeSegmentSource(const CodeSegmentData &aData, int aIndent)
: data(aData), indent(aIndent)
{
}
int CodeSegmentSource::ReadByte()
{
if(index >= data.size()) return EOF;
const std::string& s = data[index].line;
if(offset >= s.size())
{
offset = 0;
++index;
return '\n';
}
return (uint8_t) s[offset++];
}
int CodeSegmentSource::PeekByte()
{
if(index >= data.size()) return EOF;
const std::string& s = data[index].line;
if(offset >= s.size()) return '\n';
return (uint8_t) s[offset];
}
void CodeSegmentSource::SkipByte()
{
if(index >= data.size()) return;
const std::string& s = data[index].line;
if(offset >= s.size())
{
offset = 0;
++index;
}
else
{
++offset;
}
}
//============================================================================
int CodeSegmentSource::GetCurrentLineNumber() const
{
if(data.size() == 0) return 0;
if(index >= data.size()) return data[index-1].lineNumber;
return data[index].lineNumber;
}
const std::string CodeSegmentSource::GetPreviousLine() const
{
if(data.size() == 0) return "";
if(index == 0) return data[0].line;
return data[index-1].line;
}
const std::string CodeSegmentSource::GetCurrentLine() const
{
if(data.size() == 0) return "";
if(index >= data.size()) return data[index-1].line;
return data[index].line;
}
int CodeSegmentSource::GetCurrentFileIndex() const
{
if(data.size() == 0) return 0;
if(index >= data.size()) return data[index-1].fileIndex;
return data[index].fileIndex;
}
bool CodeSegmentSource::GetCurrentLineIsPreprocessor() const
{
if(data.size() == 0) return false;
if(index >= data.size()) return data[index-1].isPreprocessor;
return data[index].isPreprocessor;
}
//============================================================================
| 22.231579 | 79 | 0.551136 | jthlim |
164fb7502e74fbb74baf2e56db0e25f829ea3ece | 10,317 | cpp | C++ | dotth/D3D11RHI.cpp | jaefunk/dotth | d93c69a1744c545606bec3ee0cdc8f46b5c19d36 | [
"MIT"
] | null | null | null | dotth/D3D11RHI.cpp | jaefunk/dotth | d93c69a1744c545606bec3ee0cdc8f46b5c19d36 | [
"MIT"
] | 8 | 2019-11-05T00:06:59.000Z | 2022-03-28T09:20:40.000Z | dotth/D3D11RHI.cpp | jaefunk/dotth | d93c69a1744c545606bec3ee0cdc8f46b5c19d36 | [
"MIT"
] | null | null | null | #include "D3D11RHI.h"
#include "D3D11Shader.h"
D3D11RHI::~D3D11RHI()
{
D3D11RHI::Instance()->_Device->Release();
D3D11RHI::Instance()->_Context->Release();;
D3D11RHI::Instance()->_SwapChain->Release();
D3D11RHI::Instance()->_BackBufferRTV->Release();
D3D11RHI::Instance()->_RasterizerStateSolid->Release();
D3D11RHI::Instance()->_SamplerState->Release();
D3D11RHI::Instance()->_DepthStencilView->Release();;
}
bool D3D11RHI::Initialize(HWND hwnd, unsigned int width, unsigned int height)
{
D3D11RHI::Instance()->_Width = width;
D3D11RHI::Instance()->_Height = height;
D3D11RHI::Instance()->_FeatureLevel = D3D_FEATURE_LEVEL_11_1;
UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
//createDeviceFlags |= D3D11_DEBUG;
#endif
if (FAILED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, &D3D11RHI::Instance()->_FeatureLevel, 1, D3D11_SDK_VERSION, &D3D11RHI::Instance()->_Device, nullptr, &D3D11RHI::Instance()->_Context)))
{
return false;
}
IDXGIFactory* factory = nullptr;
if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory)))
{
return false;
}
const unsigned int RenderTargetWidth = width;
const unsigned int RenderTargetHeight = height;
DXGI_SWAP_CHAIN_DESC scd;
ZeroMemory(&scd, sizeof(scd));
scd.BufferCount = 1;
scd.BufferDesc.Width = RenderTargetWidth;
scd.BufferDesc.Height = RenderTargetHeight;
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
scd.BufferDesc.RefreshRate.Numerator = 60;
scd.BufferDesc.RefreshRate.Denominator = 1;
scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = (HWND)hwnd;
scd.SampleDesc.Count = 1;
scd.SampleDesc.Quality = 0;
scd.Windowed = true;
scd.Flags = 0;
if (FAILED(factory->CreateSwapChain(D3D11RHI::Instance()->_Device, &scd, &D3D11RHI::Instance()->_SwapChain)))
{
return false;
}
ID3D11Texture2D* backbuffer = nullptr;
D3D11RHI::SwapChain()->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backbuffer));
D3D11RHI::Device()->CreateRenderTargetView(backbuffer, NULL, &D3D11RHI::Instance()->_BackBufferRTV);
backbuffer->Release();
D3D11_TEXTURE2D_DESC db;
ZeroMemory(&db, sizeof(db));
db.Width = RenderTargetWidth;
db.Height = RenderTargetHeight;
db.MipLevels = 1;
db.ArraySize = 1;
db.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
db.SampleDesc.Count = 1;
db.SampleDesc.Quality = 0;
db.Usage = D3D11_USAGE_DEFAULT;
db.BindFlags = D3D11_BIND_DEPTH_STENCIL;
db.CPUAccessFlags = 0;
db.MiscFlags = 0;
ID3D11Texture2D* depthstencilbuffer = nullptr;
D3D11RHI::Device()->CreateTexture2D(&db, NULL, &depthstencilbuffer);
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
D3D11RHI::Device()->CreateDepthStencilState(&depthStencilDesc, &D3D11RHI::Instance()->_DepthStencilState);
D3D11RHI::Context()->OMSetDepthStencilState(D3D11RHI::Instance()->_DepthStencilState, 1);
D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = db.Format;
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvd.Texture2D.MipSlice = 0;
D3D11RHI::Device()->CreateDepthStencilView(depthstencilbuffer, &dsvd, &D3D11RHI::Instance()->_DepthStencilView);
depthstencilbuffer->Release();
D3D11RHI::Context()->OMSetRenderTargets(1, &D3D11RHI::Instance()->_BackBufferRTV, D3D11RHI::DepthStencilView());
D3D11_RASTERIZER_DESC rd;
ZeroMemory(&rd, sizeof(D3D11_RASTERIZER_DESC));
rd.AntialiasedLineEnable = false;
rd.CullMode = D3D11_CULL_BACK;
rd.DepthBias = 0;
rd.DepthBiasClamp = 0.0f;
rd.DepthClipEnable = true;
rd.FillMode = D3D11_FILL_SOLID;
rd.FrontCounterClockwise = false;
rd.MultisampleEnable = false;
rd.ScissorEnable = false;
rd.SlopeScaledDepthBias = 0.0f;
D3D11RHI::Device()->CreateRasterizerState(&rd, &D3D11RHI::Instance()->_RasterizerStateSolid);
D3D11RHI::Context()->RSSetState(D3D11RHI::Instance()->_RasterizerStateSolid);
D3D11_SAMPLER_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sd.ComparisonFunc = D3D11_COMPARISON_NEVER;
sd.MinLOD = 0;
sd.MaxLOD = D3D11_FLOAT32_MAX;
if (FAILED(D3D11RHI::Device()->CreateSamplerState(&sd, &D3D11RHI::Instance()->_SamplerState)))
{
return false;
}
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
viewport.Width = static_cast<float>(RenderTargetWidth);
viewport.Height = static_cast<float>(RenderTargetHeight);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
D3D11RHI::Context()->RSSetViewports(1, &viewport);
D3D11RHI::Instance()->_DeferredBuffer = std::make_shared<D3D11DeferredBuffer>();
D3D11RHI::Instance()->_DeferredBuffer->Initialize(D3D11RHI::Device(), RenderTargetWidth, RenderTargetHeight);
D3D11RHI::Instance()->_OrthoRect = std::make_shared<D3D11OrthoRect>();
D3D11RHI::Instance()->_OrthoRect->Initialize(D3D11RHI::Device(), RenderTargetWidth, RenderTargetHeight);
D3D11RHI::Instance()->_Light = std::make_shared<D3D11Light>();
D3D11RHI::Instance()->_Light->Initialize(D3D11RHI::Device(), hwnd);
D3D11RHI::Instance()->_OrthoMatrix = XMMatrixOrthographicLH(static_cast<float>(D3D11RHI::Instance()->_Width), static_cast<float>(D3D11RHI::Instance()->_Height), 0.f, 1000.f);
return true;
}
void D3D11RHI::InitializeImGui(HWND hwnd, unsigned int width, unsigned int height)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
//ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(D3D11RHI::Device(), D3D11RHI::Context());
}
void D3D11RHI::StandbyDeferred(void)
{
float clear_color_with_alpha[4] = { 0.f, 0.f, 0.f, 0.f };
D3D11RHI::DeferredBuffer()->SetRenderTargets(D3D11RHI::Context());
D3D11RHI::DeferredBuffer()->ClearRenderTargets(D3D11RHI::Context(), clear_color_with_alpha);
}
void D3D11RHI::Draw(void)
{
float clear_color_with_alpha[4] = { 0.f, 0.f, 0.f, 0.f };
D3D11RHI::Context()->OMSetRenderTargets(1, &D3D11RHI::Instance()->_BackBufferRTV, D3D11RHI::DepthStencilView());
D3D11RHI::Context()->ClearRenderTargetView(D3D11RHI::BackBuffer(), clear_color_with_alpha);
D3D11RHI::Context()->ClearDepthStencilView(D3D11RHI::DepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);
D3D11RHI::Context()->OMSetDepthStencilState(D3D11RHI::DepthStencilState(), 0);
D3D11RHI::Instance()->_OrthoRect->Render(D3D11RHI::Context());
D3D11RHI::Instance()->_Light->Render(
D3D11RHI::Context(), 6,
XMMatrixIdentity(),
XMMatrixIdentity(),
D3D11RHI::Instance()->_OrthoMatrix,
D3D11RHI::DeferredBuffer()->GetShaderResourceView(0),
D3D11RHI::DeferredBuffer()->GetShaderResourceView(1),
XMFLOAT3(-1.f, -1.f, 1.f));
}
void D3D11RHI::BeginImGui(void)
{
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
}
void D3D11RHI::EndImGui(void)
{
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
void D3D11RHI::Present(void)
{
D3D11RHI::SwapChain()->Present(1, 0);
}
ID3D11Device* D3D11RHI::Device()
{
return D3D11RHI::Instance()->_Device;
}
ID3D11DeviceContext* D3D11RHI::Context()
{
return D3D11RHI::Instance()->_Context;
}
IDXGISwapChain* D3D11RHI::SwapChain()
{
return D3D11RHI::Instance()->_SwapChain;
}
ID3D11RenderTargetView* D3D11RHI::BackBuffer()
{
return D3D11RHI::Instance()->_BackBufferRTV;
}
ID3D11DepthStencilView* D3D11RHI::DepthStencilView()
{
return D3D11RHI::Instance()->_DepthStencilView;
}
ID3D11SamplerState* D3D11RHI::Sampler()
{
return D3D11RHI::Instance()->_SamplerState;
}
ID3D11DepthStencilState* D3D11RHI::DepthStencilState()
{
return D3D11RHI::Instance()->_DepthStencilState;
}
//
//ID3D11Buffer * D3D11RHI::CreateBuffer(const D3D11_BUFFER_DESC* desc, const D3D11_SUBRESOURCE_DATA* data)
//{
// ID3D11Buffer* buffer = nullptr;
// Device()->CreateBuffer(desc, data, &buffer);
// return buffer;
//}
//
//ID3D11VertexShader * D3D11RHI::CreateVertexShader(ID3DBlob * blob)
//{
// ID3D11VertexShader* shader = nullptr;
// Device()->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &shader);
// return shader;
//}
//
//ID3D11PixelShader * D3D11RHI::CreatePixelShader(ID3DBlob * blob)
//{
// ID3D11PixelShader* shader = nullptr;
// Device()->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &shader);
// return shader;
//}
//
//ID3D11InputLayout * D3D11RHI::CreateInputLayout(ID3DBlob * blob, D3D11_INPUT_ELEMENT_DESC * desc, unsigned int desc_size)
//{
// ID3D11InputLayout* layout = nullptr;
// Device()->CreateInputLayout(desc, desc_size, blob->GetBufferPointer(), blob->GetBufferSize(), &layout);
// return layout;
//}
//
//void D3D11RHI::BindVertexBuffer(ID3D11Buffer* buffer, unsigned int size, unsigned int offset)
//{
// D3D11RHI::Context()->IASetVertexBuffers(0, 1, &buffer, &size, &offset);
//
//}
//
//void D3D11RHI::BindIndexBuffer(ID3D11Buffer* buffer)
//{
// D3D11RHI::Context()->IASetIndexBuffer(buffer, DXGI_FORMAT_R32_UINT, 0);
//}
std::shared_ptr<D3D11DeferredBuffer> D3D11RHI::DeferredBuffer(void)
{
return D3D11RHI::Instance()->_DeferredBuffer;
}
void D3D11RHI::GetViewportSize(unsigned int& width, unsigned int& height)
{
width = D3D11RHI::Instance()->_Width;
height = D3D11RHI::Instance()->_Height;
} | 33.9375 | 245 | 0.765048 | jaefunk |
1650e602e330de0258ece84363a3c6137e7cfed6 | 4,886 | cpp | C++ | src/3rdparty/libnbtplusplus/src/tag_list.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | src/3rdparty/libnbtplusplus/src/tag_list.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | src/3rdparty/libnbtplusplus/src/tag_list.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | /*
* libnbt++ - A library for the Minecraft Named Binary Tag format.
* Copyright (C) 2013, 2015 ljfa-ag
*
* This file is part of libnbt++.
*
* libnbt++ is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* libnbt++ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with libnbt++. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tag_list.h"
#include "nbt_tags.h"
#include "io/stream_reader.h"
#include "io/stream_writer.h"
#include <istream>
namespace nbt
{
tag_list::tag_list(std::initializer_list<int8_t> il) { init<tag_byte>(il); }
tag_list::tag_list(std::initializer_list<int16_t> il) { init<tag_short>(il); }
tag_list::tag_list(std::initializer_list<int32_t> il) { init<tag_int>(il); }
tag_list::tag_list(std::initializer_list<int64_t> il) { init<tag_long>(il); }
tag_list::tag_list(std::initializer_list<float> il) { init<tag_float>(il); }
tag_list::tag_list(std::initializer_list<double> il) { init<tag_double>(il); }
tag_list::tag_list(std::initializer_list<std::string> il) { init<tag_string>(il); }
tag_list::tag_list(std::initializer_list<tag_byte_array> il) { init<tag_byte_array>(il); }
tag_list::tag_list(std::initializer_list<tag_list> il) { init<tag_list>(il); }
tag_list::tag_list(std::initializer_list<tag_compound> il) { init<tag_compound>(il); }
tag_list::tag_list(std::initializer_list<tag_int_array> il) { init<tag_int_array>(il); }
tag_list::tag_list(std::initializer_list<tag_long_array> il) { init<tag_long_array>(il); }
tag_list::tag_list(std::initializer_list<value> init)
{
if(init.size() == 0)
el_type_ = tag_type::Null;
else
{
el_type_ = init.begin()->get_type();
for(const value& val: init)
{
if(!val || val.get_type() != el_type_)
throw std::invalid_argument("The values are not all the same type");
}
tags.assign(init.begin(), init.end());
}
}
value& tag_list::at(size_t i)
{
return tags.at(i);
}
const value& tag_list::at(size_t i) const
{
return tags.at(i);
}
void tag_list::set(size_t i, value&& val)
{
if(val.get_type() != el_type_)
throw std::invalid_argument("The tag type does not match the list's content type");
tags.at(i) = std::move(val);
}
void tag_list::push_back(value_initializer&& val)
{
if(!val) //don't allow null values
throw std::invalid_argument("The value must not be null");
if(el_type_ == tag_type::Null) //set content type if undetermined
el_type_ = val.get_type();
else if(el_type_ != val.get_type())
throw std::invalid_argument("The tag type does not match the list's content type");
tags.push_back(std::move(val));
}
void tag_list::reset(tag_type type)
{
clear();
el_type_ = type;
}
void tag_list::read_payload(io::stream_reader& reader)
{
tag_type lt = reader.read_type(true);
int32_t length;
reader.read_num(length);
if(length < 0)
reader.get_istr().setstate(std::ios::failbit);
if(!reader.get_istr())
throw io::input_error("Error reading length of tag_list");
if(lt != tag_type::End)
{
reset(lt);
tags.reserve(length);
for(int32_t i = 0; i < length; ++i)
tags.emplace_back(reader.read_payload(lt));
}
else
{
//In case of tag_end, ignore the length and leave the type undetermined
reset(tag_type::Null);
}
}
void tag_list::write_payload(io::stream_writer& writer) const
{
if(size() > io::stream_writer::max_array_len)
{
writer.get_ostr().setstate(std::ios::failbit);
throw std::length_error("List is too large for NBT");
}
writer.write_type(el_type_ != tag_type::Null
? el_type_
: tag_type::End);
writer.write_num(static_cast<int32_t>(size()));
for(const auto& val: tags)
{
//check if the value is of the correct type
if(val.get_type() != el_type_)
{
writer.get_ostr().setstate(std::ios::failbit);
throw std::logic_error("The tags in the list do not all match the content type");
}
writer.write_payload(val);
}
}
bool operator==(const tag_list& lhs, const tag_list& rhs)
{
return lhs.el_type_ == rhs.el_type_ && lhs.tags == rhs.tags;
}
bool operator!=(const tag_list& lhs, const tag_list& rhs)
{
return !(lhs == rhs);
}
}
| 32.144737 | 93 | 0.651658 | AgustinSRG |