hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
51e7098934b5e0e3d3c1be331921771523063552 | 1,613 | hpp | C++ | src/test/_test.hpp | BigDataAnalyticsGroup/RewiredCracking | b12bf39b54672d28175f4608d266c505e3611459 | [
"Apache-2.0"
] | 3 | 2019-04-21T07:23:03.000Z | 2019-12-04T02:10:04.000Z | src/test/_test.hpp | BigDataAnalyticsGroup/RewiredCracking | b12bf39b54672d28175f4608d266c505e3611459 | [
"Apache-2.0"
] | null | null | null | src/test/_test.hpp | BigDataAnalyticsGroup/RewiredCracking | b12bf39b54672d28175f4608d266c505e3611459 | [
"Apache-2.0"
] | null | null | null | #ifndef TABLE
#error "#define TABLE to some hash table"
#endif
#ifndef HASH
#error "#define HASH to some hash function"
#endif
#include "test/catch.hpp"
#include <cstdint>
#define STRINGIFY(X) #X
#define STR(X) STRINGIFY(X)
#define PREFIX STR(TABLE) "/" STR(HASH)
using table_type = TABLE<uint64_t, uint64_t, HASH<uint64_t>>;
TEST_CASE( PREFIX )
{
table_type table(-1, 32);
REQUIRE(table.find(42) == table.end());
REQUIRE(table.end() == table.end());
}
TEST_CASE( PREFIX "/insert" )
{
table_type table(-1, 1024);
for (uint64_t i = 0; i != 42; ++i)
table.insert(i, i);
for (uint64_t i = 0; i != 42; ++i) {
auto it = table.find(i);
REQUIRE(it != table.end());
REQUIRE((*it).key == i);
REQUIRE((*it).value == i);
}
for (uint64_t i = 42; i != 1024; ++i)
REQUIRE(table.find(i) == table.end());
}
TEST_CASE( PREFIX "/rehash" )
{
table_type table(-1, 32);
/* initial fill */
for (uint64_t i = 0; i != 10; ++i)
table.insert(i, i);
for (uint64_t i = 0; i != 10; ++i) {
auto it = table.find(i);
REQUIRE(it != table.end());
REQUIRE((*it).key == i);
}
/* fill to trigger rehash(es) */
for (uint64_t i = 10; i != 1000; ++i)
table.insert(i, i);
/* verify state */
REQUIRE(table.size() == 1000);
REQUIRE(table.capacity() >= 1000);
for (uint64_t i = 0; i != 1000; ++i) {
auto it = table.find(i);
REQUIRE(it != table.end());
REQUIRE((*it).key == i);
}
}
#undef TABLE
#undef HASH
#undef STRINGIFY
#undef STR
#undef PREFIX
| 21.223684 | 61 | 0.548667 | BigDataAnalyticsGroup |
51edb584ab6ed521376076b7cf871d1235b04a63 | 43,538 | cpp | C++ | src/modules/GenericPropagation/GenericPropagationModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 3 | 2019-03-04T22:31:32.000Z | 2021-04-20T11:19:17.000Z | src/modules/GenericPropagation/GenericPropagationModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 27 | 2019-04-01T12:25:46.000Z | 2021-09-03T12:20:19.000Z | src/modules/GenericPropagation/GenericPropagationModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 15 | 2017-08-08T14:57:51.000Z | 2021-06-26T17:16:21.000Z | /**
* @file
* @brief Implementation of generic charge propagation module
* @remarks Based on code from Paul Schuetze
* @copyright Copyright (c) 2017-2020 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "GenericPropagationModule.hpp"
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <Eigen/Core>
#include <Math/Point3D.h>
#include <Math/Vector3D.h>
#include <TCanvas.h>
#include <TFile.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TPaveText.h>
#include <TPolyLine3D.h>
#include <TPolyMarker3D.h>
#include <TStyle.h>
#include "core/config/Configuration.hpp"
#include "core/messenger/Messenger.hpp"
#include "core/utils/distributions.h"
#include "core/utils/log.h"
#include "core/utils/unit.h"
#include "tools/ROOT.h"
#include "tools/runge_kutta.h"
#include "objects/DepositedCharge.hpp"
#include "objects/PropagatedCharge.hpp"
using namespace allpix;
/**
* Besides binding the message and setting defaults for the configuration, the module copies some configuration variables to
* local copies to speed up computation.
*/
GenericPropagationModule::GenericPropagationModule(Configuration& config,
Messenger* messenger,
std::shared_ptr<Detector> detector)
: Module(config, detector), messenger_(messenger), detector_(std::move(detector)) {
// Save detector model
model_ = detector_->getModel();
// Require deposits message for single detector
messenger_->bindSingle<DepositedChargeMessage>(this, MsgFlags::REQUIRED);
// Set default value for config variables
config_.setDefault<double>("spatial_precision", Units::get(0.25, "nm"));
config_.setDefault<double>("timestep_start", Units::get(0.01, "ns"));
config_.setDefault<double>("timestep_min", Units::get(0.001, "ns"));
config_.setDefault<double>("timestep_max", Units::get(0.5, "ns"));
config_.setDefault<double>("integration_time", Units::get(25, "ns"));
config_.setDefault<unsigned int>("charge_per_step", 10);
config_.setDefault<double>("temperature", 293.15);
// Models:
config_.setDefault<std::string>("mobility_model", "jacoboni");
config_.setDefault<std::string>("recombination_model", "none");
config_.setDefault<bool>("output_linegraphs", false);
config_.setDefault<bool>("output_animations", false);
config_.setDefault<bool>("output_plots",
config_.get<bool>("output_linegraphs") || config_.get<bool>("output_animations"));
config_.setDefault<bool>("output_animations_color_markers", false);
config_.setDefault<double>("output_plots_step", config_.get<double>("timestep_max"));
config_.setDefault<bool>("output_plots_use_pixel_units", false);
config_.setDefault<bool>("output_plots_align_pixels", false);
config_.setDefault<double>("output_plots_theta", 0.0f);
config_.setDefault<double>("output_plots_phi", 0.0f);
config_.setDefault<bool>("output_plots_lines_at_implants", false);
// Set defaults for charge carrier propagation:
config_.setDefault<bool>("propagate_electrons", true);
config_.setDefault<bool>("propagate_holes", false);
if(!config_.get<bool>("propagate_electrons") && !config_.get<bool>("propagate_holes")) {
throw InvalidValueError(
config_,
"propagate_electrons",
"No charge carriers selected for propagation, enable 'propagate_electrons' or 'propagate_holes'.");
}
config_.setDefault<bool>("ignore_magnetic_field", false);
// Copy some variables from configuration to avoid lookups:
temperature_ = config_.get<double>("temperature");
timestep_min_ = config_.get<double>("timestep_min");
timestep_max_ = config_.get<double>("timestep_max");
timestep_start_ = config_.get<double>("timestep_start");
integration_time_ = config_.get<double>("integration_time");
target_spatial_precision_ = config_.get<double>("spatial_precision");
output_plots_ = config_.get<bool>("output_plots");
output_linegraphs_ = config_.get<bool>("output_linegraphs");
output_animations_ = config_.get<bool>("output_animations");
output_plots_step_ = config_.get<double>("output_plots_step");
output_plots_lines_at_implants_ = config_.get<bool>("output_plots_lines_at_implants");
propagate_electrons_ = config_.get<bool>("propagate_electrons");
propagate_holes_ = config_.get<bool>("propagate_holes");
charge_per_step_ = config_.get<unsigned int>("charge_per_step");
// Enable multithreading of this module if multithreading is enabled and no per-event output plots are requested:
// FIXME: Review if this is really the case or we can still use multithreading
if(!(output_animations_ || output_linegraphs_)) {
allow_multithreading();
} else {
LOG(WARNING) << "Per-event line graphs or animations requested, disabling parallel event processing";
}
boltzmann_kT_ = Units::get(8.6173e-5, "eV/K") * temperature_;
// Parameter for charge transport in magnetic field (approximated from graphs:
// http://www.ioffe.ru/SVA/NSM/Semicond/Si/electric.html) FIXME
electron_Hall_ = 1.15;
hole_Hall_ = 0.9;
}
void GenericPropagationModule::create_output_plots(uint64_t event_num, OutputPlotPoints& output_plot_points) {
LOG(TRACE) << "Writing output plots";
// Convert to pixel units if necessary
if(config_.get<bool>("output_plots_use_pixel_units")) {
for(auto& deposit_points : output_plot_points) {
for(auto& point : deposit_points.second) {
point.SetX(point.x() / model_->getPixelSize().x());
point.SetY(point.y() / model_->getPixelSize().y());
}
}
}
// Calculate the axis limits
double minX = FLT_MAX, maxX = FLT_MIN;
double minY = FLT_MAX, maxY = FLT_MIN;
unsigned long tot_point_cnt = 0;
double start_time = std::numeric_limits<double>::max();
unsigned int total_charge = 0;
unsigned int max_charge = 0;
for(auto& [deposit, points] : output_plot_points) {
for(auto& point : points) {
minX = std::min(minX, point.x());
maxX = std::max(maxX, point.x());
minY = std::min(minY, point.y());
maxY = std::max(maxY, point.y());
}
start_time = std::min(start_time, deposit.getGlobalTime());
total_charge += deposit.getCharge();
max_charge = std::max(max_charge, deposit.getCharge());
tot_point_cnt += points.size();
}
// Compute frame axis sizes if equal scaling is requested
if(config_.get<bool>("output_plots_use_equal_scaling", true)) {
double centerX = (minX + maxX) / 2.0;
double centerY = (minY + maxY) / 2.0;
if(config_.get<bool>("output_plots_use_pixel_units")) {
minX = centerX - model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;
maxX = centerX + model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;
minY = centerY - model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;
maxY = centerY + model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;
} else {
minX = centerX - model_->getSensorSize().z() / 2.0;
maxX = centerX + model_->getSensorSize().z() / 2.0;
minY = centerY - model_->getSensorSize().z() / 2.0;
maxY = centerY + model_->getSensorSize().z() / 2.0;
}
}
// Align on pixels if requested
if(config_.get<bool>("output_plots_align_pixels")) {
if(config_.get<bool>("output_plots_use_pixel_units")) {
minX = std::floor(minX - 0.5) + 0.5;
minY = std::floor(minY + 0.5) - 0.5;
maxX = std::ceil(maxX - 0.5) + 0.5;
maxY = std::ceil(maxY + 0.5) - 0.5;
} else {
double div = minX / model_->getPixelSize().x();
minX = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().x();
div = minY / model_->getPixelSize().y();
minY = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().y();
div = maxX / model_->getPixelSize().x();
maxX = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().x();
div = maxY / model_->getPixelSize().y();
maxY = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().y();
}
}
// Use a histogram to create the underlying frame
auto* histogram_frame = new TH3F(("frame_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
10,
minX,
maxX,
10,
minY,
maxY,
10,
model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,
model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0);
histogram_frame->SetDirectory(getROOTDirectory());
// Create the canvas for the line plot and set orientation
auto canvas = std::make_unique<TCanvas>(("line_plot_" + std::to_string(event_num)).c_str(),
("Propagation of charge for event " + std::to_string(event_num)).c_str(),
1280,
1024);
canvas->cd();
canvas->SetTheta(config_.get<float>("output_plots_theta") * 180.0f / ROOT::Math::Pi());
canvas->SetPhi(config_.get<float>("output_plots_phi") * 180.0f / ROOT::Math::Pi());
// Draw the frame on the canvas
histogram_frame->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetYaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetZaxis()->SetTitle("z (mm)");
histogram_frame->Draw();
// Loop over all point sets created during propagation
// The vector of unique_pointers is required in order not to delete the objects before the canvas is drawn.
std::vector<std::unique_ptr<TPolyLine3D>> lines;
short current_color = 1;
for(auto& [deposit, points] : output_plot_points) {
auto line = std::make_unique<TPolyLine3D>();
for(auto& point : points) {
line->SetNextPoint(point.x(), point.y(), point.z());
}
// Plot all lines with at least three points with different color
if(line->GetN() >= 3) {
EColor plot_color = (deposit.getType() == CarrierType::ELECTRON ? EColor::kAzure : EColor::kOrange);
current_color = static_cast<short int>(plot_color - 9 + (static_cast<int>(current_color) + 1) % 19);
line->SetLineColor(current_color);
line->Draw("same");
}
lines.push_back(std::move(line));
}
// Draw and write canvas to module output file, then clear the stored lines
canvas->Draw();
getROOTDirectory()->WriteTObject(canvas.get());
lines.clear();
// Create canvas for GIF animition of process
canvas = std::make_unique<TCanvas>(("animation_" + std::to_string(event_num)).c_str(),
("Propagation of charge for event " + std::to_string(event_num)).c_str(),
1280,
1024);
canvas->cd();
// Change axis labels if close to zero or PI as they behave different here
if(std::fabs(config_.get<double>("output_plots_theta") / (ROOT::Math::Pi() / 2.0) -
std::round(config_.get<double>("output_plots_theta") / (ROOT::Math::Pi() / 2.0))) < 1e-6 ||
std::fabs(config_.get<double>("output_plots_phi") / (ROOT::Math::Pi() / 2.0) -
std::round(config_.get<double>("output_plots_phi") / (ROOT::Math::Pi() / 2.0))) < 1e-6) {
histogram_frame->GetXaxis()->SetLabelOffset(-0.1f);
histogram_frame->GetYaxis()->SetLabelOffset(-0.075f);
} else {
histogram_frame->GetXaxis()->SetTitleOffset(2.0f);
histogram_frame->GetYaxis()->SetTitleOffset(2.0f);
}
// Draw frame on canvas
histogram_frame->Draw();
if(output_animations_) {
// Create the contour histogram
std::vector<std::string> file_name_contour;
std::vector<TH2F*> histogram_contour;
file_name_contour.push_back(createOutputFile("contourX" + std::to_string(event_num) + ".gif"));
histogram_contour.push_back(new TH2F(("contourX_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
100,
minY,
maxY,
100,
model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,
model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));
histogram_contour.back()->SetDirectory(getROOTDirectory());
file_name_contour.push_back(createOutputFile("contourY" + std::to_string(event_num) + ".gif"));
histogram_contour.push_back(new TH2F(("contourY_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
100,
minX,
maxX,
100,
model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,
model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));
histogram_contour.back()->SetDirectory(getROOTDirectory());
file_name_contour.push_back(createOutputFile("contourZ" + std::to_string(event_num) + ".gif"));
histogram_contour.push_back(new TH2F(("contourZ_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
100,
minX,
maxX,
100,
minY,
maxY));
histogram_contour.back()->SetDirectory(getROOTDirectory());
// Create file and disable statistics for histogram
std::string file_name_anim = createOutputFile("animation" + std::to_string(event_num) + ".gif");
for(size_t i = 0; i < 3; ++i) {
histogram_contour[i]->SetStats(false);
}
// Remove temporary created files
auto ret = remove(file_name_anim.c_str());
for(size_t i = 0; i < 3; ++i) {
ret |= remove(file_name_contour[i].c_str());
}
if(ret != 0) {
throw ModuleError("Could not delete temporary animation files.");
}
// Create color table
TColor* colors[80]; // NOLINT
for(int i = 20; i < 100; ++i) {
auto color_idx = TColor::GetFreeColorIndex();
colors[i - 20] = new TColor(color_idx,
static_cast<float>(i) / 100.0f - 0.2f,
static_cast<float>(i) / 100.0f - 0.2f,
static_cast<float>(i) / 100.0f - 0.2f);
}
// Create animation of moving charges
auto animation_time = static_cast<unsigned int>(
std::round((Units::convert(config_.get<long double>("output_plots_step"), "ms") / 10.0) *
config_.get<long double>("output_animations_time_scaling", 1e9)));
unsigned long plot_idx = 0;
unsigned int point_cnt = 0;
LOG_PROGRESS(INFO, getUniqueName() + "_OUTPUT_PLOTS") << "Written 0 of " << tot_point_cnt << " points for animation";
while(point_cnt < tot_point_cnt) {
std::vector<std::unique_ptr<TPolyMarker3D>> markers;
unsigned long min_idx_diff = std::numeric_limits<unsigned long>::max();
// Reset the canvas
canvas->Clear();
canvas->SetTheta(config_.get<float>("output_plots_theta") * 180.0f / ROOT::Math::Pi());
canvas->SetPhi(config_.get<float>("output_plots_phi") * 180.0f / ROOT::Math::Pi());
canvas->Draw();
// Reset the histogram frame
histogram_frame->SetTitle("Charge propagation in sensor");
histogram_frame->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetYaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetZaxis()->SetTitle("z (mm)");
histogram_frame->Draw();
auto text = std::make_unique<TPaveText>(-0.75, -0.75, -0.60, -0.65);
auto time_ns = Units::convert(plot_idx * config_.get<long double>("output_plots_step"), "ns");
std::stringstream sstr;
sstr << std::fixed << std::setprecision(2) << time_ns << "ns";
auto time_str = std::string(8 - sstr.str().size(), ' ');
time_str += sstr.str();
text->AddText(time_str.c_str());
text->Draw();
// Plot all the required points
for(auto& [deposit, points] : output_plot_points) {
auto diff = static_cast<unsigned long>(
std::round((deposit.getGlobalTime() - start_time) / config_.get<long double>("output_plots_step")));
if(plot_idx < diff) {
min_idx_diff = std::min(min_idx_diff, diff - plot_idx);
continue;
}
auto idx = plot_idx - diff;
if(idx >= points.size()) {
continue;
}
min_idx_diff = 0;
auto marker = std::make_unique<TPolyMarker3D>();
marker->SetMarkerStyle(kFullCircle);
marker->SetMarkerSize(
static_cast<float>(deposit.getCharge() * config_.get<double>("output_animations_marker_size", 1)) /
static_cast<float>(max_charge));
auto initial_z_perc = static_cast<int>(
((points[0].z() + model_->getSensorSize().z() / 2.0) / model_->getSensorSize().z()) * 80);
initial_z_perc = std::max(std::min(79, initial_z_perc), 0);
if(config_.get<bool>("output_animations_color_markers")) {
marker->SetMarkerColor(static_cast<Color_t>(colors[initial_z_perc]->GetNumber()));
}
marker->SetNextPoint(points[idx].x(), points[idx].y(), points[idx].z());
marker->Draw();
markers.push_back(std::move(marker));
histogram_contour[0]->Fill(points[idx].y(), points[idx].z(), deposit.getCharge());
histogram_contour[1]->Fill(points[idx].x(), points[idx].z(), deposit.getCharge());
histogram_contour[2]->Fill(points[idx].x(), points[idx].y(), deposit.getCharge());
++point_cnt;
}
// Create a step in the animation
if(min_idx_diff != 0) {
canvas->Print((file_name_anim + "+100").c_str());
plot_idx += min_idx_diff;
} else {
// print animation
if(point_cnt < tot_point_cnt - 1) {
canvas->Print((file_name_anim + "+" + std::to_string(animation_time)).c_str());
} else {
canvas->Print((file_name_anim + "++100").c_str());
}
// Draw and print contour histograms
for(size_t i = 0; i < 3; ++i) {
canvas->Clear();
canvas->SetTitle((std::string("Contour of charge propagation projected on the ") +
static_cast<char>('X' + i) + "-axis")
.c_str());
switch(i) {
case 0 /* x */:
histogram_contour[i]->GetXaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
histogram_contour[i]->GetYaxis()->SetTitle("z (mm)");
break;
case 1 /* y */:
histogram_contour[i]->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
histogram_contour[i]->GetYaxis()->SetTitle("z (mm)");
break;
case 2 /* z */:
histogram_contour[i]->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
histogram_contour[i]->GetYaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
break;
default:;
}
histogram_contour[i]->SetMinimum(1);
histogram_contour[i]->SetMaximum(total_charge /
config_.get<double>("output_animations_contour_max_scaling", 10));
histogram_contour[i]->Draw("CONTZ 0");
if(point_cnt < tot_point_cnt - 1) {
canvas->Print((file_name_contour[i] + "+" + std::to_string(animation_time)).c_str());
} else {
canvas->Print((file_name_contour[i] + "++100").c_str());
}
histogram_contour[i]->Reset();
}
++plot_idx;
}
markers.clear();
LOG_PROGRESS(INFO, getUniqueName() + "_OUTPUT_PLOTS")
<< "Written " << point_cnt << " of " << tot_point_cnt << " points for animation";
}
}
}
void GenericPropagationModule::initialize() {
auto detector = getDetector();
// Check for electric field and output warning for slow propagation if not defined
if(!detector->hasElectricField()) {
LOG(WARNING) << "This detector does not have an electric field.";
}
// For linear fields we can in addition check if the correct carriers are propagated
if(detector->getElectricFieldType() == FieldType::LINEAR) {
auto model = detector_->getModel();
auto probe_point = ROOT::Math::XYZPoint(model->getSensorCenter().x(),
model->getSensorCenter().y(),
model->getSensorCenter().z() + model->getSensorSize().z() / 2.01);
// Get the field close to the implants and check its sign:
auto efield = detector->getElectricField(probe_point);
auto direction = std::signbit(efield.z());
// Compare with propagated carrier type:
if(direction && !propagate_electrons_) {
LOG(WARNING) << "Electric field indicates electron collection at implants, but electrons are not propagated!";
}
if(!direction && !propagate_holes_) {
LOG(WARNING) << "Electric field indicates hole collection at implants, but holes are not propagated!";
}
}
// Check for magnetic field
has_magnetic_field_ = detector->hasMagneticField();
if(has_magnetic_field_) {
if(config_.get<bool>("ignore_magnetic_field")) {
has_magnetic_field_ = false;
LOG(WARNING) << "A magnetic field is switched on, but is set to be ignored for this module.";
} else {
LOG(DEBUG) << "This detector sees a magnetic field.";
magnetic_field_ = detector_->getMagneticField();
}
}
if(output_plots_) {
step_length_histo_ =
CreateHistogram<TH1D>("step_length_histo",
"Step length;length [#mum];integration steps",
100,
0,
static_cast<double>(Units::convert(0.25 * model_->getSensorSize().z(), "um")));
drift_time_histo_ = CreateHistogram<TH1D>("drift_time_histo",
"Drift time;Drift time [ns];charge carriers",
static_cast<int>(Units::convert(integration_time_, "ns") * 5),
0,
static_cast<double>(Units::convert(integration_time_, "ns")));
uncertainty_histo_ =
CreateHistogram<TH1D>("uncertainty_histo",
"Position uncertainty;uncertainty [nm];integration steps",
100,
0,
static_cast<double>(4 * Units::convert(config_.get<double>("spatial_precision"), "nm")));
group_size_histo_ = CreateHistogram<TH1D>("group_size_histo",
"Charge carrier group size;group size;number of groups transported",
static_cast<int>(charge_per_step_ - 1),
1,
static_cast<double>(charge_per_step_));
recombine_histo_ =
CreateHistogram<TH1D>("recombination_histo",
"Fraction of recombined charge carriers;recombination [N / N_{total}] ;number of events",
100,
0,
1);
}
// Prepare mobility model
try {
mobility_ = Mobility(config_.get<std::string>("mobility_model"), temperature_, detector->hasDopingProfile());
} catch(ModelError& e) {
throw InvalidValueError(config_, "mobility_model", e.what());
}
// Prepare recombination model
try {
recombination_ = Recombination(config_.get<std::string>("recombination_model"), detector->hasDopingProfile());
} catch(ModelError& e) {
throw InvalidValueError(config_, "recombination_model", e.what());
}
}
void GenericPropagationModule::run(Event* event) {
auto deposits_message = messenger_->fetchMessage<DepositedChargeMessage>(this, event);
// Create vector of propagated charges to output
std::vector<PropagatedCharge> propagated_charges;
// List of points to plot to plot for output plots
OutputPlotPoints output_plot_points;
// Loop over all deposits for propagation
LOG(TRACE) << "Propagating charges in sensor";
unsigned int propagated_charges_count = 0;
unsigned int recombined_charges_count = 0;
unsigned int step_count = 0;
long double total_time = 0;
for(const auto& deposit : deposits_message->getData()) {
if((deposit.getType() == CarrierType::ELECTRON && !propagate_electrons_) ||
(deposit.getType() == CarrierType::HOLE && !propagate_holes_)) {
LOG(DEBUG) << "Skipping charge carriers (" << deposit.getType() << ") on "
<< Units::display(deposit.getLocalPosition(), {"mm", "um"});
continue;
}
// Only process if within requested integration time:
if(deposit.getLocalTime() > integration_time_) {
LOG(DEBUG) << "Skipping charge carriers deposited beyond integration time: "
<< Units::display(deposit.getGlobalTime(), "ns") << " global / "
<< Units::display(deposit.getLocalTime(), {"ns", "ps"}) << " local";
continue;
}
// Loop over all charges in the deposit
unsigned int charges_remaining = deposit.getCharge();
LOG(DEBUG) << "Set of charge carriers (" << deposit.getType() << ") on "
<< Units::display(deposit.getLocalPosition(), {"mm", "um"});
auto charge_per_step = charge_per_step_;
while(charges_remaining > 0) {
// Define number of charges to be propagated and remove charges of this step from the total
if(charge_per_step > charges_remaining) {
charge_per_step = charges_remaining;
}
charges_remaining -= charge_per_step;
// Get position and propagate through sensor
auto initial_position = deposit.getLocalPosition();
// Add point of deposition to the output plots if requested
if(output_linegraphs_) {
auto global_position = detector_->getGlobalPosition(initial_position);
std::lock_guard<std::mutex> lock{stats_mutex_};
output_plot_points.emplace_back(PropagatedCharge(initial_position,
global_position,
deposit.getType(),
charge_per_step,
deposit.getLocalTime(),
deposit.getGlobalTime()),
std::vector<ROOT::Math::XYZPoint>());
}
// Propagate a single charge deposit
auto [final_position, time, alive] = propagate(
initial_position, deposit.getType(), deposit.getLocalTime(), event->getRandomEngine(), output_plot_points);
if(!alive) {
LOG(DEBUG) << " Recombined " << charge_per_step << " at " << Units::display(final_position, {"mm", "um"})
<< " in " << Units::display(time, "ns") << " time, removing";
recombined_charges_count += charge_per_step;
continue;
}
LOG(DEBUG) << " Propagated " << charge_per_step << " to " << Units::display(final_position, {"mm", "um"})
<< " in " << Units::display(time, "ns") << " time";
// Create a new propagated charge and add it to the list
auto global_position = detector_->getGlobalPosition(final_position);
PropagatedCharge propagated_charge(final_position,
global_position,
deposit.getType(),
charge_per_step,
deposit.getLocalTime() + time,
deposit.getGlobalTime() + time,
&deposit);
propagated_charges.push_back(std::move(propagated_charge));
// Update statistical information
++step_count;
propagated_charges_count += charge_per_step;
total_time += charge_per_step * time;
if(output_plots_) {
drift_time_histo_->Fill(static_cast<double>(Units::convert(time, "ns")), charge_per_step);
group_size_histo_->Fill(charge_per_step);
}
}
}
// Output plots if required
if(output_linegraphs_) {
create_output_plots(event->number, output_plot_points);
}
// Write summary and update statistics
long double average_time = total_time / std::max(1u, propagated_charges_count);
LOG(INFO) << "Propagated " << propagated_charges_count << " charges in " << step_count << " steps in average time of "
<< Units::display(average_time, "ns") << std::endl
<< "Recombined " << recombined_charges_count << " charges during transport";
total_propagated_charges_ += propagated_charges_count;
total_steps_ += step_count;
total_time_picoseconds_ += static_cast<long unsigned int>(total_time * 1e3);
if(output_plots_) {
recombine_histo_->Fill(static_cast<double>(recombined_charges_count) /
(propagated_charges_count + recombined_charges_count));
}
// Create a new message with propagated charges
auto propagated_charge_message = std::make_shared<PropagatedChargeMessage>(std::move(propagated_charges), detector_);
// Dispatch the message with propagated charges
messenger_->dispatchMessage(this, propagated_charge_message, event);
}
/**
* Propagation is simulated using a parameterization for the electron mobility. This is used to calculate the electron
* velocity at every point with help of the electric field map of the detector. An Runge-Kutta integration is applied in
* multiple steps, adding a random diffusion to the propagating charge every step.
*/
std::tuple<ROOT::Math::XYZPoint, double, bool>
GenericPropagationModule::propagate(const ROOT::Math::XYZPoint& pos,
const CarrierType& type,
const double initial_time,
RandomNumberGenerator& random_generator,
OutputPlotPoints& output_plot_points) const {
// Create a runge kutta solver using the electric field as step function
Eigen::Vector3d position(pos.x(), pos.y(), pos.z());
// Define a function to compute the diffusion
auto carrier_diffusion = [&](double efield_mag, double doping_concentration, double timestep) -> Eigen::Vector3d {
double diffusion_constant = boltzmann_kT_ * mobility_(type, efield_mag, doping_concentration);
double diffusion_std_dev = std::sqrt(2. * diffusion_constant * timestep);
// Compute the independent diffusion in three
allpix::normal_distribution<double> gauss_distribution(0, diffusion_std_dev);
Eigen::Vector3d diffusion;
for(int i = 0; i < 3; ++i) {
diffusion[i] = gauss_distribution(random_generator);
}
return diffusion;
};
// Survival probability of this charge carrier package, evaluated at every step
std::uniform_real_distribution<double> survival(0, 1);
// Define lambda functions to compute the charge carrier velocity with or without magnetic field
std::function<Eigen::Vector3d(double, const Eigen::Vector3d&)> carrier_velocity_noB =
[&](double, const Eigen::Vector3d& cur_pos) -> Eigen::Vector3d {
auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));
Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());
auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(cur_pos));
return static_cast<int>(type) * mobility_(type, efield.norm(), doping) * efield;
};
std::function<Eigen::Vector3d(double, const Eigen::Vector3d&)> carrier_velocity_withB =
[&](double, const Eigen::Vector3d& cur_pos) -> Eigen::Vector3d {
auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));
Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());
Eigen::Vector3d velocity;
Eigen::Vector3d bfield(magnetic_field_.x(), magnetic_field_.y(), magnetic_field_.z());
auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(cur_pos));
auto mob = mobility_(type, efield.norm(), doping);
auto exb = efield.cross(bfield);
Eigen::Vector3d term1;
double hallFactor = (type == CarrierType::ELECTRON ? electron_Hall_ : hole_Hall_);
term1 = static_cast<int>(type) * mob * hallFactor * exb;
Eigen::Vector3d term2 = mob * mob * hallFactor * hallFactor * efield.dot(bfield) * bfield;
auto rnorm = 1 + mob * mob * hallFactor * hallFactor * bfield.dot(bfield);
return static_cast<int>(type) * mob * (efield + term1 + term2) / rnorm;
};
// Create the runge kutta solver with an RKF5 tableau, using different velocity calculators depending on the magnetic
// field
auto runge_kutta = make_runge_kutta(
tableau::RK5, (has_magnetic_field_ ? carrier_velocity_withB : carrier_velocity_noB), timestep_start_, position);
// Continue propagation until the deposit is outside the sensor
Eigen::Vector3d last_position = position;
double last_time = 0;
size_t next_idx = 0;
bool is_alive = true;
while(detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position)) &&
(initial_time + runge_kutta.getTime()) < integration_time_ && is_alive) {
// Update output plots if necessary (depending on the plot step)
if(output_linegraphs_) {
auto time_idx = static_cast<size_t>(runge_kutta.getTime() / output_plots_step_);
while(next_idx <= time_idx) {
output_plot_points.back().second.push_back(static_cast<ROOT::Math::XYZPoint>(position));
next_idx = output_plot_points.back().second.size();
}
}
// Save previous position and time
last_position = position;
last_time = runge_kutta.getTime();
// Execute a Runge Kutta step
auto step = runge_kutta.step();
// Get the current result and timestep
auto timestep = runge_kutta.getTimeStep();
position = runge_kutta.getValue();
// Get electric field at current position and fall back to empty field if it does not exist
auto efield = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(position));
auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(position));
// Apply diffusion step
auto diffusion = carrier_diffusion(std::sqrt(efield.Mag2()), doping, timestep);
position += diffusion;
runge_kutta.setValue(position);
// Check if charge carrier is still alive:
is_alive = !recombination_(type,
detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(position)),
survival(random_generator),
timestep);
LOG(TRACE) << "Step from " << Units::display(static_cast<ROOT::Math::XYZPoint>(last_position), {"um", "mm"})
<< " to " << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {"um", "mm"}) << " at "
<< Units::display(initial_time + runge_kutta.getTime(), {"ps", "ns", "us"})
<< (is_alive ? "" : ", recombined");
// Adapt step size to match target precision
double uncertainty = step.error.norm();
// Update step length histogram
if(output_plots_) {
step_length_histo_->Fill(static_cast<double>(Units::convert(step.value.norm(), "um")));
uncertainty_histo_->Fill(static_cast<double>(Units::convert(step.error.norm(), "nm")));
}
// Lower timestep when reaching the sensor edge
if(std::fabs(model_->getSensorSize().z() / 2.0 - position.z()) < 2 * step.value.z()) {
timestep *= 0.75;
} else {
if(uncertainty > target_spatial_precision_) {
timestep *= 0.75;
} else if(2 * uncertainty < target_spatial_precision_) {
timestep *= 1.5;
}
}
// Limit the timestep to certain minimum and maximum step sizes
if(timestep > timestep_max_) {
timestep = timestep_max_;
} else if(timestep < timestep_min_) {
timestep = timestep_min_;
}
runge_kutta.setTimeStep(timestep);
}
// Find proper final position in the sensor
auto time = runge_kutta.getTime();
if(!detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position))) {
auto check_position = position;
check_position.z() = last_position.z();
if(position.z() > 0 && detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(check_position))) {
// Carrier left sensor on the side of the pixel grid, interpolate end point on surface
auto z_cur_border = std::fabs(position.z() - model_->getSensorSize().z() / 2.0);
auto z_last_border = std::fabs(model_->getSensorSize().z() / 2.0 - last_position.z());
auto z_total = z_cur_border + z_last_border;
position = (z_last_border / z_total) * position + (z_cur_border / z_total) * last_position;
time = (z_last_border / z_total) * time + (z_cur_border / z_total) * last_time;
} else {
// Carrier left sensor on any order border, use last position inside instead
position = last_position;
time = last_time;
}
}
// If requested, remove charge drift lines from plots if they did not reach the implant side within the integration time:
if(output_linegraphs_ && output_plots_lines_at_implants_) {
// If drift time is larger than integration time or the charge carriers have been collected at the backside, remove
if(time >= integration_time_ || last_position.z() < -model_->getSensorSize().z() * 0.45) {
output_plot_points.pop_back();
}
}
if(!is_alive) {
LOG(DEBUG) << "Charge carrier recombined after " << Units::display(last_time, {"ns"});
}
// Return the final position of the propagated charge
return std::make_tuple(static_cast<ROOT::Math::XYZPoint>(position), initial_time + time, is_alive);
}
void GenericPropagationModule::finalize() {
if(output_plots_) {
step_length_histo_->Write();
drift_time_histo_->Write();
uncertainty_histo_->Write();
group_size_histo_->Write();
recombine_histo_->Write();
}
long double average_time = static_cast<long double>(total_time_picoseconds_) / 1e3 /
std::max(1u, static_cast<unsigned int>(total_propagated_charges_));
LOG(INFO) << "Propagated total of " << total_propagated_charges_ << " charges in " << total_steps_
<< " steps in average time of " << Units::display(average_time, "ns");
}
| 49.475 | 125 | 0.571593 | bencline1 |
51edfece79314dc7d87e1282ddbda109954e4ae2 | 2,601 | cpp | C++ | example_bar_plot/src/ofApp.cpp | nickgillian/ofxGrt | 689c068b76af9e614f7124dbd4f38c8640c3a06d | [
"MIT"
] | 127 | 2016-01-04T20:33:15.000Z | 2021-11-30T07:18:48.000Z | example_bar_plot/src/ofApp.cpp | nickgillian/ofxGrt | 689c068b76af9e614f7124dbd4f38c8640c3a06d | [
"MIT"
] | 29 | 2016-01-05T20:39:14.000Z | 2021-01-04T04:07:37.000Z | example_bar_plot/src/ofApp.cpp | nickgillian/ofxGrt | 689c068b76af9e614f7124dbd4f38c8640c3a06d | [
"MIT"
] | 33 | 2016-01-05T18:44:57.000Z | 2020-08-09T00:13:47.000Z |
#include "ofApp.h"
#define NUM_DIMENSIONS 20
//--------------------------------------------------------------
void ofApp::setup(){
ofSetBackgroundColor(255);
//Load the font for the graph
font.load("verdana.ttf", 12, true, true);
font.setLineHeight(14.0f);
//Setup the plot
plot1.setup( NUM_DIMENSIONS, "sine data");
plot1.setRanges( -1.0, 1.0, true );
}
//--------------------------------------------------------------
void ofApp::update(){
//Update the data
vector< float > data( NUM_DIMENSIONS );
for(unsigned int i=0; i<NUM_DIMENSIONS; i++){
data[i] = sin( ofMap(i,0,NUM_DIMENSIONS-1,0.0,TWO_PI) );
}
plot1.update( data );
}
//--------------------------------------------------------------
void ofApp::draw(){
int plotX = 10;
int plotY = 10;
int plotW = ofGetWidth() - plotX*2;
int plotH = ofGetHeight() - 20;
ofSetColor(255,255,255);
ofFill();
plot1.draw( plotX, plotY, plotW, plotH );
ofSetColor(255,0,0);
ofNoFill();
ofDrawRectangle( plotX, plotY, plotW, plotH );
plotX += 25 + plotW;
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key){
case 'q':
{
ofImage img;
img.grabScreen(0, 0 , ofGetWidth(), ofGetHeight());
img.save( ofToDataPath( "screenshot_" + Util::timeAsString() + ".png") );
}
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 23.017699 | 89 | 0.38985 | nickgillian |
51ef9a043c754240e5c35ab326db8e2a7dee9b42 | 4,009 | cpp | C++ | fileformats/GOB_Reader.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | 1 | 2021-07-25T15:10:39.000Z | 2021-07-25T15:10:39.000Z | fileformats/GOB_Reader.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | null | null | null | fileformats/GOB_Reader.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | null | null | null | #include "GOB_Reader.h"
#include "../EngineSettings.h"
#include "../ui/XL_Console.h"
#include <string.h>
#include <stdio.h>
#include <cstdint>
GOB_Reader::GOB_Reader() : Archive()
{
m_CurFile = -1;
m_pFile = NULL;
m_FileList.pEntries = NULL;
}
bool GOB_Reader::Open(const char *pszName)
{
sprintf(m_szFileName, "%s%s", EngineSettings::get().GetGameDataDir(), pszName);
m_bGOB = true;
size_t l = strlen(pszName);
if ( (pszName[l-3] == 'l' && pszName[l-2] == 'a' && pszName[l-1] == 'b') ||
(pszName[l-3] == 'L' && pszName[l-2] == 'A' && pszName[l-1] == 'B') )
{
//this is a LAB file - very similar to a gob though.
m_bGOB = false;
}
FILE *f = fopen(m_szFileName, "rb");
if ( f )
{
fread(&m_Header, sizeof(GOB_Header_t), 1, f);
if ( m_bGOB )
{
fseek(f, m_Header.MASTERX, SEEK_SET);
fread(&m_FileList.MASTERN, sizeof(int32_t), 1, f);
m_FileList.pEntries = xlNew GOB_Entry_t[m_FileList.MASTERN];
fread(m_FileList.pEntries, sizeof(GOB_Entry_t), m_FileList.MASTERN, f);
}
else
{
int32_t stringTableSize;
fread(&m_FileList.MASTERN, sizeof(int32_t), 1, f);
fread(&stringTableSize, sizeof(int32_t), 1, f);
m_FileList.pEntries = xlNew GOB_Entry_t[m_FileList.MASTERN];
//now read string table.
fseek(f, 16*(m_FileList.MASTERN+1), SEEK_SET);
char *pStringTable = xlNew char[stringTableSize+1];
fread(pStringTable, 1, stringTableSize, f);
//now read the entries.
fseek(f, 16, SEEK_SET);
for (int32_t e=0; e<m_FileList.MASTERN; e++)
{
uint32_t fname_offs;
uint32_t start, size, dummy;
fread(&fname_offs, sizeof(uint32_t), 1, f);
fread(&start, sizeof(uint32_t), 1, f);
fread(&size, sizeof(uint32_t), 1, f);
fread(&dummy, sizeof(uint32_t), 1, f);
m_FileList.pEntries[e].IX = start;
m_FileList.pEntries[e].LEN = size;
strcpy(m_FileList.pEntries[e].NAME, &pStringTable[fname_offs]);
}
xlDelete [] pStringTable;
pStringTable = NULL;
}
fclose(f);
m_bOpen = true;
return true;
}
XL_Console::PrintF("^1Error: Failed to load %s", m_szFileName);
return false;
}
void GOB_Reader::Close()
{
CloseFile();
if ( m_FileList.pEntries )
{
xlDelete [] m_FileList.pEntries;
m_FileList.pEntries = NULL;
}
m_bOpen = false;
}
bool GOB_Reader::OpenFile(const char *pszFile)
{
m_pFile = fopen(m_szFileName, "rb");
m_CurFile = -1;
if ( m_pFile )
{
//search for this file.
for (int32_t i=0; i<m_FileList.MASTERN; i++)
{
if ( stricmp(pszFile, m_FileList.pEntries[i].NAME) == 0 )
{
m_CurFile = i;
break;
}
}
if ( m_CurFile == -1 )
{
XL_Console::PrintF("^1Error: Failed to load %s from \"%s\"", pszFile, m_szFileName);
}
}
return m_CurFile > -1 ? true : false;
}
void GOB_Reader::CloseFile()
{
if ( m_pFile )
{
fclose(m_pFile);
m_pFile = NULL;
}
m_CurFile = -1;
}
uint32_t GOB_Reader::GetFileLen()
{
return (uint32_t)m_FileList.pEntries[ m_CurFile ].LEN;
}
bool GOB_Reader::ReadFile(void *pData, uint32_t uLength)
{
if ( !m_pFile ) { return false; }
fseek(m_pFile, m_FileList.pEntries[ m_CurFile ].IX, SEEK_SET);
if ( uLength == 0 )
uLength = (uint32_t)m_FileList.pEntries[ m_CurFile ].LEN;
fread(pData, uLength, 1, m_pFile);
return true;
}
int32_t GOB_Reader::GetFileCount()
{
return m_FileList.MASTERN;
}
const char *GOB_Reader::GetFileName(int32_t nFileIdx)
{
return m_FileList.pEntries[nFileIdx].NAME;
}
| 25.864516 | 96 | 0.555251 | kcat |
51f5e616d09849a78be384d0b82a56cbceaef6c3 | 3,769 | hpp | C++ | crit_crauser.hpp | kaini/sssp-simulation | 0ee9cefb9b5d3a79c59eedd44092cd0401e99581 | [
"MIT"
] | null | null | null | crit_crauser.hpp | kaini/sssp-simulation | 0ee9cefb9b5d3a79c59eedd44092cd0401e99581 | [
"MIT"
] | null | null | null | crit_crauser.hpp | kaini/sssp-simulation | 0ee9cefb9b5d3a79c59eedd44092cd0401e99581 | [
"MIT"
] | null | null | null | #pragma once
#include "criteria.hpp"
#include "dijkstra.hpp"
#include "graph.hpp"
#include "stringy_enum.hpp"
#include <boost/heap/pairing_heap.hpp>
#include <unordered_set>
namespace sssp {
// Implements Crauser's IN criteria. Additionally instead of using the minimal edges,
// with dynamic=true, one can use the minimal non-settled edge.
class crauser_in : public criteria {
public:
crauser_in(const sssp::graph* graph, size_t start_node, bool dynamic);
virtual void relaxable_nodes(todo_output& output) const override;
virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;
virtual void relaxed_node(size_t node) override;
virtual bool is_complete() const override { return true; }
bool dynamic() const { return m_dynamic; }
private:
struct node_info;
struct node_info_compare_distance {
bool operator()(const node_info* a, const node_info* b) const;
};
// threshold(n) = tentative(n) - min{ cost of incmoing edges (not settled if dynamic) }
// Called "i" in the paper.
struct node_info_compare_threshold {
bool operator()(const node_info* a, const node_info* b) const;
};
using distance_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_distance>>;
using threshold_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_threshold>>;
struct node_info {
node_info(const sssp::graph& g, size_t index);
size_t index;
std::vector<edge_info> incoming;
double tentative_distance = INFINITY;
bool settled = false;
distance_queue::handle_type distance_queue_handle;
threshold_queue::handle_type threshold_queue_handle;
double threshold() const;
};
bool m_dynamic;
node_map<node_info> m_node_info;
distance_queue m_distance_queue;
threshold_queue m_threshold_queue;
};
// Implements Crauser's OUT criteria. Additionally instead of using the minimal edges,
// with dynamic=true, one can use the minimal non-settled edge.
class crauser_out : public criteria {
public:
crauser_out(const sssp::graph* graph, size_t start_node, bool dynamic);
virtual void relaxable_nodes(todo_output& output) const override;
virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;
virtual void relaxed_node(size_t node) override;
virtual bool is_complete() const override { return true; }
bool dynamic() const { return m_dynamic; }
private:
struct node_info;
struct node_info_compare_distance {
bool operator()(const node_info* a, const node_info* b) const;
};
// threshold(n) = tentative(n) + min{ outgoing edge (not settled if dynamic) }
// Called "L" in the paper (to be exact this are the values of all nodes, not the final L)
struct node_info_compare_threshold {
bool operator()(const node_info* a, const node_info* b) const;
};
using distance_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_distance>>;
using threshold_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_threshold>>;
struct node_info {
node_info(const sssp::graph& g, size_t index);
size_t index;
std::vector<edge_info> outgoing;
double tentative_distance = INFINITY;
bool settled = false;
distance_queue::handle_type distance_queue_handle;
threshold_queue::handle_type threshold_queue_handle;
double threshold() const;
};
bool m_dynamic;
node_map<node_info> m_node_info;
distance_queue m_distance_queue;
threshold_queue m_threshold_queue;
};
} // namespace sssp | 38.85567 | 117 | 0.71982 | kaini |
51f675ab28f07d980f2f0c9d3af113cc9ce3ce67 | 451 | cpp | C++ | solutions/1010.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/1010.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/1010.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | #include <array>
#include <vector>
class Solution {
public:
int numPairsDivisibleBy60(std::vector<int>& time) {
std::array<int, 60> durations = {0};
for (auto t : time) {
++durations[t % 60];
}
int result = (durations[0] - 1) * durations[0] / 2 +
(durations[30] - 1) * durations[30] / 2;
for (size_t t = 1; t < 30; ++t) {
result += durations[t] * durations[60 - t];
}
return result;
}
};
| 23.736842 | 57 | 0.534368 | tdakhran |
51fa9dbde53d3c04cf97e87eca10e5da112e306c | 2,857 | cpp | C++ | source/src/multilanguage/qrlanguager.cpp | Qters/QrCommon | 0e90365c1ad58c63ff17c259bb298f27c78d7d91 | [
"Apache-2.0"
] | null | null | null | source/src/multilanguage/qrlanguager.cpp | Qters/QrCommon | 0e90365c1ad58c63ff17c259bb298f27c78d7d91 | [
"Apache-2.0"
] | null | null | null | source/src/multilanguage/qrlanguager.cpp | Qters/QrCommon | 0e90365c1ad58c63ff17c259bb298f27c78d7d91 | [
"Apache-2.0"
] | null | null | null | #include "qrlanguager.h"
#include <algorithm>
#include <QTranslator>
#include <qapplication.h>
#include <QtCore/qdebug.h>
#include "qrutf8.h"
NS_QRCOMMON_BEGIN
class QrLanguagerPrivate
{
QR_DECLARE_PUBLIC(QrLanguager)
public:
int curLanaugeIndex = -1;
QVector<QrLanguagData> languageDatas;
QTranslator translator;
public:
QrLanguagerPrivate(QrLanguager *q) : q_ptr(q) {}
bool loadLanguage(const QString &qmFileName);
};
bool QrLanguagerPrivate::loadLanguage(const QString& qmFileName)
{
qApp->removeTranslator(&translator);
auto absFileName = QApplication::applicationDirPath() + "/translations/" + qmFileName;
if(translator.load(absFileName)){
return qApp->installTranslator(&translator);
} else {
qDebug() << "load language fail, " << absFileName;
}
return false;
}
NS_QRCOMMON_END
///////////////////////////////////////////////////////
USING_NS_QRCOMMON;
QR_SINGLETON_IMPLEMENT(QrLanguager)
QrLanguager::QrLanguager()
: QrSingleton<QrLanguager>("qrlanguager"),
d_ptr(new QrLanguagerPrivate(this))
{
}
void QrLanguager::initLanguages(const QVector<QrLanguagData> &languageDatas)
{
Q_D(QrLanguager);
d->languageDatas = languageDatas;
if(d->languageDatas.isEmpty()) {
d->curLanaugeIndex = -1;
} else {
d->curLanaugeIndex = 0;
}
}
bool QrLanguager::setLanguageByName(const QString& display)
{
Q_D(QrLanguager);
auto find = std::find_if(d->languageDatas.begin(), d->languageDatas.end(),
[display](QrLanguagData languageData){
return languageData.display == display;
});
if(d->languageDatas.end() == find) {
qDebug() << "fail to set language, could'nt find by " << display;
return false;
}
return d->loadLanguage(find->qmFileName);
}
bool QrLanguager::setLanaugeByIndex(int index)
{
Q_D(QrLanguager);
auto find = std::find_if(d->languageDatas.begin(), d->languageDatas.end(),
[index](QrLanguagData languageData){
return languageData.index == index;
});
if(d->languageDatas.end() == find) {
qDebug() << "fail to set language, could'nt find by " << index;
return false;
}
return d->loadLanguage(find->qmFileName);
}
QrLanguagData QrLanguager::curLanguage() const
{
Q_D(const QrLanguager);
if(d->curLanaugeIndex >= d->languageDatas.count()) {
qDebug() << "language index is unvalid.";
return QrLanguagData();
}
return d->languageDatas.at(d->curLanaugeIndex);
}
QStringList QrLanguager::getDisplayNames() const
{
QStringList names;
Q_D(const QrLanguager);
std::for_each(d->languageDatas.begin(),
d->languageDatas.end(),
[&names](QrLanguagData languageData){
names.push_back(languageData.display);
});
return names;
}
| 23.808333 | 90 | 0.652083 | Qters |
51fb4572055fdce043c3f3d02f02452838b0656e | 2,592 | cpp | C++ | src/scene.cpp | martin-pr/embree_viewer | 4e382f0352a8b76ff5d955024b5f56f1855d20c1 | [
"MIT"
] | 23 | 2018-03-15T00:02:53.000Z | 2022-03-19T17:44:40.000Z | src/scene.cpp | martin-pr/embree_viewer | 4e382f0352a8b76ff5d955024b5f56f1855d20c1 | [
"MIT"
] | null | null | null | src/scene.cpp | martin-pr/embree_viewer | 4e382f0352a8b76ff5d955024b5f56f1855d20c1 | [
"MIT"
] | 5 | 2019-03-06T06:48:44.000Z | 2021-03-21T16:56:30.000Z | #include "scene.h"
#include <cmath>
#include <iostream>
#include <limits>
#include <embree3/rtcore_ray.h>
#include "mesh.h"
Scene::SceneHandle::SceneHandle(Device& device) {
m_scene = rtcNewScene(device);
rtcSetSceneFlags(m_scene, RTC_SCENE_FLAG_COMPACT);
}
Scene::SceneHandle::~SceneHandle() {
rtcReleaseScene(m_scene);
}
Scene::SceneHandle::operator RTCScene& () {
return m_scene;
}
Scene::SceneHandle::operator const RTCScene& () const {
return m_scene;
}
////////////
Scene::Scene() : m_scene(new SceneHandle(m_device)) {
}
Scene::~Scene() {
}
Scene::Scene(Scene&& s) : m_device(s.m_device), m_scene(std::move(s.m_scene)) {
}
Scene& Scene::operator = (Scene&& s) {
if(&s != this) {
m_device = s.m_device;
m_scene = std::move(s.m_scene);
}
return *this;
}
unsigned Scene::addMesh(Mesh&& geom) {
unsigned int geomID = rtcAttachGeometry(*m_scene, geom.geom());
rtcCommitGeometry(geom.geom());
return geomID;
}
unsigned Scene::addInstance(const Scene& s, const Mat4& _tr) {
RTCGeometry instance = rtcNewGeometry(m_device, RTC_GEOMETRY_TYPE_INSTANCE);
rtcSetGeometryInstancedScene(instance, *s.m_scene);
unsigned int geomID = rtcAttachGeometry(*m_scene, instance);
rtcReleaseGeometry(instance);
Mat4 tr = _tr;
// tr.transpose();
rtcSetGeometryTransform(instance, 0, RTC_FORMAT_FLOAT4X4_COLUMN_MAJOR, tr.m);
rtcCommitGeometry(instance);
return geomID;
}
void Scene::commit() {
rtcCommitScene(*m_scene);
}
Vec3 Scene::renderPixel(const Ray& r) const {
RTCRayHit rayhit = trace(r);
Vec3 color{0, 0, 0};
if(rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {
//color = Vec3{(float)(rayhit.hit.geomID & 1), (float)((rayhit.hit.geomID >> 1) & 1), (float)((rayhit.hit.geomID >> 2) & 1)};
color = Vec3(1, 1, 1);
Vec3 norm(rayhit.hit.Ng_x, rayhit.hit.Ng_y, rayhit.hit.Ng_z);
norm.normalize();
const float d = std::abs(r.direction.dot(norm));
color.x *= d;
color.y *= d;
color.z *= d;
}
return color;
}
RTCRayHit Scene::trace(const Ray& r) const {
RTCIntersectContext context;
rtcInitIntersectContext(&context);
RTCRayHit rayhit;
rayhit.ray.org_x = r.origin.x;
rayhit.ray.org_y = r.origin.y;
rayhit.ray.org_z = r.origin.z;
rayhit.ray.tnear = 0;
rayhit.ray.tfar = std::numeric_limits<float>::infinity();
rayhit.ray.dir_x = r.direction.x;
rayhit.ray.dir_y = r.direction.y;
rayhit.ray.dir_z = r.direction.z;
rayhit.ray.time = 0;
rayhit.ray.mask = 0xFFFFFFFF;
rayhit.ray.id = 0;
rayhit.ray.flags = 0;
rayhit.hit.geomID = RTC_INVALID_GEOMETRY_ID;
rtcIntersect1(*m_scene, &context, &rayhit);
return rayhit;
}
| 20.25 | 127 | 0.697145 | martin-pr |
51fc876792446d7d9bed7541049214da83741401 | 2,777 | cpp | C++ | ConsoleEditor/libeditor/HtmlDocumentFormatter.cpp | AlK2x/OOD | 7ce78cfa7708978483f67642d93a8bc2873c2285 | [
"MIT"
] | null | null | null | ConsoleEditor/libeditor/HtmlDocumentFormatter.cpp | AlK2x/OOD | 7ce78cfa7708978483f67642d93a8bc2873c2285 | [
"MIT"
] | 5 | 2016-03-20T20:28:52.000Z | 2016-06-30T18:17:42.000Z | ConsoleEditor/libeditor/HtmlDocumentFormatter.cpp | AlK2x/OOD | 7ce78cfa7708978483f67642d93a8bc2873c2285 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "HtmlDocumentFormatter.h"
namespace fs = boost::filesystem;
CHtmlDocumentFormatter::CHtmlDocumentFormatter(CTempFolder const & tempFolder)
:m_tempFolder(tempFolder)
{
m_htmlEntities.push_back({ '&', "&" });
m_htmlEntities.push_back({ '<', "<" });
m_htmlEntities.push_back({ '>', ">" });
m_htmlEntities.push_back({ '"', """ });
}
std::string CHtmlDocumentFormatter::EscapeHtmlEntities(const std::string & str)
{
std::string escaped = str;
for (auto const & htmlEntity : m_htmlEntities)
{
std::string::size_type pos = escaped.find_first_of(htmlEntity.first);
while (pos != std::string::npos)
{
escaped.replace(pos, 1, htmlEntity.second);
pos = escaped.find_first_of(htmlEntity.first, pos + htmlEntity.second.size());
}
}
return escaped;
}
void CHtmlDocumentFormatter::CreateDocumentFilesImpl(IDocument const & document, std::string const & path)
{
fs::path p{ path };
fs::path parentPath(p.parent_path());
fs::file_status s = fs::status(p);
if (!fs::exists(s) && !fs::is_directory(p))
{
fs::create_directory(parentPath);
}
fs::path imagePath(parentPath);
imagePath /= m_tempFolder.GetImagePath();
if (!fs::is_directory(imagePath))
{
fs::create_directory(imagePath);
}
else
{
fs::remove_all(imagePath);
fs::create_directory(imagePath);
}
for (size_t i = 0; i < document.GetItemsCount(); ++i)
{
CConstDocumentItem item = document.GetItem(i);
std::shared_ptr<const IImage> m_image = item.GetImage();
if (m_image != nullptr)
{
fs::path from = m_tempFolder.GetPath();
from /= m_image->GetPath();
fs::path absoluteImagePath(parentPath);
absoluteImagePath /= m_image->GetPath();
fs::copy_file(from, absoluteImagePath, fs::copy_option::overwrite_if_exists);
}
}
}
void CHtmlDocumentFormatter::FormatHeader(IDocument const & document, std::ostream & out)
{
std::string escapedTitle = EscapeHtmlEntities(document.GetTitle());
out << boost::format{ R"(
<!DOCTYPE html>
<html>
<head>
<title>%1%</title>
</head>
<body>)" } % escapedTitle;
}
void CHtmlDocumentFormatter::FormatDocumentItem(CConstDocumentItem const & item, size_t position, std::ostream & out)
{
(void)position;
std::shared_ptr<const IImage> imagePtr = item.GetImage();
std::shared_ptr<const IParagraph> paragraphPtr = item.GetParagraph();
if (paragraphPtr != nullptr)
{
out << boost::format(R"(<p>%1%</p>)") % EscapeHtmlEntities(paragraphPtr->GetText()) << std::endl;
}
if (imagePtr != nullptr)
{
out << boost::format(R"(<img height="%1%" width="%2%" src="%3%" />)")
% imagePtr->GetWidth()
% imagePtr->GetHeight()
% imagePtr->GetPath().string()
<< std::endl;
}
}
void CHtmlDocumentFormatter::FormatFooter(std::ostream & out)
{
out << R"(
</body>
</html>)";
}
| 25.245455 | 117 | 0.685992 | AlK2x |
a406b386fceea856d3a50693083c7c58718ee026 | 1,013 | cpp | C++ | AP325/P-6-20.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | 1 | 2019-09-07T15:56:05.000Z | 2019-09-07T15:56:05.000Z | AP325/P-6-20.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | AP325/P-6-20.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
constexpr const ll INF = 1L << 60;
constexpr const ll MOD = 1e9 + 9;
ll solve(vector<ll> &values) {
vector<ll> dp(values.size());
vector<bool> pushed(values.size());
queue<ll> que;
que.push(0);
while (!que.empty()) {
ll node = que.front();
que.pop();
ll flip = 1, next;
while (flip < values.size()) {
next = node | flip;
if (next > node)
dp[next] = dp[node] + values[node] > dp[next] ? dp[node] + values[node]
: dp[next];
if (!pushed[next]) {
pushed[next] = true;
que.push(next);
}
flip <<= 1;
}
}
return dp.back() + values.back();
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
ll power;
cin >> power;
ll size = 1;
for (int i = 0; i < power; ++i) size <<= 1;
vector<ll> values(size);
for (auto &x : values) cin >> x;
cout << solve(values) << "\n";
return 0;
}
| 20.673469 | 79 | 0.516288 | Superdanby |
a40b558cec5fb88f3b6895e11f595b7c0cca599e | 2,109 | cpp | C++ | qsdlrectangle.cpp | CrimsonAS/qtsdl | a0c2487c175393d54d27574f9f02bfa436c34e79 | [
"Unlicense"
] | 2 | 2018-06-23T17:06:27.000Z | 2019-01-29T21:31:53.000Z | qsdlrectangle.cpp | CrimsonAS/qtsdl | a0c2487c175393d54d27574f9f02bfa436c34e79 | [
"Unlicense"
] | null | null | null | qsdlrectangle.cpp | CrimsonAS/qtsdl | a0c2487c175393d54d27574f9f02bfa436c34e79 | [
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2014 Robin Burchell <robin+git@viroteck.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <QQmlInfo>
#include <QFile>
#include <SDL.h>
#include "qsdlwindow.h"
#include "qsdlrectangle.h"
QSdlRectangle::QSdlRectangle(QObject *parent)
: QSdlItem(parent)
{
}
QSdlRectangle::~QSdlRectangle()
{
}
QColor QSdlRectangle::color() const
{
return m_color;
}
void QSdlRectangle::setColor(const QColor &color)
{
m_color = color;
emit colorChanged();
}
void QSdlRectangle::render()
{
SDL_Rect rect;
rect.x = x();
rect.y = y();
rect.w = width();
rect.h = height();
SDL_SetRenderDrawColor(window()->renderer(), color().red(), color().green(), color().blue(), color().alpha());
SDL_RenderFillRect(window()->renderer(), &rect);
QSdlItem::render();
}
| 30.128571 | 114 | 0.726885 | CrimsonAS |
a40f8b7b85852101ddbc2c946cdb585a06270f80 | 406 | hpp | C++ | external-memory/Common/Timer.hpp | Why1221/iDEC | a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb | [
"MIT"
] | 2 | 2021-06-15T14:58:59.000Z | 2022-01-06T17:17:57.000Z | in-memory/Common/Timer.hpp | Why1221/iDEC | a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb | [
"MIT"
] | null | null | null | in-memory/Common/Timer.hpp | Why1221/iDEC | a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb | [
"MIT"
] | null | null | null | #ifndef __TIMER_HPP_
#define __TIMER_HPP_
#include <chrono>
using namespace std::chrono;
struct HighResolutionTimer {
void restart() {
_start = high_resolution_clock::now();
}
double elapsed() const {
auto cur = high_resolution_clock::now();
return duration<double, std::micro>(cur - _start).count();
}
private:
high_resolution_clock::time_point _start;
};
#endif // __TIMER_HPP_ | 19.333333 | 62 | 0.714286 | Why1221 |
a416992d74323ce478fd892fdfda3f79a2e49ba5 | 6,131 | cpp | C++ | SOURCE/allProjects/car_data/car_dataBase_tree/carBinaryTree.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/car_data/car_dataBase_tree/carBinaryTree.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/car_data/car_dataBase_tree/carBinaryTree.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | #include"carBinaryTree.h"
#include"binarySearchTree.h"
#include"binaryTreeType.h"
#include"carType.h"
#include<string>
#include<fstream>
#include<vector>
using namespace std;
void carBinaryTree::genSearch() {
int count = 0;
string make;
string id;
string model;
string year;
string engine;
string door;
string drive;
string fuelType;
string trim;
string trans;
string condition;
string price;
//int inStock;
cout << "Enter Make\n";
getline(cin, make);
cout << "enter id\n";
getline(cin, id);
cout << "Enter Model\n";
getline(cin, model);
cout << "enter Year\n";
getline(cin, year);
cout << "Enter engine\n";
getline(cin, engine);
cout << "Enter number of doors\n";
getline(cin, door);
cout << "Enter type of Drive\n";
getline(cin, drive);
cout << "Enter Fuel type\n";
getline(cin, fuelType);
cout << "enter Trim\n";
getline(cin, trim);
cout << "Enter type of Transmission\n";
getline(cin, trans);
cout << "Enter condition\n";
getline(cin, condition);
int countCar = 0;
binaryTreeNode<carType>* current = root;
if (current == NULL) {
cout << " No cars in archive\n";
return ;
}
genSearchRec(current, count, make, model, year, engine, door, drive, fuelType, trim, trans, condition, price);
cout << "Number of car encounterd; " << count << endl;
}
void carBinaryTree::genSearchRec(binaryTreeNode<carType>* current,int& count,string make, string model, string year, string engine,
string door, string drive, string fuelType, string trim, string trans, string condition, string price) {
if(current){
if ((current->info.getMake() == make || make == "") && (current->info.getModel() == model || model == "") &&
(current->info.getYear() == year || year == "") &&(current->info.getEngine()==engine||engine=="") &&
(current->info.getDoor()==door||door=="")&&(current->info.getDrive()==drive||drive=="")&&(current->info.getFuel()==fuelType||fuelType=="")&&
(current->info.getTrim() == trim || trim == "") && (current->info.getTrans() == trans || trans == "") &&
(current->info.getCond() == condition || condition == "") && (current->info.getPrice() == price || price == "")) {
count+=current->info.getInStock();
cout << current->info;
}
genSearchRec(current->llink,count, make, model, year, engine, door, drive, fuelType, trim, trans, condition, price);
genSearchRec(current->rlink,count, make, model, year, engine, door, drive, fuelType, trim, trans, condition, price);
}
}
void carBinaryTree::searchCarList(string make, bool& found, binaryTreeNode<carType>* ¤t)const
{
found = false;
current = root;
if (current == NULL) //the tree is empty
cout << "Cannot search an empty tree. " << endl;
else
{
found = false; //set found to false
while (!found && current != NULL) //search the tree
if(current->info.getMake()==make)
found = true;
else if (current->info.getMake() > make)
current = current->llink;
else
current = current->rlink;
} //end else
}
void carBinaryTree::searchCarListId(string make,string id, bool& found, binaryTreeNode<carType>* ¤t)const
{
found = false;
current = root;
if (current == NULL) //the tree is empty
cout << "Cannot search an empty tree. " << endl;
else
{
found = false; //set found to false
while (!found && current != NULL) //search the tree
if (current->info.getId() == id)
found = true;
else if (current->info.getMake() > make)
current = current->llink;
else
current = current->rlink;
} //end else
}
void carBinaryTree::inorderMake(binaryTreeNode<carType> *p)
{
if (p != NULL)
{
inorderMake(p->llink);
p->info.printMake();
inorderMake(p->rlink);
}
}
void carBinaryTree::carPrintMake()
{
inorderMake(root);
}
bool carBinaryTree::isCarAvailable(string title) const
{
bool found;
binaryTreeNode<carType> *location;
searchCarList(title, found, location);
if (found)
found = (location->info.getInStock() > 0);
else
found = false;
return found;
}
void carBinaryTree::carCheckIn(string make,string id)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarListId(make,id, found, location);
if (found)
location->info.checkIn();
else
cout << "The store does not carry " << make
<< endl;
}
void carBinaryTree::carCheckOut(string make,string id)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarListId(make,id, found, location);
if (found)
location->info.checkOut();
else
cout << "The store does not carry " << make
<< endl;
}
bool carBinaryTree::carCheckMake(string make) const
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location); //search the list
return found;
}
void carBinaryTree::carUpdateInStock(string make, int num)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location); //search the list
if (found)
location->info.updateInStock(num);
else
cout << "The store does not carry " << make
<< endl;
}
void carBinaryTree::carSetCarInStock(string make, int num)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location);
if (found)
location->info.setCopiesInStock(num);
else
cout << "The store does not carry " << make
<< endl;
}
bool carBinaryTree::carSearch(string make) const
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location);
return found;
}
void carBinaryTree::saveCarTree() {
binaryTreeNode<carType>* current = root;
ofstream outfile;
outfile.open(saveAddress);
savePreorder(current,outfile);
outfile.close();
}
void carBinaryTree::saveCarTreeTest() {
binaryTreeNode<carType>* current = root;
ofstream outfile;
outfile.open(saveAddressTest);
savePreorder(current, outfile);
outfile.close();
}
void carBinaryTree::savePreorder( binaryTreeNode<carType>* p,ofstream& outfile)
{
if (p != NULL) {
outfile << p->info << endl;
savePreorder(p->llink,outfile);
savePreorder(p->rlink,outfile);
}
}
void carBinaryTree::setSaveAddress(string addInput) {
saveAddress = addInput;
}
void carBinaryTree::setSaveAddressTest(string addInput) {
saveAddressTest = addInput;
}
| 27.493274 | 143 | 0.686185 | llanesjuan |
a41b27829873d759cadc2158f6c017d2024d36da | 568 | cpp | C++ | Typhoon/Src/Typhoon/Timestep.cpp | Stangui/TyphoonEngine | 20dfdac4ded598ebbc26a48acc5d0d1adc97c833 | [
"Apache-2.0"
] | null | null | null | Typhoon/Src/Typhoon/Timestep.cpp | Stangui/TyphoonEngine | 20dfdac4ded598ebbc26a48acc5d0d1adc97c833 | [
"Apache-2.0"
] | null | null | null | Typhoon/Src/Typhoon/Timestep.cpp | Stangui/TyphoonEngine | 20dfdac4ded598ebbc26a48acc5d0d1adc97c833 | [
"Apache-2.0"
] | null | null | null | #include "TyphoonPCH.h"
#include "Timestep.h"
#include "Typhoon/Core.h"
#if TE_PLATFORM_WINDOWS
#include "Platform/Windows/WindowsTimestep.h"
#endif ////TE_PLATFORM_WINDOWS
namespace TyphoonEngine
{
Timestep* Timestep::Create()
{
#if TE_PLATFORM_WINDOWS
return new WindowsTimestep();
#endif ////TE_PLATFORM_WINDOWS
#if TE_PLATFORM_LINUX
return new LinuxTimestep();
#endif ////TE_PLATFORM_WINDOWS
#if TE_PLATFORM_MACOS
return new MacOSTimestep();
#endif ////TE_PLATFORM_WINDOWS
TE_ASSERT( false, "Unsupported timestep platform!" );
return nullptr;
}
}
| 20.285714 | 55 | 0.762324 | Stangui |
a41ff93d55a486a613bbe6fe4887358d42122ae3 | 411 | cpp | C++ | Practice Programs/small_factorials.cpp | C-Nikks/CPP_Language_Programs | e3ed1990aedd6b41f2746cdab7661c40f24d5588 | [
"MIT"
] | 3 | 2021-02-04T17:59:00.000Z | 2022-01-29T17:21:42.000Z | Practice Programs/small_factorials.cpp | C-Nikks/CPP_Language_Programs | e3ed1990aedd6b41f2746cdab7661c40f24d5588 | [
"MIT"
] | null | null | null | Practice Programs/small_factorials.cpp | C-Nikks/CPP_Language_Programs | e3ed1990aedd6b41f2746cdab7661c40f24d5588 | [
"MIT"
] | 3 | 2021-10-02T14:38:21.000Z | 2021-10-05T06:19:22.000Z | #include <iostream>
using namespace std;
int fact(int n)
{
int f = n;
while (f != 1)
{
n = n * (f - 1);
f--;
}
return n;
}
int main()
{
int t, n;
cin >> t;
int arr[t];
for (int i = 1; i <= t; i++)
{
cin >> n;
arr[i] = fact(n);
}
for (int i = 1; i <= t; i++)
{
cout << endl
<< arr[i];
}
return 0;
} | 13.7 | 32 | 0.350365 | C-Nikks |
a4202259b3eb2128d67232881e1f8772fb155cb3 | 5,365 | cpp | C++ | src/cell-simulation/core/engine.cpp | firestack/cell-simulation | 11eacc685afe7c283c1fc2ed6f8b312785f45f98 | [
"MIT"
] | null | null | null | src/cell-simulation/core/engine.cpp | firestack/cell-simulation | 11eacc685afe7c283c1fc2ed6f8b312785f45f98 | [
"MIT"
] | null | null | null | src/cell-simulation/core/engine.cpp | firestack/cell-simulation | 11eacc685afe7c283c1fc2ed6f8b312785f45f98 | [
"MIT"
] | null | null | null | #include "engine.h"
// Standard includes.
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// SFML includes.
#include <SFML/OpenGL.hpp>
#include <SFML/Window/Keyboard.hpp>
// Project includes.
#include "content.h"
#include "console.h"
Engine::Engine() :
m_avgRenderTime(0.0f),
m_avgRenderAcc(0.0f),
m_avgRenderCounter(1.0f),
m_avgUpdateTime(0.0f),
m_avgUpdateAcc(0.0f),
m_avgUpdateCounter(1.0f),
m_fps(0),
m_fpsTicks(0),
m_maxDeltaTime(0.0f),
m_entityTrackingIndex(0)
{ }
Engine::~Engine()
{ }
bool Engine::initialize()
{
time_t t;
time(&t);
srand(t);
// Initialize and load the content before we create the rest of the objects
// Since they may need to use them.
if(!Content::initialize()) {
return false;
}
m_debugText = new sf::Text();
m_debugText->setPosition(1.0f, 1.0f);
m_debugText->setCharacterSize(16);
m_debugText->setStyle(sf::Text::Bold);
m_debugText->setFont(*Content::font);
m_shader = Content::shader;
if (!m_world.initialize()) {
return false;
}
m_camera.trackEntity(m_world.getEntities()[0]);
return m_ircBot.initialize();
}
void Engine::destroy()
{
m_ircBot.destroy();
if (m_debugText)
delete m_debugText;
Console::destroy();
m_world.destroy();
Content::destroy();
}
void Engine::resize(const uint32 width, const uint32 height)
{
m_textView = sf::View(sf::FloatRect(sf::Vector2f(), sf::Vector2f(width, height)));
m_camera.resize(width, height);
}
void Engine::keyPress(sf::Event::KeyEvent e)
{
bool nowTracking = false;
if (e.code == sf::Keyboard::R) {
// Make sure the index is valid after adding.
m_entityTrackingIndex = (m_entityTrackingIndex + 1) % m_world.getEntityCount();
nowTracking = true;
}
else if (e.code == sf::Keyboard::T) {
// Make sure the index is valid after subtracting.
m_entityTrackingIndex = (m_entityTrackingIndex - 1) % m_world.getEntityCount();
nowTracking = true;
}
else if (e.code == sf::Keyboard::Space) {
// Make sure the index is valid.
m_entityTrackingIndex = (m_entityTrackingIndex) % m_world.getEntityCount();
nowTracking = true;
}
else if (e.code == sf::Keyboard::I) {
// Swap the debug flag.
m_world.setDebug(!m_world.getDebug());
}
if (nowTracking) {
Entity* entity = m_world.getEntity(m_entityTrackingIndex);
uint32 counter = 0;
while(entity->getType() != type::Cell && counter < m_world.getEntityCount()) {
m_entityTrackingIndex = (m_entityTrackingIndex + 1) % m_world.getEntityCount();
entity = m_world.getEntity(m_entityTrackingIndex);
counter++;
}
if (entity)
m_camera.trackEntity(entity);
}
}
void Engine::update(const float dt)
{
// Begin the measuring the time for this update cycle.
m_updateTimer.restart();
m_camera.applyKeyboardControls(dt);
m_world.update(dt);
m_camera.update(dt);
// Update the average update time.
m_avgUpdateAcc += m_updateTimer.getElapsedTime().asSeconds();
m_avgUpdateCounter++;
m_avgUpdateTime = m_avgUpdateAcc / m_avgUpdateCounter;
// Reset the average update counter after so many.
/*if (m_avgUpdateCounter > 2500) {
m_avgUpdateCounter = 1.0f;
m_avgUpdateAcc = 0.0f;
}*/
Console::update();
if (dt > m_maxDeltaTime) {
m_maxDeltaTime = dt;
}
}
void Engine::updateDebugInfo()
{
if (m_debugTextTimer.getElapsedTime().asSeconds() >= 0.2) {
m_debugTextTimer.restart();
std::stringstream str;
str << std::fixed << std::setprecision(8);
str << "avg rtime: " << m_avgRenderTime << std::endl;
str << "avg utime: " << m_avgUpdateTime << std::endl;
str << std::setprecision(2);
str << "fps: " << m_fps << std::endl;
str << "max dt: " << m_maxDeltaTime << std::endl;
//str << "scale: " << m_worldScale << std::endl;
vec2f cameraLocation = m_camera.getLocation();
str << "cam offset: (x: " << cameraLocation.x << ", y: " << cameraLocation.y << ")" << std::endl;
m_debugText->setString(str.str());
}
}
void Engine::render(sf::RenderTarget& target)
{
// Being the measuring the time for this render cycle.
m_renderTimer.restart();
// Make sure we have updated d
updateDebugInfo();
// Draw stuff here in the world view.
m_world.render(target, m_camera, m_textView);
// Update the view so we see text properly.
target.setView(m_textView);
target.draw(*m_debugText);
Console::render(target);
// Reset the average render counter after so many.
/*if (m_avgRenderCounter > 2500) {
m_avgRenderCounter = 1.0f;
m_avgRenderAcc = 0.0f;
}*/
// Average the render time measured with the render time.
m_avgRenderAcc += m_renderTimer.getElapsedTime().asSeconds();
m_avgRenderCounter++;
m_avgRenderTime = m_avgRenderAcc / m_avgRenderCounter;
// Update the frame counter too. we don't really need it but why not.
m_fpsTicks++;
if (m_fpsTimer.getElapsedTime().asSeconds() >= 1.0f) {
m_fpsTimer.restart();
m_fps = m_fpsTicks;
m_fpsTicks = 0;
}
}
| 25.306604 | 105 | 0.627213 | firestack |
a424e61811f8df783ec4a974ca1cc6f0f4378a57 | 4,576 | hpp | C++ | slope/slope/math/vector3.hpp | muleax/slope | 254138703163705b57332fc7490dd2eea0082b57 | [
"MIT"
] | 6 | 2022-02-05T23:28:12.000Z | 2022-02-24T11:08:04.000Z | slope/slope/math/vector3.hpp | muleax/slope | 254138703163705b57332fc7490dd2eea0082b57 | [
"MIT"
] | null | null | null | slope/slope/math/vector3.hpp | muleax/slope | 254138703163705b57332fc7490dd2eea0082b57 | [
"MIT"
] | null | null | null | #pragma once
#include "slope/math/math_utils.hpp"
namespace slope {
class vec3 {
public:
static constexpr vec3 zero() { return {}; }
constexpr vec3() : x(0.f), y(0.f), z(0.f) {}
explicit constexpr vec3(float all) : x(all), y(all), z(all) {}
constexpr vec3(float x, float y, float z) : x(x), y(y), z(z) {}
constexpr vec3 operator+(const vec3& rhs) const { return {x + rhs.x, y + rhs.y, z + rhs.z }; }
constexpr vec3 operator-(const vec3& rhs) const { return {x - rhs.x, y - rhs.y, z - rhs.z }; }
constexpr vec3& operator+=(const vec3& value);
constexpr vec3& operator-=(const vec3& value);
friend constexpr vec3 operator*(float lhs, const vec3& rhs) { return {lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; }
constexpr vec3 operator*(float rhs) const { return rhs * *this; }
constexpr vec3 operator/(float rhs) const { return {x / rhs, y / rhs, z / rhs }; }
constexpr vec3& operator*=(float value);
constexpr vec3& operator/=(float value);
constexpr vec3 operator-() const { return {-x, -y, -z }; }
constexpr bool operator==(const vec3& value) const { return x == value.x && y == value.y && z == value.z; }
constexpr bool operator!=(const vec3& value) const { return x != value.x || y != value.y || z != value.z; }
constexpr float& operator[](size_t index) { return data[index]; }
constexpr const float& operator[](size_t index) const { return data[index]; }
void set_zero();
constexpr float dot(const vec3& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }
constexpr vec3 cross(const vec3& rhs) const;
constexpr float length_squared() const { return sqr(x) + sqr(y) + sqr(z); }
float length() const { return std::sqrt(length_squared()); }
constexpr float square_distance(const vec3& rhs) const;
float distance(const vec3& rhs) const { return std::sqrt(square_distance(rhs)); }
vec3 normalized() const;
bool is_zero() const { return x == 0.f && y == 0.f && z == 0.f; }
bool is_finite() const { return std::isfinite(x) && std::isfinite(y) && std::isfinite(z); }
constexpr bool equal(const vec3& rhs, float epsilon = EQUALITY_EPSILON) const;
constexpr bool equal(float rhs, float epsilon = EQUALITY_EPSILON) const;
union {
struct {
float x, y, z;
};
float data[3]{};
};
};
constexpr vec3 lerp(const vec3& from, const vec3& to, float factor)
{
return from + (to - from) * factor;
}
inline vec3 min(const vec3& lhs, const vec3& rhs)
{
return {std::fmin(lhs.x, rhs.x), std::fmin(lhs.y, rhs.y), std::fmin(lhs.z, rhs.z)};
}
inline vec3 max(const vec3& lhs, const vec3& rhs)
{
return {std::fmax(lhs.x, rhs.x), std::fmax(lhs.y, rhs.y), std::fmax(lhs.z, rhs.z)};
}
inline vec3 vec3::normalized() const
{
float multiplier = 1.f / length();
return {x * multiplier, y * multiplier, z * multiplier};
}
constexpr vec3& vec3::operator+=(const vec3& value)
{
x += value.x;
y += value.y;
z += value.z;
return *this;
}
constexpr vec3& vec3::operator-=(const vec3& value)
{
x -= value.x;
y -= value.y;
z -= value.z;
return *this;
}
constexpr vec3& vec3::operator*=(float value)
{
x *= value;
y *= value;
z *= value;
return *this;
}
constexpr vec3& vec3::operator/=(float value)
{
float rcp = 1.f / value;
x *= rcp;
y *= rcp;
z *= rcp;
return *this;
}
inline void vec3::set_zero()
{
x = 0.f;
y = 0.f;
z = 0.f;
}
constexpr vec3 vec3::cross(const vec3& rhs) const
{
return {y * rhs.z - z * rhs.y,
z * rhs.x - x * rhs.z,
x * rhs.y - y * rhs.x};
}
constexpr float vec3::square_distance(const vec3& rhs) const
{
return sqr(x - rhs.x) + sqr(y - rhs.y) + sqr(z - rhs.z);
}
constexpr bool vec3::equal(const vec3& rhs, float epsilon) const
{
return slope::equal(x, rhs.x, epsilon) && slope::equal(y, rhs.y, epsilon) && slope::equal(z, rhs.z, epsilon);
}
constexpr bool vec3::equal(float rhs, float epsilon) const
{
return slope::equal(x, rhs, epsilon) && slope::equal(y, rhs, epsilon) && slope::equal(z, rhs, epsilon);
}
} // slope
| 32.453901 | 121 | 0.547421 | muleax |
a42765efaa4612abd78e0a55bd3947086cce6c8f | 503 | hpp | C++ | include/axl.util/Protocol.hpp | Defalt8/axl.util | 71375e37d7df5d91d813d6e0fe99416220ce4dca | [
"MIT"
] | 1 | 2021-02-12T12:48:28.000Z | 2021-02-12T12:48:28.000Z | include/axl.util/Protocol.hpp | Defalt8/axl.util | 71375e37d7df5d91d813d6e0fe99416220ce4dca | [
"MIT"
] | null | null | null | include/axl.util/Protocol.hpp | Defalt8/axl.util | 71375e37d7df5d91d813d6e0fe99416220ce4dca | [
"MIT"
] | null | null | null | #pragma once
#include "lib.hpp"
#include "types.hpp"
#include "ds/Array.hpp"
#include "ds/List.hpp"
#include "Serial.hpp"
namespace axl {
namespace util {
class AXLUTILCXXAPI Protocol
{
public:
Protocol();
virtual ~Protocol();
virtual ds::Array<byte, axl::util::ds::Allocators::Malloc<byte>> serialize(const Serial& serial) const = 0;
virtual bool deserialize(Serial& serial, const ds::Array<byte, axl::util::ds::Allocators::Malloc<byte>>& serial_data) const = 0;
};
} // axl.util
} // axl
| 21.869565 | 130 | 0.699801 | Defalt8 |
a4291633209df533c172ee350b015c3434babc47 | 9,038 | cpp | C++ | src/gtest/test-utils-basic.cpp | w5292c/mcode | bb5d09c09b54d870bcc4e6a220176168d6618f60 | [
"MIT"
] | null | null | null | src/gtest/test-utils-basic.cpp | w5292c/mcode | bb5d09c09b54d870bcc4e6a220176168d6618f60 | [
"MIT"
] | null | null | null | src/gtest/test-utils-basic.cpp | w5292c/mcode | bb5d09c09b54d870bcc4e6a220176168d6618f60 | [
"MIT"
] | 1 | 2017-04-15T09:14:33.000Z | 2017-04-15T09:14:33.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 Alexander Chumakov
*
* 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 "utils.h"
#include <gtest/gtest.h>
using namespace testing;
class UtilsBasic : public Test
{
protected:
void SetUp() override {
}
void TearDown() override {
}
bool is_whitespace(char ch) {
return isspace(ch) || !ch;
}
bool is_numeric(char ch) {
return ch >= '0' && ch <= '9';
}
bool is_hex(char ch) {
return (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f') || is_numeric(ch);
}
};
TEST_F(UtilsBasic, MCharIsWhitespace)
{
int ch;
for (ch = 0; ch < 256; ++ch) {
const bool whitespace = char_is_whitespace(ch);
ASSERT_EQ(whitespace, is_whitespace(ch)) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, MCharIsNumeric)
{
int ch;
for (ch = 0; ch < 256; ++ch) {
ASSERT_EQ(char_is_digit(ch), is_numeric(ch)) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, MCharIsHex)
{
int ch;
for (ch = 0; ch < 256; ++ch) {
ASSERT_EQ(char_is_hex(ch), is_hex(ch)) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, GlobChToVal)
{
char ch;
uint8_t value;
for (ch = '0'; ch <= '9'; ++ch) {
value = glob_ch_to_val(ch);
ASSERT_EQ(value, ch - '0') << "Character: [" << (char)ch << "], code: " << ch;
}
for (ch = 'a'; ch <= 'f'; ++ch) {
value = glob_ch_to_val(ch);
ASSERT_EQ(value, ch - 'a' + 10) << "Character: [" << (char)ch << "], code: " << ch;
}
for (ch = 'A'; ch <= 'F'; ++ch) {
value = glob_ch_to_val(ch);
ASSERT_EQ(value, ch - 'A' + 10) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, GlobGetByte)
{
uint8_t value = glob_get_byte("9F");
ASSERT_EQ(value, 0x9fu);
value = glob_get_byte("00");
ASSERT_EQ(value, 0x00u);
value = glob_get_byte("FF");
ASSERT_EQ(value, 0xffu);
}
TEST_F(UtilsBasic, GlobStrToUint16)
{
uint16_t value = glob_str_to_uint16("0000");
ASSERT_EQ(value, 0x0000u);
value = glob_str_to_uint16("ffff");
ASSERT_EQ(value, 0xffffu);
value = glob_str_to_uint16("FFFF");
ASSERT_EQ(value, 0xffffu);
value = glob_str_to_uint16("80DE");
ASSERT_EQ(value, 0x80deu);
value = glob_str_to_uint16("1234");
ASSERT_EQ(value, 0x1234u);
value = glob_str_to_uint16("4567");
ASSERT_EQ(value, 0x4567u);
value = glob_str_to_uint16("89ab");
ASSERT_EQ(value, 0x89abu);
value = glob_str_to_uint16("cdef");
ASSERT_EQ(value, 0xcdefu);
value = glob_str_to_uint16("98BA");
ASSERT_EQ(value, 0x98bau);
value = glob_str_to_uint16("DCFE");
ASSERT_EQ(value, 0xdcfeu);
}
TEST_F(UtilsBasic, StringSkipWhitespace)
{
const char *const input1 = "abcdef qwerty";
const char *const input2 = " poiuyt asdfg";
const char *result = string_skip_whitespace(input1);
ASSERT_EQ(result, input1);
result = string_skip_whitespace(result);
ASSERT_EQ(result, input1);
result = string_skip_whitespace(input2);
ASSERT_EQ(result, input2 + 4);
result = string_skip_whitespace(result);
ASSERT_EQ(result, input2 + 4);
result = string_skip_whitespace(NULL);
ASSERT_EQ(result, (const char *)NULL);
result = string_skip_whitespace("");
ASSERT_EQ(result, (const char *)NULL);
result = string_skip_whitespace(" ");
ASSERT_EQ(result, (const char *)NULL);
result = string_skip_whitespace(" \r\n\r\f\t\v ");
ASSERT_EQ(result, (const char *)NULL);
}
TEST_F(UtilsBasic, StringNextDecimalNumber)
{
uint16_t value = 0;
const char *result = string_next_number("12345, new", &value);
ASSERT_EQ(value, 12345);
ASSERT_STREQ(result, ", new");
result = string_next_number("12345", &value);
ASSERT_EQ(value, 12345);
ASSERT_EQ(result, (const char *)NULL);
result = string_next_number("26143hello", &value);
ASSERT_EQ(value, 26143);
ASSERT_STREQ(result, "hello");
result = string_next_number("1234567890 ", &value);
ASSERT_EQ(value, 722);
ASSERT_STREQ(result, " ");
value = 0;
result = string_next_number(NULL, &value);
ASSERT_EQ(value, 0);
ASSERT_EQ(result, (const char *)NULL);
result = string_next_number("", &value);
ASSERT_EQ(value, 0);
ASSERT_EQ(result, (const char *)NULL);
}
TEST_F(UtilsBasic, StringNextHexNumber)
{
uint16_t value = 0;
const char *result = string_next_number("0x2345, old", &value);
ASSERT_EQ(value, 0x2345u);
ASSERT_STREQ(result, ", old");
result = string_next_number("0xfe10", &value);
ASSERT_EQ(value, 0xfe10u);
ASSERT_EQ(result, (const char *)NULL);
result = string_next_number("0x261fhello", &value);
ASSERT_EQ(value, 0x261fu);
ASSERT_STREQ(result, "hello");
result = string_next_number("0x1234567890abcdef ", &value);
ASSERT_EQ(value, 0xcdefu);
ASSERT_STREQ(result, " ");
}
TEST_F(UtilsBasic, StringNextToken)
{
int length = 0;
const char *result = string_next_token("word 12345678", &length);
ASSERT_EQ(length, 4);
ASSERT_STREQ(result, " 12345678");
result = string_next_token("token", &length);
ASSERT_EQ(length, 5);
ASSERT_STREQ(result, (const char *)NULL);
}
TEST_F(UtilsBasic, StringToBuffer)
{
uint8_t length = 0;
uint8_t buffer[128];
memset(buffer, 0, sizeof (buffer));
const char *result = string_to_buffer("00012ef677ff00aa", sizeof (buffer), buffer, &length);
ASSERT_EQ(buffer[0], 0x00u);
ASSERT_EQ(buffer[1], 0x01u);
ASSERT_EQ(buffer[2], 0x2eu);
ASSERT_EQ(buffer[3], 0xf6u);
ASSERT_EQ(buffer[4], 0x77u);
ASSERT_EQ(buffer[5], 0xffu);
ASSERT_EQ(buffer[6], 0x00u);
ASSERT_EQ(buffer[7], 0xaau);
ASSERT_EQ(length, 8);
ASSERT_EQ(result, (const char *)NULL);
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer("55X", sizeof (buffer), buffer, &length);
ASSERT_EQ(buffer[0], 0x55u);
ASSERT_EQ(length, 1);
ASSERT_STREQ(result, "X");
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer("", sizeof (buffer), buffer, &length);
ASSERT_EQ(length, 0);
ASSERT_STREQ(result, (const char *)NULL);
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer(NULL, sizeof (buffer), buffer, &length);
ASSERT_EQ(length, 0);
ASSERT_STREQ(result, (const char *)NULL);
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer("1234567890abcdef", 2, buffer, &length);
ASSERT_EQ(length, 2);
ASSERT_EQ(buffer[0], 0x12u);
ASSERT_EQ(buffer[1], 0x34u);
ASSERT_STREQ(result, "567890abcdef");
}
TEST_F(UtilsBasic, DISABLED_StringToBuffer)
{
/* This case is disabled, as it gives an error, needs to be fixed or removed */
uint8_t length = 0;
uint8_t buffer[128];
memset(buffer, 0, sizeof (buffer));
const char *result = string_to_buffer("123", sizeof (buffer), buffer, &length);
ASSERT_EQ(length, 1);
ASSERT_EQ(buffer[0], 0x12u);
ASSERT_STREQ(result, "3");
}
TEST_F(UtilsBasic, FromPdu7bit)
{
char buffer[256] = { 0 };
size_t length = 0;
bool res = from_pdu_7bit("F4F29C0E", -1, buffer, sizeof (buffer), &length);
ASSERT_EQ(res, true);
ASSERT_STREQ(buffer, "test");
memset(buffer, 0, sizeof (buffer));
res = from_pdu_7bit("F4F29C0EX", -1, buffer, sizeof (buffer), &length);
/* Failure is reported, as the 'X' char is illigal in this context */
ASSERT_EQ(res, false);
ASSERT_STREQ(buffer, "test");
memset(buffer, 0, sizeof (buffer));
res = from_pdu_7bit(NULL, -1, buffer, sizeof (buffer), &length);
/* Failure is reported, as the 'X' char is illigal in this context */
ASSERT_EQ(res, false);
length = 0;
memset(buffer, 0, sizeof (buffer));
res = from_pdu_7bit("F3B29BDC4ABBCD6F50AC3693B14022F2DB5D16B140381A", -1, buffer, sizeof (buffer), &length);
ASSERT_EQ(res, true);
ASSERT_STREQ(buffer, "send-info 1532, \"done\", 84");
}
TEST_F(UtilsBasic, DISABLED_FromPdu7bit)
{
char buffer[256] = { 0 };
size_t length = 0;
bool res = from_pdu_7bit("F4F29C0E", -1, buffer, 2, &length);
/* Failure is reported, as the 'X' char is illigal in this context */
ASSERT_EQ(res, true);
ASSERT_EQ(length, 2);
ASSERT_STREQ(buffer, "te");
}
| 30.430976 | 110 | 0.67526 | w5292c |
a43036417a0914982d39e989c28dae5882427f12 | 253 | cc | C++ | 13/31/31.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 5 | 2019-08-01T07:52:27.000Z | 2022-03-27T08:09:35.000Z | 13/31/31.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 1 | 2020-10-03T17:29:59.000Z | 2020-11-17T10:03:10.000Z | 13/31/31.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 6 | 2019-08-24T08:55:56.000Z | 2022-02-09T08:41:44.000Z | #include <iostream>
#include <vector>
#include <algorithm>
#include "HasPtr.h"
using std::swap;
int main()
{
HasPtr a("Hello"), b("World!"), c("Goodbye");
std::vector<HasPtr> hps{a,b,c};
std::sort(hps.begin(), hps.end());
return 0;
}
| 15.8125 | 49 | 0.600791 | williamgherman |
bf9bc13732089d87feed946edf4cbdcf759af657 | 7,555 | cpp | C++ | src/fuml/src_gen/fUML/impl/ValueImpl.cpp | MichaelBranz/MDE4CPP | 5b918850a37e9cee54f6c3b92f381b0458451724 | [
"MIT"
] | null | null | null | src/fuml/src_gen/fUML/impl/ValueImpl.cpp | MichaelBranz/MDE4CPP | 5b918850a37e9cee54f6c3b92f381b0458451724 | [
"MIT"
] | 1 | 2019-03-01T00:54:13.000Z | 2019-03-04T02:15:50.000Z | src/fuml/src_gen/fUML/impl/ValueImpl.cpp | vallesch/MDE4CPP | 7f8a01dd6642820913b2214d255bef2ea76be309 | [
"MIT"
] | null | null | null | #include "fUML/impl/ValueImpl.hpp"
#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif
#ifdef ACTIVITY_DEBUG_ON
#define ACT_DEBUG(a) a
#else
#define ACT_DEBUG(a) /**/
#endif
//#include "util/ProfileCallCount.hpp"
#include <cassert>
#include <iostream>
#include <sstream>
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
#include "fUML/impl/FUMLPackageImpl.hpp"
#include "abstractDataTypes/Subset.hpp"
#include "uml/Classifier.hpp"
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence
#include "fUML/FUMLFactory.hpp"
#include "fUML/FUMLPackage.hpp"
#include <exception> // used in Persistence
#include "uml/Classifier.hpp"
#include "fUML/SemanticVisitor.hpp"
#include "fUML/Value.hpp"
#include "uml/ValueSpecification.hpp"
#include "ecore/EcorePackage.hpp"
#include "ecore/EcoreFactory.hpp"
#include "fUML/FUMLPackage.hpp"
#include "fUML/FUMLFactory.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
using namespace fUML;
//*********************************
// Constructor / Destructor
//*********************************
ValueImpl::ValueImpl()
{
//*********************************
// Attribute Members
//*********************************
//*********************************
// Reference Members
//*********************************
//References
//Init references
}
ValueImpl::~ValueImpl()
{
#ifdef SHOW_DELETION
std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete Value "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}
ValueImpl::ValueImpl(const ValueImpl & obj):ValueImpl()
{
//create copy of all Attributes
#ifdef SHOW_COPIES
std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy Value "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
#endif
//copy references with no containment (soft copy)
//Clone references with containment (deep copy)
}
std::shared_ptr<ecore::EObject> ValueImpl::copy() const
{
std::shared_ptr<ValueImpl> element(new ValueImpl(*this));
element->setThisValuePtr(element);
return element;
}
std::shared_ptr<ecore::EClass> ValueImpl::eStaticClass() const
{
return FUMLPackageImpl::eInstance()->getValue_EClass();
}
//*********************************
// Attribute Setter Getter
//*********************************
//*********************************
// Operations
//*********************************
bool ValueImpl::equals(std::shared_ptr<fUML::Value> otherValue)
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
std::shared_ptr<Bag<uml::Classifier> > myTypes = this->getTypes();
std::shared_ptr<Bag<uml::Classifier> > otherTypes = otherValue->getTypes();
DEBUG_MESSAGE(std::cout<<"in Value"<<std::endl;)
bool isEqual = true;
if(myTypes->size() != otherTypes->size())
{
isEqual = false;
}
else
{
unsigned int i = 0;
while(isEqual && i < myTypes->size())
{
bool matched = false;
unsigned int j = 0;
while(!matched && j < otherTypes->size())
{
matched = (otherTypes->at(j) == myTypes->at(i));
j = j + 1;
}
isEqual = matched;
i = i + 1;
}
}
return isEqual;
//end of body
}
std::shared_ptr<Bag<uml::Classifier> > ValueImpl::getTypes() const
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
bool ValueImpl::hasTypes(std::shared_ptr<uml::Classifier> type)
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
std::shared_ptr<Bag<uml::Classifier> > types = this->getTypes();
bool found = false;
unsigned int i = 0;
while(!found && i < types->size())
{
found = (types->at(i) == type);
i = i + 1;
}
return found;
//end of body
}
std::string ValueImpl::objectId()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
return "SemanticVisitor";//typename(SemanticVisitor); //return super.toString();
//end of body
}
std::shared_ptr<uml::ValueSpecification> ValueImpl::specify()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
std::string ValueImpl::toString()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
//*********************************
// References
//*********************************
//*********************************
// Union Getter
//*********************************
std::shared_ptr<Value> ValueImpl::getThisValuePtr() const
{
return m_thisValuePtr.lock();
}
void ValueImpl::setThisValuePtr(std::weak_ptr<Value> thisValuePtr)
{
m_thisValuePtr = thisValuePtr;
setThisSemanticVisitorPtr(thisValuePtr);
}
std::shared_ptr<ecore::EObject> ValueImpl::eContainer() const
{
return nullptr;
}
//*********************************
// Structural Feature Getter/Setter
//*********************************
Any ValueImpl::eGet(int featureID, bool resolve, bool coreType) const
{
switch(featureID)
{
}
return SemanticVisitorImpl::eGet(featureID, resolve, coreType);
}
bool ValueImpl::internalEIsSet(int featureID) const
{
switch(featureID)
{
}
return SemanticVisitorImpl::internalEIsSet(featureID);
}
bool ValueImpl::eSet(int featureID, Any newValue)
{
switch(featureID)
{
}
return SemanticVisitorImpl::eSet(featureID, newValue);
}
//*********************************
// Persistence Functions
//*********************************
void ValueImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
loadAttributes(loadHandler, attr_list);
//
// Create new objects (from references (containment == true))
//
// get FUMLFactory
std::shared_ptr<fUML::FUMLFactory> modelFactory = fUML::FUMLFactory::eInstance();
int numNodes = loadHandler->getNumOfChildNodes();
for(int ii = 0; ii < numNodes; ii++)
{
loadNode(loadHandler->getNextNodeName(), loadHandler, modelFactory);
}
}
void ValueImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{
SemanticVisitorImpl::loadAttributes(loadHandler, attr_list);
}
void ValueImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::shared_ptr<fUML::FUMLFactory> modelFactory)
{
SemanticVisitorImpl::loadNode(nodeName, loadHandler, modelFactory);
}
void ValueImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references)
{
SemanticVisitorImpl::resolveReferences(featureID, references);
}
void ValueImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
saveContent(saveHandler);
SemanticVisitorImpl::saveContent(saveHandler);
ecore::EObjectImpl::saveContent(saveHandler);
}
void ValueImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
try
{
std::shared_ptr<fUML::FUMLPackage> package = fUML::FUMLPackage::eInstance();
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
}
| 24.609121 | 234 | 0.617207 | MichaelBranz |
bf9c3244794c75dce20a9630a31ab3cdb0c460c0 | 1,978 | cpp | C++ | tests/test_Reflection_Spectrum.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 4 | 2021-02-26T10:30:36.000Z | 2021-03-17T01:49:18.000Z | tests/test_Reflection_Spectrum.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 7 | 2021-02-09T16:32:05.000Z | 2022-02-03T09:20:08.000Z | tests/test_Reflection_Spectrum.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 1 | 2022-01-03T03:54:24.000Z | 2022-01-03T03:54:24.000Z | #include "Reflection_Spectrum.hpp"
#include "gtest/gtest.h"
#include <mpi.h>
#include "libphysica/Integration.hpp"
#include "libphysica/Natural_Units.hpp"
#include "obscura/DM_Halo_Models.hpp"
#include "obscura/DM_Particle_Standard.hpp"
using namespace DaMaSCUS_SUN;
using namespace libphysica::natural_units;
int main(int argc, char* argv[])
{
int result = 0;
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
TEST(TestReflectionSpectrum, TestSpectrum)
{
// ARRANGE
Solar_Model solar_model;
obscura::Standard_Halo_Model SHM;
double mDM = 0.1;
obscura::DM_Particle_SI DM(mDM);
DM.Set_Low_Mass_Mode(true);
DM.Set_Sigma_Proton(1e-1 * pb);
solar_model.Interpolate_Total_DM_Scattering_Rate(DM, 100, 50);
Simulation_Data data_set(10, 0, 1);
int fixed_seed = 13;
data_set.Generate_Data(DM, solar_model, SHM, fixed_seed);
double v = 1e-3;
// ACT & ASSERT
Reflection_Spectrum spectrum(data_set, solar_model, SHM, mDM);
EXPECT_DOUBLE_EQ(spectrum.Differential_Spectrum(v), 4.0 * M_PI * AU * AU * spectrum.Differential_DM_Flux(v));
EXPECT_GT(spectrum.PDF_Speed(v), 0.0);
std::function<double(double)> pdf = [&spectrum](double v) {
return spectrum.PDF_Speed(v);
};
double norm = libphysica::Integrate(pdf, spectrum.Minimum_DM_Speed(), spectrum.Maximum_DM_Speed());
EXPECT_NEAR(norm, 1.0, 1e-3);
double flux_1 = spectrum.Differential_DM_Flux(v);
spectrum.Set_Distance(2.0 * AU);
double flux_2 = spectrum.Differential_DM_Flux(v);
EXPECT_DOUBLE_EQ(flux_1, 4.0 * flux_2);
}
TEST(TestReflectionSpectrum, TestDMEnteringRate)
{
// ARRANGE
Solar_Model solar_model;
obscura::Standard_Halo_Model SHM;
double mDM_1 = 1.0;
double mDM_2 = 2.0;
// ACT
double rate_1 = DM_Entering_Rate(solar_model, SHM, mDM_1);
double rate_2 = DM_Entering_Rate(solar_model, SHM, mDM_2);
// ASSERT
ASSERT_DOUBLE_EQ(rate_1, 2.0 * rate_2);
ASSERT_NEAR(rate_1, 1.06689e+30 / sec, 1.0e27 / sec);
} | 27.09589 | 110 | 0.747725 | temken |
bf9ebce3a48163c0b6c517e39a9b67d59e11fe6c | 4,913 | cpp | C++ | Components/Camera.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | Components/Camera.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | Components/Camera.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | #include "Camera.h"
#include "../GameObject.h"
#include "Component.h"
#include "../Application.h"
#include "../ModuleRender.h"
#include "../ModuleWindow.h"
#include "../ModuleCamera.h"
#include "../ModuleScene.h"
#include "../ModuleProgram.h"
#include "../ModuleModelLoader.h"
#include <math.h>
#include "../imgui/imgui.h"
#include "../Utils/DebugDraw.h"
Camera::Camera(GameObject* owner, int number) : Component(owner, ComponentType::Camera)
{
aspect = App->window->width / App->window->height;
frustum.type = FrustumType::PerspectiveFrustum;
if (number == 1) {
frustum.pos = float3::unitX;
}
else {
frustum.pos = float3{ 6.0F, 0.0F, -10.0F };
}
//skybox = new Skybox();
frustum.front = float3::unitZ;
frustum.up = float3::unitY;
frustum.nearPlaneDistance = 1.0F;
frustum.farPlaneDistance = 100.0F;
frustum.verticalFov = PI / 4.0F;
frustum.horizontalFov = 2.0F*atanf(tanf(frustum.verticalFov*0.5F)*aspect);
//setting up our proj
proj = frustum.ProjectionMatrix();
model = float4x4::FromTRS(float3(0.0F, -5.0F, 20.0F), float3x3::RotateY(0.0F), float3(1.0F, 1.0F, 1.0F));
view = frustum.ViewMatrix();
float4x4 transform = proj * view * float4x4(model);
glGenFramebuffers(1, &fbo);
}
Camera::~Camera()
{
glDeleteFramebuffers(1, &fbo);
glDeleteFramebuffers(1, &fb_depth);
}
void Camera::CreateRay(const float2& normalizedPos, LineSegment &value) const
{
value = frustum.UnProjectLineSegment(normalizedPos.x, normalizedPos.y);
}
void Camera::DrawFrustumPlanes()
{
float4x4 clipMatrix = proj * view;
dd::frustum(clipMatrix.Inverted(), float3(0, 0, 1));
}
int Camera::isCollidingFrustum(const AABB& aabb) const
{
float3 edges[8];
int totalPointsIn = 6;
aabb.GetCornerPoints(edges);
Plane viewportPlanes[6];
frustum.GetPlanes(viewportPlanes);
for (int pl = 0; pl < 6; pl++)
{
int isInPlane = 1;
for (int p = 0; p < 8; p++)
{
if (viewportPlanes[pl].IsOnPositiveSide(edges[p]))
{
isInPlane = 0;
--totalPointsIn;
}
}
}
if (totalPointsIn == 6)
{
return IS_IN;
}
if (totalPointsIn == 0)
{
return IS_OUT;
}
return INTERSECT;
}
void Camera::Draw(const char* name)
{
ImGui::Begin(name);
if (ImGui::IsWindowHovered())
{
isHovered = true;
}
else
{
isHovered = false;
}
width = ImGui::GetWindowContentRegionWidth();
height = ImGui::GetContentRegionAvail().y;
ImGui::SetNextWindowPos(ImVec2(256.0f, 0.0f), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(800.0f, 600.0f), ImGuiCond_FirstUseEver);
BindBuffers(width, height);
App->camera->SetAspectRatio(width/height, this);
ImGui::GetWindowDrawList()->AddImage(
(void*)fb_tex,
ImVec2(ImGui::GetCursorScreenPos()),
ImVec2(ImGui::GetCursorScreenPos().x + fb_width,
ImGui::GetCursorScreenPos().y + fb_height),
ImVec2(0, 1), ImVec2(1, 0));
//ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
void Camera::BindBuffers(unsigned w, unsigned h)
{
if (fb_tex)
{
glDeleteTextures(1, &fb_tex);
}
else {
glGenTextures(1, &fb_tex);
}
if (fb_depth)
{
glDeleteRenderbuffers(1, &fb_depth);
}
else {
glGenRenderbuffers(1, &fb_depth);
}
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glBindRenderbuffer(GL_RENDERBUFFER, fb_depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, fb_tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb_tex, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fb_depth);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
fb_width = w;
fb_height = h;
//glDrawBuffer(GL_COLOR_ATTACHMENT0);
}
void Camera::GenerateFBOTexture(unsigned w, unsigned h)
{
BindBuffers(w, h);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
unsigned int program = App->program->defaultProgram;
glUseProgram(program);
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_TRUE, &(model[0][0]));
glUniformMatrix4fv(glGetUniformLocation(program, "view"), 1, GL_TRUE, &(view[0][0]));
glUniformMatrix4fv(glGetUniformLocation(program, "proj"), 1, GL_TRUE, &(proj[0][0]));
glViewport(0, 0, width, height);
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
App->renderer->ShowAxis();
DrawFrustumPlanes();
App->renderer->ShowGrid();
App->scene->DrawAllBoundingBoxes();
App->modelLoader->Draw(program);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
| 24.688442 | 125 | 0.718095 | raulgonzalezupc |
bf9f398f8966a85086a2095312c25886bb8197a2 | 59,794 | hh | C++ | src/Mesh.hh | nmaxwell/OpenMesh-Python | daa461069decb459f990bfcc1131c55a2db7b5e5 | [
"BSD-3-Clause"
] | 9 | 2019-09-16T10:03:37.000Z | 2022-02-03T17:56:24.000Z | src/Mesh.hh | Jiawei1996/OpenMesh-Python | daa461069decb459f990bfcc1131c55a2db7b5e5 | [
"BSD-3-Clause"
] | null | null | null | src/Mesh.hh | Jiawei1996/OpenMesh-Python | daa461069decb459f990bfcc1131c55a2db7b5e5 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T15:23:59.000Z | 2020-04-13T15:23:59.000Z | #ifndef OPENMESH_PYTHON_MESH_HH
#define OPENMESH_PYTHON_MESH_HH
#include "Utilities.hh"
#include "MeshTypes.hh"
#include "Iterator.hh"
#include "Circulator.hh"
#include <algorithm>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
namespace py = pybind11;
namespace OM = OpenMesh;
/**
* Thin wrapper for assign_connectivity.
*
* @tparam Mesh A mesh type.
* @tparam OtherMesh A mesh type.
*
* @param _self The mesh instance that is to be used.
* @param _other The mesh from which the connectivity is to be copied.
*/
template <class Mesh, class OtherMesh>
void assign_connectivity(Mesh& _self, const OtherMesh& _other) {
_self.assign_connectivity(_other);
}
/**
* Get an iterator.
*/
template <class Mesh, class Iterator, size_t (OM::ArrayKernel::*n_items)() const>
IteratorWrapperT<Iterator, n_items> get_iterator(Mesh& _self) {
return IteratorWrapperT<Iterator, n_items>(_self, typename Iterator::value_type(0));
}
/**
* Get a skipping iterator.
*/
template <class Mesh, class Iterator, size_t (OM::ArrayKernel::*n_items)() const>
IteratorWrapperT<Iterator, n_items> get_skipping_iterator(Mesh& _self) {
return IteratorWrapperT<Iterator, n_items>(_self, typename Iterator::value_type(0), true);
}
/**
* Get a circulator.
*
* @tparam Mesh A Mesh type.
* @tparam Circulator A circulator type.
* @tparam CenterEntityHandle The appropriate handle type.
*
* @param _self The mesh instance that is to be used.
* @param _handle The handle of the item to circulate around.
*/
template <class Mesh, class Circulator, class CenterEntityHandle>
CirculatorWrapperT<Circulator, CenterEntityHandle> get_circulator(Mesh& _self, CenterEntityHandle _handle) {
return CirculatorWrapperT<Circulator, CenterEntityHandle>(_self, _handle);
}
/**
* Garbage collection using lists instead of vectors to keep track of a set of
* handles.
*
* @tparam Mesh A Mesh type.
*
* @param _self The mesh instance that is to be used.
* @param _vh_to_update The list of vertex handles to be updated.
* @param _hh_to_update The list of halfedge handles to be updated.
* @param _fh_to_update The list of face handles to be updated.
* @param _v Remove deleted vertices?
* @param _e Remove deleted edges?
* @param _f Remove deleted faces?
*/
template <class Mesh>
void garbage_collection(Mesh& _self, py::list& _vh_to_update, py::list& _hh_to_update, py::list& _fh_to_update, bool _v = true, bool _e = true, bool _f = true) {
// Convert list of handles to vector of pointers
std::vector<OM::VertexHandle*> vh_vector;
for (auto item : _vh_to_update) {
if (py::isinstance<OM::VertexHandle>(item)) {
vh_vector.push_back(item.cast<OM::VertexHandle*>());
}
}
// Convert list of handles to vector of pointers
std::vector<OM::HalfedgeHandle*> hh_vector;
for (auto item : _hh_to_update) {
if (py::isinstance<OM::HalfedgeHandle>(item)) {
hh_vector.push_back(item.cast<OM::HalfedgeHandle*>());
}
}
// Convert list of handles to vector of pointers
std::vector<OM::FaceHandle*> fh_vector;
for (auto item : _fh_to_update) {
if (py::isinstance<OM::FaceHandle>(item)) {
fh_vector.push_back(item.cast<OM::FaceHandle*>());
}
}
// Call garbage collection
_self.garbage_collection(vh_vector, hh_vector, fh_vector, _v, _e, _f);
}
/**
* Converts OpenMesh vectors to numpy arrays.
*
* @tparam vector A Vector type.
* @param _vec The vector to be converted.
*/
template<class Vector>
py::array_t<typename Vector::value_type> vec2numpy(const Vector& _vec) {
typedef typename Vector::value_type dtype;
dtype *data = new dtype[_vec.size()];
std::copy_n(_vec.data(), _vec.size(), data);
py::capsule base = free_when_done(data);
return py::array_t<dtype>({_vec.size()}, {sizeof(dtype)}, data, base);
}
/**
* Converts OpenMesh vectors to numpy arrays.
*
* The returned array references the vector's underlying data, i.e. changes
* made to the returned array affect the original mesh.
*
* @tparam Mesh A Mesh type.
* @tparam vector A Vector type.
*
* @param _mesh The mesh that owns the vector's underlying memory. In order
* to avaoid dangling pointers, the lifetime of this mesh is tied to the
* lifetime of the returned numpy array.
* @param _vec The vector to be converted.
*/
template<class Mesh, class Vector>
py::array_t<typename Vector::value_type> vec2numpy(Mesh& _mesh, Vector& _vec, size_t _n = 1) {
typedef typename Vector::value_type dtype;
std::vector<size_t> shape;
std::vector<size_t> strides;
if (_n == 1) {
shape = {_vec.size()};
strides = {sizeof(dtype)};
}
else {
shape = {_n, _vec.size()};
strides = {_vec.size() * sizeof(dtype), sizeof(dtype)};
}
return py::array_t<dtype>(shape, strides, _vec.data(), py::cast(_mesh));
}
template<class Mesh>
py::array_t<float> flt2numpy(Mesh& _mesh, const float& _flt, size_t _n = 1) {
return py::array_t<float>({_n}, {sizeof(float)}, &_flt, py::cast(_mesh));
}
template<class Mesh>
py::array_t<double> flt2numpy(Mesh& _mesh, const double& _flt, size_t _n = 1) {
return py::array_t<double>({_n}, {sizeof(double)}, &_flt, py::cast(_mesh));
}
py::array_t<int> face_vertex_indices_trimesh(TriMesh& _self) {
if (_self.n_faces() == 0) {
return py::array_t<int>();
}
const bool has_status = _self.has_face_status();
int *indices = new int[_self.n_faces() * 3];
py::capsule base = free_when_done(indices);
for (auto fh : _self.all_faces()) {
if (has_status && _self.status(fh).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
auto fv_it = _self.fv_iter(fh);
indices[fh.idx() * 3 + 0] = fv_it->idx(); ++fv_it;
indices[fh.idx() * 3 + 1] = fv_it->idx(); ++fv_it;
indices[fh.idx() * 3 + 2] = fv_it->idx();
}
const auto shape = {_self.n_faces(), size_t(3)};
const auto strides = {3 * sizeof(int), sizeof(int)};
return py::array_t<int>(shape, strides, indices, base);
}
struct FuncEdgeVertex {
static void call(const OM::ArrayKernel& _mesh, OM::EdgeHandle _eh, int *_ptr) {
const auto heh = _mesh.halfedge_handle(_eh, 0);
_ptr[0] = _mesh.from_vertex_handle(heh).idx();
_ptr[1] = _mesh.to_vertex_handle(heh).idx();
}
};
struct FuncEdgeFace {
static void call(const OM::ArrayKernel& _mesh, OM::EdgeHandle _eh, int *_ptr) {
const auto heh1 = _mesh.halfedge_handle(_eh, 0);
const auto heh2 = _mesh.halfedge_handle(_eh, 1);
_ptr[0] = _mesh.face_handle(heh1).idx();
_ptr[1] = _mesh.face_handle(heh2).idx();
}
};
struct FuncEdgeHalfedge {
static void call(const OM::ArrayKernel& _mesh, OM::EdgeHandle _eh, int *_ptr) {
_ptr[0] = _mesh.halfedge_handle(_eh, 0).idx();
_ptr[1] = _mesh.halfedge_handle(_eh, 1).idx();
}
};
struct FuncHalfedgeToVertex {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.to_vertex_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeFromVertex {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.from_vertex_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeFace {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.face_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeEdge {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.edge_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeVertex {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
_ptr[0] = _mesh.from_vertex_handle(_heh).idx();
_ptr[1] = _mesh.to_vertex_handle(_heh).idx();
}
static size_t dim() { return 2; }
};
template <class Mesh, class CopyFunc>
py::array_t<int> edge_other_indices(Mesh& _self) {
if (_self.n_edges() == 0) {
return py::array_t<int>();
}
const bool has_status = _self.has_edge_status();
int *indices = new int[_self.n_edges() * 2];
py::capsule base = free_when_done(indices);
for (auto eh : _self.all_edges()) {
if (has_status && _self.status(eh).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
CopyFunc::call(_self, eh, &indices[eh.idx() * 2]);
}
const auto shape = {_self.n_edges(), size_t(2)};
const auto strides = {2 * sizeof(int), sizeof(int)};
return py::array_t<int>(shape, strides, indices, base);
}
template <class Mesh, class CopyFunc>
py::array_t<int> halfedge_other_indices(Mesh& _self) {
if (_self.n_halfedges() == 0) {
return py::array_t<int>();
}
const bool has_status = _self.has_halfedge_status();
const size_t dim = CopyFunc::dim();
int *indices = new int[_self.n_halfedges() * dim];
py::capsule base = free_when_done(indices);
for (auto heh : _self.all_halfedges()) {
if (has_status && _self.status(heh).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
CopyFunc::call(_self, heh, &indices[heh.idx() * dim]);
}
std::vector<size_t> shape;
std::vector<size_t> strides;
if (dim == 1) {
shape = {_self.n_halfedges()};
strides = {sizeof(int)};
}
else {
shape = {_self.n_halfedges(), dim};
strides = {dim * sizeof(int), sizeof(int)};
}
return py::array_t<int>(shape, strides, indices, base);
}
template <class Mesh, class Handle, class Circulator>
py::array_t<int> indices(Mesh& _self) {
const size_t n = _self.py_n_items(Handle());
if (n == 0) return py::array_t<int>();
const bool has_status = _self.py_has_status(Handle());
// find max valence and check status
int max_valence = 0;
for (size_t i = 0; i < n; ++i) {
Handle hnd(i);
if (has_status && _self.status(hnd).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
int valence = 0;
for (auto it = Circulator(_self, hnd); it.is_valid(); ++it) {
valence++;
}
max_valence = std::max(max_valence, valence);
}
// allocate memory
int *indices = new int[n * max_valence];
// copy indices
for (size_t i = 0; i < n; ++i) {
int valence = 0;
for (auto it = Circulator(_self, Handle(i)); it.is_valid(); ++it) {
indices[i * max_valence + valence] = it->idx();
valence++;
}
for (size_t j = valence; j < max_valence; ++j) {
indices[i * max_valence + j] = -1;
}
}
// make numpy array
const auto shape = {n, size_t(max_valence)};
const auto strides = {max_valence * sizeof(int), sizeof(int)};
py::capsule base = free_when_done(indices);
return py::array_t<int>(shape, strides, indices, base);
}
/**
* This function template is used to expose mesh member functions that are only
* available for a specific type of mesh (i.e. they are available for polygon
* meshes or triangle meshes, but not both).
*
* @tparam Class A pybind11::class type.
*
* @param _class The pybind11::class instance for which the member
* functions are to be defined.
*/
template <class Class>
void expose_type_specific_functions(Class& _class) {
// See the template specializations below
}
/**
* Function template specialization for polygon meshes.
*/
template <>
void expose_type_specific_functions(py::class_<PolyMesh>& _class) {
typedef PolyMesh::Scalar Scalar;
typedef PolyMesh::Point Point;
typedef PolyMesh::Normal Normal;
typedef PolyMesh::Color Color;
typedef py::array_t<typename Point::value_type> np_point_t;
OM::FaceHandle (PolyMesh::*add_face_4_vh)(OM::VertexHandle, OM::VertexHandle, OM::VertexHandle, OM::VertexHandle) = &PolyMesh::add_face;
_class
.def("add_face", add_face_4_vh)
.def("split", [](PolyMesh& _self, OM::EdgeHandle _eh, np_point_t _arr) {
_self.split(_eh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split", [](PolyMesh& _self, OM::FaceHandle _fh, np_point_t _arr) {
_self.split(_fh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("insert_edge", &PolyMesh::insert_edge)
.def("face_vertex_indices", &indices<PolyMesh, OM::FaceHandle, PolyMesh::FaceVertexIter>)
.def("fv_indices", &indices<PolyMesh, OM::FaceHandle, PolyMesh::FaceVertexIter>)
.def("calc_face_normal", [](PolyMesh& _self, np_point_t _p0, np_point_t _p1, np_point_t _p2) {
const Point p0(_p0.at(0), _p0.at(1), _p0.at(2));
const Point p1(_p1.at(0), _p1.at(1), _p1.at(2));
const Point p2(_p2.at(0), _p2.at(1), _p2.at(2));
return vec2numpy(_self.calc_face_normal(p0, p1, p2));
})
;
}
/**
* Function template specialization for triangle meshes.
*/
template <>
void expose_type_specific_functions(py::class_<TriMesh>& _class) {
typedef TriMesh::Scalar Scalar;
typedef TriMesh::Point Point;
typedef TriMesh::Normal Normal;
typedef TriMesh::Color Color;
typedef py::array_t<typename Point::value_type> np_point_t;
void (TriMesh::*split_copy_eh_vh)(OM::EdgeHandle, OM::VertexHandle) = &TriMesh::split_copy;
OM::HalfedgeHandle (TriMesh::*vertex_split_vh)(OM::VertexHandle, OM::VertexHandle, OM::VertexHandle, OM::VertexHandle) = &TriMesh::vertex_split;
_class
.def("split", [](TriMesh& _self, OM::EdgeHandle _eh, np_point_t _arr) {
return _self.split(_eh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split", [](TriMesh& _self, OM::FaceHandle _fh, np_point_t _arr) {
return _self.split(_fh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split_copy", split_copy_eh_vh)
.def("split_copy", [](TriMesh& _self, OM::EdgeHandle _eh, np_point_t _arr) {
return _self.split_copy(_eh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split_copy", [](TriMesh& _self, OM::FaceHandle _fh, np_point_t _arr) {
return _self.split_copy(_fh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("opposite_vh", &TriMesh::opposite_vh)
.def("opposite_he_opposite_vh", &TriMesh::opposite_he_opposite_vh)
.def("vertex_split", vertex_split_vh)
.def("vertex_split", [](TriMesh& _self, np_point_t _arr, OM::VertexHandle _v1, OM::VertexHandle _vl, OM::VertexHandle _vr) {
return _self.vertex_split(Point(_arr.at(0), _arr.at(1), _arr.at(2)), _v1, _vl, _vr);
})
.def("is_flip_ok", &TriMesh::is_flip_ok)
.def("flip", &TriMesh::flip)
.def("face_vertex_indices", &face_vertex_indices_trimesh)
.def("fv_indices", &face_vertex_indices_trimesh)
;
}
/**
* Expose a mesh type to %Python.
*
* @tparam Mesh A mesh type.
*
* @param _name The name of the mesh type to be exposed.
*/
template <class Mesh>
void expose_mesh(py::module& m, const char *_name) {
typedef typename Mesh::Scalar Scalar;
typedef typename Mesh::Point Point;
typedef typename Mesh::Normal Normal;
typedef typename Mesh::Color Color;
typedef typename Mesh::TexCoord1D TexCoord1D;
typedef typename Mesh::TexCoord2D TexCoord2D;
typedef typename Mesh::TexCoord3D TexCoord3D;
typedef typename Mesh::TextureIndex TextureIndex;
//======================================================================
// KernelT Function Pointers
//======================================================================
// Get the i'th item
OM::VertexHandle (Mesh::*vertex_handle_uint )(unsigned int) const = &Mesh::vertex_handle;
OM::HalfedgeHandle (Mesh::*halfedge_handle_uint)(unsigned int) const = &Mesh::halfedge_handle;
OM::EdgeHandle (Mesh::*edge_handle_uint )(unsigned int) const = &Mesh::edge_handle;
OM::FaceHandle (Mesh::*face_handle_uint )(unsigned int) const = &Mesh::face_handle;
// Delete items
void (Mesh::*garbage_collection_bools)(bool, bool, bool) = &Mesh::garbage_collection;
void (*garbage_collection_lists_bools)(Mesh&, py::list&, py::list&, py::list&, bool, bool, bool) = &garbage_collection;
// Vertex connectivity
OM::HalfedgeHandle (Mesh::*halfedge_handle_vh)(OM::VertexHandle) const = &Mesh::halfedge_handle;
OM::HalfedgeHandle (Mesh::*halfedge_handle_fh)(OM::FaceHandle ) const = &Mesh::halfedge_handle;
// Halfedge connectivity
OM::FaceHandle (Mesh::*face_handle_hh )(OM::HalfedgeHandle) const = &Mesh::face_handle;
OM::HalfedgeHandle (Mesh::*prev_halfedge_handle_hh)(OM::HalfedgeHandle) const = &Mesh::prev_halfedge_handle;
OM::EdgeHandle (Mesh::*edge_handle_hh )(OM::HalfedgeHandle) const = &Mesh::edge_handle;
// Edge connectivity
OM::HalfedgeHandle (Mesh::*halfedge_handle_eh_uint)(OM::EdgeHandle, unsigned int) const = &Mesh::halfedge_handle;
// Set halfedge
void (Mesh::*set_halfedge_handle_vh_hh)(OM::VertexHandle, OM::HalfedgeHandle) = &Mesh::set_halfedge_handle;
void (Mesh::*set_halfedge_handle_fh_hh)(OM::FaceHandle, OM::HalfedgeHandle) = &Mesh::set_halfedge_handle;
// Low-level adding new items
OM::VertexHandle (Mesh::*new_vertex_void )(void ) = &Mesh::new_vertex;
OM::FaceHandle (Mesh::*new_face_void )(void ) = &Mesh::new_face;
OM::FaceHandle (Mesh::*new_face_face )(const typename Mesh::Face& ) = &Mesh::new_face;
// Kernel item iterators
IteratorWrapperT<typename Mesh::VertexIter, &Mesh::n_vertices > (*vertices )(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::HalfedgeIter, &Mesh::n_halfedges> (*halfedges)(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::EdgeIter, &Mesh::n_edges > (*edges )(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::FaceIter, &Mesh::n_faces > (*faces )(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::VertexIter, &Mesh::n_vertices > (*svertices )(Mesh&) = &get_skipping_iterator;
IteratorWrapperT<typename Mesh::HalfedgeIter, &Mesh::n_halfedges> (*shalfedges)(Mesh&) = &get_skipping_iterator;
IteratorWrapperT<typename Mesh::EdgeIter, &Mesh::n_edges > (*sedges )(Mesh&) = &get_skipping_iterator;
IteratorWrapperT<typename Mesh::FaceIter, &Mesh::n_faces > (*sfaces )(Mesh&) = &get_skipping_iterator;
//======================================================================
// BaseKernel Function Pointers
//======================================================================
// Copy all properties
void (Mesh::*copy_all_properties_vh_vh_bool)(OM::VertexHandle, OM::VertexHandle, bool) = &Mesh::copy_all_properties;
void (Mesh::*copy_all_properties_hh_hh_bool)(OM::HalfedgeHandle, OM::HalfedgeHandle, bool) = &Mesh::copy_all_properties;
void (Mesh::*copy_all_properties_eh_eh_bool)(OM::EdgeHandle, OM::EdgeHandle, bool) = &Mesh::copy_all_properties;
void (Mesh::*copy_all_properties_fh_fh_bool)(OM::FaceHandle, OM::FaceHandle, bool) = &Mesh::copy_all_properties;
//======================================================================
// PolyConnectivity Function Pointers
//======================================================================
// Assign connectivity
void (*assign_connectivity_poly)(Mesh&, const PolyMesh&) = &assign_connectivity;
void (*assign_connectivity_tri )(Mesh&, const TriMesh& ) = &assign_connectivity;
// Adding items to a mesh
OM::FaceHandle (Mesh::*add_face_3_vh)(OM::VertexHandle, OM::VertexHandle, OM::VertexHandle) = &Mesh::add_face;
OM::FaceHandle (Mesh::*add_face_list)(const std::vector<OM::VertexHandle>&) = &Mesh::add_face;
// Vertex and face valence
unsigned int (Mesh::*valence_vh)(OM::VertexHandle) const = &Mesh::valence;
unsigned int (Mesh::*valence_fh)(OM::FaceHandle ) const = &Mesh::valence;
// Triangulate face or mesh
void (Mesh::*triangulate_fh )(OM::FaceHandle) = &Mesh::triangulate;
void (Mesh::*triangulate_void)( ) = &Mesh::triangulate;
// Vertex and Face circulators
CirculatorWrapperT<typename Mesh::VertexVertexIter, OM::VertexHandle > (*vv )(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexIHalfedgeIter, OM::VertexHandle > (*vih)(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexOHalfedgeIter, OM::VertexHandle > (*voh)(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexEdgeIter, OM::VertexHandle > (*ve )(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexFaceIter, OM::VertexHandle > (*vf )(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceVertexIter, OM::FaceHandle > (*fv )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceHalfedgeIter, OM::FaceHandle > (*fh )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceEdgeIter, OM::FaceHandle > (*fe )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceFaceIter, OM::FaceHandle > (*ff )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::HalfedgeLoopIter, OM::HalfedgeHandle> (*hl )(Mesh&, OM::HalfedgeHandle) = &get_circulator;
// Boundary and manifold tests
bool (Mesh::*is_boundary_hh)(OM::HalfedgeHandle ) const = &Mesh::is_boundary;
bool (Mesh::*is_boundary_eh)(OM::EdgeHandle ) const = &Mesh::is_boundary;
bool (Mesh::*is_boundary_vh)(OM::VertexHandle ) const = &Mesh::is_boundary;
bool (Mesh::*is_boundary_fh)(OM::FaceHandle, bool) const = &Mesh::is_boundary;
//======================================================================
// PolyMeshT Function Pointers
//======================================================================
Scalar (Mesh::*calc_edge_length_eh)(OM::EdgeHandle ) const = &Mesh::calc_edge_length;
Scalar (Mesh::*calc_edge_length_hh)(OM::HalfedgeHandle) const = &Mesh::calc_edge_length;
Scalar (Mesh::*calc_edge_sqr_length_eh)(OM::EdgeHandle ) const = &Mesh::calc_edge_sqr_length;
Scalar (Mesh::*calc_edge_sqr_length_hh)(OM::HalfedgeHandle) const = &Mesh::calc_edge_sqr_length;
Scalar (Mesh::*calc_dihedral_angle_fast_hh)(OM::HalfedgeHandle) const = &Mesh::calc_dihedral_angle_fast;
Scalar (Mesh::*calc_dihedral_angle_fast_eh)(OM::EdgeHandle ) const = &Mesh::calc_dihedral_angle_fast;
Scalar (Mesh::*calc_dihedral_angle_hh)(OM::HalfedgeHandle) const = &Mesh::calc_dihedral_angle;
Scalar (Mesh::*calc_dihedral_angle_eh)(OM::EdgeHandle ) const = &Mesh::calc_dihedral_angle;
unsigned int (Mesh::*find_feature_edges)(Scalar) = &Mesh::find_feature_edges;
void (Mesh::*split_fh_vh)(OM::FaceHandle, OM::VertexHandle) = &Mesh::split;
void (Mesh::*split_eh_vh)(OM::EdgeHandle, OM::VertexHandle) = &Mesh::split;
void (Mesh::*split_copy_fh_vh)(OM::FaceHandle, OM::VertexHandle) = &Mesh::split_copy;
//======================================================================
// Mesh Type
//======================================================================
py::class_<Mesh> class_mesh(m, _name);
class_mesh
.def(py::init<>())
.def(py::init([](py::array_t<typename Point::value_type> _points, py::array_t<int> _faces) {
Mesh mesh;
// return if _points is empty
if (_points.size() == 0) {
return mesh;
}
// _points is not empty, throw if _points has wrong shape
if (_points.ndim() != 2 || _points.shape(1) != 3) {
PyErr_SetString(PyExc_RuntimeError, "Array 'points' must have shape (n, 3)");
throw py::error_already_set();
}
for (ssize_t i = 0; i < _points.shape(0); ++i) {
mesh.add_vertex(Point(_points.at(i, 0), _points.at(i, 1), _points.at(i, 2)));
}
// return if _faces is empty
if (_faces.size() == 0) {
return mesh;
}
// _faces is not empty, throw if _faces has wrong shape
if (_faces.ndim() != 2 || _faces.shape(1) < 3) {
PyErr_SetString(PyExc_RuntimeError, "Array 'face_vertex_indices' must have shape (n, m) with m > 2");
throw py::error_already_set();
}
for (ssize_t i = 0; i < _faces.shape(0); ++i) {
std::vector<OM::VertexHandle> vhandles;
for (ssize_t j = 0; j < _faces.shape(1); ++j) {
if (_faces.at(i, j) >= 0 && _faces.at(i, j) < _points.shape(0)) {
vhandles.push_back(OM::VertexHandle(_faces.at(i, j)));
}
}
if (vhandles.size() >= 3) {
mesh.add_face(vhandles);
}
}
return mesh;
}), py::arg("points"), py::arg("face_vertex_indices")=py::array_t<int>())
//======================================================================
// Copy interface
//======================================================================
.def("__copy__", &Mesh::py_copy)
.def("__deepcopy__", &Mesh::py_deepcopy)
//======================================================================
// KernelT
//======================================================================
.def("reserve", &Mesh::reserve)
.def("vertex_handle", vertex_handle_uint)
.def("halfedge_handle", halfedge_handle_uint)
.def("edge_handle", edge_handle_uint)
.def("face_handle", face_handle_uint)
.def("clear", &Mesh::clear)
.def("clean", &Mesh::clean)
.def("garbage_collection", garbage_collection_bools,
py::arg("v")=true, py::arg("e")=true, py::arg("f")=true)
.def("garbage_collection", garbage_collection_lists_bools,
py::arg("vh_to_update"), py::arg("hh_to_update"), py::arg("fh_to_update"),
py::arg("v")=true, py::arg("e")=true, py::arg("f")=true)
.def("n_vertices", &Mesh::n_vertices)
.def("n_halfedges", &Mesh::n_halfedges)
.def("n_edges", &Mesh::n_edges)
.def("n_faces", &Mesh::n_faces)
.def("vertices_empty", &Mesh::vertices_empty)
.def("halfedges_empty", &Mesh::halfedges_empty)
.def("edges_empty", &Mesh::edges_empty)
.def("faces_empty", &Mesh::faces_empty)
.def("halfedge_handle", halfedge_handle_vh)
.def("set_halfedge_handle", set_halfedge_handle_vh_hh)
.def("to_vertex_handle", &Mesh::to_vertex_handle)
.def("from_vertex_handle", &Mesh::from_vertex_handle)
.def("set_vertex_handle", &Mesh::set_vertex_handle)
.def("face_handle", face_handle_hh)
.def("set_face_handle", &Mesh::set_face_handle)
.def("next_halfedge_handle", &Mesh::next_halfedge_handle)
.def("set_next_halfedge_handle", &Mesh::set_next_halfedge_handle)
.def("prev_halfedge_handle", prev_halfedge_handle_hh)
.def("opposite_halfedge_handle", &Mesh::opposite_halfedge_handle)
.def("ccw_rotated_halfedge_handle", &Mesh::ccw_rotated_halfedge_handle)
.def("cw_rotated_halfedge_handle", &Mesh::cw_rotated_halfedge_handle)
.def("edge_handle", edge_handle_hh)
.def("halfedge_handle", halfedge_handle_eh_uint)
.def("halfedge_handle", halfedge_handle_fh)
.def("set_halfedge_handle", set_halfedge_handle_fh_hh)
.def("is_deleted", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::VertexHandle _h, bool _val) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
_self.status(_h).set_deleted(_val);
})
.def("is_deleted", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::HalfedgeHandle _h, bool _val) {
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
_self.status(_h).set_deleted(_val);
})
.def("is_deleted", [](Mesh& _self, OM::EdgeHandle _h) {
if (!_self.has_edge_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::EdgeHandle _h, bool _val) {
if (!_self.has_edge_status()) _self.request_edge_status();
_self.status(_h).set_deleted(_val);
})
.def("is_deleted", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::FaceHandle _h, bool _val) {
if (!_self.has_face_status()) _self.request_face_status();
_self.status(_h).set_deleted(_val);
})
.def("request_vertex_normals", &Mesh::request_vertex_normals)
.def("request_vertex_colors", &Mesh::request_vertex_colors)
.def("request_vertex_texcoords1D", &Mesh::request_vertex_texcoords1D)
.def("request_vertex_texcoords2D", &Mesh::request_vertex_texcoords2D)
.def("request_vertex_texcoords3D", &Mesh::request_vertex_texcoords3D)
.def("request_halfedge_normals", &Mesh::request_halfedge_normals)
.def("request_halfedge_colors", &Mesh::request_halfedge_colors)
.def("request_halfedge_texcoords1D", &Mesh::request_halfedge_texcoords1D)
.def("request_halfedge_texcoords2D", &Mesh::request_halfedge_texcoords2D)
.def("request_halfedge_texcoords3D", &Mesh::request_halfedge_texcoords3D)
.def("request_edge_colors", &Mesh::request_edge_colors)
.def("request_face_normals", &Mesh::request_face_normals)
.def("request_face_colors", &Mesh::request_face_colors)
.def("request_face_texture_index", &Mesh::request_face_texture_index)
.def("release_vertex_normals", &Mesh::release_vertex_normals)
.def("release_vertex_colors", &Mesh::release_vertex_colors)
.def("release_vertex_texcoords1D", &Mesh::release_vertex_texcoords1D)
.def("release_vertex_texcoords2D", &Mesh::release_vertex_texcoords2D)
.def("release_vertex_texcoords3D", &Mesh::release_vertex_texcoords3D)
.def("release_halfedge_normals", &Mesh::release_halfedge_normals)
.def("release_halfedge_colors", &Mesh::release_halfedge_colors)
.def("release_halfedge_texcoords1D", &Mesh::release_halfedge_texcoords1D)
.def("release_halfedge_texcoords2D", &Mesh::release_halfedge_texcoords2D)
.def("release_halfedge_texcoords3D", &Mesh::release_halfedge_texcoords3D)
.def("release_edge_colors", &Mesh::release_edge_colors)
.def("release_face_normals", &Mesh::release_face_normals)
.def("release_face_colors", &Mesh::release_face_colors)
.def("release_face_texture_index", &Mesh::release_face_texture_index)
.def("has_vertex_normals", &Mesh::has_vertex_normals)
.def("has_vertex_colors", &Mesh::has_vertex_colors)
.def("has_vertex_texcoords1D", &Mesh::has_vertex_texcoords1D)
.def("has_vertex_texcoords2D", &Mesh::has_vertex_texcoords2D)
.def("has_vertex_texcoords3D", &Mesh::has_vertex_texcoords3D)
.def("has_halfedge_normals", &Mesh::has_halfedge_normals)
.def("has_halfedge_colors", &Mesh::has_halfedge_colors)
.def("has_halfedge_texcoords1D", &Mesh::has_halfedge_texcoords1D)
.def("has_halfedge_texcoords2D", &Mesh::has_halfedge_texcoords2D)
.def("has_halfedge_texcoords3D", &Mesh::has_halfedge_texcoords3D)
.def("has_edge_colors", &Mesh::has_edge_colors)
.def("has_face_normals", &Mesh::has_face_normals)
.def("has_face_colors", &Mesh::has_face_colors)
.def("has_face_texture_index", &Mesh::has_face_texture_index)
.def("new_vertex", new_vertex_void)
.def("new_vertex", [](Mesh& _self, py::array_t<typename Point::value_type> _arr) {
return _self.new_vertex(Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("new_edge", &Mesh::new_edge)
.def("new_face", new_face_void)
.def("new_face", new_face_face)
.def("vertices", vertices)
.def("halfedges", halfedges)
.def("edges", edges)
.def("faces", faces)
.def("svertices", svertices)
.def("shalfedges", shalfedges)
.def("sedges", sedges)
.def("sfaces", sfaces)
.def("texture_index", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_texture_index()) _self.request_face_texture_index();
return _self.texture_index(_h);
})
.def("set_texture_index", [](Mesh& _self, OM::FaceHandle _h, TextureIndex _idx) {
if (!_self.has_face_texture_index()) _self.request_face_texture_index();
_self.set_texture_index(_h, _idx);
})
.def("texture_name", [](Mesh& _self, TextureIndex _idx) {
OM::MPropHandleT<std::map<TextureIndex, std::string> > prop;
if (_self.get_property_handle(prop, "TextureMapping")) {
const auto map = _self.property(prop);
if (map.count(_idx) == 0) {
throw py::index_error();
}
else {
return map.at(_idx);
}
}
else {
PyErr_SetString(PyExc_RuntimeError, "Mesh has no textures.");
throw py::error_already_set();
}
})
//======================================================================
// BaseKernel
//======================================================================
.def("copy_all_properties", copy_all_properties_vh_vh_bool,
py::arg("vh_from"), py::arg("vh_to"), py::arg("copy_build_in")=false)
.def("copy_all_properties", copy_all_properties_hh_hh_bool,
py::arg("hh_from"), py::arg("hh_to"), py::arg("copy_build_in")=false)
.def("copy_all_properties", copy_all_properties_eh_eh_bool,
py::arg("eh_from"), py::arg("eh_to"), py::arg("copy_build_in")=false)
.def("copy_all_properties", copy_all_properties_fh_fh_bool,
py::arg("fh_from"), py::arg("fh_to"), py::arg("copy_build_in")=false)
//======================================================================
// ArrayKernel
//======================================================================
.def("is_valid_handle", (bool (Mesh::*)(OM::VertexHandle) const) &Mesh::is_valid_handle)
.def("is_valid_handle", (bool (Mesh::*)(OM::HalfedgeHandle) const) &Mesh::is_valid_handle)
.def("is_valid_handle", (bool (Mesh::*)(OM::EdgeHandle) const) &Mesh::is_valid_handle)
.def("is_valid_handle", (bool (Mesh::*)(OM::FaceHandle) const) &Mesh::is_valid_handle)
.def("delete_isolated_vertices", [](Mesh& _self) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
_self.delete_isolated_vertices();
})
//======================================================================
// PolyConnectivity
//======================================================================
.def("assign_connectivity", assign_connectivity_poly)
.def("assign_connectivity", assign_connectivity_tri)
.def("add_face", add_face_3_vh)
.def("add_face", add_face_list)
.def("opposite_face_handle", &Mesh::opposite_face_handle)
.def("adjust_outgoing_halfedge", &Mesh::adjust_outgoing_halfedge)
.def("find_halfedge", &Mesh::find_halfedge)
.def("valence", valence_vh)
.def("valence", valence_fh)
.def("is_simple_link", &Mesh::is_simple_link)
.def("is_simply_connected", &Mesh::is_simply_connected)
.def("remove_edge", &Mesh::remove_edge)
.def("reinsert_edge", &Mesh::reinsert_edge)
.def("triangulate", triangulate_fh)
.def("triangulate", triangulate_void)
.def("split_edge", &Mesh::split_edge)
.def("split_edge_copy", &Mesh::split_edge_copy)
.def("is_collapse_ok", [](Mesh& _self, OM::HalfedgeHandle _heh) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
return _self.is_collapse_ok(_heh);
})
.def("collapse", [](Mesh& _self, OM::HalfedgeHandle _heh) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.collapse(_heh);
})
.def("add_vertex", [](Mesh& _self, py::array_t<typename Point::value_type> _arr) {
return _self.add_vertex(Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("delete_vertex", [](Mesh& _self, OM::VertexHandle _vh, bool _delete_isolated) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.delete_vertex(_vh, _delete_isolated);
}, py::arg("vh"), py::arg("delete_isolated_vertices")=true)
.def("delete_edge", [](Mesh& _self, OM::EdgeHandle _eh, bool _delete_isolated) {
if (!_self.has_vertex_status() && _delete_isolated) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.delete_edge(_eh, _delete_isolated);
}, py::arg("eh"), py::arg("delete_isolated_vertices")=true)
.def("delete_face", [](Mesh& _self, OM::FaceHandle _fh, bool _delete_isolated) {
if (!_self.has_vertex_status() && _delete_isolated) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.delete_face(_fh, _delete_isolated);
}, py::arg("fh"), py::arg("delete_isolated_vertices")=true)
.def("vv", vv)
.def("vih", vih)
.def("voh", voh)
.def("ve", ve)
.def("vf", vf)
.def("fv", fv)
.def("fh", fh)
.def("fe", fe)
.def("ff", ff)
.def("hl", hl)
.def("is_boundary", is_boundary_hh)
.def("is_boundary", is_boundary_eh)
.def("is_boundary", is_boundary_vh)
.def("is_boundary", is_boundary_fh, py::arg("fh"), py::arg("check_vertex")=false)
.def("is_manifold", &Mesh::is_manifold)
.def_static("is_triangles", &Mesh::is_triangles)
.def_readonly_static("InvalidVertexHandle", &Mesh::InvalidVertexHandle)
.def_readonly_static("InvalidHalfedgeHandle", &Mesh::InvalidHalfedgeHandle)
.def_readonly_static("InvalidEdgeHandle", &Mesh::InvalidEdgeHandle)
.def_readonly_static("InvalidFaceHandle", &Mesh::InvalidFaceHandle)
//======================================================================
// PolyMeshT
//======================================================================
.def("calc_edge_length", calc_edge_length_eh)
.def("calc_edge_length", calc_edge_length_hh)
.def("calc_edge_sqr_length", calc_edge_sqr_length_eh)
.def("calc_edge_sqr_length", calc_edge_sqr_length_hh)
.def("calc_sector_angle", &Mesh::calc_sector_angle)
.def("calc_sector_area", &Mesh::calc_sector_area)
.def("calc_dihedral_angle_fast", calc_dihedral_angle_fast_hh)
.def("calc_dihedral_angle_fast", calc_dihedral_angle_fast_eh)
.def("calc_dihedral_angle", calc_dihedral_angle_hh)
.def("calc_dihedral_angle", calc_dihedral_angle_eh)
.def("find_feature_edges", find_feature_edges, py::arg("angle_tresh")=OM::deg_to_rad(44.0))
.def("split", split_fh_vh)
.def("split", split_eh_vh)
.def("split_copy", split_copy_fh_vh)
.def("update_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
}
if (!_self.has_halfedge_normals()) {
_self.request_halfedge_normals();
}
if (!_self.has_vertex_normals()) {
_self.request_vertex_normals();
}
_self.update_normals();
})
.def("update_normal", [](Mesh& _self, OM::FaceHandle _fh) {
if (!_self.has_face_normals()) _self.request_face_normals();
_self.update_normal(_fh);
})
.def("update_face_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) _self.request_face_normals();
_self.update_face_normals();
})
.def("update_normal", [](Mesh& _self, OM::HalfedgeHandle _hh, double _feature_angle) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_halfedge_normals()) {
_self.request_halfedge_normals();
}
_self.update_normal(_hh, _feature_angle);
}, py::arg("heh"), py::arg("feature_angle")=0.8)
.def("update_halfedge_normals", [](Mesh& _self, double _feature_angle) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_halfedge_normals()) {
_self.request_halfedge_normals();
}
_self.update_halfedge_normals(_feature_angle);
}, py::arg("feature_angle")=0.8)
.def("update_normal", [](Mesh& _self, OM::VertexHandle _vh) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_vertex_normals()) {
_self.request_vertex_normals();
}
_self.update_normal(_vh);
})
.def("update_vertex_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_vertex_normals()) {
_self.request_vertex_normals();
}
_self.update_vertex_normals();
})
.def("is_estimated_feature_edge", &Mesh::is_estimated_feature_edge)
.def_static("is_polymesh", &Mesh::is_polymesh)
.def("is_trimesh", &Mesh::is_trimesh)
//======================================================================
// numpy calc_*
//======================================================================
.def("calc_face_normal", [](Mesh& _self, OM::FaceHandle _fh) {
return vec2numpy(_self.calc_face_normal(_fh));
})
.def("calc_halfedge_normal", [](Mesh& _self, OM::HalfedgeHandle _heh, double _feature_angle) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
return vec2numpy(_self.calc_halfedge_normal(_heh, _feature_angle));
}, py::arg("heh"), py::arg("feature_angle")=0.8)
.def("calc_vertex_normal", [](Mesh& _self, OM::VertexHandle _vh) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
return vec2numpy(_self.calc_vertex_normal(_vh));
})
.def("calc_vertex_normal_fast", [](Mesh& _self, OM::VertexHandle _vh) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
typename Mesh::Normal n;
_self.calc_vertex_normal_fast(_vh, n);
return vec2numpy(n);
})
.def("calc_vertex_normal_correct", [](Mesh& _self, OM::VertexHandle _vh) {
typename Mesh::Normal n;
_self.calc_vertex_normal_correct(_vh, n);
return vec2numpy(n);
})
.def("calc_vertex_normal_loop", [](Mesh& _self, OM::VertexHandle _vh) {
typename Mesh::Normal n;
_self.calc_vertex_normal_loop(_vh, n);
return vec2numpy(n);
})
.def("calc_face_centroid", [](Mesh& _self, OM::FaceHandle _fh) {
return vec2numpy(_self.calc_face_centroid(_fh));
})
.def("calc_edge_vector", [](Mesh& _self, OM::EdgeHandle _eh) {
return vec2numpy(_self.calc_edge_vector(_eh));
})
.def("calc_edge_vector", [](Mesh& _self, OM::HalfedgeHandle _heh) {
return vec2numpy(_self.calc_edge_vector(_heh));
})
.def("calc_sector_vectors", [](Mesh& _self, OM::HalfedgeHandle _heh) {
typename Mesh::Normal vec0;
typename Mesh::Normal vec1;
_self.calc_sector_vectors(_heh, vec0, vec1);
return std::make_tuple(vec2numpy(vec0), vec2numpy(vec1));
})
.def("calc_sector_normal", [](Mesh& _self, OM::HalfedgeHandle _heh) {
typename Mesh::Normal n;
_self.calc_sector_normal(_heh, n);
return vec2numpy(n);
})
//======================================================================
// numpy vector getter
//======================================================================
.def("point", [](Mesh& _self, OM::VertexHandle _h) {
return vec2numpy(_self, _self.point(_h));
})
.def("normal", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_normals()) _self.request_vertex_normals();
return vec2numpy(_self, _self.normal(_h));
})
.def("normal", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_normals()) _self.request_halfedge_normals();
return vec2numpy(_self, _self.normal(_h));
})
.def("normal", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_normals()) _self.request_face_normals();
return vec2numpy(_self, _self.normal(_h));
})
.def("color", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_colors()) _self.request_vertex_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("color", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_colors()) _self.request_halfedge_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("color", [](Mesh& _self, OM::EdgeHandle _h) {
if (!_self.has_edge_colors()) _self.request_edge_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("color", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_colors()) _self.request_face_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("texcoord1D", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_texcoords1D()) _self.request_vertex_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(_h));
})
.def("texcoord1D", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_texcoords1D()) _self.request_halfedge_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(_h));
})
.def("texcoord2D", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_texcoords2D()) _self.request_vertex_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(_h));
})
.def("texcoord2D", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_texcoords2D()) _self.request_halfedge_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(_h));
})
.def("texcoord3D", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_texcoords3D()) _self.request_vertex_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(_h));
})
.def("texcoord3D", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_texcoords3D()) _self.request_halfedge_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(_h));
})
//======================================================================
// numpy vector setter
//======================================================================
.def("set_point", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename Point::value_type> _arr) {
_self.point(_h) = Point(_arr.at(0), _arr.at(1), _arr.at(2));
})
.def("set_normal", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename Normal::value_type> _arr) {
if (!_self.has_vertex_normals()) _self.request_vertex_normals();
_self.set_normal(_h, typename Mesh::Normal(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_normal", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename Normal::value_type> _arr) {
if (!_self.has_halfedge_normals()) _self.request_halfedge_normals();
_self.set_normal(_h, typename Mesh::Normal(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_normal", [](Mesh& _self, OM::FaceHandle _h, py::array_t<typename Normal::value_type> _arr) {
if (!_self.has_face_normals()) _self.request_face_normals();
_self.set_normal(_h, typename Mesh::Normal(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_color", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_vertex_colors()) _self.request_vertex_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_color", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_halfedge_colors()) _self.request_halfedge_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_color", [](Mesh& _self, OM::EdgeHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_edge_colors()) _self.request_edge_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_color", [](Mesh& _self, OM::FaceHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_face_colors()) _self.request_face_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_texcoord1D", [](Mesh& _self, OM::VertexHandle _h, py::array_t<TexCoord1D> _arr) {
if (!_self.has_vertex_texcoords1D()) _self.request_vertex_texcoords1D();
_self.set_texcoord1D(_h, _arr.at(0));
})
.def("set_texcoord1D", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<TexCoord1D> _arr) {
if (!_self.has_halfedge_texcoords1D()) _self.request_halfedge_texcoords1D();
_self.set_texcoord1D(_h, _arr.at(0));
})
.def("set_texcoord2D", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename TexCoord2D::value_type> _arr) {
if (!_self.has_vertex_texcoords2D()) _self.request_vertex_texcoords2D();
_self.set_texcoord2D(_h, typename Mesh::TexCoord2D(_arr.at(0), _arr.at(1)));
})
.def("set_texcoord2D", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename TexCoord2D::value_type> _arr) {
if (!_self.has_halfedge_texcoords2D()) _self.request_halfedge_texcoords2D();
_self.set_texcoord2D(_h, typename Mesh::TexCoord2D(_arr.at(0), _arr.at(1)));
})
.def("set_texcoord3D", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename TexCoord3D::value_type> _arr) {
if (!_self.has_vertex_texcoords3D()) _self.request_vertex_texcoords3D();
_self.set_texcoord3D(_h, typename Mesh::TexCoord3D(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_texcoord3D", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename TexCoord3D::value_type> _arr) {
if (!_self.has_halfedge_texcoords3D()) _self.request_halfedge_texcoords3D();
_self.set_texcoord3D(_h, typename Mesh::TexCoord3D(_arr.at(0), _arr.at(1), _arr.at(2)));
})
//======================================================================
// numpy matrix getter
//======================================================================
.def("points", [](Mesh& _self) {
return vec2numpy(_self, _self.point(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_normals", [](Mesh& _self) {
if (!_self.has_vertex_normals()) _self.request_vertex_normals();
return vec2numpy(_self, _self.normal(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_colors", [](Mesh& _self) {
if (!_self.has_vertex_colors()) _self.request_vertex_colors();
return vec2numpy(_self, _self.color(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_texcoords1D", [](Mesh& _self) {
if (!_self.has_vertex_texcoords1D()) _self.request_vertex_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_texcoords2D", [](Mesh& _self) {
if (!_self.has_vertex_texcoords2D()) _self.request_vertex_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_texcoords3D", [](Mesh& _self) {
if (!_self.has_vertex_texcoords3D()) _self.request_vertex_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(OM::VertexHandle(0)), _self.n_vertices());
})
.def("halfedge_normals", [](Mesh& _self) {
if (!_self.has_halfedge_normals()) _self.request_halfedge_normals();
return vec2numpy(_self, _self.normal(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_colors", [](Mesh& _self) {
if (!_self.has_halfedge_colors()) _self.request_halfedge_colors();
return vec2numpy(_self, _self.color(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_texcoords1D", [](Mesh& _self) {
if (!_self.has_halfedge_texcoords1D()) _self.request_halfedge_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_texcoords2D", [](Mesh& _self) {
if (!_self.has_halfedge_texcoords2D()) _self.request_halfedge_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_texcoords3D", [](Mesh& _self) {
if (!_self.has_halfedge_texcoords3D()) _self.request_halfedge_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("edge_colors", [](Mesh& _self) {
if (!_self.has_edge_colors()) _self.request_edge_colors();
return vec2numpy(_self, _self.color(OM::EdgeHandle(0)), _self.n_edges());
})
.def("face_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) _self.request_face_normals();
return vec2numpy(_self, _self.normal(OM::FaceHandle(0)), _self.n_faces());
})
.def("face_colors", [](Mesh& _self) {
if (!_self.has_face_colors()) _self.request_face_colors();
return vec2numpy(_self, _self.color (OM::FaceHandle(0)), _self.n_faces());
})
//======================================================================
// numpy indices
//======================================================================
.def("vertex_vertex_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexVertexIter>)
.def("vv_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexVertexIter>)
.def("vertex_face_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexFaceIter>)
.def("vf_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexFaceIter>)
.def("vertex_edge_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexEdgeIter>)
.def("ve_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexEdgeIter>)
.def("vertex_outgoing_halfedge_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexOHalfedgeIter>)
.def("voh_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexOHalfedgeIter>)
.def("vertex_incoming_halfedge_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexIHalfedgeIter>)
.def("vih_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexIHalfedgeIter>)
.def("face_face_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceFaceIter>)
.def("ff_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceFaceIter>)
.def("face_edge_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceEdgeIter>)
.def("fe_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceEdgeIter>)
.def("face_halfedge_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceHalfedgeIter>)
.def("fh_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceHalfedgeIter>)
.def("edge_vertex_indices", &edge_other_indices<Mesh, FuncEdgeVertex>)
.def("ev_indices", &edge_other_indices<Mesh, FuncEdgeVertex>)
.def("edge_face_indices", &edge_other_indices<Mesh, FuncEdgeFace>)
.def("ef_indices", &edge_other_indices<Mesh, FuncEdgeFace>)
.def("edge_halfedge_indices", &edge_other_indices<Mesh, FuncEdgeHalfedge>)
.def("eh_indices", &edge_other_indices<Mesh, FuncEdgeHalfedge>)
.def("halfedge_vertex_indices", &halfedge_other_indices<Mesh, FuncHalfedgeVertex>)
.def("hv_indices", &halfedge_other_indices<Mesh, FuncHalfedgeVertex>)
.def("halfedge_to_vertex_indices", &halfedge_other_indices<Mesh, FuncHalfedgeToVertex>)
.def("htv_indices", &halfedge_other_indices<Mesh, FuncHalfedgeToVertex>)
.def("halfedge_from_vertex_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFromVertex>)
.def("hfv_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFromVertex>)
.def("halfedge_face_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFace>)
.def("hf_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFace>)
.def("halfedge_edge_indices", &halfedge_other_indices<Mesh, FuncHalfedgeEdge>)
.def("he_indices", &halfedge_other_indices<Mesh, FuncHalfedgeEdge>)
//======================================================================
// new property interface: single item
//======================================================================
.def("vertex_property", &Mesh::template py_property<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("halfedge_property", &Mesh::template py_property<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("edge_property", &Mesh::template py_property<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("face_property", &Mesh::template py_property<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("set_vertex_property", &Mesh::template py_set_property<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("set_halfedge_property", &Mesh::template py_set_property<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("set_edge_property", &Mesh::template py_set_property<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("set_face_property", &Mesh::template py_set_property<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("has_vertex_property", &Mesh::template py_has_property<OM::VertexHandle>)
.def("has_halfedge_property", &Mesh::template py_has_property<OM::HalfedgeHandle>)
.def("has_edge_property", &Mesh::template py_has_property<OM::EdgeHandle>)
.def("has_face_property", &Mesh::template py_has_property<OM::FaceHandle>)
.def("remove_vertex_property", &Mesh::template py_remove_property<OM::VertexHandle>)
.def("remove_halfedge_property", &Mesh::template py_remove_property<OM::HalfedgeHandle>)
.def("remove_edge_property", &Mesh::template py_remove_property<OM::EdgeHandle>)
.def("remove_face_property", &Mesh::template py_remove_property<OM::FaceHandle>)
//======================================================================
// new property interface: generic
//======================================================================
.def("vertex_property", &Mesh::template py_property_generic<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("halfedge_property", &Mesh::template py_property_generic<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("edge_property", &Mesh::template py_property_generic<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("face_property", &Mesh::template py_property_generic<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("set_vertex_property", &Mesh::template py_set_property_generic<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("set_halfedge_property", &Mesh::template py_set_property_generic<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("set_edge_property", &Mesh::template py_set_property_generic<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("set_face_property", &Mesh::template py_set_property_generic<OM::FaceHandle, typename Mesh::FPropHandle>)
//======================================================================
// new property interface: array
//======================================================================
.def("vertex_property_array", &Mesh::template py_property_array<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("halfedge_property_array", &Mesh::template py_property_array<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("edge_property_array", &Mesh::template py_property_array<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("face_property_array", &Mesh::template py_property_array<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("set_vertex_property_array", &Mesh::template py_set_property_array<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("set_halfedge_property_array", &Mesh::template py_set_property_array<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("set_edge_property_array", &Mesh::template py_set_property_array<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("set_face_property_array", &Mesh::template py_set_property_array<OM::FaceHandle, typename Mesh::FPropHandle>)
//======================================================================
// new property interface: copy
//======================================================================
.def("copy_property", &Mesh::template py_copy_property<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("copy_property", &Mesh::template py_copy_property<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("copy_property", &Mesh::template py_copy_property<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("copy_property", &Mesh::template py_copy_property<OM::FaceHandle, typename Mesh::FPropHandle>)
;
expose_type_specific_functions(class_mesh);
}
#endif
| 42.108451 | 161 | 0.674014 | nmaxwell |
bfa1e8340a88e16c329ca86b20a67fd6a41bd1d0 | 845 | hpp | C++ | libs/utils/include/suil/utils/uuid.hpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/include/suil/utils/uuid.hpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/include/suil/utils/uuid.hpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2022 Suilteam, Carter Mbotho
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*
* @author Carter
* @date 2022-03-12
*/
#pragma once
#include <cstdint>
#include <string>
namespace suil {
struct Uuid {
Uuid(unsigned char val[16]);
Uuid(const std::string_view& str = {});
std::string toString(bool lower = true) const;
bool operator==(const Uuid& other) const;
bool operator!=(const Uuid& other) const;
bool empty() const;
const unsigned char* raw() const { return &_bin[0]; }
private:
union {
struct {
uint64_t _hi;
uint64_t _lo;
};
unsigned char _bin[16] = {0};
};
};
} | 23.472222 | 74 | 0.564497 | suilteam |
bfa5cf0febca4df39ca6f4f7a29f86bd440c2c80 | 42,743 | cpp | C++ | utils/license_to_header.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | utils/license_to_header.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | utils/license_to_header.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | #include <QtCore/QFile>
#include <QtCore/QString>
#include <QFileInfo>
#include <QStringList>
#include <QHash>
#include <QCryptographicHash>
#include <QTextStream>
#include <QDebug>
#include <QSet>
#include <QJsonDocument>
#include <QMap>
#include <QDirIterator>
#include <QRegularExpression>
#include <QtCore/QCoreApplication>
#include <QtCore/QJsonArray>
#include <QJsonObject>
#include <cassert>
#ifdef _MSC_VER
#include <iso646.h>
#endif
#include <QDateTime>
#include <cstdio>
struct TpEntry
{
QString comment;
struct Entry {
QString tp_file, tp_copyright, tp_license;
};
QVector<Entry> entries;
};
QString escape_string(const QString &input)
{
QString result;
for(QChar c : input)
if (!c.isPrint() || c == '\\' || c=='"')
result += QString("\\%1").arg(uint8_t(c.toLatin1()),3,8,QChar('0'));
else
result += c;
return result;
}
class LicenseReader
{
public:
QString current;
QFile &_license_file;
int line_num = 0;
LicenseReader(QFile &license_file) : _license_file(license_file)
{
current = next_line();
}
QString next_line()
{
QString line = _license_file.readLine();
line_num += 1;
while(line.startsWith("#"))
{
line = _license_file.readLine();
line_num += 1;
}
current = line;
return line;
}
std::pair<QString,QStringList> next_tag()
{
if (not this->current.contains(':'))
return {"",{}};
QStringList parts = current.split(":");
assert(parts.size()>1);
QString tag = parts.takeFirst();
QStringList lines = { parts.join(':').trimmed() };
while((!next_line().isEmpty()) && current.startsWith(" "))
lines.append(current.trimmed());
return {tag, lines};
}
};
bool make_license_header(const QStringList &source)
{
QString src_copyright = QFileInfo(source[0]).absoluteFilePath();
QString src_license = QFileInfo(source[1]).absoluteFilePath();
QString dst = QFileInfo(source[2]).absoluteFilePath();
QFile license_file(src_license);
QFile copyright_file(src_copyright);
QFile g(dst);
if(!license_file.open(QFile::ReadOnly) || !copyright_file.open(QFile::ReadOnly) || !g.open(QFile::WriteOnly))
return false;
QTextStream out(&g);
out.setGenerateByteOrderMark(true);
out.setCodec("UTF-8");
QMap<QString,QVector<QHash<QString,QStringList>>> projects;
QVector<QStringList> license_list;
LicenseReader reader(copyright_file);
QHash<QString,QStringList> part = {};
QHash<QString,QStringList> *tgt_part = ∂
QStringList file_license_copyright_tags= {"Files", "Copyright", "License"};
while(!reader.current.isEmpty())
{
std::pair<QString,QStringList> tag_content = reader.next_tag();
if(file_license_copyright_tags.contains(tag_content.first))
{
(*tgt_part)[tag_content.first] = tag_content.second;
}
else if (tag_content.first == "Comment")
{
// attach part to named project
projects[tag_content.second[0]].append(part);
tgt_part = &projects[tag_content.second[0]].back();
}
if (tag_content.first.isEmpty() or reader.current.isEmpty())
{
// end of a paragraph start a new part
if (tgt_part->contains("License") and not tgt_part->contains("Files"))
{
// no Files tag in this one, so assume standalone license
license_list.append(part["License"]);
}
tgt_part = ∂
part.clear();
reader.next_line();
}
}
QStringList data_list;
for(auto &project : projects)
{
for(auto &part : project)
{
part["file_index"].append(QString::number(data_list.size()));
data_list.append(part["Files"]);
part["copyright_index"].append(QString::number(data_list.size()));
data_list.append(part["Copyright"]);
}
}
out << "/* THIS FILE IS GENERATED DO NOT EDIT */\n";
out << "#ifndef _EDITOR_LICENSE_H\n";
out << "#define _EDITOR_LICENSE_H\n";
out << "const char *const GODOT_LICENSE_TEXT =";
QString license_line;
QTextStream license_stream(&license_file);
while(license_stream.readLineInto(&license_line))
{
out << "\n\t\t\"" << escape_string(license_line.trimmed()) + "\\n\"";
}
out <<";\n\n";
out << "struct ComponentCopyrightPart {\n"
"\tconst char *license;\n"
"\tconst char *const *files;\n"
"\tconst char *const *copyright_statements;\n"
"\tint file_count;\n"
"\tint copyright_count;\n"
"};\n\n";
out << "struct ComponentCopyright {\n"
"\tconst char *name;\n"
"\tconst ComponentCopyrightPart *parts;\n"
"\tint part_count;\n"
"};\n\n";
out << "const char *const COPYRIGHT_INFO_DATA[] = {\n";
for (auto line : data_list)
out << "\t\"" << escape_string(line) << "\",\n";
out << "};\n\n";
out << "const ComponentCopyrightPart COPYRIGHT_PROJECT_PARTS[] = {\n";
int part_index = 0;
QMap<QString,int> part_indexes = {};
for(auto iter=projects.begin(),fin = projects.end(); iter!=fin; ++iter)
{
QString project_name = iter.key();
auto &project(iter.value());
part_indexes[project_name] = part_index;
for(const auto &part : project)
{
out << "\t{ \"" << escape_string(part["License"].front()) << "\", "
<< "©RIGHT_INFO_DATA[" << part["file_index"].join("") << "], "
<< "©RIGHT_INFO_DATA[" << part["copyright_index"].join("") << "], "
<< part["Files"].size() << ", "
<< part["Copyright"].size()<< " },\n";
part_index++;
}
}
out << "};\n\n";
out << "const int COPYRIGHT_INFO_COUNT = " << projects.size() << ";\n";
out << "const ComponentCopyright COPYRIGHT_INFO[] = {\n";
for(auto iter=projects.begin(),fin = projects.end(); iter!=fin; ++iter)
{
QString project_name = iter.key();
auto &project(iter.value());
out << "\t{ \"" << escape_string(project_name) << "\", "
<< "©RIGHT_PROJECT_PARTS[" << QString::number(part_indexes[project_name]) << "], "
<< QString::number(project.size()) << " },\n";
}
out << "};\n\n";
out << "const int LICENSE_COUNT = " << license_list.size() << ";\n";
out << "const char *const LICENSE_NAMES[] = {\n";
for (const auto &l : license_list)
out << "\t\"" << escape_string(l[0]) << "\",\n";
out << "};\n\n";
out << "const char *const LICENSE_BODIES[] = {\n\n";
for(auto & l : license_list)
{
for (const auto &line : l.mid(1))
{
if(line == ".")
out << "\t\"\\n\"\n";
else
out << "\t\"" << escape_string(line) << "\\n\"\n";
}
out << "\t\"\",\n\n";
}
out << "};\n\n";
out << "#endif\n";
return true;
}
bool make_license_header2(QStringList source)
{
QString src_copyright = QFileInfo(source[0]).absoluteFilePath();
QString src_license = QFileInfo(source[1]).absoluteFilePath();
QString dst = QFileInfo(source[2]).absoluteFilePath();
QFile f(src_license);
QFile fc(src_copyright);
QFile g(dst);
if(!f.open(QFile::ReadOnly) || !fc.open(QFile::ReadOnly) || !g.open(QFile::WriteOnly))
return false;
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#ifndef _EDITOR_LICENSE_H\n");
g.write("#define _EDITOR_LICENSE_H\n");
g.write("static const char *GODOT_LICENSE_TEXT =");
QTextStream lic_stream(&f);
QString line;
while(lic_stream.readLineInto(&line))
{
QString escaped_string = escape_string(line.trimmed());
g.write(qUtf8Printable("\n\t\"" + escaped_string + "\\n\""));
}
g.write(";\n");
int tp_current = 0;
QString tp_file = "";
QString tp_comment = "";
QString tp_copyright = "";
QString tp_license = "";
QString tp_licensename = "";
QString tp_licensebody = "";
QVector<TpEntry> tp;
QVector<QPair<QString,QString>> tp_licensetext;
QTextStream copyright_stream(&fc);
while(copyright_stream.readLineInto(&line))
{
if(line.startsWith("#"))
continue;
if(line.startsWith("Files:"))
{
tp_file = line.mid(6).trimmed();
tp_current = 1;
}
else if (line.startsWith("Comment:"))
{
tp_comment = line.mid(8).trimmed();
tp_current = 2;
}
else if (line.startsWith("Copyright:"))
{
tp_copyright = line.mid(10).trimmed();
tp_current = 3;
}
else if (line.startsWith("License:"))
{
if (tp_current != 0)
{
tp_license = line.mid(8).trimmed();
tp_current = 4;
}
else
{
tp_licensename = line.mid(8).trimmed();
tp_current = 5;
}
}
else if (line.startsWith(" "))
{
if (tp_current == 1)
tp_file += "\n" + line.trimmed();
else if (tp_current == 3)
tp_copyright += "\n" + line.trimmed();
else if (tp_current == 5)
{
if (line.trimmed() == ".")
tp_licensebody += "\n";
else
tp_licensebody += line.midRef(1);
}
}
else
{
if (tp_current != 0)
{
if (tp_current == 5)
{
tp_licensetext.append({tp_licensename, tp_licensebody});
tp_licensename = "";
tp_licensebody = "";
}
else
{
bool added = false;
for(auto &i : tp)
{
if(i.comment == tp_comment)
{
i.entries.append(TpEntry::Entry {tp_file, tp_copyright, tp_license});
added = true;
break;
}
}
if(!added)
tp.append({tp_comment,{{tp_file, tp_copyright, tp_license}}});
tp_file.clear();
tp_comment.clear();
tp_copyright.clear();
tp_license.clear();
}
tp_current = 0;
}
}
}
tp_licensetext.push_back({ tp_licensename, tp_licensebody });
QString about_thirdparty = "";
QString about_tp_copyright_count = "";
QString about_tp_license = "";
QString about_tp_copyright = "";
QString about_tp_file = "";
for(auto i : tp)
{
about_thirdparty += "\t\"" + i.comment + "\",\n";
about_tp_copyright_count += QString::number(i.entries.size()) + ", ";
for(const auto &j : i.entries)
{
QString file_body = "";
QString copyright_body = "";
for(auto k : j.tp_file.split("\n"))
{
if(!file_body.isEmpty())
file_body += "\\n\"\n";
QString escaped_string = escape_string(k.trimmed());
file_body += "\t\"" + escaped_string;
}
for(auto k : j.tp_copyright.split("\n"))
{
if(!copyright_body.isEmpty())
copyright_body += "\\n\"\n";
QString escaped_string = escape_string(k.trimmed());
copyright_body += "\t\"" + escaped_string;
}
about_tp_file += "\t" + file_body + "\",\n";
about_tp_copyright += "\t" + copyright_body + "\",\n";
about_tp_license += "\t\"" + j.tp_license + "\",\n";
}
}
QString about_license_name = "";
QString about_license_body = "";
for(const QPair<QString,QString> &i : tp_licensetext)
{
QString body = "";
for (auto j : i.second.split("\n"))
{
if(!body.isEmpty())
body += "\\n\"\n";
QString escaped_string = escape_string(j.trimmed());
body += "\t\"" + escaped_string;
}
about_license_name += "\t\"" + i.first + "\",\n";
about_license_body += "\t" + body + "\",\n";
}
g.write("static const char *about_thirdparty[] = {\n");
g.write(about_thirdparty.toUtf8());
g.write("\t0\n");
g.write("};\n");
g.write(qPrintable("#define THIRDPARTY_COUNT " + QString::number(tp.size()) + "\n"));
g.write("static const int about_tp_copyright_count[] = {\n\t");
g.write(about_tp_copyright_count.toUtf8());
g.write("0\n};\n");
g.write("static const char *about_tp_file[] = {\n");
g.write(about_tp_file.toUtf8());
g.write("\t0\n");
g.write("};\n");
g.write("static const char *about_tp_copyright[] = {\n");
g.write(about_tp_copyright.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write("static const char *about_tp_license[] = {\n");
g.write(about_tp_license.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write("static const char *LICENSE_NAMES[] = {\n");
g.write(about_license_name.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write(qPrintable("#define LICENSE_COUNT " + QString::number(tp_licensetext.size()) + "\n"));
g.write("static const char *LICENSE_BODIES[] = {\n");
g.write(about_license_body.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write("#endif\n");
g.close();
fc.close();
f.close();
return true;
}
static void close_section(QTextStream &g)
{
g << "\tnullptr\n";
g << "};\n";
}
bool make_authors_header(const QStringList &source)
{
QStringList sections = {"Project Founders", "Lead Developer", "Project Manager", "Developers"};
QStringList sections_id = { "AUTHORS_FOUNDERS", "AUTHORS_LEAD_DEVELOPERS",
"AUTHORS_PROJECT_MANAGERS", "AUTHORS_DEVELOPERS" };
QString src_authors = QFileInfo(source[0]).absoluteFilePath();
QString dst = QFileInfo(source[1]).absoluteFilePath();
QFile f(src_authors);
QFile g(dst);
if(!f.open(QFile::ReadOnly|QFile::Text) || !g.open(QFile::WriteOnly))
return false;
QTextStream out(&g);
out.setGenerateByteOrderMark(true);
out.setCodec("UTF-8");
out << "/* THIS FILE IS GENERATED DO NOT EDIT */\n";
out << "#ifndef _EDITOR_AUTHORS_H\n";
out << "#define _EDITOR_AUTHORS_H\n";
QString current_section = "";
bool reading = false;
QString line;
QTextStream authors_stream(&f);
authors_stream.setCodec("UTF-8");
authors_stream.setGenerateByteOrderMark(true);
while(authors_stream.readLineInto(&line))
{
if (reading)
{
if(line.startsWith(" "))
{
out << "\t\"" << escape_string(line.trimmed()) << "\",\n";
continue;
}
}
if (line.startsWith("## "))
{
if (reading)
{
close_section(out);
reading = false;
}
for(int i=0; i<sections.size(); ++i)
{
QString section = sections[i];
if (line.trimmed().endsWith(section))
{
current_section = escape_string(sections_id[i]);
reading = true;
out<< "static const char *" << current_section << "[] = {\n";
break;
}
}
}
}
if(reading)
close_section(out);
out << "#endif\n";
return true;
}
bool make_donors_header(QStringList source)
{
QStringList sections = { "Platinum sponsors", "Gold sponsors", "Silver sponsors", "Bronze sponsors", "Mini sponsors",
"Gold donors", "Silver donors", "Bronze donors" };
QStringList sections_id = { "DONORS_SPONSOR_PLATINUM", "DONORS_SPONSOR_GOLD", "DONORS_SPONSOR_SILVER",
"DONORS_SPONSOR_BRONZE", "DONORS_SPONSOR_MINI", "DONORS_GOLD", "DONORS_SILVER", "DONORS_BRONZE" };
QString src_donors = QFileInfo(source[0]).absoluteFilePath();
QString dst = QFileInfo(source[1]).absoluteFilePath();
QFile f(src_donors);
QFile g(dst);
if(!f.open(QFile::ReadOnly) || !g.open(QFile::WriteOnly))
return false;
QTextStream out(&g);
out.setGenerateByteOrderMark(true);
out.setCodec("UTF-8");
out << "/* THIS FILE IS GENERATED DO NOT EDIT */\n";
out << "#ifndef _EDITOR_DONORS_H\n";
out << "#define _EDITOR_DONORS_H\n";
QString current_section = "";
bool reading = false;
QString line;
QTextStream donors_stream(&f);
while(donors_stream.readLineInto(&line))
{
if(reading)
{
if (line.startsWith(" "))
{
out << "\t\"" << escape_string(line.trimmed()) << "\",\n";
continue;
}
}
if (line.startsWith("## "))
{
if (reading)
{
close_section(out);
reading = false;
}
for(int i=0; i < sections.size(); ++i)
{
if (line.trimmed().endsWith(sections[i]))
{
current_section = escape_string(sections_id[i]);
reading = true;
out << "static const char *" << current_section << "[] = {\n";
break;
}
}
}
}
if (reading)
close_section(out);
out << "#endif\n";
return true;
}
static bool _make_doc_data_class_path(const QStringList &paths,const QString &to_path)
{
QFile g(to_path+"/doc_data_class_path.gen.h");
if(!g.open(QFile::WriteOnly))
return false;
QStringList sorted;
sorted.reserve(100);
for(const QString &path : paths)
{
if(path.contains("doc/classes")) // skip engine docs
continue;
sorted.push_back(path);
}
std::sort(sorted.begin(),sorted.end());
g.write(qPrintable("static const int _doc_data_class_path_count = " + QString::number(sorted.size()) + ";\n"));
g.write("struct _DocDataClassPath { const char* name; const char* path; };\n");
g.write(qPrintable("static const _DocDataClassPath _doc_data_class_paths[" + QString::number(sorted.size()+1) + "] = {\n"));
for(auto c : sorted)
{
QFileInfo fi(c);
QString module_path = fi.path();
module_path = module_path.mid(module_path.indexOf("modules"));
g.write(qUtf8Printable(QString("\t{\"%1\", \"%2\"},\n").arg(fi.baseName(), module_path)));
}
g.write("\t{nullptr, nullptr}\n");
g.write("};\n");
g.close();
return true;
}
QStringList collect_docs(const QString &src_path,const QString &tgt_doc_path)
{
QFile list_fl(src_path);
if(!list_fl.open(QFile::ReadOnly))
return {};
QStringList all_paths = QString(list_fl.readAll()).split(';');
QStringList docs;
for(const auto &path : all_paths)
{
if(path.isEmpty())
continue;
QDirIterator dir_iter(path.trimmed(),QDir::Files,QDirIterator::Subdirectories);
while(dir_iter.hasNext())
{
docs.push_back(dir_iter.next());
}
}
_make_doc_data_class_path(docs,tgt_doc_path);
// docs = sorted(docs)
return docs;
}
static void byteArrayToHexInFile(const QByteArray &src,QFile &g)
{
int column_count=0;
for(char b : src)
{
if(column_count==0)
g.write("\t");
g.write(qPrintable(QString("0x%1,").arg(uint16_t(uint8_t(b)),2,16,QChar('0'))));
column_count++;
if(column_count==20)
{
g.write("\n");
column_count=0;
}
}
}
bool collect_and_pack_docs(QStringList args)
{
QString doc_paths=args.takeFirst();
QString tgt_path= args.takeFirst();
QString dst = tgt_path+"/doc_data_compressed.gen.h";
QStringList all_doc_paths=collect_docs(doc_paths,tgt_path);
QFile g(dst);
if(!g.open(QFile::WriteOnly))
return false;
QByteArray buf = "";
for (const QString &s : all_doc_paths)
{
if(!s.endsWith(".xml"))
continue;
QString src = QFileInfo(s).absoluteFilePath();
QFile f(src);
QByteArray content;
if(f.open(QFile::ReadOnly))
content = f.readAll();
buf.append(content);
}
int decomp_size = buf.size();
QByteArray compressed = qCompress(buf);
compressed.remove(0,4); // remove the decomp size that is added by qCompress
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#ifndef _DOC_DATA_RAW_H\n");
g.write("#define _DOC_DATA_RAW_H\n");
g.write(qPrintable("static const int _doc_data_compressed_size = " + QString::number(compressed.size()) + ";\n"));
g.write(qPrintable("static const int _doc_data_uncompressed_size = " + QString::number(decomp_size) + ";\n"));
g.write("static const unsigned char _doc_data_compressed[] = {\n");
byteArrayToHexInFile(compressed,g);
g.write("};\n");
g.write("#endif");
g.close();
return true;
}
bool make_translations_header(QStringList args)
{
QString translations_path=args.takeFirst();
QString tgt_path = args.takeFirst();
QString dst = tgt_path+"/translations.gen.h";
QFile g(dst);
if(!g.open(QFile::WriteOnly))
return false;
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#ifndef _EDITOR_TRANSLATIONS_H\n");
g.write("#define _EDITOR_TRANSLATIONS_H\n");
QDirIterator translation_files_iter(translations_path,{"*.po"},QDir::Files);
QStringList all_translation_paths;
while(translation_files_iter.hasNext())
{
all_translation_paths.push_back(translation_files_iter.next());
}
std::sort(all_translation_paths.begin(),all_translation_paths.end());
// paths = [node.srcnode().abspath for node in source]
// sorted_paths = sorted(paths, key=lambda path: os.path.splitext(os.path.basename(path))[0])
struct TranslationEntry {
QString name;
int comp_len;
int decomp_len;
};
QVector<TranslationEntry> xl_names;
for(auto path : all_translation_paths)
{
QFile fl(path);
fl.open(QFile::ReadOnly);
QByteArray buf = fl.readAll();
auto decomp_size = buf.size();
buf = qCompress(buf);
buf.remove(0,4); // remove the decomp size that is added by qCompress
QString name = QFileInfo(path).baseName();
g.write(qUtf8Printable("static const unsigned char _translation_" + name + "_compressed[] = {\n"));
byteArrayToHexInFile(buf,g);
g.write("};\n");
xl_names.append({name, buf.size(), decomp_size});
}
g.write("struct EditorTranslationList {\n");
g.write("\tconst char* lang;\n");
g.write("\tint comp_size;\n");
g.write("\tint uncomp_size;\n");
g.write("\tconst unsigned char* data;\n");
g.write("};\n\n");
g.write("static EditorTranslationList _editor_translations[] = {\n");
for (TranslationEntry &x : xl_names)
{
g.write(qUtf8Printable(QString("\t{ \"%1\", %2, %3, _translation_%1_compressed},\n")
.arg(x.name).arg(x.comp_len).arg(x.decomp_len)));
}
g.write("\t{nullptr, 0, 0, nullptr}\n");
g.write("};\n");
g.write("#endif");
g.close();
return true;
}
bool make_default_controller_mappings(QStringList args)
{
QString dst = args.takeFirst();
QFile g(dst);
QDir d;
d.mkpath(QFileInfo(dst).path());
if(!g.open(QFile::WriteOnly))
return false;
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#include \"core/input/default_controller_mappings.h\"\n");
// ensure mappings have a consistent order
QMap<QString,QMap<QString,QString>> platform_mappings;
for(const QString &src : args)
{
QString src_path = QFileInfo(src).absoluteFilePath();
QFile f(src_path);
QStringList mapping_file_lines;
if(f.open(QFile::ReadOnly))
{
QTextStream inp_text_stream(&f);
//# read mapping file and skip header
QString z;
while(inp_text_stream.readLineInto(&z))
mapping_file_lines.push_back(z);
mapping_file_lines = mapping_file_lines.mid(2);
}
QString current_platform;
for(QString line : mapping_file_lines)
{
if(line.isEmpty())
continue;
line = line.trimmed();
if(line.isEmpty())
continue;
if (line[0] == "#")
{
current_platform = line.mid(1).trimmed();
}
else if (!current_platform.isEmpty())
{
QStringList line_parts = line.split(',');
QString guid = line_parts[0];
if(platform_mappings[current_platform].contains(guid))
g.write(qPrintable(
QString("// WARNING - DATABASE %1 OVERWROTE PRIOR MAPPING: %2 %3\n").arg(src_path, current_platform, platform_mappings[current_platform][guid])));
bool valid_mapping = true;
for(const auto &input_map : line_parts.mid(2))
{
if(input_map.contains("+") or input_map.contains("-") or input_map.contains("~") )
{
g.write(qPrintable(
QString("// WARNING - DISCARDED UNSUPPORTED MAPPING TYPE FROM DATABASE %1: %2 %3\n").arg(src_path, current_platform, line)));
valid_mapping = false;
break;
}
}
if (valid_mapping)
platform_mappings[current_platform][guid] = line;
}
}
}
QMap<QString,QString> platform_variables = {
{"Linux", "#if X11_ENABLED"},
{"Windows", "#ifdef WINDOWS_ENABLED"},
{"Mac OS X", "#ifdef OSX_ENABLED"},
{"Android", "#if defined(__ANDROID__)"},
{"iOS", "#ifdef IPHONE_ENABLED"},
{"Javascript", "#ifdef JAVASCRIPT_ENABLED"},
{"UWP", "#ifdef UWP_ENABLED"},
};
g.write("const char* DefaultControllerMappings::mappings[] = {\n");
for(auto iter=platform_mappings.begin(),fin=platform_mappings.end(); iter!=fin; ++iter)
{
QString variable = platform_variables[iter.key()];
g.write(qPrintable(variable+"\n"));
for(auto plat_iter=iter.value().constKeyValueBegin(),plat_fin=iter.value().constKeyValueEnd(); plat_iter!=plat_fin; ++plat_iter)
{
g.write(qPrintable(QString("\t\"%1\",\n").arg((*plat_iter).second)));
}
g.write("#endif\n");
}
g.write("\tnullptr\n};\n");
g.close();
return true;
}
bool gen_script_encryption(QStringList args)
{
QString txt = "0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0";
QString e = qgetenv("SCRIPT_AES256_ENCRYPTION_KEY");
if (!e.isEmpty())
{
txt = "";
bool ec_valid = true;
if (e.size() != 64)
ec_valid = false;
else
{
for(int i=0; i<e.size()/2; ++i)
{
if (i > 0)
txt += ",";
bool parse_ok;
e.midRef(i*2,2).toInt(&parse_ok,16);
ec_valid &= parse_ok;
txt += QString("0x%1").arg(e.midRef(i*2,2));
}
}
if (not ec_valid)
{
txt = "0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0";
qCritical()<<"Invalid AES256 encryption key, not 64 bits hex:" << e;
return false;
}
}
QString target_path = args.takeFirst() + "/script_encryption_key.gen.cpp";
QFile fl(target_path);
if(fl.open(QFile::WriteOnly))
{
fl.write(qPrintable("#include \"core/project_settings.h\"\nuint8_t script_encryption_key[32]={" + txt + "};\n"));
return true;
}
return false;
}
QString _spaced(QString e)
{
if(e.endsWith('*'))
return e;
return e + " ";
}
QStringList generate_extension_struct(QString name,const QJsonObject &ext,bool include_version=true)
{
QStringList ret_val;
if(ext.contains("next") && ext["next"].isObject())
{
ret_val.append(generate_extension_struct(name, ext["next"].toObject()));
}
ret_val.append({
QString("typedef struct godot_gdnative_ext_") + name + (
(not include_version) ? "" :
QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(
ext["version"]["minor"].toInt())) + "_api_struct {",
"\tunsigned int type;",
"\tgodot_gdnative_api_version version;",
"\tconst godot_gdnative_api_struct *next;"
});
for(const QJsonValue &funcdef : ext["api"].toArray())
{
QStringList args;
for(const QJsonValue &arg_elem : funcdef["arguments"].toArray())
{
QJsonArray arg_elems = arg_elem.toArray();
args.append(QString("%1%2").arg(_spaced(arg_elems.at(0).toString()),arg_elems.at(1).toString()));
}
ret_val.append(QString("\t%1(*%2)(%3);").arg(_spaced(funcdef["return_type"].toString()),
funcdef["name"].toString(), args.join(",")));
}
ret_val += {
"} godot_gdnative_ext_" + name + ((not include_version) ? QString("") : QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt())) + "_api_struct;",
""
};
return ret_val;
}
QString _build_gdnative_api_struct_header(QJsonDocument &api)
{
QStringList gdnative_api_init_macro = {
"\textern const godot_gdnative_core_api_struct *_gdnative_wrapper_api_struct;"
};
QJsonValue extensions = api["extensions"];
assert(extensions.isArray());
if(extensions.isArray())
{
for(QJsonValue ext : extensions.toArray())
{
QString name = ext["name"].toString();
gdnative_api_init_macro.append(
QString("\textern const godot_gdnative_ext_%1_api_struct *_gdnative_wrapper_%1_api_struct;").arg(name));
}
}
gdnative_api_init_macro.append("\t_gdnative_wrapper_api_struct = options->api_struct;");
gdnative_api_init_macro.append("\tfor (unsigned int i = 0; i < _gdnative_wrapper_api_struct->num_extensions; i++) { ");
gdnative_api_init_macro.append("\t\tswitch (_gdnative_wrapper_api_struct->extensions[i]->type) {");
for(QJsonValue ext : extensions.toArray())
{
QString name = ext["name"].toString();
QString type = ext["type"].toString();
gdnative_api_init_macro.append(
QString("\t\t\tcase GDNATIVE_EXT_%1:").arg(type));
gdnative_api_init_macro.append(
QString("\t\t\t\t_gdnative_wrapper_%1_api_struct = (godot_gdnative_ext_%1_api_struct *)"
" _gdnative_wrapper_api_struct->extensions[i];").arg(name));
gdnative_api_init_macro.append("\t\t\t\tbreak;");
}
gdnative_api_init_macro.append("\t\t}");
gdnative_api_init_macro.append("\t}");
QStringList out = {
"/* THIS FILE IS GENERATED DO NOT EDIT */",
"#ifndef GODOT_GDNATIVE_API_STRUCT_H",
"#define GODOT_GDNATIVE_API_STRUCT_H",
"",
"#include <gdnative/gdnative.h>",
"#include <android/godot_android.h>",
"#include <arvr/godot_arvr.h>",
"#include <nativescript/godot_nativescript.h>",
"#include <net/godot_net.h>",
"#include <pluginscript/godot_pluginscript.h>",
"#include <videodecoder/godot_videodecoder.h>",
"",
"#define GDNATIVE_API_INIT(options) do { \\\n" + gdnative_api_init_macro.join(" \\\n") + " \\\n } while (0)",
"",
"#ifdef __cplusplus",
"extern \"C\" {",
"#endif",
"",
"enum GDNATIVE_API_TYPES {",
"\tGDNATIVE_" + api["core"]["type"].toString() + ','
};
for(QJsonValue ext : extensions.toArray())
out.push_back(QString("\tGDNATIVE_EXT_") + ext["type"].toString() + ',');
out.push_back("};");
out.push_back("");
for(QJsonValue ext : extensions.toArray())
{
QString name = ext["name"].toString();
out.append(generate_extension_struct(name, ext.toObject(), false));
}
out.append({
"typedef struct godot_gdnative_core_api_struct {",
"\tunsigned int type;",
"\tgodot_gdnative_api_version version;",
"\tconst godot_gdnative_api_struct *next;",
"\tunsigned int num_extensions;",
"\tconst godot_gdnative_api_struct **extensions;",
});
assert(api["core"]["api"].isArray());
for(const QJsonValue &funcdef : api["core"]["api"].toArray())
{
QStringList args;
for(const QJsonValue &arg_elem : funcdef["arguments"].toArray())
{
QJsonArray arg_elems = arg_elem.toArray();
args.append(QString("%1%2").arg(_spaced(arg_elems.at(0).toString()),arg_elems.at(1).toString()));
}
out.append(QString("\t%1(*%2)(%3);").arg(_spaced(funcdef["return_type"].toString()), funcdef["name"].toString(), args.join(',')));
}
out.append({
"} godot_gdnative_core_api_struct;",
"",
"#ifdef __cplusplus",
"}",
"#endif",
"",
"#endif // GODOT_GDNATIVE_API_STRUCT_H",
""
});
return out.join('\n');
}
static QString get_extension_struct_name(QString name,const QJsonObject &ext, bool include_version=true)
{
return "godot_gdnative_ext_" + name + ((not include_version)? QString("") :QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt())) + "_api_struct";
};
static QString get_extension_struct_instance_name(QString name,const QJsonObject &ext, bool include_version=true)
{
return "api_extension_" + name + ((not include_version)? QString("") :QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt())) + "_struct";
}
static QStringList get_extension_struct_definition(QString name,const QJsonObject &ext, bool include_version=true)
{
QStringList ret_val;
if(ext.contains("next") && ext["next"].isObject())
{
ret_val += get_extension_struct_definition(name, ext["next"].toObject());
}
ret_val.append({
QString("extern const ") + get_extension_struct_name(name, ext, include_version) + ' ' + get_extension_struct_instance_name(name, ext, include_version) + " = {",
QString("\tGDNATIVE_EXT_") + ext["type"].toString() + ',',
QString("\t{%1, %2},").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt()),
QString("\t") + (not ext["next"].isObject() ? "nullptr" :("(const godot_gdnative_api_struct *)&" + get_extension_struct_instance_name(name, ext["next"].toObject()))) + ','
});
for(const QJsonValue &funcdef : ext["api"].toArray())
ret_val.append(QString("\t%1,").arg(funcdef["name"].toString()));
ret_val.append("};\n");
return ret_val;
}
QString _build_gdnative_api_struct_source(QJsonDocument &api)
{
QStringList out = {
"/* THIS FILE IS GENERATED DO NOT EDIT */",
"",
"#include <gdnative_api_struct.gen.h>",
""
};
for(QJsonValue ext : api["extensions"].toArray())
{
QString name = ext["name"].toString();
out.append(get_extension_struct_definition(name, ext.toObject(), false));
}
out.append({"", "const godot_gdnative_api_struct *gdnative_extensions_pointers[] = {"});
for(QJsonValue ext : api["extensions"].toArray())
{
QString name = ext["name"].toString();
out.append({QString("\t(godot_gdnative_api_struct *)&api_extension_") + name + "_struct,"});
}
out.append("};\n");
out.append({
QStringLiteral("extern const godot_gdnative_core_api_struct api_struct = {"),
QString("\tGDNATIVE_") + api["core"]["type"].toString() + ',',
QString("\t{%1, %2},").arg(api["core"]["version"]["major"].toInt()).arg(api["core"]["version"]["minor"].toInt()),
QStringLiteral("\tnullptr,"),
QString("\t%1,").arg(api["extensions"].toArray().size()),
"\tgdnative_extensions_pointers,",
});
for(const QJsonValue &funcdef : api["core"]["api"].toArray())
out.append(QString("\t%1,").arg(funcdef["name"].toString()));
out.append("};\n");
return out.join("\n");
}
bool build_gdnative_api_struct(QStringList args)
{
// gensource = gdn_env.Command(['include/gdnative_api_struct.gen.h', 'gdnative_api_struct.gen.cpp'],
// 'gdnative_api.json', build_gdnative_api_struct)
QString src_json = args.takeFirst();
QFile json_doc(src_json);
if(!json_doc.open(QFile::ReadOnly))
return false;
QJsonDocument api = QJsonDocument::fromJson(json_doc.readAll());
QString tgt_dir = args.takeFirst();
QString header = tgt_dir+"/gdnative_api_struct.gen.h";
QString source = tgt_dir+"/gdnative_api_struct.gen.cpp";
QFile header_file(header);
if(!header_file.open(QFile::WriteOnly))
return false;
header_file.write(_build_gdnative_api_struct_header(api).toUtf8());
QFile src_file(source);
if(!src_file.open(QFile::WriteOnly))
return false;
src_file.write(_build_gdnative_api_struct_source(api).toUtf8());
return true;
}
bool generate_mono_glue(QStringList args) {
QString src = args.takeFirst();
QString dst = args.takeFirst();
QString version_dst = args.takeFirst();
QFile header(dst);
QDir d(".");
qDebug()<<QFileInfo(dst).path();
d.mkpath(QFileInfo(dst).path());
if(!header.open(QFile::WriteOnly)) {
qCritical("Failed to open destination file");
return false;
}
QStringList lines = {
"/* THIS FILE IS GENERATED DO NOT EDIT */",
"#ifndef CS_COMPRESSED_H",
"#define CS_COMPRESSED_H\n",
"#ifdef TOOLS_ENABLED\n",
"#include \"core/map.h\"",
"#include \"core/string.h\"",
};
QStringList inserted_files;
int cs_file_count = 0;
QDirIterator visitor(src,QDirIterator::Subdirectories);
QCryptographicHash hash(QCryptographicHash::Sha256);
QStringList files;
while(visitor.hasNext()) {
QString fname = visitor.next();
if(fname.contains("Generated") || fname.contains("obj/"))
continue;
if(!fname.endsWith(".cs"))
continue;
files.push_back(fname);
}
files.sort();
for(const QString & fname : files) {
QFileInfo fi(fname);
QFile file(fname);
file.open(QFile::ReadOnly);
QCryptographicHash hash2(QCryptographicHash::Sha256);
QByteArray contents = file.readAll();
// remove end of line chars to normalize hash between windows/linux files.
contents.replace('\n',"");
contents.replace('\r',"");
hash.addData(contents);
hash2.addData(contents);
qDebug() << "Hashing"<<fname<<QString::number(qHash(hash.result()),16);
cs_file_count += 1;
}
auto hashed = hash.result();
auto glue_version = qHash(hashed); // simply hash the array containing sha256
d.mkpath(QFileInfo(version_dst).path());
QFile version_header(version_dst);
if(!version_header.open(QFile::WriteOnly)) {
qCritical("Failed to open destination file");
return false;
}
version_header.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
version_header.write("#pragma once\n");
version_header.write(("#define CS_GLUE_VERSION UINT32_C(" + QString::number(glue_version) + ")\n").toLatin1());
return true;
}
void report_arg_error(const char *mode,int required_args)
{
qWarning("Not enough arguments for editor_to_header %s mode",mode);
}
int main(int argc, char **argv)
{
QCoreApplication app(argc,argv);
if(argc<3)
{
qWarning("Not enough arguments for editor_to_header");
return -1;
}
QString mode = app.arguments()[1];
if(mode=="license")
{
if(argc<5)
{
report_arg_error("license",argc);
return -1;
}
return make_license_header(app.arguments().mid(2)) ? 0 : -1;
}
if(mode=="authors")
{
if(argc<4)
{
report_arg_error("authors",argc);
return -1;
}
return make_authors_header(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="donors")
{
if(argc<4)
{
report_arg_error("donors",argc);
return -1;
}
return make_donors_header(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="docs")
{
if(argc!=4)
{
report_arg_error("docs",argc);
return -1;
}
return collect_and_pack_docs(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="translations")
{
if(argc!=4)
{
report_arg_error("translations",argc);
return -1;
}
return make_translations_header(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="controllers")
{
if(argc<4)
{
report_arg_error("controllers",argc);
return -1;
}
return make_default_controller_mappings(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="encryption")
{
if(argc<3)
{
report_arg_error("encryption",argc);
return -1;
}
return gen_script_encryption(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="gdnative") // exe gdnative json_file target_path
{
if(argc!=4)
{
report_arg_error("gdnative",argc);
return -1;
}
return build_gdnative_api_struct(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="mono") {
if(argc!=5)
{
report_arg_error("mono",argc);
return -1;
}
return generate_mono_glue(app.arguments().mid(2)) ? 0 : -1;
}
}
| 33.735596 | 194 | 0.564092 | ZopharShinta |
bfa6e8d9093c3196f4da3168a70e6307077600ba | 7,226 | cpp | C++ | smart-ptrs/unique_advanced/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | smart-ptrs/unique_advanced/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | smart-ptrs/unique_advanced/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | #include "../unique.h"
#include "deleters.h"
#include "../my_int.h"
#include <catch.hpp>
#include <tuple>
TEST_CASE("Construction with deleters") {
SECTION("From copyable deleter") {
const CopyableDeleter<MyInt> cd;
UniquePtr<MyInt, CopyableDeleter<MyInt>> s(new MyInt, cd);
}
SECTION("From move-only deleter") {
Deleter<MyInt> d;
UniquePtr<MyInt, Deleter<MyInt>> s(new MyInt, std::move(d));
}
SECTION("From temporary") {
UniquePtr<MyInt, Deleter<MyInt>> s(new MyInt, Deleter<MyInt>{});
}
SECTION("Deleter type is non-const reference") {
Deleter<MyInt> d;
UniquePtr<MyInt, Deleter<MyInt>&> s(new MyInt, d);
}
SECTION("Deleter type is const reference") {
Deleter<MyInt> d;
UniquePtr<MyInt, const Deleter<MyInt>&> s1(new MyInt, d);
const Deleter<MyInt>& cr = d;
UniquePtr<MyInt, const Deleter<MyInt>&> s2(new MyInt, cr);
}
}
TEST_CASE("Swap with deleters") {
SECTION("If storing deleter by value") {
MyInt* p1 = new MyInt(1);
UniquePtr<MyInt, Deleter<MyInt>> s1(p1, Deleter<MyInt>(1));
MyInt* p2 = new MyInt(2);
UniquePtr<MyInt, Deleter<MyInt>> s2(p2, Deleter<MyInt>(2));
s1.Swap(s2);
REQUIRE(s1.Get() == p2);
REQUIRE(*s1 == 2);
REQUIRE(s2.Get() == p1);
REQUIRE(*s2 == 1);
REQUIRE(s1.GetDeleter().GetTag() == 2);
REQUIRE(s2.GetDeleter().GetTag() == 1);
REQUIRE(MyInt::AliveCount() == 2);
std::swap(s1, s2);
REQUIRE(s1.Get() == p1);
REQUIRE(*s1 == 1);
REQUIRE(s2.Get() == p2);
REQUIRE(*s2 == 2);
REQUIRE(s1.GetDeleter().GetTag() == 1);
REQUIRE(s2.GetDeleter().GetTag() == 2);
}
/*
* SECTION("If storing reference to deleter") {
*
* }
*
* well, me think it's enough for you this time...
*/
}
TEST_CASE("Moving deleters") {
SECTION("Move with custom deleter") {
UniquePtr<MyInt, Deleter<MyInt>> s1(new MyInt, Deleter<MyInt>(5));
MyInt* p = s1.Get();
UniquePtr<MyInt, Deleter<MyInt>> s2(new MyInt);
REQUIRE(MyInt::AliveCount() == 2);
REQUIRE(s1.GetDeleter().GetTag() == 5);
REQUIRE(s2.GetDeleter().GetTag() == 0);
s2 = std::move(s1);
REQUIRE(s2.Get() == p);
REQUIRE(s1.Get() == nullptr);
REQUIRE(MyInt::AliveCount() == 1);
REQUIRE(s2.GetDeleter().GetTag() == 5);
REQUIRE(s1.GetDeleter().GetTag() == 0);
}
SECTION("Move with reference deleter type") {
CopyableDeleter<MyInt> d1(5);
UniquePtr<MyInt, CopyableDeleter<MyInt>&> s1(new MyInt, d1);
MyInt* p1 = s1.Get();
CopyableDeleter<MyInt> d2(6);
UniquePtr<MyInt, CopyableDeleter<MyInt>&> s2(new MyInt, d2);
REQUIRE(MyInt::AliveCount() == 2);
s2 = std::move(s1);
REQUIRE(s2.Get() == p1);
REQUIRE(s1.Get() == nullptr);
REQUIRE(MyInt::AliveCount() == 1);
REQUIRE(d1.GetTag() == 5);
REQUIRE(d2.GetTag() == 5);
}
}
TEST_CASE("GetDeleter") {
SECTION("Get deleter") {
UniquePtr<MyInt, Deleter<MyInt>> p;
REQUIRE(!p.GetDeleter().IsConst());
}
SECTION("Get deleter const") {
const UniquePtr<MyInt, Deleter<MyInt>> p;
REQUIRE(p.GetDeleter().IsConst());
}
SECTION("Get deleter reference") {
using UDRef = UniquePtr<MyInt, Deleter<MyInt>&>;
Deleter<MyInt> d;
UDRef p(nullptr, d);
const UDRef& cp = p;
REQUIRE(!p.GetDeleter().IsConst());
REQUIRE(!cp.GetDeleter().IsConst());
}
SECTION("Get deleter const reference") {
using UDConstRef = UniquePtr<MyInt, const Deleter<MyInt>&>;
const Deleter<MyInt> d;
UDConstRef p(nullptr, d);
const UDConstRef& cp = p;
REQUIRE(p.GetDeleter().IsConst());
REQUIRE(cp.GetDeleter().IsConst());
}
}
struct VoidPtrDeleter {
void operator()(void* ptr) {
free(ptr);
}
};
TEST_CASE("UniquePtr<void, VoidPtrDeleter>") {
SECTION("It compiles!") {
UniquePtr<void, VoidPtrDeleter> p(malloc(100));
}
}
TEST_CASE("Array specialization") {
SECTION("delete[] is called") {
UniquePtr<MyInt[]> u(new MyInt[100]);
REQUIRE(MyInt::AliveCount() == 100);
u.Reset();
REQUIRE(MyInt::AliveCount() == 0);
}
SECTION("Able to use custom deleters") {
UniquePtr<MyInt[], Deleter<MyInt[]>> u(new MyInt[100]);
REQUIRE(MyInt::AliveCount() == 100);
u.Reset();
REQUIRE(MyInt::AliveCount() == 0);
}
SECTION("Operator []") {
int* arr = new int[5];
for (size_t i = 0; i < 5; ++i) {
arr[i] = i;
}
UniquePtr<int[]> u(arr);
for (int i = 0; i < 5; ++i) {
REQUIRE(u[i] == i);
u[i] = -i;
REQUIRE(u[i] == -i);
}
}
}
template <typename T>
void DeleteFunction(T* ptr) {
delete ptr;
}
template <typename T>
struct StatefulDeleter {
int some_useless_field = 0;
void operator()(T* ptr) {
delete ptr;
++some_useless_field;
}
};
TEST_CASE("Compressed pair usage") {
SECTION("Stateless struct deleter") {
static_assert(sizeof(UniquePtr<int>) == sizeof(void*));
static_assert(sizeof(UniquePtr<int, std::default_delete<int>>) == sizeof(int*));
}
SECTION("Stateful struct deleter") {
static_assert(sizeof(UniquePtr<int, StatefulDeleter<int>>) ==
sizeof(std::pair<int*, StatefulDeleter<int>>));
}
SECTION("Stateless lambda deleter") {
auto lambda_deleter = [](int* ptr) { delete ptr; };
static_assert(sizeof(UniquePtr<int, decltype(lambda_deleter)>) == sizeof(int*));
}
SECTION("Stateful lambda deleter") {
int some_useless_counter = 0;
auto lambda_deleter = [&some_useless_counter](int* ptr) {
delete ptr;
++some_useless_counter;
};
static_assert(sizeof(UniquePtr<int, decltype(lambda_deleter)>) ==
sizeof(std::pair<int*, decltype(lambda_deleter)>));
}
SECTION("Function pointer deleter") {
static_assert(sizeof(UniquePtr<int, decltype(&DeleteFunction<int>)>) ==
sizeof(std::pair<int*, decltype(&DeleteFunction<int>)>));
}
}
template <typename T>
class DerivedDeleter : public Deleter<T> {};
TEST_CASE("Upcasts") {
SECTION("Upcast in move constructor") {
UniquePtr<MyInt, DerivedDeleter<MyInt>> s(new MyInt);
UniquePtr<MyInt, Deleter<MyInt>> s2(std::move(s));
}
SECTION("Upcast in move assignment") {
UniquePtr<MyInt, DerivedDeleter<MyInt>> s(new MyInt);
UniquePtr<MyInt, Deleter<MyInt>> s2(new MyInt);
s2 = std::move(s);
}
}
TEST_CASE("Deleter call check") {
SECTION("Was called") {
Deleter<int> d;
{ UniquePtr<int, Deleter<int>&> up(new int, d); }
REQUIRE(d.WasCalled());
}
SECTION("Was not called") {
Deleter<int> d;
{ UniquePtr<int, Deleter<int>&> up(nullptr, d); }
REQUIRE(!d.WasCalled());
}
}
| 26.962687 | 88 | 0.562137 | DenisOstashov |
bfa92077cc14ec83225cb95b353196d81c49d6ad | 20,655 | cpp | C++ | source/GTest/FX/Fx.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 3 | 2020-04-29T03:17:50.000Z | 2021-05-26T19:53:46.000Z | source/GTest/FX/Fx.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 1 | 2020-04-29T03:12:47.000Z | 2020-04-29T03:12:47.000Z | source/GTest/FX/Fx.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | null | null | null | /****************************************************************************************/
/* Fx.c */
/* */
/* Author: John Pollard */
/* Description: */
/* */
/* Copyright (c) 1999 WildTangent, Inc.; All rights reserved. */
/* */
/* See the accompanying file LICENSE.TXT for terms on the use of this library. */
/* This library is distributed in the hope that it will be useful but WITHOUT */
/* ANY WARRANTY OF ANY KIND and without any implied warranty of MERCHANTABILITY */
/* or FITNESS FOR ANY PURPOSE. Refer to LICENSE.TXT for more details. */
/* */
/****************************************************************************************/
#include <Windows.h>
#include <Assert.h>
#include "Genesis.h"
#include "Errorlog.h"
#include "Ram.h"
#include "Fx.h"
#include "..\\Procedurals\gebmutil.h"
static geBoolean ControlParticleAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time);
#define POLY_FLAGS (GE_RENDER_DEPTH_SORT_BF)
//#define POLY_FLAGS (GE_RENDER_DO_NOT_OCCLUDE_OTHERS)
extern geFloat EffectScale;
static char SmokeBitmapNames[NUM_SMOKE_TEXTURES][32] = {
"Bmp\\Fx\\Smoke_01.Bmp",
"Bmp\\Fx\\Smoke_02.Bmp",
"Bmp\\Fx\\Smoke_03.Bmp",
"Bmp\\Fx\\Smoke_04.Bmp",
"Bmp\\Fx\\Smoke_05.Bmp",
"Bmp\\Fx\\Smoke_06.Bmp",
"Bmp\\Fx\\Smoke_07.Bmp",
"Bmp\\Fx\\Smoke_08.Bmp",
"Bmp\\Fx\\Smoke_09.Bmp",
"Bmp\\Fx\\Smoke_10.Bmp"
};
static char SmokeBitmapANames[NUM_SMOKE_TEXTURES][32] = {
"Bmp\\Fx\\A_Smk01.Bmp",
"Bmp\\Fx\\A_Smk02.Bmp",
"Bmp\\Fx\\A_Smk03.Bmp",
"Bmp\\Fx\\A_Smk04.Bmp",
"Bmp\\Fx\\A_Smk05.Bmp",
"Bmp\\Fx\\A_Smk06.Bmp",
"Bmp\\Fx\\A_Smk07.Bmp",
"Bmp\\Fx\\A_Smk08.Bmp",
"Bmp\\Fx\\A_Smk09.Bmp",
"Bmp\\Fx\\A_Smk10.Bmp",
};
static char ExplodeBitmapNames[NUM_EXPLODE_TEXTURES][32] = {
"Bmp\\Explode\\1EXP01.Bmp",
"Bmp\\Explode\\1EXP02.Bmp",
"Bmp\\Explode\\1EXP03.Bmp",
"Bmp\\Explode\\1EXP04.Bmp",
"Bmp\\Explode\\1EXP05.Bmp",
"Bmp\\Explode\\1EXP06.Bmp"
};
static char ExplodeBitmapANames[NUM_EXPLODE_TEXTURES][32] = {
"Bmp\\Explode\\A_1EXP01.Bmp",
"Bmp\\Explode\\A_1EXP02.Bmp",
"Bmp\\Explode\\A_1EXP03.Bmp",
"Bmp\\Explode\\A_1EXP04.Bmp",
"Bmp\\Explode\\A_1EXP05.Bmp",
"Bmp\\Explode\\A_1EXP06.Bmp"
};
static char ParticleBitmapNames[NUM_PARTICLE_TEXTURES][32] = {
"Bmp\\Fx\\Parti1.Bmp",
"Bmp\\Fx\\Parti2.Bmp",
"Bmp\\Fx\\Parti3.Bmp",
"Bmp\\Fx\\Parti4.Bmp",
"Bmp\\Fx\\Parti5.Bmp",
"Bmp\\Fx\\Parti6.Bmp",
"Bmp\\Fx\\Parti7.Bmp",
"Bmp\\Fx\\Parti8.Bmp",
};
static char ParticleBitmapANames[NUM_PARTICLE_TEXTURES][32] = {
"Bmp\\Fx\\Parti1.Bmp",
"Bmp\\Fx\\Parti2.Bmp",
"Bmp\\Fx\\Parti3.Bmp",
"Bmp\\Fx\\Parti4.Bmp",
"Bmp\\Fx\\Parti5.Bmp",
"Bmp\\Fx\\Parti6.Bmp",
"Bmp\\Fx\\Parti7.Bmp",
"Bmp\\Fx\\Parti8.Bmp",
};
//=====================================================================================
// Private local static functions
//=====================================================================================
static geBoolean StartupSmokeTrail(Fx_System *Fx, Fx_Player *Player);
static geBoolean ShutdownSmokeTrail(Fx_System *Fx, Fx_Player *Player);
static geBoolean LoadFxTextures(Fx_System *Fx);
static geBoolean FreeFxTextures(Fx_System *Fx);
static geBoolean ControlExplode1Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time);
static geBoolean ControlExplode2Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time);
static geBoolean ControlParticleTrail(Fx_System *Fx, Fx_Player *Player, float Time);
static geBoolean ControlSmokeTrail(Fx_System *Fx, Fx_Player *Player, float Time);
static geBoolean ControlShredderFx(Fx_System *Fx, Fx_Player *Player, float Time);
//=====================================================================================
// Fx_SystemCreate
//=====================================================================================
Fx_System *Fx_SystemCreate(geWorld *World, Console_Console *Console)
{
Fx_System *Fx;
assert(World);
//assert(Console);
Fx = GE_RAM_ALLOCATE_STRUCT(Fx_System);
if (!Fx)
return NULL;
memset(Fx, 0, sizeof(Fx_System));
Fx->World = World;
Fx->Console = Console;
if (!LoadFxTextures(Fx))
{
Fx_SystemDestroy(Fx);
return NULL;
}
return Fx;
}
//=====================================================================================
// Fx_SystemDestroy
//=====================================================================================
void Fx_SystemDestroy(Fx_System *Fx)
{
geBoolean Ret;
assert(Fx);
Ret = FreeFxTextures(Fx);
assert(Ret == GE_TRUE);
geRam_Free(Fx);
}
//=====================================================================================
// Fx_SystemFrame
//=====================================================================================
geBoolean Fx_SystemFrame(Fx_System *Fx, float Time)
{
Fx_TempPlayer *Player;
int32 i;
// Control the temp players
Player = Fx->TempPlayers;
for (i=0; i< FX_MAX_TEMP_PLAYERS; i++, Player++)
{
if (!Player->Active)
continue;
if (!Player->Control)
continue;
// Call the players control routine...
if (!Player->Control(Fx, Player, Time))
return GE_FALSE;
}
return GE_TRUE;
}
//=====================================================================================
// Fx_SpawnFx
//=====================================================================================
geBoolean Fx_SpawnFx(Fx_System *Fx, geVec3d *Pos, uint8 Type)
{
Fx_TempPlayer *TempPlayer;
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well, they just won't see any smoke...
TempPlayer->Pos = *Pos;
TempPlayer->Time = 0.0f;
switch(Type)
{
case FX_EXPLODE1:
TempPlayer->Control = ControlExplode1Anim;
break;
case FX_EXPLODE2:
TempPlayer->Control = ControlExplode2Anim;
break;
default:
return GE_FALSE;
}
return GE_TRUE;
}
//=====================================================================================
// Fx_SystemAddTempPlayer
//=====================================================================================
Fx_TempPlayer *Fx_SystemAddTempPlayer(Fx_System *Fx)
{
Fx_TempPlayer *Player, *End;
int32 i;
Player = Fx->CurrentTempPlayer;
if (!Player)
Player = Fx->TempPlayers;
End = &Fx->TempPlayers[FX_MAX_TEMP_PLAYERS-1];
for (i=0; i< FX_MAX_TEMP_PLAYERS; i++)
{
if (!Player->Active) // Look for a non active player
{
Fx->CurrentTempPlayer = Player;
memset(Player, 0, sizeof(Fx_TempPlayer));
Player->Active = GE_TRUE;
return Player;
}
Player++;
if (Player >= End) // Wrap player at end of structure to beginning
Player = Fx->TempPlayers;
}
return NULL;
}
//=====================================================================================
// Fx_SystemRemoveTempPlayer
//=====================================================================================
void Fx_SystemRemoveTempPlayer(Fx_System *Fx, Fx_TempPlayer *Player)
{
Player->Active = GE_FALSE;
Fx->CurrentTempPlayer = Player; // Easy steal for any one who wants to create a temp player
}
//=====================================================================================
// Fx_PlayerSetFxFlags
//=====================================================================================
geBoolean Fx_PlayerSetFxFlags(Fx_System *Fx, Fx_Player *Player, uint16 FxFlags)
{
if (FxFlags == Player->FxFlags)
return GE_TRUE; // Nothing to change...
//Console_Printf(Fx->Console, "Flags changed.\n");
if ((Player->FxFlags & FX_SMOKE_TRAIL) && !(FxFlags & FX_SMOKE_TRAIL))
ShutdownSmokeTrail(Fx, Player);
else if (!(Player->FxFlags & FX_SMOKE_TRAIL) && (FxFlags & FX_SMOKE_TRAIL))
StartupSmokeTrail(Fx, Player);
Player->FxFlags = FxFlags; // The flags are now current
return GE_TRUE;
}
//=====================================================================================
// Fx_PlayerFrame
//=====================================================================================
geBoolean Fx_PlayerFrame(Fx_System *Fx, Fx_Player *Player, const geXForm3d *XForm, float Time)
{
Player->XForm = *XForm;
if (Player->FxFlags & FX_SMOKE_TRAIL)
ControlSmokeTrail(Fx, Player, Time);
if (Player->FxFlags & FX_PARTICLE_TRAIL)
ControlParticleTrail(Fx, Player, Time);
if (Player->FxFlags & FX_SHREDDER)
ControlShredderFx(Fx, Player, Time);
return GE_TRUE;
}
//=====================================================================================
// StartupSmokeTrail
//=====================================================================================
static geBoolean StartupSmokeTrail(Fx_System *Fx, Fx_Player *Player)
{
//Console_Printf(Fx->Console, "Smoke trail started.\n");
return GE_TRUE;
}
//=====================================================================================
// ShutdownSmokeTrail
//=====================================================================================
static geBoolean ShutdownSmokeTrail(Fx_System *Fx, Fx_Player *Player)
{
//Console_Printf(Fx->Console, "Smoke trail stopped.\n");
return GE_TRUE;
}
//=====================================================================================
// ControlExplode1Anim
//=====================================================================================
static geBoolean ControlExplode1Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_EXPLODE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_EXPLODE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ExplodeBitmaps[Frame], GE_TEXTURED_POINT, GE_RENDER_DEPTH_SORT_BF, 10.0f * EffectScale);
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ExplodeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 10.0f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlExplode2Anim
//=====================================================================================
static geBoolean ControlExplode2Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = 255.0f;
Vert.b = 100.0f;
Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_PARTICLE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_PARTICLE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 8.0f * EffectScale);
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 8.0f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// LoadFxTextures
//=====================================================================================
extern geVFile *MainFS;
static geBoolean LoadFxTextures(Fx_System *Fx)
{
int32 i;
assert(Fx);
assert(Fx->World);
for (i=0; i< NUM_SMOKE_TEXTURES; i++)
{
Fx->SmokeBitmaps[i] = geBitmapUtil_CreateFromFileAndAlphaNames(MainFS, SmokeBitmapNames[i], SmokeBitmapANames[i]);
if (!Fx->SmokeBitmaps[i])
{
char Str[1024];
sprintf(Str, "%s, %s", SmokeBitmapNames[i], SmokeBitmapANames[i]);
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geBitmapUtil_CreateFromFileAndAlphaNames failed:", Str);
goto ExitWithError;
}
if (!geWorld_AddBitmap(Fx->World, Fx->SmokeBitmaps[i]))
{
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geWorld_AddBItmap failed.", NULL);
goto ExitWithError;
}
}
for (i=0; i< NUM_PARTICLE_TEXTURES; i++)
{
Fx->ParticleBitmaps[i] = geBitmapUtil_CreateFromFileAndAlphaNames(MainFS, ParticleBitmapNames[i], ParticleBitmapANames[i]);
if (!Fx->ParticleBitmaps[i])
{
char Str[1024];
sprintf(Str, "%s, %s", ParticleBitmapNames[i], ParticleBitmapANames[i]);
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geBitmapUtil_CreateFromFileAndAlphaNames failed:", Str);
goto ExitWithError;
}
if (!geWorld_AddBitmap(Fx->World, Fx->ParticleBitmaps[i]))
{
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geWorld_AddBItmap failed.", NULL);
goto ExitWithError;
}
}
for (i=0; i< NUM_EXPLODE_TEXTURES; i++)
{
Fx->ExplodeBitmaps[i] = geBitmapUtil_CreateFromFileAndAlphaNames(MainFS, ExplodeBitmapNames[i], ExplodeBitmapANames[i]);
if (!Fx->ExplodeBitmaps[i])
{
char Str[1024];
sprintf(Str, "%s, %s", ExplodeBitmapNames[i], ExplodeBitmapANames[i]);
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geBitmapUtil_CreateFromFileAndAlphaNames failed:", Str);
goto ExitWithError;
}
if (!geWorld_AddBitmap(Fx->World, Fx->ExplodeBitmaps[i]))
{
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geWorld_AddBItmap failed.", NULL);
goto ExitWithError;
}
}
return GE_TRUE;
ExitWithError:
{
FreeFxTextures(Fx);
return GE_FALSE;
}
}
//=====================================================================================
// LoadFxTextures
//=====================================================================================
static geBoolean FreeFxTextures(Fx_System *Fx)
{
int32 i;
assert(Fx);
assert(Fx->World);
for (i=0; i< NUM_SMOKE_TEXTURES; i++)
{
if (Fx->SmokeBitmaps[i])
{
geWorld_RemoveBitmap(Fx->World, Fx->SmokeBitmaps[i]);
geBitmap_Destroy(&Fx->SmokeBitmaps[i]);
Fx->SmokeBitmaps[i] = NULL;
}
}
for (i=0; i< NUM_PARTICLE_TEXTURES; i++)
{
if (Fx->ParticleBitmaps[i])
{
geWorld_RemoveBitmap(Fx->World, Fx->ParticleBitmaps[i]);
geBitmap_Destroy(&Fx->ParticleBitmaps[i]);
Fx->ParticleBitmaps[i] = NULL;
}
}
for (i=0; i< NUM_EXPLODE_TEXTURES; i++)
{
if (Fx->ExplodeBitmaps[i])
{
geWorld_RemoveBitmap(Fx->World, Fx->ExplodeBitmaps[i]);
geBitmap_Destroy(&Fx->ExplodeBitmaps[i]);
Fx->ExplodeBitmaps[i] = NULL;
}
}
return GE_TRUE;
}
//=====================================================================================
// FxPlayer controls
//=====================================================================================
//=====================================================================================
// ControlParticleAnim
//=====================================================================================
static geBoolean ControlParticleAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_PARTICLE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_PARTICLE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.3f * EffectScale);
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.3f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlParticleTrail
//=====================================================================================
static geBoolean ControlParticleTrail(Fx_System *Fx, Fx_Player *Player, float Time)
{
Fx_TempPlayer *TempPlayer;
Player->Time += Time;
if (Player->Time >= 0.04f)
{
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well, they just won't see any smoke...
TempPlayer->Control = ControlParticleAnim;
TempPlayer->Pos = Player->XForm.Translation;
TempPlayer->Time = 0.0f;
Player->Time = 0.0f;
}
return GE_TRUE;
}
//=====================================================================================
// ControlSmokeAnim
//=====================================================================================
static geBoolean ControlSmokeAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time + ((float)(rand()%1000) * (1.0f/1000.0f)* 0.1f);
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*15.0f);
if (Frame >= NUM_SMOKE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_SMOKE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.6f * EffectScale); // 2,6
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.6f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlSmokeTrail
//=====================================================================================
static geBoolean ControlSmokeTrail(Fx_System *Fx, Fx_Player *Player, float Time)
{
Fx_TempPlayer *TempPlayer;
Player->Time += Time;
if (Player->Time >= 0.04f)
{
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well, they just won't see any smoke...
TempPlayer->Control = ControlSmokeAnim;
TempPlayer->Pos = Player->XForm.Translation;
TempPlayer->Time = 0.0f;
Player->Time = 0.0f;
}
return GE_TRUE;
}
//=====================================================================================
// ControlSmokeAnim
//=====================================================================================
static geBoolean ControlShredderAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_SMOKE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_SMOKE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 0.6f * EffectScale); // 2,6
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 0.6f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlShredderFx
//=====================================================================================
static geBoolean ControlShredderFx(Fx_System *Fx, Fx_Player *Player, float Time)
{
assert(Fx);
assert(Player);
Player->Time += Time;
if (Player->Time >= 0.03f)
{
Fx_TempPlayer *TempPlayer;
GE_Collision Collision;
geVec3d Front, Back, In;
geVec3d Mins = {-1.0f, -1.0f, -1.0f};
geVec3d Maxs = { 1.0f, 1.0f, 1.0f};
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well...
TempPlayer->Control = ControlShredderAnim;
TempPlayer->Time = 0.0f;
Front = Player->XForm.Translation;
geXForm3d_GetIn(&Player->XForm, &In);
geVec3d_AddScaled(&Front, &In, 10000.0f, &Back);
if (geWorld_Collision(Fx->World, NULL, NULL, &Front, &Back, GE_CONTENTS_CANNOT_OCCUPY, GE_COLLIDE_ACTORS | GE_COLLIDE_MODELS, 0xffffffff, NULL, NULL, &Collision))
{
// Move it back a little from the wall
geVec3d_AddScaled(&Collision.Impact, &In, -50.0f, &Collision.Impact);
// Randomize the impact point
Collision.Impact.X += (float)(rand()%15);
Collision.Impact.Y += (float)(rand()%15);
Collision.Impact.Z += (float)(rand()%15);
TempPlayer->Pos = Collision.Impact;
}
else
TempPlayer->Pos = Player->XForm.Translation;
Player->Time = 0.0f;
}
return GE_TRUE;
}
| 29.173729 | 164 | 0.541515 | paradoxnj |
bfaae1bbde6de98b6131ebed61b9324dc20b3d91 | 52 | cpp | C++ | Graph/Common Graph Templates/cycleDetect.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | 4 | 2020-03-21T04:32:09.000Z | 2021-07-14T13:49:00.000Z | Graph/Common Graph Templates/cycleDetect.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | null | null | null | Graph/Common Graph Templates/cycleDetect.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | 1 | 2020-12-11T06:06:06.000Z | 2020-12-11T06:06:06.000Z | // cycle detection for directed and undirected graph | 52 | 52 | 0.826923 | aminPial |
bfac1857cac402b861fa6a09633de259ddfc12f2 | 13,324 | inl | C++ | Engine/Include/Sapphire/Maths/Space/Quaternion.inl | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | 2 | 2020-03-18T09:06:21.000Z | 2020-04-09T00:07:56.000Z | Engine/Include/Sapphire/Maths/Space/Quaternion.inl | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | Engine/Include/Sapphire/Maths/Space/Quaternion.inl | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | // Copyright 2020 Sapphire development team. All Rights Reserved.
namespace Sa
{
template <typename T>
const Quat<T> Quat<T>::Zero{ T(0), T(0), T(0), T(0) };
template <typename T>
const Quat<T> Quat<T>::Identity{ T(1), T(0), T(0), T(0) };
template <typename T>
constexpr Quat<T>::Quat(T _w, T _x, T _y, T _z) noexcept :
w{ _w },
x{ _x },
y{ _y },
z{ _z }
{
}
template <typename T>
Quat<T>::Quat(Deg<T> _angle, const Vec3<T>& _axis) noexcept
{
const Rad<T> halfAngle = _angle / 2.0f;
w = Maths::Cos(halfAngle);
Vec3<T>& inAxis = reinterpret_cast<Vec3<T>&>(x);
#if SA_DEBUG
if (!_axis.IsNormalized())
{
SA_LOG("Axis should be normalized!", Warning, Maths);
inAxis = _axis.GetNormalized() * Maths::Sin(halfAngle);
return;
}
#endif
inAxis = _axis * Maths::Sin(halfAngle);
}
template <typename T>
template <typename TIn>
constexpr Quat<T>::Quat(const Quat<TIn>& _other) noexcept :
w{ static_cast<T>(_other.w) },
x{ static_cast<T>(_other.x) },
y{ static_cast<T>(_other.y) },
z{ static_cast<T>(_other.z) }
{
}
template <typename T>
constexpr bool Quat<T>::IsZero() const noexcept
{
return Maths::Equals0(w) && Maths::Equals0(x) && Maths::Equals0(y) && Maths::Equals0(z);
}
template <typename T>
constexpr bool Quat<T>::IsIdentity() const noexcept
{
return Maths::Equals1(w) && Maths::Equals0(x) && Maths::Equals0(y) && Maths::Equals0(z);
}
template <typename T>
constexpr bool Quat<T>::Equals(const Quat& _other, T _threshold) const noexcept
{
return Maths::Equals(w, _other.w, _threshold) &&
Maths::Equals(x, _other.x, _threshold) &&
Maths::Equals(y, _other.y, _threshold) &&
Maths::Equals(z, _other.z, _threshold);
}
template <typename T>
constexpr T Quat<T>::Length() const noexcept
{
return Maths::Sqrt(SqrLength());
}
template <typename T>
constexpr T Quat<T>::SqrLength() const noexcept
{
return w * w + x * x + y * y + z * z;
}
template <typename T>
T* Quat<T>::Data() noexcept
{
return &w;
}
template <typename T>
const T* Quat<T>::Data() const noexcept
{
return &w;
}
template <typename T>
Quat<T>& Quat<T>::Normalize()
{
SA_ASSERT(!IsZero(), DivisionBy0, Maths, L"Normalize null quaternion!");
const T norm = Length();
w /= norm;
x /= norm;
y /= norm;
z /= norm;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetNormalized() const
{
SA_ASSERT(!IsZero(), DivisionBy0, Maths, L"Normalize null quaternion!");
const T norm = Length();
return Quat(w / norm, x / norm, y / norm, z / norm);
}
template <typename T>
constexpr bool Quat<T>::IsNormalized() const noexcept
{
/// Handle Maths::Sqrt() miss precision.
return Maths::Equals1(SqrLength(), 3.0f * Limits<T>::epsilon);
}
template <typename T>
constexpr Quat<T>& Quat<T>::Inverse()
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion must be normalized!");
// Inverse of normalized quaternion is conjugate.
x = -x;
y = -y;
z = -z;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetInversed() const
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion must be normalized!");
// Inverse of normalized quaternion is conjugate.
return Quat(w, -x, -y, -z);
}
template <typename T>
constexpr Deg<T> Quat<T>::GetAngle() const noexcept
{
return Maths::ACos(w) * 2.0f;
}
template <typename T>
constexpr Vec3<T> Quat<T>::GetAxis() const noexcept
{
#if SA_DEBUG
if (Maths::Equals1(w))
{
SA_LOG("Get axis of an idendity quaternion.", Warning, Maths);
return Vec3<T>::Zero;
}
#endif
const Vec3<T>& axis = reinterpret_cast<const Vec3<T>&>(x);
const Rad<T> halfAngle = Maths::ACos(w);
return (axis / Maths::Sin(halfAngle)).GetNormalized();
}
template <typename T>
Quat<T>& Quat<T>::Scale(T _scale) noexcept
{
w *= _scale;
x *= _scale;
y *= _scale;
z *= _scale;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetScaled(T _scale) const noexcept
{
return Quat(w - _scale, x * _scale, y * _scale, z * _scale);
}
template <typename T>
Quat<T>& Quat<T>::UnScale(T _scale)
{
SA_ASSERT(!Maths::Equals0(_scale), DivisionBy0, Maths, L"Inverse scale quaternion by 0!");
w /= _scale;
x /= _scale;
y /= _scale;
z /= _scale;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetUnScaled(T _scale) const
{
SA_ASSERT(!Maths::Equals0(_scale), DivisionBy0, Maths, L"Inverse scale quaternion by 0!");
return Quat(w / _scale, x / _scale, y / _scale, z / _scale);
}
template <typename T>
constexpr Quat<T> Quat<T>::Rotate(const Quat<T>& _other) const
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion multiplication must be normalized. This quaternion is not normalized!");
SA_ASSERT(_other.IsNormalized(), NonNormalized, Maths, L"Quaternion multiplication must be normalized. Other quaternion is not normalized!");
T resW = w * _other.w - x * _other.x - y * _other.y - z * _other.z;
T resX = w * _other.x + x * _other.w + y * _other.z - z * _other.y;
T resY = w * _other.y - x * _other.z + y * _other.w + z * _other.x;
T resZ = w * _other.z + x * _other.y - y * _other.x + z * _other.w;
return Quat(resW, resX, resY, resZ);
}
template <typename T>
constexpr Vec3<T> Quat<T>::Rotate(const Vec3<T>& _vec) const
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion multiplication must be normalized. This quaternion is not normalized!");
// Quaternion-vector multiplication optimization:
// http://people.csail.mit.edu/bkph/articles/Quaternions.pdf
// v' = q * p * q-1
// Pure imaginary optimization:
// v' = v + q * 2.0f * (q X v) + q * 2.0f * (q X v).
// v' = v + q * ( A ) + q * ( A ).
// Vector component from quaternion.
const Vec3<T> qVec(x, y, z);
// Compute A = 2.0f * (q X v).
const Vec3<T> A = 2.0f * Vec3<T>::Cross(qVec, _vec);
return _vec + (w * A) + Vec3<T>::Cross(qVec, A);
}
template <typename T>
constexpr Quat<T> Quat<T>::UnRotate(const Quat<T>& _other) const
{
return GetInversed().Rotate(_other);
}
template <typename T>
constexpr Vec3<T> Quat<T>::UnRotate(const Vec3<T>& _vec) const
{
return GetInversed().Rotate(_vec);
}
template <typename T>
constexpr Vec3<T> Quat<T>::RightVector() const
{
return Rotate(Vec3<T>::Right);
}
template <typename T>
constexpr Vec3<T> Quat<T>::UpVector() const
{
return Rotate(Vec3<T>::Up);
}
template <typename T>
constexpr Vec3<T> Quat<T>::ForwardVector() const
{
return Rotate(Vec3<T>::Forward);
}
template <typename T>
constexpr Vec3<Deg<T>> Quat<T>::ToEuler() const noexcept
{
// Source: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
Vec3<Deg<T>> result;
// Pitch - X axis
{
const T cosPitch = 1.0f - 2.0f * (x * x + y * y);
const T sinPitch = 2.0f * (w * x + y * z);
result.x = Maths::ATan2(sinPitch, cosPitch);
}
// Yaw - Y axis
{
const T sinYaw = 2.0f * (w * y - z * x);
result.y = Maths::Abs(sinYaw) < 1.0f ? Maths::ASin(sinYaw) : Rad<T>(Maths::PiOv4 * Maths::Sign(sinYaw)); // 90 degrees if out of range.
}
// Roll - Z axis
{
const T cosRoll = 1.0f - 2.0f * (y * y + z * z);
const T sinRoll = 2.0f * (w * z + x * y);
result.z = Maths::ATan2(sinRoll, cosRoll);
}
return result;
}
template <typename T>
constexpr Quat<T> Quat<T>::FromEuler(const Vec3<Deg<T>>& _angles) noexcept
{
// Source: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
Vec3<Rad<T>> halfRadAngles = _angles * 0.5f;
const T cosPitch = Maths::Cos(halfRadAngles.x);
const T sinPitch = Maths::Sin(halfRadAngles.x);
const T cosYaw = Maths::Cos(halfRadAngles.y);
const T sinYaw = Maths::Sin(halfRadAngles.y);
const T cosRoll = Maths::Cos(halfRadAngles.z);
const T sinRoll = Maths::Sin(halfRadAngles.z);
Quat result;
result.w = cosPitch * cosYaw * cosRoll + sinPitch * sinYaw * sinRoll;
result.x = sinPitch * cosYaw * cosRoll - cosPitch * sinYaw * sinRoll;
result.y = cosPitch * sinYaw * cosRoll + sinPitch * cosYaw * sinRoll;
result.z = cosPitch * cosYaw * sinRoll - sinPitch * sinYaw * cosRoll;
return result;
}
template <typename T>
constexpr T Quat<T>::Dot(const Quat<T>& _lhs, const Quat& _rhs) noexcept
{
return _lhs.w * _rhs.w +
_lhs.x * _rhs.x +
_lhs.y * _rhs.y +
_lhs.z * _rhs.z;
}
template <typename T>
Quat<T> Quat<T>::Lerp(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::Lerp(_start, _end, _alpha).GetNormalized();
}
template <typename T>
Quat<T> Quat<T>::LerpUnclamped(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::LerpUnclamped(_start, _end, _alpha).GetNormalized();
}
template <typename T>
Quat<T> Quat<T>::SLerp(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::SLerp(_start, _end, _alpha).GetNormalized();
}
template <typename T>
Quat<T> Quat<T>::SLerpUnclamped(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::SLerpUnclamped(_start, _end, _alpha).GetNormalized();
}
template <typename T>
constexpr Quat<T> Quat<T>::operator-() const noexcept
{
return Quat(-w, -x, -y, -z);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator*(T _scale) const noexcept
{
return GetScaled(_scale);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator/(T _scale) const
{
return GetUnScaled(_scale);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator+(const Quat<T>& _rhs) const noexcept
{
return Quat(
w + _rhs.w,
x + _rhs.x,
y + _rhs.y,
z + _rhs.z
);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator-(const Quat<T>& _rhs) const noexcept
{
return Quat(
w - _rhs.w,
x - _rhs.x,
y - _rhs.y,
z - _rhs.z
);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator*(const Quat& _rhs) const
{
return Rotate(_rhs);
}
template <typename T>
constexpr Vec3<T> Quat<T>::operator*(const Vec3<T>& _rhs) const
{
return Rotate(_rhs);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator/(const Quat& _rhs) const
{
return UnRotate(_rhs);
}
template <typename T>
constexpr Vec3<T> Quat<T>::operator/(const Vec3<T>& _rhs) const
{
return UnRotate(_rhs);
}
template <typename T>
constexpr T Quat<T>::operator|(const Quat& _rhs) const noexcept
{
return Dot(*this, _rhs);
}
template <typename T>
Quat<T>& Quat<T>::operator*=(T _scale) const noexcept
{
Scale(_scale);
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator/=(T _scale) const
{
UnScale(_scale);
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator+=(const Quat<T>& _rhs) noexcept
{
w += _rhs.w;
x += _rhs.x;
y += _rhs.y;
z += _rhs.z;
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator-=(const Quat<T>& _rhs) noexcept
{
w -= _rhs.w;
x -= _rhs.x;
y -= _rhs.y;
z -= _rhs.z;
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator*=(const Quat& _rhs) noexcept
{
return *this = (*this) * _rhs;
}
template <typename T>
Quat<T>& Quat<T>::operator/=(const Quat& _rhs) noexcept
{
return *this = (*this) / _rhs;
}
template <typename T>
constexpr bool Quat<T>::operator==(const Quat<T>& _rhs) noexcept
{
return Equals(_rhs);
}
template <typename T>
constexpr bool Quat<T>::operator!=(const Quat<T>& _rhs) noexcept
{
return !(*this == _rhs);
}
template <typename T>
T& Quat<T>::operator[](uint32 _index)
{
SA_ASSERT(_index <= 3u, OutOfRange, Maths, _index, 0u, 3u);
return Data()[_index];
}
template <typename T>
T Quat<T>::operator[](uint32 _index) const
{
SA_ASSERT(_index <= 3u, OutOfRange, Maths, _index, 0u, 3u);
return Data()[_index];
}
template <typename T>
constexpr Quat<T> operator*(T _lhs, const Quat<T>& _rhs) noexcept
{
return _rhs * _lhs;
}
template <typename T>
constexpr Quat<T> operator/(T _lhs, const Quat<T>& _rhs)
{
return Quat(
_lhs / _rhs.w,
_lhs / _rhs.x,
_lhs / _rhs.y,
_lhs / _rhs.z
);
}
template <typename T>
constexpr Vec3<T> operator*(const Vec3<T>& _lhs, const Quat<T>& _rhs) noexcept
{
return _rhs * _lhs;
}
template <typename T>
constexpr Vec3<T> operator/(const Vec3<T>& _lhs, const Quat<T>& _rhs)
{
return _rhs / _lhs;
}
template <typename T>
template <typename TIn>
constexpr Quat<T>::operator Quat<TIn>() const noexcept
{
return Quat<TIn>(*this);
}
}
| 21.878489 | 143 | 0.645827 | SapphireSuite |
bfac974de42b3e3c1f3b5bc90349d2f648f20f69 | 28,880 | cpp | C++ | NULL Engine/Source/C_Animator.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-29T12:28:31.000Z | 2021-06-08T17:32:56.000Z | NULL Engine/Source/C_Animator.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | null | null | null | NULL Engine/Source/C_Animator.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-01T17:06:32.000Z | 2021-01-09T16:58:50.000Z | #include "MathGeoLib/include/Geometry/LineSegment.h"
#include "Profiler.h"
#include "JSONParser.h"
#include "Time.h"
#include "Channel.h"
#include "AnimatorClip.h"
#include "Application.h"
#include "M_ResourceManager.h"
#include "R_Animation.h"
#include "GameObject.h"
#include "C_Transform.h"
#include "C_Animator.h"
typedef std::map<double, float3>::const_iterator PositionKeyframe;
typedef std::map<double, Quat>::const_iterator RotationKeyframe;
typedef std::map<double, float3>::const_iterator ScaleKeyframe;
C_Animator::C_Animator(GameObject* owner) : Component(owner, COMPONENT_TYPE::ANIMATOR),
current_clip (nullptr),
blending_clip (nullptr),
current_root_bone (nullptr)
{
blend_frames = 0;
play = false;
pause = false;
step = false;
stop = true;
playback_speed = 1.0f;
interpolate = true;
loop_animation = false;
play_on_start = true;
camera_culling = true;
show_bones = false;
}
C_Animator::~C_Animator()
{
current_clip = nullptr;
blending_clip = nullptr;
current_root_bone = nullptr;
}
bool C_Animator::Update()
{
BROFILER_CATEGORY("Animation Component Update", Profiler::Color::DarkSlateBlue);
bool ret = true;
AddAnimationsToAdd();
if (play || step)
{
if (current_clip != nullptr)
{
StepAnimation();
}
step = false;
}
return ret;
}
bool C_Animator::CleanUp()
{
bool ret = true;
for (uint i = 0; i < animations.size(); ++i)
{
App->resource_manager->FreeResource(animations[i]->GetUID());
}
animations.clear();
animation_bones.clear();
clips.clear();
current_bones.clear();
blending_bones.clear();
display_bones.clear();
animations_to_add.clear();
return ret;
}
bool C_Animator::SaveState(ParsonNode& root) const
{
bool ret = true;
root.SetNumber("Type", (double)GetType());
// Animations
ParsonArray animations_array = root.SetArray("Animations");
for (auto animation = animations.cbegin(); animation != animations.cend(); ++animation)
{
ParsonNode animation_node = animations_array.SetNode((*animation)->GetName());
animation_node.SetNumber("UID", (*animation)->GetUID());
animation_node.SetString("Name", (*animation)->GetAssetsFile());
animation_node.SetString("Path", (*animation)->GetLibraryPath());
animation_node.SetString("File", (*animation)->GetLibraryFile());
}
// Clips
ParsonArray clips_array = root.SetArray("Clips");
for (auto clip = clips.cbegin(); clip != clips.cend(); ++clip)
{
if (strstr(clip->first.c_str(), "Default") != nullptr)
{
continue;
}
ParsonNode clip_node = clips_array.SetNode(clip->second.GetName());
clip->second.SaveState(clip_node);
}
// Current Clip
if (current_clip != nullptr)
{
ParsonNode current_clip_node = root.SetNode("CurrentClip");
current_clip_node.SetString("AnimationName", current_clip->GetAnimationName());
current_clip_node.SetString("Name", current_clip->GetName());
}
return ret;
}
bool C_Animator::LoadState(ParsonNode& root)
{
bool ret = true;
ParsonArray animations_array = root.GetArray("Animations");
for (uint i = 0; i < animations_array.size; ++i)
{
ParsonNode animation_node = animations_array.GetNode(i);
if (!animation_node.NodeIsValid())
{
continue;
}
std::string assets_path = ASSETS_MODELS_PATH + std::string(animation_node.GetString("Name"));
App->resource_manager->AllocateResource((uint32)animation_node.GetNumber("UID"), assets_path.c_str());
R_Animation* r_animation = (R_Animation*)App->resource_manager->RequestResource((uint32)animation_node.GetNumber("UID"));
if (r_animation != nullptr)
{
animations_to_add.push_back(r_animation);
//AddAnimation(r_animation);
}
}
ParsonArray clips_array = root.GetArray("Clips");
for (uint i = 0; i < clips_array.size; ++i)
{
ParsonNode clip_node = clips_array.GetNode(i);
AnimatorClip clip = AnimatorClip();
clip.LoadState(clip_node);
clips.emplace(clip.GetName(), clip);
}
ParsonNode current_clip_node = root.GetNode("CurrentClip");
auto item = clips.find(current_clip_node.GetString("Name"));
if (item != clips.end())
{
SetCurrentClip(&item->second);
}
return ret;
}
// --- C_ANIMATION METHODS ---
bool C_Animator::StepAnimation()
{
bool ret = true;
bool success = ValidateCurrentClip();
if (!success)
{
return false;
}
success = StepClips();
if (!success)
{
return false;
}
for (uint i = 0; i < current_bones.size(); ++i)
{
const BoneLink& bone = current_bones[i];
C_Transform* c_transform = bone.game_object->GetComponent<C_Transform>();
if (c_transform == nullptr)
{
LOG("[WARNING] Animation Component: GameObject { %s } did not have a Transform Component!", bone.game_object->GetName());
continue;
}
const Transform& original_transform = Transform(c_transform->GetLocalTransform());
if (interpolate)
{
Transform& interpolated_transform = GetInterpolatedTransform(current_clip->GetAnimationFrame(), bone.channel, original_transform);
if (BlendingClipExists())
{
interpolated_transform = GetBlendedTransform(blending_clip->GetAnimationFrame(), blending_bones[i].channel, interpolated_transform);
}
c_transform->ImportTransform(interpolated_transform);
}
else
{
if (current_clip->in_new_tick)
{
Transform& pose_to_pose_transform = GetPoseToPoseTransform(current_clip->GetAnimationTick(), bone.channel, original_transform);
if (BlendingClipExists())
{
pose_to_pose_transform = GetBlendedTransform(blending_clip->GetAnimationTick(), blending_bones[i].channel, pose_to_pose_transform);
}
c_transform->ImportTransform(pose_to_pose_transform);
}
}
}
UpdateDisplayBones();
return ret;
}
bool C_Animator::StepClips()
{
bool ret = true;
bool current_exists = CurrentClipExists();
bool blending_exists = BlendingClipExists();
if (!current_exists && !blending_exists)
{
LOG("[ERROR] Animator Component: Could not Step Clips! Error: There were no Current or Blending Clips set.");
return false;
}
if (!current_exists && blending_exists)
{
SwitchBlendingToCurrent();
}
if (BlendingClipExists())
{
if (blending_clip->GetAnimationFrame() > (float)(blending_clip->GetStart() + blend_frames))
{
SwitchBlendingToCurrent();
}
}
float dt = (App->play) ? Time::Game::GetDT() : Time::Real::GetDT(); // In case a clip preview is needed outside Game Mode.
float step_value = dt * playback_speed;
if (CurrentClipExists())
{
bool success = current_clip->StepClip(step_value);
if (!success)
{
if (BlendingClipExists())
{
blending_clip->StepClip(step_value);
SwitchBlendingToCurrent();
return true;
}
else
{
if (!current_clip->IsLooped())
{
Stop();
ResetBones();
return false;
}
}
}
if (BlendingClipExists())
{
blending_clip->StepClip(step_value);
}
}
return ret;
}
bool C_Animator::BlendAnimation()
{
bool ret = true;
return ret;
}
bool C_Animator::ValidateCurrentClip()
{
bool ret = true;
if (current_clip == nullptr)
{
if (blending_clip != nullptr)
{
SwitchBlendingToCurrent();
ret = true;
}
else
{
ret = false;
}
}
return ret;
}
void C_Animator::SwitchBlendingToCurrent()
{
if (current_clip != nullptr)
{
current_clip->playing = false;
current_clip->ClearClip();
ClearCurrentClip();
}
SetCurrentClip(blending_clip);
ClearBlendingClip();
}
void C_Animator::ResetBones()
{
if (current_clip == nullptr)
{
LOG("[ERROR] Animator Component: Could not Reset Bones! Error: Current Clip was nullptr.");
return;
}
for (auto bone = current_bones.cbegin(); bone != current_bones.cend(); ++bone)
{
const Transform& transform = Transform(bone->game_object->GetComponent<C_Transform>()->GetLocalTransform());
const Transform& interpolated_transform = GetInterpolatedTransform((double)current_clip->GetStart(), bone->channel, transform);
bone->game_object->GetComponent<C_Transform>()->ImportTransform(interpolated_transform);
}
UpdateDisplayBones();
}
void C_Animator::AddAnimationsToAdd()
{
if (!animations_to_add.empty())
{
for (uint i = 0; i < animations_to_add.size(); ++i)
{
AddAnimation(animations_to_add[i]);
}
animations_to_add.clear();
}
}
Transform C_Animator::GetInterpolatedTransform(const double& keyframe, const Channel& channel, const Transform& original_transform) const
{
float3 interpolated_position = GetInterpolatedPosition(keyframe, channel, original_transform.position);
Quat interpolated_rotation = GetInterpolatedRotation(keyframe, channel, original_transform.rotation);
float3 interpolated_scale = GetInterpolatedScale(keyframe, channel, original_transform.scale);
return Transform(interpolated_position, interpolated_rotation, interpolated_scale);
}
const float3 C_Animator::GetInterpolatedPosition(const double& keyframe, const Channel& channel, const float3& original_position) const
{
if (!channel.HasPositionKeyframes())
{
return original_position;
}
PositionKeyframe prev_keyframe = channel.GetClosestPrevPositionKeyframe(keyframe);
PositionKeyframe next_keyframe = channel.GetClosestNextPositionKeyframe(keyframe);
float rate = (float)(keyframe / next_keyframe->first);
float3 ret = (prev_keyframe == next_keyframe) ? prev_keyframe->second : prev_keyframe->second.Lerp(next_keyframe->second, rate);
return ret;
}
const Quat C_Animator::GetInterpolatedRotation(const double& keyframe, const Channel& channel, const Quat& original_rotation) const
{
if (!channel.HasRotationKeyframes())
{
return original_rotation;
}
RotationKeyframe prev_keyframe = channel.GetClosestPrevRotationKeyframe(keyframe);
RotationKeyframe next_keyframe = channel.GetClosestNextRotationKeyframe(keyframe);
float rate = (float)(keyframe / next_keyframe->first);
Quat ret = (prev_keyframe == next_keyframe) ? prev_keyframe->second : prev_keyframe->second.Slerp(next_keyframe->second, rate);
return ret;
}
const float3 C_Animator::GetInterpolatedScale(const double& keyframe, const Channel& channel, const float3& original_scale) const
{
if (!channel.HasScaleKeyframes())
{
return original_scale;
}
ScaleKeyframe prev_keyframe = channel.GetClosestPrevScaleKeyframe(keyframe);
ScaleKeyframe next_keyframe = channel.GetClosestNextScaleKeyframe(keyframe);
float rate = (float)(keyframe / next_keyframe->first);
float3 ret = (prev_keyframe == next_keyframe) ? prev_keyframe->second : prev_keyframe->second.Lerp(next_keyframe->second, rate);
return ret;
}
Transform C_Animator::GetPoseToPoseTransform(const uint& tick, const Channel& channel, const Transform& original_transform) const
{
const float3& position = GetPoseToPosePosition(tick, channel, original_transform.position);
const Quat& rotation = GetPoseToPoseRotation(tick, channel, original_transform.rotation);
const float3& scale = GetPoseToPoseScale(tick, channel, original_transform.scale);
return Transform(position, rotation, scale);
}
const float3 C_Animator::GetPoseToPosePosition(const uint& tick, const Channel& channel, const float3& original_position) const
{
if (!channel.HasPositionKeyframes())
{
return original_position;
}
return channel.GetPositionKeyframe(tick)->second;
}
const Quat C_Animator::GetPoseToPoseRotation(const uint& tick, const Channel& channel, const Quat& original_rotation) const
{
if (!channel.HasRotationKeyframes())
{
return original_rotation;
}
return channel.GetRotationKeyframe(tick)->second;
}
const float3 C_Animator::GetPoseToPoseScale(const uint& tick, const Channel& channel, const float3& original_scale) const
{
if (!channel.HasScaleKeyframes())
{
return original_scale;
}
return channel.GetScaleKeyframe(tick)->second;
}
Transform C_Animator::GetBlendedTransform(const double& blended_keyframe, const Channel& blended_channel, const Transform& original_transform) const
{
const float3& position = GetBlendedPosition(blended_keyframe, blended_channel, original_transform.position);
const Quat& rotation = GetBlendedRotation(blended_keyframe, blended_channel, original_transform.rotation);
const float3& scale = GetBlendedScale(blended_keyframe, blended_channel, original_transform.scale);
return Transform(position, rotation, scale);
}
const float3 C_Animator::GetBlendedPosition(const double& blending_keyframe, const Channel& blending_channel, const float3& original_position) const
{
if (!blending_channel.HasPositionKeyframes())
{
return original_position;
}
float3 position = GetInterpolatedPosition(blending_keyframe, blending_channel, original_position);
double blend_frame = blending_keyframe - blending_clip->GetStart();
float blend_rate = (float)(blend_frame / blend_frames);
float3 blended_position = original_position.Lerp(position, blend_rate);
return blended_position;
}
const Quat C_Animator::GetBlendedRotation(const double& blending_keyframe, const Channel& blending_channel, const Quat& original_rotation) const
{
if (!blending_channel.HasRotationKeyframes())
{
return original_rotation;
}
Quat rotation = GetInterpolatedRotation(blending_keyframe, blending_channel, original_rotation);
double blend_frame = blending_keyframe - blending_clip->GetStart();
float blend_rate = (float)(blend_frame / blend_frames);
Quat blended_rotation = original_rotation.Slerp(rotation, blend_rate);
return blended_rotation;
}
const float3 C_Animator::GetBlendedScale(const double& blending_keyframe, const Channel& blending_channel, const float3& original_scale) const
{
if (!blending_channel.HasScaleKeyframes())
{
return original_scale;
}
float3 scale = GetInterpolatedScale(blending_keyframe, blending_channel, original_scale);
double blend_frame = blending_keyframe - blending_clip->GetStart();
float blend_rate = (float)(blend_frame / blend_frames);
float3 blended_scale = original_scale.Lerp(scale, blend_rate);
return blended_scale;
}
void C_Animator::FindAnimationBones(const R_Animation* r_animation)
{
if (r_animation == nullptr)
{
return;
}
if (r_animation->channels.empty())
{
return;
}
std::vector<BoneLink> links;
bool success = FindBoneLinks(r_animation, links);
if (success)
{
animation_bones.emplace(r_animation->GetUID(), links);
GameObject* root_bone = FindRootBone(links);
if (root_bone != nullptr)
{
SetRootBone(root_bone);
UpdateDisplayBones();
}
}
}
bool C_Animator::FindBoneLinks(const R_Animation* r_animation, std::vector<BoneLink>& links)
{
if (r_animation == nullptr)
{
LOG("[ERROR] Animator Component: Could not find Bone Links! Error: Given R_Animation* was nullptr.");
return false;
}
if (r_animation->channels.empty())
{
LOG("[ERROR] Animator Component: Could not find { %s }'s Bone Links! Error: R_Animation* had no channels.");
return false;
}
if (this->GetOwner()->childs.empty())
{
LOG("[ERROR] Animator Component: Could not find { %s }'s Bone Links! Error: Component Owner { %s } had no Childs.", this->GetOwner()->GetName());
return false;
}
std::map<std::string, GameObject*> childs;
this->GetOwner()->GetAllChilds(childs);
for (auto channel = r_animation->channels.cbegin(); channel != r_animation->channels.cend(); ++channel) // Trying out the auto keyword
{
auto go_item = childs.find(channel->name);
if (go_item != childs.end())
{
go_item->second->is_bone = true;
links.push_back(BoneLink((*channel), go_item->second));
}
}
childs.clear();
return true;
}
GameObject* C_Animator::FindRootBone(const std::vector<BoneLink>& links)
{
for (auto link = links.cbegin(); link != links.cend(); ++link) // Trying out the auto keyword
{
if (link->game_object->parent == nullptr)
{
continue;
}
if (!link->game_object->parent->is_bone)
{
return link->game_object;
}
}
return nullptr;
}
void C_Animator::SetRootBone(const GameObject* root_bone)
{
if (root_bone == nullptr)
{
LOG("[ERROR] Animator Component: Could not Set Root Bone! Error: Given GameObject* was nullptr.");
return;
}
if (current_root_bone == nullptr)
{
current_root_bone = root_bone;
}
else
{
if (current_root_bone != root_bone)
{
LOG("[WARNING] Animator Component: Disparity between root bones detected! A: [%s], B: [%s]", current_root_bone->GetName(), root_bone->GetName());
}
}
}
void C_Animator::UpdateDisplayBones()
{
display_bones.clear();
if (current_root_bone != nullptr)
{
GenerateBoneSegments(current_root_bone);
}
return;
}
void C_Animator::GenerateBoneSegments(const GameObject* bone)
{
if (bone == nullptr)
{
LOG("[ERROR] Animation Component: Could not Generate Bone Segments! Error: Given GameObject* was nullptr.");
return;
}
if (bone->childs.empty() || !bone->is_bone)
{
return;
}
C_Transform* bone_transform = bone->GetComponent<C_Transform>();
for (uint i = 0; i < bone->childs.size(); ++i)
{
LineSegment display_bone = { float3::zero, float3::zero };
display_bone.a = bone_transform->GetWorldPosition();
display_bone.b = bone->childs[i]->GetComponent<C_Transform>()->GetWorldPosition();
display_bones.push_back(display_bone);
GenerateBoneSegments(bone->childs[i]);
}
}
bool C_Animator::GenerateDefaultClip(const R_Animation* r_animation, AnimatorClip& default_clip)
{
if (r_animation == nullptr)
{
LOG("[ERROR] Animator Component: Could not Generate Default Clip! Error: Given R_Animation* was nullptr.");
return false;
}
std::string default_name = r_animation->GetName() + std::string(" Default");
default_clip = AnimatorClip(r_animation, default_name, 0, (uint)r_animation->GetDuration(), false);
return true;
}
void C_Animator::SortBoneLinksByHierarchy(const std::vector<BoneLink>& bone_links, const GameObject* root_bone, std::vector<BoneLink>& sorted)
{
if (root_bone == nullptr)
{
return;
}
if (root_bone == current_root_bone)
{
for (uint j = 0; j < bone_links.size(); ++j)
{
if (bone_links[j].channel.name == root_bone->GetName())
{
sorted.push_back(bone_links[j]);
}
}
}
for (uint i = 0; i < root_bone->childs.size(); ++i)
{
for (uint j = 0; j < bone_links.size(); ++j)
{
if (bone_links[j].channel.name == root_bone->childs[i]->GetName())
{
sorted.push_back(bone_links[j]);
}
}
}
for (uint i = 0; i < root_bone->childs.size(); ++i)
{
SortBoneLinksByHierarchy(bone_links, root_bone->childs[i], sorted);
}
}
void C_Animator::AddAnimation(R_Animation* r_animation)
{
if (r_animation == nullptr)
{
LOG("[ERROR] Animator Component: Could not Add Animation to %s's Animation Component! Error: Argument R_Animation* was nullptr.", this->GetOwner()->GetName());
return;
}
animations.push_back(r_animation);
FindAnimationBones(r_animation);
AnimatorClip default_clip = AnimatorClip();
bool success = GenerateDefaultClip(r_animation, default_clip);
if (success)
{
clips.emplace(default_clip.GetName(), default_clip);
if (current_clip == nullptr)
{
SetCurrentClip(&clips.find(default_clip.GetName())->second);
}
}
}
bool C_Animator::AddClip(const AnimatorClip& clip)
{
if (clip.GetAnimation() == nullptr)
{
LOG("[ERROR] Animator Component: Could not Add Clip { %s }! Error: Clip's R_Animation* was nullptr.", clip.GetName());
return false;
}
if (clips.find(clip.GetName()) != clips.end())
{
LOG("[ERROR] Animator Component: Could not Add Clip { %s }! Error: A clip with the same name already exists.", clip.GetName());
return false;
}
clips.emplace(clip.GetName(), clip);
if (current_clip == nullptr)
{
current_clip = (AnimatorClip*)&clip;
}
return true;
}
void C_Animator::PlayClip(const std::string& clip_name, const uint& blend_frames)
{
auto item = clips.find(clip_name);
if (item == clips.end())
{
LOG("[ERROR] Animator Component: Could not Play Clip! Error: Could not find any clip with the given name!");
return;
}
if (current_clip != nullptr && current_clip->GetName() == clip_name)
{
return;
}
if (current_clip == nullptr || blend_frames == 0 || blend_frames > item->second.GetDuration())
{
Stop();
SetCurrentClip(&item->second);
}
else
{
SetBlendingClip(&item->second, blend_frames);
}
Play();
}
bool C_Animator::Play()
{
if (current_clip == nullptr)
{
return false;
}
play = true;
pause = false;
step = false;
stop = false;
current_clip->playing = true;
if (BlendingClipExists())
{
blending_clip->playing = true;
};
return play;
}
bool C_Animator::Pause()
{
if (play)
{
pause = true;
play = false;
step = false;
}
else
{
LOG("[WARNING] Animation Component: Cannot Pause a Stopped Animation!");
}
return pause;
}
bool C_Animator::Step()
{
if (pause)
{
step = true;
}
else
{
LOG("[WARNING] Animation Component: Only Paused Animations can be Stepped!");
}
return step;
}
bool C_Animator::Stop()
{
stop = true;
play = false;
pause = false;
step = false;
current_clip->playing = false;
current_clip->ClearClip();
if (BlendingClipExists())
{
blending_clip->playing = false;
blending_clip->ClearClip();
}
return stop;
}
// --- DEBUG METHODS
bool C_Animator::StepToPrevKeyframe()
{
if (play)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Prev Keyframe! Error: Cannot step an animation that is being currently Played.");
return false;
}
if (current_clip == nullptr)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Prev Keyframe! Error: Current Clip (AnimatorClip*) was nullptr.");
return false;
}
current_clip->StepClipToPrevKeyframe();
for (uint i = 0; i < current_bones.size(); ++i)
{
const Transform& transform = Transform(current_bones[i].game_object->GetComponent<C_Transform>()->GetLocalTransform());
const Transform& interpolated_transform = GetInterpolatedTransform((double)current_clip->GetClipTick(), current_bones[i].channel, transform);
current_bones[i].game_object->GetComponent<C_Transform>()->ImportTransform(interpolated_transform);
}
UpdateDisplayBones();
return true;
}
bool C_Animator::StepToNextKeyframe()
{
if (play)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Next Keyframe! Error: Cannot step an animation that is being currently Played.");
return false;
}
if (current_clip == nullptr)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Next Keyframe! Error: Current Clip (AnimatorClip*) was nullptr.");
return false;
}
current_clip->StepClipToNextKeyframe();
for (uint i = 0; i < current_bones.size(); ++i)
{
const Transform& transform = Transform(current_bones[i].game_object->GetComponent<C_Transform>()->GetLocalTransform());
const Transform& interpolated_transform = GetInterpolatedTransform((double)current_clip->GetClipTick(), current_bones[i].channel, transform);
current_bones[i].game_object->GetComponent<C_Transform>()->ImportTransform(interpolated_transform);
}
UpdateDisplayBones();
return false;
}
bool C_Animator::RefreshBoneDisplay()
{
UpdateDisplayBones();
return true;
}
// --- CURRENT/BLENDING ANIMATION METHODS
AnimatorClip* C_Animator::GetCurrentClip() const
{
return current_clip;
}
AnimatorClip* C_Animator::GetBlendingClip() const
{
return blending_clip;
}
void C_Animator::SetCurrentClip(AnimatorClip* clip)
{
std::string error_string = "[ERROR] Animator Component: Could not Set Current Clip to { " + std::string(this->GetOwner()->GetName()) + " }'s Animator Component";
if (clip == nullptr)
{
LOG("%s! Error: Given AnimatorClip* was nullptr.", error_string.c_str());
return;
}
if (clips.find(clip->GetName()) == clips.end())
{
LOG("%s! Error: Could not find the given AnimatorClip* in the clips map.", error_string.c_str());
return;
}
if (clip->GetAnimation() == nullptr)
{
LOG("%s! Error: Given AnimatorClip* had no R_Animation* assigned to it.", error_string.c_str());
return;
}
auto bones = animation_bones.find(clip->GetAnimation()->GetUID());
if (bones == animation_bones.end())
{
LOG("%s! Error: Could not find the Bones of the Clip's animation (R_Animation*).");
return;
}
current_clip = clip;
current_bones = bones->second;
//current_clip->ClearClip();
}
void C_Animator::SetBlendingClip(AnimatorClip* clip, uint blend_frames)
{
std::string error_string = "[ERROR] Animator Component: Could not Set Blending Clip in { " + std::string(this->GetOwner()->GetName()) + " }'s Animator Component";
if (clip == nullptr)
{
LOG("%s! Error: Given AnimatorClip* was nullptr.", error_string.c_str());
return;
}
if (clips.find(clip->GetName()) == clips.end())
{
LOG("%s! Error: Could not find the given AnimatorClip* in the clips map.", error_string.c_str());
return;
}
if (clip->GetAnimation() == nullptr)
{
LOG("%s! Error: Given AnimatorClip* had no R_Animation* assigned to it.", error_string.c_str());
return;
}
auto bones = animation_bones.find(clip->GetAnimation()->GetUID());
if (bones == animation_bones.end())
{
LOG("%s! Error: Could not find the Bones of the Clip's animation (R_Animation*).");
return;
}
blending_clip = clip;
blending_bones = bones->second;
this->blend_frames = blend_frames;
blending_clip->ClearClip(); // Resetting the clip just in case.
}
void C_Animator::SetCurrentClipByIndex(const uint& index)
{
if (index >= clips.size())
{
LOG("[ERROR] Animator Component: Could not Set Current Clip By Index! Error: Given Index was out of bounds.");
return;
}
std::string error_string = "[ERROR] Animator Component: Could not Set Current Clip in { " + std::string(this->GetOwner()->GetName()) + " }'s Animator Component";
uint i = 0;
for (auto item = clips.cbegin(); item != clips.cend(); ++item)
{
if (i == index) // Dirty way of finding items in a map by index.
{
const AnimatorClip& clip = item->second;
if (animation_bones.find(clip.GetAnimation()->GetUID()) == animation_bones.end())
{
LOG("%s! Error: Could not find the Bones of the Clip's animation (R_Animation*).");
return;
}
current_clip = (AnimatorClip*)&clip;
current_bones = animation_bones.find(clip.GetAnimation()->GetUID())->second;
current_clip->ClearClip();
return;
}
++i;
}
}
/*void C_Animator::SetBlendingClipByIndex(const uint& index, const uint& blend_frames)
{
}*/
bool C_Animator::CurrentClipExists() const
{
return (current_clip != nullptr) ? true : false;
}
bool C_Animator::BlendingClipExists() const
{
return (blending_clip != nullptr) ? true : false;
}
void C_Animator::ClearCurrentClip()
{
current_clip = nullptr;
current_bones.clear();
}
void C_Animator::ClearBlendingClip()
{
blending_clip = nullptr;
blend_frames = 0;
blending_bones.clear();
}
// --- GET/SET METHODS
std::vector<LineSegment> C_Animator::GetDisplayBones() const
{
return display_bones;
}
std::vector<std::string> C_Animator::GetClipNamesAsVector() const
{
std::vector<std::string> clip_names;
for (auto clip = clips.cbegin(); clip != clips.cend(); ++clip)
{
clip_names.push_back(clip->first);
}
return clip_names;
}
std::string C_Animator::GetClipNamesAsString() const
{
std::string clip_names = "";
for (auto clip = clips.cbegin(); clip != clips.cend(); ++clip)
{
clip_names += clip->first.c_str();
clip_names += '\0';
}
return clip_names;
}
std::string C_Animator::GetAnimationNamesAsString() const
{
std::string animation_names = "";
for (auto animation = animations.cbegin(); animation != animations.cend(); ++animation)
{
animation_names += (*animation)->GetName();
animation_names += '\0';
}
return animation_names;
}
R_Animation* C_Animator::GetAnimationByIndex(const uint& index) const
{
if (index >= animations.size())
{
LOG("[ERROR] Animator Component: Could not get Animation by Index! Error: Given index was out of bounds.");
return nullptr;
}
return animations[index];
}
float C_Animator::GetPlaybackSpeed() const
{
return playback_speed;
}
bool C_Animator::GetInterpolate() const
{
return interpolate;
}
bool C_Animator::GetLoopAnimation() const
{
return loop_animation;
}
bool C_Animator::GetPlayOnStart() const
{
return play_on_start;
}
bool C_Animator::GetCameraCulling() const
{
return camera_culling;
}
bool C_Animator::GetShowBones() const
{
return show_bones;
}
void C_Animator::SetPlaybackSpeed(const float& playback_speed)
{
this->playback_speed = playback_speed;
}
void C_Animator::SetInterpolate(const bool& set_to)
{
interpolate = set_to;
}
void C_Animator::SetLoopAnimation(const bool& set_to)
{
loop_animation = set_to;
}
void C_Animator::SetPlayOnStart(const bool& set_to)
{
play_on_start = set_to;
}
void C_Animator::SetCameraCulling(const bool& set_to)
{
camera_culling = set_to;
}
void C_Animator::SetShowBones(const bool& set_to)
{
show_bones = set_to;
}
// --- BONE LINK METHODS
BoneLink::BoneLink() :
channel(Channel()),
game_object(nullptr)
{
}
BoneLink::BoneLink(const Channel& channel, GameObject* game_object) :
channel(channel),
game_object(game_object)
{
} | 24.066667 | 163 | 0.717209 | BarcinoLechiguino |
bfb0c309a82246f243c3b88be364e76a9130da04 | 1,547 | cpp | C++ | 72.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 72.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 72.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <climits>
#include <stack>
#include <sstream>
#include <numeric>
#include <unordered_map>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
if (word1.size() > word2.size())
swap(word1, word2);
int n = word1.size();
int m = word2.size();
//cout << word1 << " " << word2 << endl;
//cout << n << " " << m << endl;
if (m == 0)
return 0;
int** f = new int*[n+1];
for (int i = 0; i <= n; ++ i)
f[i] = new int[m+1];
for (int j = 0; j <= m; ++ j)
f[0][j] = j;
for (int i = 0; i <= n; ++ i)
f[i][0] = i;
for (int i = 1; i <= n; ++ i) {
for (int j = 1; j <= m; ++ j) {
if (word1[i-1] == word2[j-1]) {
f[i][j] = f[i-1][j-1];
}
else {
f[i][j] = min( min(f[i-1][j-1], f[i-1][j]), f[i][j-1] ) + 1;
//cout << " i = " << i << " j = " << j << " f[i][j] = " << f[i][j] << endl;
}
}
}
int mindist = INT_MAX;
for (int j = 0; j <= m; ++ j) {
mindist = min(mindist, f[n][j] + m - j);
}
for (int i = 0; i <= n; ++ i)
delete [] f[i];
delete [] f;
return mindist;
}
};
int main() {
cout << Solution().minDistance("aihfk","hk") << endl;
return 0;
} | 19.3375 | 93 | 0.405301 | machinecc |
bfb142a1dd1886deb273bc875837356c2354d332 | 1,132 | cpp | C++ | uva/11747.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | uva/11747.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | uva/11747.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
#define le 10004
using namespace std;
int p[le];
struct edge{
int u, v, w;
};
bool comp(edge a, edge b){
return a.w < b.w;
}
int fnc(int a){
if(p[a] == a) return a;
p[a] = fnc(p[a]);
return p[a];
}
vector<edge> v;
vector<int> ve;
void mst(){
sort(v.begin(), v.end(), comp);
for(int i = 0; i < (int)v.size(); i++){
int a = fnc(v[i].u);
int b = fnc(v[i].v);
if(a != b) p[b] = a;
else ve.push_back(v[i].w);
}
}
int main(){
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, m, a, b, c;
while(scanf("%d %d", &n, &m) != EOF && n){
ve.clear();
for(int i = 0; i < n; p[i] = i, i++);
edge eg;
for(int i = 0; i < m; i++){
scanf("%d %d %d", &a, &b, &c);
eg.u = a;
eg.v = b;
eg.w = c;
v.push_back(eg);
}
mst();
if(ve.size() == 0) printf("forest\n");
else{
sort(ve.begin(), ve.end());
for(int i = 0; i < ve.size() - 1; printf("%d ", ve[i]), i++);
printf("%d\n", ve[ve.size() - 1]);
}
v.clear();
}
return 0;
}
| 21.358491 | 68 | 0.437279 | cosmicray001 |
bfb245ebe64e3492f568d038fde248756b0c25f6 | 62 | cpp | C++ | libboost-proto/tests/basics/driver.cpp | build2-packaging/boost | 203d505dd3ba04ea50785bc8b247a295db5fc718 | [
"BSL-1.0"
] | 4 | 2021-02-23T11:24:33.000Z | 2021-09-11T20:10:46.000Z | libboost-proto/tests/basics/driver.cpp | build2-packaging/boost | 203d505dd3ba04ea50785bc8b247a295db5fc718 | [
"BSL-1.0"
] | null | null | null | libboost-proto/tests/basics/driver.cpp | build2-packaging/boost | 203d505dd3ba04ea50785bc8b247a295db5fc718 | [
"BSL-1.0"
] | null | null | null | #include <boost/proto/proto.hpp>
int
main ()
{
return 0;
}
| 7.75 | 32 | 0.629032 | build2-packaging |
bfb8c6398e002eb181771ab525fa372dd4129c84 | 1,322 | cpp | C++ | Scripting/Source/ScriptManager.cpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | Scripting/Source/ScriptManager.cpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | Scripting/Source/ScriptManager.cpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | #include "../Include/ScriptManager.hpp"
#include "../Include/Script.hpp"
using namespace Fnd::Scripting;
ScriptManager::ScriptManager():
_entity_system(nullptr),
_input_handler(nullptr)
{
}
void ScriptManager::AddScript( unsigned int entity_id, Script* script )
{
_entities[entity_id].entity_id = entity_id;
_entities[entity_id].scripts.push_back(std::shared_ptr<Script>(script));
}
void ScriptManager::SetEntitySystem( Fnd::EntitySystem::EntitySystem* entity_system )
{
_entity_system = entity_system;
}
void ScriptManager::SetInputHandler( Fnd::Input::IInput* input_handler )
{
_input_handler = input_handler;
}
void ScriptManager::Update( const Fnd::CommonResources::FrameData& frame_data )
{
for ( auto entity_iter = _entities.begin(); entity_iter != _entities.end(); ++entity_iter )
{
for ( auto script_iter = entity_iter->second.scripts.begin(); script_iter != entity_iter->second.scripts.end(); ++script_iter )
{
// Doesn't yet handle adding/removing entities/components.
script_iter->get()->OnUpdate( frame_data );
}
}
}
Fnd::EntitySystem::EntitySystem* ScriptManager::GetEntitySystem()
{
return _entity_system;
}
Fnd::Input::IInput* ScriptManager::GetInputHandler()
{
return _input_handler;
}
ScriptManager::~ScriptManager()
{
} | 24.943396 | 130 | 0.721634 | jordanlittlefair |
bfba0c83f795186379ebfa623bfc563b934b1d63 | 388 | cpp | C++ | 2020-12-01/area.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | 2 | 2020-12-12T00:02:40.000Z | 2021-04-21T19:49:59.000Z | 2020-12-01/area.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | 2020-12-01/area.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
const double pi = 4*atan(1);
int main() {
double d = sqrt(3) - 1;
double cc = pi/12 - sin(pi/12)*cos(pi/12);
double a1 = d*d/2.0 + 4*cc;
double a3 = 8*(1/2.0 - sqrt(3)/8.0 - pi/12);
double a2 = 1-a1-a3;
double f;
while(scanf(" %lf", &f)==1) {
printf("%.3lf %.3lf %.3lf\n", a1*f*f, a2*f*f, a3*f*f);
}
return 0;
}
| 21.555556 | 59 | 0.507732 | pufe |
bfbb5f214d1edbff97c28d8afab524374a29ea32 | 2,577 | cpp | C++ | tools/utmostcp/src/utmostcp.cpp | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
] | null | null | null | tools/utmostcp/src/utmostcp.cpp | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
] | null | null | null | tools/utmostcp/src/utmostcp.cpp | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <string.h>
#define IN_FN argv[ 1 ]
#define OUT_FN argv[ 2 ]
#define SKIP_K argv[ 3 ]
#define INT64 __int64
int percents_c = 0;
INT64 in_size, byte_i, bads_c = 0, skip_k = 0, skip_c = 1;
int calc_percents_c() { return percents_c = ( byte_i * 100 ) / in_size; }
void print_status() {
printf( "%i%% - %iB", calc_percents_c(), bads_c );
if ( skip_c > 1 ) printf( " >>> %iB", skip_c );
else printf( "\t\t\t" );
printf( "\015" );
fflush( stdout );
}
int main( int argc, char** argv ) {
if ( ( argc != 3 ) && ( argc != 4 ) ) puts( "utmostcp 1.1 2002-01-07\nCopyright (C) 2003 Denis Ryzhkov ( Creon ) mail@creon.cjb.net\ndoes: utmost copy of source file to destination file or folder\nneed when: for example MPEG from bad CD\ncomment: almost as slow as effective\nusage: utmostcp <source> <destination> [<skip-coefficient>]" );
else {
FILE* in_f = fopen( IN_FN, "rb" );
if ( !in_f ) printf( "can't read file \"%s\"\n", IN_FN );
else {
char out_fn[ _MAX_PATH ];
strcpy( out_fn, OUT_FN );
if ( out_fn[ strlen( out_fn ) - 1 ] == '\\' ) strcat( out_fn, IN_FN );
FILE* out_f = fopen( out_fn, "wb" );
if ( !out_f ) printf( "can't write file \"%s\"\n", out_fn );
else {
if ( argc == 4 ) skip_k = atoi( SKIP_K );
if ( skip_k < 0 ) skip_k = 0;
bool ok;
in_size = _filelengthi64( _fileno( in_f ) );
int percents_old_c = 0;
print_status();
for ( byte_i = 0; byte_i < in_size; byte_i++ ) {
int buf = fgetc( in_f );
if ( buf != EOF ) {
if ( !ok ) { // get out of bads
ok = true;
skip_c = 1;
print_status();
} // eo get out of bads
fputc( buf, out_f );
} else { // skip bads
if ( !ok && skip_k ) { // use skip_k
skip_c *= skip_k;
for ( INT64 skip_i = 0; ( skip_i < skip_c ) && ( byte_i < in_size ); skip_i++, byte_i++, bads_c++ )
fputc( 0, out_f );
} else { // no skip_k
ok = false;
fputc( 0, out_f );
bads_c++;
} // eo no skip_k
print_status();
fseek( in_f, byte_i + 1, SEEK_SET );
} // eo skip bads
if ( calc_percents_c() != percents_old_c ) {
percents_old_c = percents_c;
print_status();
} // eo calc_percents_c() != percents_old_c
fflush( out_f );
} // eo for byte_i
fclose( out_f );
print_status();
puts( "\n" );
} // eo ok out_f
fclose( in_f );
} // eo ok in_f
} // eo argc != 1
return 0;
} // eo main
| 32.620253 | 341 | 0.54676 | denis-ryzhkov |
bfbccac119a001b8a798ed189e936ad82ee7c40d | 3,329 | cpp | C++ | thirdparty/graph-tools-master/src/graphalign/KmerIndexOperations.cpp | AlesMaver/ExpansionHunter | 274903d26a33cfbc546aac98c85bbfe51701fd3b | [
"BSL-1.0",
"Apache-2.0"
] | 122 | 2017-01-06T16:19:31.000Z | 2022-03-08T00:05:50.000Z | thirdparty/graph-tools-master/src/graphalign/KmerIndexOperations.cpp | AlesMaver/ExpansionHunter | 274903d26a33cfbc546aac98c85bbfe51701fd3b | [
"BSL-1.0",
"Apache-2.0"
] | 90 | 2017-01-04T00:23:34.000Z | 2022-02-27T12:55:52.000Z | thirdparty/graph-tools-master/src/graphalign/KmerIndexOperations.cpp | AlesMaver/ExpansionHunter | 274903d26a33cfbc546aac98c85bbfe51701fd3b | [
"BSL-1.0",
"Apache-2.0"
] | 35 | 2017-03-02T13:39:58.000Z | 2022-03-30T17:34:11.000Z | //
// GraphTools library
// Copyright 2017-2019 Illumina, Inc.
// All rights reserved.
//
// Author: Egor Dolzhenko <edolzhenko@illumina.com>,
// Peter Krusche <pkrusche@illumina.com>
//
// 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 "graphalign/KmerIndexOperations.hh"
#include <list>
#include <boost/algorithm/string.hpp>
#include "graphutils/SequenceOperations.hh"
using std::list;
using std::string;
namespace graphtools
{
list<string> extractKmersFromAllPositions(const string& sequence, int32_t kmer_len)
{
list<string> kmers;
for (size_t pos = 0; pos + kmer_len <= sequence.length(); ++pos)
{
string kmer = sequence.substr(pos, static_cast<std::size_t>(kmer_len));
boost::to_upper(kmer);
kmers.push_back(kmer);
}
return kmers;
}
int32_t countKmerMatches(const KmerIndex& kmer_index, const std::string& seq)
{
const list<string> kmers = extractKmersFromAllPositions(seq, kmer_index.kmerLength());
int32_t num_kmer_matches = 0;
for (const string& kmer : kmers)
{
if (kmer_index.numPaths(kmer) != 0)
{
++num_kmer_matches;
}
}
return num_kmer_matches;
}
bool checkIfForwardOriented(const KmerIndex& kmer_index, const std::string& sequence)
{
const int32_t num_forward_matches = countKmerMatches(kmer_index, sequence);
const int32_t num_revcomp_matches = countKmerMatches(kmer_index, reverseComplement(sequence));
return num_forward_matches >= num_revcomp_matches;
}
/**
* Find minimum kmer length that covers each node with a unique kmer
* @param graph a graph
* @param min_unique_kmers_per_edge min number of unique kmers to cover each edge
* @param min_unique_kmers_per_node min number of unique kmers to cover each node
* @return
*/
int findMinCoveringKmerLength(Graph const* graph, size_t min_unique_kmers_per_edge, size_t min_unique_kmers_per_node)
{
for (int32_t k = 10; k < 64; ++k)
{
KmerIndex index(*graph, k);
bool any_below = false;
for (NodeId node_id = 0; node_id != graph->numNodes(); ++node_id)
{
if (index.numUniqueKmersOverlappingNode(node_id) < min_unique_kmers_per_node)
{
any_below = true;
break;
}
// this will enumerate all edges
for (const auto succ : graph->successors(node_id))
{
if (index.numUniqueKmersOverlappingEdge(node_id, succ) < min_unique_kmers_per_edge)
{
any_below = true;
break;
}
}
if (any_below)
{
break;
}
}
if (any_below)
{
continue;
}
return k;
}
return -1;
}
}
| 29.201754 | 117 | 0.645539 | AlesMaver |
bfbe5bbdba6aea439903878b04d4f033b58c9ac6 | 1,395 | cpp | C++ | beringei/lib/tests/CaseUtilsTest.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 2,780 | 2016-12-22T19:25:26.000Z | 2018-05-21T11:29:42.000Z | beringei/lib/tests/CaseUtilsTest.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 57 | 2016-12-23T09:22:18.000Z | 2018-05-04T06:26:48.000Z | beringei/lib/tests/CaseUtilsTest.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 254 | 2016-12-22T20:53:12.000Z | 2018-05-16T06:14:10.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <gtest/gtest.h>
#include <unordered_map>
#include <folly/String.h>
#include "TestKeyList.h"
#include "beringei/lib/CaseUtils.h"
using namespace ::testing;
using namespace facebook::gorilla;
TEST(CaseUtilsTest, CaseEq) {
CaseEq eq;
EXPECT_TRUE(eq("foo", "FoO"));
EXPECT_TRUE(eq("foo", "foo"));
EXPECT_TRUE(eq("FOO", "foO"));
EXPECT_FALSE(eq("foo", "bar"));
EXPECT_FALSE(eq("foo", "b"));
}
TEST(CaseUtilsTest, CaseHash) {
CaseHash hash;
EXPECT_EQ(hash("foo"), hash("FoO"));
EXPECT_EQ(hash("BaR"), hash("bAr"));
EXPECT_NE(hash("foo"), hash("bar"));
}
const static int kNumHashes = 10000000;
const static int kKeyListSize = 400000;
TEST(CaseUtilsTest, Perf) {
CaseHash hsh;
TestKeyList keyList(kKeyListSize, 10);
size_t x = 0;
for (int i = 0; i < kNumHashes; i++) {
x ^= hsh(keyList.testStr(i));
}
LOG(INFO) << x;
}
TEST(CaseUtilsTest, PerfComparison) {
std::hash<std::string> hsh;
TestKeyList keyList(kKeyListSize);
size_t x = 0;
for (int i = 0; i < kNumHashes; i++) {
x ^= hsh(keyList.testStr(i));
}
LOG(INFO) << x;
}
| 23.644068 | 78 | 0.666667 | pidb |
bfcc3c02ed1648435fe862c9662a3dddf3d13db6 | 10,678 | cpp | C++ | src/NGM.cpp | monsanto-pinheiro/ngmlr | 8d7677929001d1d13c6b4593c409a52044180dca | [
"MIT"
] | 239 | 2017-01-18T15:14:34.000Z | 2022-03-09T10:44:08.000Z | src/NGM.cpp | monsanto-pinheiro/ngmlr | 8d7677929001d1d13c6b4593c409a52044180dca | [
"MIT"
] | 96 | 2017-01-13T15:03:29.000Z | 2022-02-07T14:27:18.000Z | src/NGM.cpp | monsanto-pinheiro/ngmlr | 8d7677929001d1d13c6b4593c409a52044180dca | [
"MIT"
] | 44 | 2017-03-17T20:31:08.000Z | 2021-12-02T07:27:09.000Z | /**
* Contact: philipp.rescheneder@gmail.com
*/
#include "NGM.h"
#include <memory.h>
#include <stdlib.h>
#include <limits.h>
#include "CS.h"
#include "PrefixTable.h"
#include "ReadProvider.h"
#include "PlainFileWriter.h"
#include "SAMWriter.h"
#include "Timing.h"
#include "StrippedSW.h"
#undef module_name
#define module_name "NGM"
_NGM * _NGM::pInstance = 0;
NGMOnceControl _NGM::once_control = NGM_ONCE_INIT;
char const * _NGM::AppName = 0;
namespace __NGM {
inline int min(int a, int b) {
return (a < b) ? a : b;
}
}
void _NGM::Init() {
pInstance = new _NGM();
}
_NGM & _NGM::Instance() {
NGMOnce(&_NGM::once_control, Init);
return *pInstance;
}
_NGM::_NGM() : Stats(new NGMStats()), m_ActiveThreads(0), m_NextThread(0), m_CurStart(0), m_CurCount(0), m_SchedulerMutex(), m_SchedulerWait(), m_TrackUnmappedReads(false), m_UnmappedReads(0), m_MappedReads(0), m_WrittenReads(0), m_ReadReads(0), m_RefProvider(0), m_ReadProvider(0) {
char const * const output_name = Config.getOutputFile();
// if (!Config.getBAM()) {
if (output_name != 0) {
Log.Message("Opening for output (SAM): %s", output_name);
} else {
Log.Message("Writing output (SAM) to stdout");
}
m_Output = new PlainFileWriter(output_name);
// } else {
// if (output_name != 0) {
// Log.Message("Opening for output (BAM): %s", output_name);
// } else {
// Log.Message("Wrinting output (BAM) to stdout");
// }
// m_Output = new FileWriterBam(output_name);
// }
Log.Verbose("NGM Core initialization");
NGMInitMutex(&m_Mutex);
NGMInitMutex(&m_OutputMutex);
NGMInitMutex(&m_UMRMutex);
NGMInitWait(&m_CSWait);
NGMInitMutex(&m_SchedulerMutex);
NGMInitWait(&m_SchedulerWait);
writer = 0;
memset(m_StageThreadCount, 0, cMaxStage * sizeof(int));
memset(m_BlockedThreads, 0, cMaxStage * sizeof(int));
memset(m_ToBlock, 0, cMaxStage * sizeof(int));
}
void _NGM::InitProviders() {
CS::Init();
SequenceProvider.Init(); // Prepares input data
m_RefProvider = new CompactPrefixTable();
m_ReadProvider = new ReadProvider();
uint readCount = m_ReadProvider->init();
}
_NGM::~_NGM() {
delete Stats;
Stats = 0;
if (m_RefProvider != 0)
delete m_RefProvider;
if (m_ReadProvider != 0)
delete m_ReadProvider;
}
void _NGM::StartThread(NGMTask * task, int cpu) {
Log.Verbose("Starting thread %i <%s> on cpu %i", m_NextThread, task->GetName(), cpu);
NGMLock(&m_Mutex);
task->m_TID = m_NextThread;
m_Tasks[m_NextThread] = task;
m_Threads[m_NextThread] = NGMCreateThread(&_NGM::ThreadFunc, task, false);
++m_StageThreadCount[task->GetStage()];
++m_NextThread;
++m_ActiveThreads;
NGMUnlock(&m_Mutex);
}
void * _NGM::getWriter() {
return m_Output;
}
void _NGM::ReleaseWriter() {
if (m_Output != 0) {
// if (!Config.getBAM()) {
delete (FileWriter*) m_Output;
// } else {
// delete (FileWriterBam*) m_Output;
// }
m_Output = 0;
}
}
void _NGM::AddUnmappedRead(MappedRead const * const read, int reason) {
AtomicInc(&m_UnmappedReads);
Log.Debug(LOG_OUTPUT_DETAILS, "Read %s (%i) not mapped (%i)", read->name, read->ReadId, reason);
}
int _NGM::GetUnmappedReadCount() const {
return m_UnmappedReads;
}
void _NGM::AddMappedRead(int readid) {
AtomicInc(&m_MappedReads);
}
int _NGM::GetMappedReadCount() const {
return m_MappedReads;
}
void _NGM::AddWrittenRead(int readid) {
AtomicInc(&m_WrittenReads);
}
int _NGM::GetWrittenReadCount() const {
return m_WrittenReads;
}
void _NGM::AddReadRead(int readid) {
AtomicInc(&m_ReadReads);
}
int _NGM::GetReadReadCount() const {
return m_ReadReads;
}
int _NGM::GetStageThreadCount(int stage) {
NGMLock(&m_Mutex);
int cnt = 0;
for (int i = 0; i <= stage; ++i) {
cnt += m_StageThreadCount[i];
}
NGMUnlock(&m_Mutex);
return cnt;
}
void _NGM::FinishStage(int tid) {
NGMLock(&m_Mutex);
int stage = m_Tasks[tid]->GetStage();
--m_StageThreadCount[stage];
NGMUnlock(&m_Mutex);
Log.Verbose("Thread %i finished its stage (Stage %i, now %i active)", tid, stage, m_StageThreadCount[stage]);
}
void _NGM::FinishThread(int tid) {
AtomicDec(&m_ActiveThreads);
Log.Verbose("Thread %i finished (%i worker threads remaining)", tid, m_ActiveThreads);
m_Tasks[tid]->FinishStage();
delete m_Tasks[tid];
m_Tasks[tid] = 0;
}
bool eof = false;
std::vector<MappedRead*> _NGM::GetNextReadBatch(int desBatchSize) {
NGMLock(&m_Mutex);
std::vector<MappedRead*> list;
desBatchSize &= ~1;
if (m_CurCount == 0) {
m_CurStart = 0;
NGMSignal(&m_CSWait);
}
list.reserve(desBatchSize);
int count = 0;
//Long PacBio reads are split into smaller parts.
//Each part should have its own id.
int idJump = 2000;
int i = 0;
while (count < desBatchSize && !eof) {
MappedRead * read1 = 0;
eof = !NGM.GetReadProvider()->GenerateRead(m_CurStart + i * idJump, read1, 0, read1);
i += 1;
if (!eof) {
if (read1 != 0) {
count += 1;
Stats->readLengthSum += read1->length;
if (read1->group == 0) {
// Short read found: not split into read group
list.push_back(read1);
} else {
// Long read found: push subreads
for (int j = 0; j < read1->group->readNumber; ++j) {
list.push_back(read1->group->reads[j]);
}
}
}
}
}
m_CurStart += count;
m_CurCount -= desBatchSize;
NGMUnlock(&m_Mutex);
#ifdef _DEBUGCS
if(m_CurStart > 100000) {
Log.Warning("Debug CS mode: quitting after 100000 reads!");
list.clear();
}
#endif
return list;
}
NGMTHREADFUNC _NGM::ThreadFunc(void* data) {
NGMTask * task = (NGMTask*) data;
int tid = task->m_TID;
try {
Log.Verbose("Running thread %i", tid);
task->Run();
Log.Verbose("Thread %i run return, finishing", tid);
NGM.FinishThread(tid);
Log.Verbose("Thread %i finished", tid);
} catch (...) {
Log.Error("Unhandled exception in thread %i", tid);
NGM.FinishThread(tid);
}
Log.Verbose("ThreadFunc on thread %i returning", tid);
return 0;
}
void _NGM::InitQuit() {
static int quitState = 0;
++quitState;
if (quitState == 1) {
Log.Warning("Hit 'Q' two more times to quit program.");
} else if (quitState >= 3) {
CleanupPlatform();
Log.Error("Terminate by user request");
Log.Message("%i Threads still active", m_ActiveThreads);
for (int i = 0; i < cMaxStage; ++i) {
if (m_StageThreadCount[i] > 0)
Log.Message("Stage %i got %i threads still running", i, m_StageThreadCount[i]);
}
exit(-1);
}
}
void _NGM::AquireOutputLock() {
NGMLock(&m_OutputMutex);
}
void _NGM::ReleaseOutputLock() {
NGMUnlock(&m_OutputMutex);
}
IRefProvider const * _NGM::GetRefProvider(int const tid) {
return m_RefProvider;
}
IReadProvider * _NGM::GetReadProvider() {
return m_ReadProvider;
}
bool _NGM::ThreadActive(int tid, int stage) {
if (m_ToBlock[stage] > 0) {
NGMLock(&m_SchedulerMutex);
bool blocked = false;
if (m_ToBlock[stage] > 0) {
--m_ToBlock[stage];
blocked = true;
m_BlockedThreads[stage]++;
while (blocked) {
Log.Green("Block %i @ %i", tid, stage);
NGMWait(&m_SchedulerMutex, &m_SchedulerWait);
if (m_ToBlock[stage] < 0) {
++m_ToBlock[stage];
blocked = false;
m_BlockedThreads[stage]--;
Log.Green("Unblock %i @ %i", tid, stage);
}
}
}
NGMUnlock(&m_SchedulerMutex);
}
return true;
}
void _NGM::StopThreads() {
}
void _NGM::StartThreads() {
StartCS(Config.getThreads());
}
void _NGM::StartCS(int cs_threadcount) {
for (int i = 0; i < cs_threadcount; ++i) {
NGMTask * cs = 0;
cs = new CS();
StartThread(cs, -1);
}
}
IAlignment * _NGM::CreateAlignment(int const mode) {
IAlignment * instance = 0;
switch (Config.getSubreadAligner()) {
case 2:
instance = new StrippedSW();
break;
default:
Log.Error("Invalid subread alignerd: %d", Config.getSubreadAligner());
throw "";
}
return instance;
}
void _NGM::DeleteAlignment(IAlignment* instance) {
Log.Verbose("Delete alignment called");
if (instance != 0) {
delete instance;
instance = 0;
}
}
void _NGM::MainLoop() {
Timer tmr;
tmr.ST();
bool const progress = Config.getProgress();
int processed = 0;
float runTime = 0.0f;
float readsPerSecond = 0.0f;
float alignSuccessRatio = 0.0f;
int avgCorridor = 0;
while (Running()) {
Sleep(2000);
if (progress) {
processed = std::max(1, NGM.GetMappedReadCount() + NGM.GetUnmappedReadCount());
runTime = tmr.ET();
readsPerSecond = processed / runTime;
if((NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount) > 0) {
avgCorridor = NGM.Stats->corridorLen / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
alignSuccessRatio = NGM.Stats->alignmentCount * 1.0f / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
}
float avgAlignPerc = 0.0f;
int avgReadLenght = 0;
float alignRate = 0.0f;
if(processed > 0) {
avgAlignPerc = NGM.Stats->avgAlignPerc / std::max(1, NGM.GetMappedReadCount());
avgReadLenght = (int)(NGM.Stats->readLengthSum / processed);
alignRate = NGM.GetMappedReadCount() * 1.0f / processed;
}
Log.Progress("Processed: %d (%.2f), R/S: %.2f, RL: %d, Time: %.2f %.2f %.2f, Align: %.2f, %d, %.2f", processed, alignRate, readsPerSecond, avgReadLenght, NGM.Stats->csTime, NGM.Stats->scoreTime, NGM.Stats->alignTime, alignSuccessRatio, avgCorridor, avgAlignPerc);
}
}
if (progress) {
processed = std::max(1, NGM.GetMappedReadCount() + NGM.GetUnmappedReadCount());
runTime = tmr.ET();
readsPerSecond = processed / runTime;
if((NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount) > 0) {
alignSuccessRatio = NGM.Stats->alignmentCount * 1.0f / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
avgCorridor = NGM.Stats->corridorLen / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
}
float avgAlignPerc = 0.0f;
int avgReadLenght = 0;
float alignRate = 0.0f;
if(processed > 0) {
avgAlignPerc = NGM.Stats->avgAlignPerc / std::max(1, NGM.GetMappedReadCount());
avgReadLenght = (int)(NGM.Stats->readLengthSum / processed);
alignRate = NGM.GetMappedReadCount() * 1.0f / processed;
}
Log.Message("Processed: %d (%.2f), R/S: %.2f, RL: %d, Time: %.2f %.2f %.2f, Align: %.2f, %d, %.2f", processed, alignRate, readsPerSecond, avgReadLenght, NGM.Stats->csTime, NGM.Stats->scoreTime, NGM.Stats->alignTime, alignSuccessRatio, avgCorridor, avgAlignPerc);
}
}
| 24.832558 | 284 | 0.648342 | monsanto-pinheiro |
bfcd50b60d6e0c74def2ebbf04a98a32b10807bf | 4,903 | cpp | C++ | src/managers/framebuffer_manager.cpp | Romop5/holoinjector | db11922e6c57b4664beeec31199385a4877e1619 | [
"MIT"
] | 2 | 2021-04-12T06:09:57.000Z | 2021-05-20T11:56:01.000Z | src/managers/framebuffer_manager.cpp | Romop5/holoinjector | db11922e6c57b4664beeec31199385a4877e1619 | [
"MIT"
] | null | null | null | src/managers/framebuffer_manager.cpp | Romop5/holoinjector | db11922e6c57b4664beeec31199385a4877e1619 | [
"MIT"
] | null | null | null | /*****************************************************************************
*
* PROJECT: HoloInjector - https://github.com/Romop5/holoinjector
* LICENSE: See LICENSE in the top level directory
* FILE: managers/framebuffer_manager.cpp
*
*****************************************************************************/
#define GL_GLEXT_PROTOTYPES 1
#include <GL/gl.h>
#include "context.hpp"
#include "framebuffer_manager.hpp"
#include "pipeline/output_fbo.hpp"
#include "pipeline/viewport_area.hpp"
#include "trackers/framebuffer_tracker.hpp"
#include "utils/opengl_debug.hpp"
#include "utils/opengl_state.hpp"
#include "utils/opengl_utils.hpp"
using namespace hi;
using namespace hi::managers;
void FramebufferManager::clear(Context& context, GLbitfield mask)
{
if (context.m_IsMultiviewActivated && context.getFBOTracker().isFBODefault() && context.getOutputFBO().hasImage())
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
context.getOutputFBO().renderToBackbuffer(context.getCameraParameters());
context.getOutputFBO().clearBuffers();
}
glClear(mask);
}
void FramebufferManager::bindFramebuffer(Context& context, GLenum target, GLuint framebuffer)
{
CLEAR_GL_ERROR();
context.getFBOTracker().bind(framebuffer);
if (framebuffer == 0)
{
if (context.m_IsMultiviewActivated)
{
glBindFramebuffer(target, context.getOutputFBO().getFBOId());
glViewport(0, 0, context.getOutputFBO().getParams().getTextureWidth(), context.getOutputFBO().getParams().getTextureHeight());
}
else
{
glBindFramebuffer(target, 0);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
ASSERT_GL_ERROR();
}
}
else
{
if (context.m_IsMultiviewActivated)
{
auto id = framebuffer;
auto fbo = context.getFBOTracker().getBound();
/*
* Only create & bind shadow FBO when original FBO is complete (thus has any attachment)
*/
if (fbo->hasAnyAttachment())
{
if (!fbo->hasShadowFBO() && context.getFBOTracker().isSuitableForRepeating())
{
fbo->createShadowedFBO(context.getOutputFBO().getParams().getLayers());
if (!fbo->hasShadowFBO())
{
Logger::logError("Failed to create shadow FBO for FBO: ", id, HI_POS);
}
}
// Creation of shadow FBO should never fail
id = (fbo->hasShadowFBO() ? fbo->getShadowFBO() : id);
}
else
{
Logger::logDebug("Missing any attachment for FBOTracker::bind()");
}
glBindFramebuffer(target, id);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
// TODO: shadowed textures are the same size as OutputFBO
/* if(context.m_IsMultiviewActivated) */
/* { */
/* glViewport(0,0,context.getOutputFBO().getParams().getTextureWidth(), context.getOutputFBO().getParams().getTextureHeight()); */
/* } */
}
else
{
glBindFramebuffer(target, framebuffer);
}
}
}
void FramebufferManager::swapBuffers(Context& context, std::function<void(void)> swapit)
{
swapit();
}
void FramebufferManager::renderFromOutputFBO(Context& context)
{
hi::utils::restoreStateFunctor({ GL_CULL_FACE, GL_DEPTH_TEST, GL_SCISSOR_TEST }, [this, &context]() {
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_STENCIL_TEST);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
if (context.m_IsMultiviewActivated && context.getOutputFBO().hasImage())
{
debug::logTrace("Dumping OutputFBO to backbuffer");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
context.getOutputFBO().renderToBackbuffer(context.getCameraParameters());
context.getOutputFBO().clearBuffers();
}
});
}
| 38.606299 | 146 | 0.607995 | Romop5 |
bfcda35f798d306b4537f7d1f1b501ff1af5a884 | 433 | cpp | C++ | test/Vec3Tests.cpp | craft-coder/Softwareentwicklung-2021 | 6c9cf6201b333796a058394c017c8b3e72a3f631 | [
"MIT"
] | null | null | null | test/Vec3Tests.cpp | craft-coder/Softwareentwicklung-2021 | 6c9cf6201b333796a058394c017c8b3e72a3f631 | [
"MIT"
] | null | null | null | test/Vec3Tests.cpp | craft-coder/Softwareentwicklung-2021 | 6c9cf6201b333796a058394c017c8b3e72a3f631 | [
"MIT"
] | 4 | 2021-04-21T13:19:13.000Z | 2021-12-18T20:19:16.000Z | #include "gtest/gtest.h"
#include "Vec3.h"
TEST(Vec3, DefaultConstructor_XisZero) {
raytracer::Vec3 vec{};
double x = vec.x();
EXPECT_NEAR(x, 0.0, 0.00001);
}
TEST(Vec3, DefaultConstructor_YisZero) {
raytracer::Vec3 vec{};
double y = vec.y();
EXPECT_NEAR(y, 0.0, 0.00001);
}
TEST(Vec3, DefaultConstructor_ZisZero) {
raytracer::Vec3 vec{};
double z = vec.z();
EXPECT_NEAR(z, 0.0, 0.00001);
}
| 18.041667 | 40 | 0.630485 | craft-coder |
bfd0133a1aaf2601faa26d94b1f7a79c3f4146ff | 72 | cpp | C++ | Algorithmns/gcd.cpp | waba359/VAULT | 5680882f76848f3df19a2f86b55eece5ae9df20f | [
"CC0-1.0"
] | 1 | 2019-12-27T04:06:31.000Z | 2019-12-27T04:06:31.000Z | Algorithmns/gcd.cpp | waba359/VAULT | 5680882f76848f3df19a2f86b55eece5ae9df20f | [
"CC0-1.0"
] | null | null | null | Algorithmns/gcd.cpp | waba359/VAULT | 5680882f76848f3df19a2f86b55eece5ae9df20f | [
"CC0-1.0"
] | null | null | null | ll gcd(ll m, ll n){
if(n == 0) return m;
return gcd(n, m%n);
}
| 14.4 | 25 | 0.472222 | waba359 |
bfd5b33b318b4966638c44135a5aa058c92d3199 | 2,586 | cpp | C++ | writesinglecoildialog.cpp | tonylin0826/ModbusMasterTool | d751126ac4937838660f2684e16c7c04d66481d8 | [
"MIT"
] | null | null | null | writesinglecoildialog.cpp | tonylin0826/ModbusMasterTool | d751126ac4937838660f2684e16c7c04d66481d8 | [
"MIT"
] | null | null | null | writesinglecoildialog.cpp | tonylin0826/ModbusMasterTool | d751126ac4937838660f2684e16c7c04d66481d8 | [
"MIT"
] | null | null | null | #include "writesinglecoildialog.hpp"
#include <QIntValidator>
#include "mainwindow.hpp"
#include "ui_writesinglecoildialog.h"
WriteSingleCoilDialog::WriteSingleCoilDialog(QWidget *parent, quint16 startingAddress)
: QDialog(parent), _ui(new Ui::WriteSingleCoilDialog), _onOffGroup(new QButtonGroup(this)) {
_setupUI(startingAddress);
}
WriteSingleCoilDialog::~WriteSingleCoilDialog() { delete _ui; }
void WriteSingleCoilDialog::on_btnCancel_clicked() { close(); }
void WriteSingleCoilDialog::on_btnSend_clicked() {
if (_ui->inputAddress->text().isEmpty() || _ui->inputSlaveId->text().isEmpty()) {
return;
}
const auto address = _ui->inputAddress->text().toUShort();
const auto slaveId = _ui->inputSlaveId->text().toUShort();
const auto on = _onOffGroup->checkedId() == 1;
const auto modbus = qobject_cast<MainWindow *>(parentWidget())->modbus();
if (!modbus) {
_ui->labelStatus->setText("Failed - Modbus not connected");
_ui->labelStatus->setStyleSheet("QLabel { color : Crimson; }");
return;
}
const auto reply = modbus->sendWriteRequest(
QModbusDataUnit(QModbusDataUnit::RegisterType::Coils, address, QVector<quint16>({on})), slaveId);
if (!reply) {
_ui->labelStatus->setText("Failed - No reply");
_ui->labelStatus->setStyleSheet("QLabel { color : Crimson; }");
return;
}
if (reply->isFinished()) {
delete reply;
return;
}
_ui->labelStatus->setText("Sending");
_ui->labelStatus->setStyleSheet("QLabel { color : DodgerBlue; }");
QObject::connect(reply, &QModbusReply::finished, [=]() {
if (reply->error() != QModbusDevice::NoError) {
_ui->labelStatus->setText(QString("Failed - %1(code: %2)")
.arg(reply->errorString(), QString::number(reply->rawResult().exceptionCode())));
_ui->labelStatus->setStyleSheet("QLabel { color : Crimson; }");
delete reply;
return;
}
_ui->labelStatus->setText("Success");
_ui->labelStatus->setStyleSheet("QLabel { color : Chartreuse; }");
delete reply;
});
}
void WriteSingleCoilDialog::_setupUI(quint16 startingAddress) {
setAttribute(Qt::WA_DeleteOnClose);
_ui->setupUi(this);
setWindowTitle("Write Single Coil");
_ui->inputAddress->setValidator(new QIntValidator(0, 65535, this));
_ui->inputAddress->setText(QString::number(startingAddress));
_ui->inputSlaveId->setText("1");
_ui->inputSlaveId->setValidator(new QIntValidator(0, 255, this));
_onOffGroup->addButton(_ui->btnOff, 0);
_onOffGroup->addButton(_ui->btnOn, 1);
_ui->btnOn->setChecked(true);
}
| 31.925926 | 117 | 0.686775 | tonylin0826 |
bfdd440d5a33f15bffd244b332ee184245e3573f | 1,884 | cpp | C++ | node_modules/nodeimu/RTIMULib2/RTHost/RTIMULibGL/QtGLLib/QtGLPlaneComponent.cpp | RGUCode/pi-sensor | c5219abc3a7557c44bce4f7f8f909fffa00ef071 | [
"MIT"
] | null | null | null | node_modules/nodeimu/RTIMULib2/RTHost/RTIMULibGL/QtGLLib/QtGLPlaneComponent.cpp | RGUCode/pi-sensor | c5219abc3a7557c44bce4f7f8f909fffa00ef071 | [
"MIT"
] | 1 | 2020-07-16T19:00:53.000Z | 2020-07-16T19:00:53.000Z | node_modules/nodeimu/RTIMULib2/RTHost/RTIMULibGL/QtGLLib/QtGLPlaneComponent.cpp | RGUCode/pi-sensor | c5219abc3a7557c44bce4f7f8f909fffa00ef071 | [
"MIT"
] | 1 | 2019-03-23T10:00:55.000Z | 2019-03-23T10:00:55.000Z | ////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULib
//
// Copyright (c) 2014, richards-tech
//
// 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 "QtGL.h"
QtGLPlaneComponent::QtGLPlaneComponent()
{
}
QtGLPlaneComponent::~QtGLPlaneComponent()
{
}
void QtGLPlaneComponent::generate(float width, float height)
{
static const float coords[4][2] = {{+0.5f, +0.5f}, {-0.5f, +0.5f}, {-0.5f, -0.5f}, {+0.5f, -0.5f}};
reset();
for (int vert = 0; vert < 4; vert++) {
addTextureCoord(QVector2D(vert == 0 || vert == 3, vert == 0 || vert == 1));
addVertex(QVector3D(width * coords[vert][0], height * coords[vert][1], 0));
}
}
void QtGLPlaneComponent::draw()
{
QtGLComponent::draw(GL_TRIANGLE_FAN);
}
| 36.941176 | 104 | 0.657113 | RGUCode |
bfde6ea67dba61936ee0963ed6f96a32c9adbf84 | 1,241 | cpp | C++ | CPP, C++ Solutions/64. Minimum Path Sum.cpp | arpitkekri/My-Leetcode-Solution-In-CPP | 345f1c53c627fce33ee84672c5d3661863367040 | [
"MIT"
] | 4 | 2021-06-21T04:32:12.000Z | 2021-11-02T04:20:36.000Z | CPP, C++ Solutions/64. Minimum Path Sum.cpp | arpitkekri/My-Leetcode-Solution-In-CPP | 345f1c53c627fce33ee84672c5d3661863367040 | [
"MIT"
] | null | null | null | CPP, C++ Solutions/64. Minimum Path Sum.cpp | arpitkekri/My-Leetcode-Solution-In-CPP | 345f1c53c627fce33ee84672c5d3661863367040 | [
"MIT"
] | 2 | 2021-08-19T11:27:18.000Z | 2021-09-26T14:51:30.000Z | /*********** Method-1(TC - O(NM), SC - O(NM)) **************************************
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m+1, vector<int>(n+1, INT_MAX));
for(int i = m-1; i >= 0; i--) {
for(int j = n-1; j >= 0; j--) {
if(min(dp[i+1][j], dp[i][j+1]) == INT_MAX)
dp[i][j] = grid[i][j];
else
dp[i][j] = grid[i][j] + min(dp[i+1][j], dp[i][j+1]);
}
}
return dp[0][0];
}
};
***********************************************************************************/
/**********************Method-2 (TC-O(NM), SC-O(N))**************************************/
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> dp(n+1, INT_MAX);
// Base case
dp[n-1] = 0;
// Bottom to Top, R to L
for(int i = m-1; i >= 0; i--)
for(int j = n-1; j >= 0; j--)
dp[j] = grid[i][j] + min(dp[j], dp[j+1]);
return dp[0];
}
}; | 30.268293 | 90 | 0.33199 | arpitkekri |
bfe3422c9f0d9f28a4a0468c73ae125920403fe9 | 4,273 | cpp | C++ | Samples/Unicode/cppwinrt/Scenario1_FindId.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,504 | 2019-05-07T06:56:42.000Z | 2022-03-31T19:37:59.000Z | Samples/Unicode/cppwinrt/Scenario1_FindId.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 314 | 2019-05-08T16:56:30.000Z | 2022-03-21T07:13:45.000Z | Samples/Unicode/cppwinrt/Scenario1_FindId.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,219 | 2019-05-07T00:47:26.000Z | 2022-03-30T21:12:31.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario1_FindId.h"
#include "Scenario1_FindId.g.cpp"
#include <sstream>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Data::Text;
using namespace Windows::UI::Xaml;
namespace
{
// This is a helper method that an app could create to find one or all available
// ids within a string. An id begins with a character for which IsIdStart,
// and continues with characters that are IsIdContinue. Invalid sequences are ignored.
std::vector<std::wstring> FindIdsInString(std::wstring_view const& inputString)
{
// Vector where we maintain the ids found in the input string
std::vector<std::wstring> idList;
// Maintains the beginning index of the id found in the input string
size_t indexIdStart = std::wstring_view::npos;
// Iterate through each of the characters in the string
size_t i = 0;
while (i < inputString.size())
{
size_t nextIndex;
uint32_t codepoint = inputString[i];
if (UnicodeCharacters::IsHighSurrogate(codepoint))
{
// If the character is a high surrogate, then the next characters must be a low surrogate.
if ((i < inputString.size()) && (UnicodeCharacters::IsLowSurrogate(inputString[i + 1])))
{
// Update the code point with the surrogate pair.
codepoint = UnicodeCharacters::GetCodepointFromSurrogatePair(codepoint, inputString[i + 1]);
nextIndex = i + 2;
}
else
{
// Warning: High surrogate not followed by low surrogate.
codepoint = 0;
nextIndex = i + 1;
}
}
else
{
// Not a surrogate pair.
nextIndex = i + 1;
}
if (indexIdStart == std::wstring_view::npos)
{
// Not in an id. Have we found an id start?
if (UnicodeCharacters::IsIdStart(codepoint))
{
indexIdStart = i;
}
}
else if (!UnicodeCharacters::IsIdContinue(codepoint))
{
// We have not found an id continue, so the id is complete. We need to
// create the identifier string
idList.emplace_back(inputString.substr(indexIdStart, i - indexIdStart));
// Reset back the index start and re-examine the current code point
// in next iteration
indexIdStart = std::wstring::npos;
nextIndex = i;
}
i = nextIndex;
}
// Do we have a pending id at the end of the string?
if (indexIdStart != std::wstring_view::npos)
{
// We need to create the identifier string
idList.emplace_back(inputString.substr(indexIdStart, i - indexIdStart));
}
// Return the list of identifiers found in the string
return idList;
}
}
namespace winrt::SDKTemplate::implementation
{
Scenario1_FindId::Scenario1_FindId()
{
InitializeComponent();
}
void Scenario1_FindId::Default_Click(IInspectable const&, RoutedEventArgs const&)
{
std::wstringstream result;
bool first = true;
for (auto id : FindIdsInString(TextInput().Text()))
{
if (!first)
{
result << L", ";
}
first = false;
result << id;
}
TextOutput().Text(result.str());
}
}
| 34.739837 | 113 | 0.532179 | dujianxin |
bfefb2d820718c89ee8b6674b9b43b9655a2308c | 12,264 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/detail/graphics_impl.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/detail/graphics_impl.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/detail/graphics_impl.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null |
namespace svl {
namespace graphics
{
pen::pen(color colour)
: pen_( win32::create_pen(PS_SOLID, 1, win32::rgb_from_color(colour) ))
{}
pen::pen(color colour, unsigned width)
: pen_( win32::create_pen(PS_SOLID, static_cast<int>(width), win32::rgb_from_color(colour) ))
{}
pen::pen(pen const& other)
: pen_( other.pen_ )
{}
pen& pen::operator = (pen const& other)
{
pen_ = other.pen_;
return *this;
}
pen::~pen()
{}
HPEN pen::win32_handle() const
{
return pen_;
}
pen::pen(HPEN hpen, win32::system_object_t)
: pen_( hpen, win32::system_object )
{}
/*----------------------------------------------------------------------*/
brush::brush(color colour)
: brush_( win32::create_solid_brush( win32::rgb_from_color(colour) ))
{}
brush::brush(brush const& other)
: brush_( other.brush_ )
{}
brush& brush::operator = (brush const& other)
{
brush_ = other.brush_;
return *this;
}
HBRUSH brush::win32_handle() const
{
return brush_;
}
brush::~brush()
{}
brush::brush(HBRUSH hbrush, win32::system_object_t)
: brush_( hbrush, win32::system_object )
{}
brush const brush::transparent = brush( win32::get_stock_object<HBRUSH>(HOLLOW_BRUSH), win32::system_object );
/*----------------------------------------------------------------------*/
font::font(str_ref name, int height, unsigned styles)
: font_( create_font( name, height, styles ))
{}
font::font(font const& other)
: font_( other.font_ )
{}
font& font::operator = (font const& other)
{
font_ = other.font_;
return *this;
}
HFONT font::create_font(str_ref name, int height, unsigned styles)
{
HFONT hfont = SVL_MS(CreateFont)(
/* nHeight */ height,
/* nWidth */ 0,
/* nEscapement */ 0,
/* nOrientation */ 0,
/* fnWeight */ (styles & font::bold) ? FW_BOLD : FW_NORMAL,
/* fdwItalic */ (styles & font::italic) ? TRUE : FALSE,
/* fdwUnderline */ (styles & font::underline) ? TRUE : FALSE,
/* fdwStrikeOut */ FALSE,
/* fdwCharSet */ ANSI_CHARSET,
/* fdwOutputPrecision */ OUT_DEFAULT_PRECIS,
/* fdwClipPrecision */ CLIP_DEFAULT_PRECIS,
/* fdwQuality */ DEFAULT_QUALITY,
/* fdwPitchAndFamily */ DEFAULT_PITCH,
/* lpszFace */ name.data());
if (hfont == 0)
throw win32_error( "CreateFont" );
return hfont;
}
HFONT font::win32_handle() const
{
return font_;
}
font::~font()
{}
font::font(HFONT hfont, win32::system_object_t)
: font_( hfont, win32::system_object )
{}
font const font::def = font( win32::get_stock_object<HFONT>(DEFAULT_GUI_FONT), win32::system_object );
/*----------------------------------------------------------------------*/
edge::edge(border::type outer, border::type inner, unsigned lines)
: borders_( outer | +inner << 2 )
, lines_( lines )
{}
edge::border::type edge::outer() const
{
return static_cast<border::type>( borders_ & 0x03 );
}
edge::border::type edge::inner() const
{
return static_cast<border::type>( borders_ >> 2 );
}
unsigned edge::lines() const
{
return lines_;
}
unsigned edge::borders() const
{
return borders_;
}
edge edge::none = edge( edge::border::none );
edge edge::bump = edge( edge::border::raised, edge::border::sunken );
edge edge::etched = edge( edge::border::sunken, edge::border::raised );
edge edge::raised = edge( edge::border::raised, edge::border::raised );
edge edge::sunken = edge( edge::border::sunken, edge::border::sunken );
/*----------------------------------------------------------------------*/
painting::painting()
: def_pen_ ( 0 )
, cur_pen_ ( 0 )
, def_brush_( 0 )
, cur_brush_( 0 )
, def_font_ ( 0 )
, cur_font_ ( 0 )
{
SVL_IN_DEBUG_2( hdc_ = 0; )
}
painting::~painting()
{
SVL_ASSERT_2( hdc_ == 0 );
}
void painting::open( HDC hdc ) // throw()
{
SVL_ASSERT_2( hdc_ == 0 );
hdc_ = hdc;
}
void painting::close() // throw()
{
if (def_pen_ != 0)
win32::select_object<std::nothrow_t>( hdc_, def_pen_ );
if (def_brush_ != 0)
win32::select_object<std::nothrow_t>( hdc_, def_brush_ );
if (def_font_ != 0)
win32::select_object<std::nothrow_t>( hdc_, def_font_ );
SVL_IN_DEBUG_2( hdc_ = 0; )
}
void painting::select(pen const& p)
{
HPEN hpen = p.win32_handle();
if (hpen != cur_pen_)
{
HGDIOBJ prev = win32::select_object( hdc_, hpen );
cur_pen_ = hpen;
if (def_pen_ == 0)
def_pen_ = prev;
}
}
void painting::select(brush const& b)
{
HBRUSH hbrush = b.win32_handle();
if (hbrush != cur_brush_)
{
HGDIOBJ prev = win32::select_object( hdc_, hbrush );
cur_brush_ = hbrush;
if (def_brush_ == 0)
def_brush_ = prev;
}
}
void painting::select(font const& f)
{
HFONT hfont = f.win32_handle();
if (hfont != cur_font_)
{
HGDIOBJ prev = win32::select_object( hdc_, hfont );
cur_font_ = hfont;
if (def_font_ == 0)
def_font_ = prev;
}
}
HDC painting::win32_handle() const
{
return hdc_;
}
void painting::draw_pixel(point const& p, color c)
{
::SetPixel( hdc_, p.x, p.y, win32::rgb_from_color(c) );
}
void painting::move_to(point const& pos)
{
SVL_VERIFY( ::MoveToEx( hdc_, pos.x, pos.y, 0 ), != 0 );
}
void painting::draw_line_to(point const& pos, pen const& p)
{
select( p );
SVL_VERIFY( ::LineTo( hdc_, pos.x, pos.y ), != 0 );
}
void painting::draw_line(point const& from, point const& to, pen const& p)
{
move_to( from );
draw_line_to( to, p );
}
void painting::draw_rectangle(rect2 const& r, brush const& b)
{
RECT R = win32::from_rect2( r );
SVL_VERIFY( ::FillRect( hdc_, &R, b.win32_handle() ), != 0 );
}
void painting::draw_rectangle(rect2 const& r, pen const& p, brush const& b)
{
select( p );
select( b );
SVL_VERIFY( ::Rectangle( hdc_, r.x0, r.y0, r.x1, r.y1 ), != 0 );
}
void painting::draw_round_rect(rect2 const& r, size const& ell_sz, pen const& p, brush const& b)
{
select( p );
select( b );
SVL_VERIFY( ::RoundRect( hdc_, r.x0, r.y0, r.x1, r.y1, ell_sz.dx, ell_sz.dy ), != 0 );
}
void painting::draw_ellipse(rect2 const& r, pen const& p, brush const& b)
{
select( p );
select( b );
SVL_VERIFY( ::Ellipse( hdc_, r.x0, r.y0, r.x1, r.y1 ), != 0 );
}
void painting::draw_pie( rect2 const& r, point const& p0, point const& p1, pen const& p, brush const& b )
{
select( p );
select( b );
SVL_VERIFY( ::Pie( hdc_, r.x0, r.y0, r.x1, r.y1, p0.x, p0.y, p1.x, p1.y ), != 0 );
}
point painting::draw_text(str_ref str, point const& p, font const& f, color text_color, color back_color)
{
select( f );
SVL_VERIFY( ::SetTextAlign( hdc_, TA_LEFT | TA_TOP | TA_UPDATECP ), != GDI_ERROR );
SVL_VERIFY( ::SetTextColor( hdc_, win32::rgb_from_color(text_color)), != CLR_INVALID );
if (back_color.argb() == color::transparent)
{
SVL_VERIFY( ::SetBkMode( hdc_, TRANSPARENT ), != 0 );
}
else
{
SVL_VERIFY( ::SetBkColor( hdc_, win32::rgb_from_color(back_color) ), != CLR_INVALID );
SVL_VERIFY( ::SetBkMode( hdc_, OPAQUE ), != 0 );
}
SVL_VERIFY( ::MoveToEx( hdc_, p.x, p.y, 0 ), != 0 );
SVL_VERIFY( SVL_MS(TextOut)( hdc_, 0, 0, str.data(), static_cast<int>(str.size()) ), != 0 );
POINT P;
SVL_VERIFY( ::MoveToEx( hdc_, 0, 0, &P ), != 0 );
return win32::to_point( P );
}
void painting::draw_text(str_ref str, rect2 const& r, text::format frmt, font const& f, color text_color, color back_color)
{
select( f );
SVL_VERIFY( ::SetTextAlign( hdc_, TA_LEFT | TA_TOP | TA_NOUPDATECP ), != GDI_ERROR );
SVL_VERIFY( ::SetTextColor( hdc_, win32::rgb_from_color(text_color)), != CLR_INVALID );
if (back_color.argb() == color::transparent)
{
SVL_VERIFY( ::SetBkMode( hdc_, TRANSPARENT ), != 0 );
}
else
{
SVL_VERIFY( ::SetBkColor( hdc_, win32::rgb_from_color(back_color) ), != CLR_INVALID );
SVL_VERIFY( ::SetBkMode( hdc_, OPAQUE ), != 0 );
}
RECT R = win32::from_rect2( r );
SVL_MS(DrawText)( hdc_, str.data(), static_cast<int>( str.size() ), &R, frmt );
}
void painting::draw(edge e, rect2 const& r)
{
RECT R = win32::from_rect2( r );
SVL_VERIFY( ::DrawEdge( hdc_, &R, e.borders(), e.lines() ), != 0 );
}
void painting::draw(image const& img, point const& p)
{
draw( img, p, rect(point(0,0), img.size()) );
}
void painting::draw(image const& img, point const& p, rect const& r)
{
win32::compatible_dc mem_dc( win32_handle() );
HGDIOBJ def_bitmap = win32::select_object( mem_dc.handle(), img.win32_handle() );
SVL_VERIFY( ::BitBlt( win32_handle(), p.x, p.y, r.dx, r.dy, mem_dc.handle(), r.x, r.y, SRCCOPY ), != 0 );
win32::select_object<std::nothrow_t>( mem_dc.handle(), def_bitmap );
}
/*----------------------------------------------------------------------*/
canvas::canvas(window& wnd)
{
hwnd_ = wnd.win32_handle();
HDC hdc = wnd.get_env().device_contexts.find( wnd );
own_ = hdc == 0;
if (own_)
hdc = win32::dc::get( hwnd_ );
open( hdc );
}
canvas::~canvas()
{
HDC hdc = win32_handle();
close();
if (own_)
win32::dc::release( hwnd_, hdc );
}
/*----------------------------------------------------------------------*/
image::image( svl::size const& sz)
: bitmap_( 0, win32::system_object )
, size_ ( sz )
{
resize( sz );
}
image::~image()
{}
size image::size() const
{
return size_;
}
void image::resize(svl::size const& sz)
{
if ( 0 < sz.dx && 0 < sz.dy )
{
win32::dc dc( svl::detail::env::shared_instance()->sys_window );
win32::gdi_object<HBITMAP> new_bitmap(
win32::create_compatible_bitmap(dc.handle(), sz.dx, sz.dy )
);
bitmap_.swap( new_bitmap );
size_ = sz;
}
else
{
win32::gdi_object<HBITMAP> empty_bitmap( 0, win32::system_object );
bitmap_.swap( empty_bitmap );
size_ = svl::size( 0, 0 );
}
}
HBITMAP image::win32_handle() const
{
return bitmap_;
}
/*----------------------------------------------------------------------*/
image_canvas::image_canvas(image& img)
: bitmap_( img.bitmap_ )
{
win32::dc dc( svl::detail::env::shared_instance()->sys_window );
win32::compatible_dc mem_dc( dc.handle() );
open( mem_dc.handle() );
def_bitmap_ = win32::select_object( mem_dc.handle(), bitmap_ );
mem_dc.detach();
}
image_canvas::~image_canvas()
{
HDC hdc = win32_handle();
close();
win32::select_object<std::nothrow_t>( hdc, def_bitmap_ );
win32::compatible_dc::delete_dc( hdc );
}
/*----------------------------------------------------------------------*/
image& buffered_canvas::shared_image()
{
return svl::detail::env::shared_instance()->shared_image;
}
image& buffered_canvas::widen(image& img, size const& sz)
{
size img_size = img.size();
if (img_size.dx < sz.dx || img_size.dy < sz.dy)
{
img_size = size(
(std::max)(img_size.dx, sz.dx),
(std::max)(img_size.dy, sz.dy)
);
img.resize( img_size );
}
return img;
}
buffered_canvas::buffered_canvas(window& w, image& img)
: size_( w.size() )
, bitmap_( widen( img, size_ ).bitmap_ )
, hwnd_( w.win32_handle() )
{
wnd_hdc_ = w.get_env().device_contexts.find( w );
own_ = wnd_hdc_ == 0;
if (own_)
wnd_hdc_ = win32::dc::get( hwnd_ );
try
{
win32::compatible_dc mem_dc( wnd_hdc_ );
open( mem_dc.handle() );
def_bitmap_ = win32::select_object( mem_dc.handle(), bitmap_ );
mem_dc.detach();
}
catch (...)
{
if (own_)
win32::dc::release( hwnd_, wnd_hdc_ );
throw;
}
}
buffered_canvas::~buffered_canvas()
{
try
{
flush();
}
catch (...)
{
SVL_ASSERT_FALSE();
}
HDC mem_hdc = win32_handle();
close();
win32::select_object<std::nothrow_t>( mem_hdc, def_bitmap_ );
win32::compatible_dc::delete_dc( mem_hdc );
if (own_)
win32::dc::release( hwnd_, wnd_hdc_ );
}
void buffered_canvas::flush()
{
SVL_VERIFY( ::BitBlt( wnd_hdc_, 0, 0, size_.dx, size_.dy, win32_handle(), 0, 0, SRCCOPY ), != 0 );
}
void buffered_canvas::fill_window_area(brush const& b)
{
draw_rectangle( rect2(0, 0, size_.dx, size_.dy), b );
}
void buffered_canvas::fill_window_area()
{
HBRUSH hbrush = reinterpret_cast<HBRUSH>(
SVL_MS(GetClassLongPtr)( hwnd_, GCLP_HBRBACKGROUND )
);
if (hbrush != 0)
fill_window_area( brush(hbrush, win32::system_object) );
}
}}
| 23.584615 | 124 | 0.595401 | yklishevich |
bff0487727502bcf7237bc13320e3f364972bf26 | 23,065 | cpp | C++ | sources/libcpp83gts_callback_and_action/cb_trace_files.cpp | Savraska2/GTS | 78c8b4d634f1379eb3e33642716717f53bf7e1ad | [
"BSD-3-Clause"
] | 61 | 2016-03-26T03:04:43.000Z | 2021-09-17T02:11:18.000Z | sources/libcpp83gts_callback_and_action/cb_trace_files.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 92 | 2016-04-10T23:40:22.000Z | 2022-03-11T21:49:12.000Z | sources/libcpp83gts_callback_and_action/cb_trace_files.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 18 | 2016-03-26T11:19:14.000Z | 2021-08-07T00:26:02.000Z | #include <cstdio> // std::rename(-)
#include <iostream> // std::cout
#include <sstream> // std::ostringstream
#include <iomanip> // std::setfill(-) ,std::setw(-)
#include <FL/fl_ask.H> // fl_alert(-) fl_input(-)
#include "pri.h"
#include "ptbl_returncode.h"
#include "osapi_exist.h"
#ifdef _WIN32
#include "osapi_mbs_wcs.h" // osapi::cp932_from_utf8(-)
#endif
#include "ids_path_fltk_native_browse.h"
#ifdef _WIN32
#include "wincom_native_browse_directory.h"
#endif
#include "ids_path_level_from_files.h"
#include "cb_trace_files.h"
#include "gts_gui.h"
#include "gts_master.h"
//----------------------------------------------------------------------
/* 2値化処理実行 */
int cb_trace_files::read_and_save_crnt_(
const int file_num
,const int list_num
)
{
/* 表示:リストを対象項目が見える場所にスクロール */
cl_gts_gui.selbro_number_list->middleline(list_num);
/* 読込:番号に対するファイルパスを得る */
std::string fpath_open( this->get_open_path(file_num) );
if (fpath_open.empty()) {
pri_funct_err_bttvr(
"Error : this->get_open_path(%d) returns nullptr"
, file_num
);
return NG;
}
/* 読込:ファイルがあるかチェック */
if ( osapi::exist_utf8_mbs( fpath_open ) == false ) {
pri_funct_msg_ttvr(
"Error : Not exist \"%s\"",fpath_open.c_str());
return NG;
}
/* 読込:ファイルパスを設定 */
if (cl_gts_master.cl_iip_read.cl_name.set_name(fpath_open.c_str())
!= OK) {
pri_funct_err_bttvr(
"Error : cl_gts_master.cl_iip_read.cl_name.set_name(%s) returns NG",
fpath_open.c_str());
return NG;
}
/* 読込 */
if (cl_gts_master.cl_iip_read.file() != OK) {
pri_funct_err_bttvr(
"Error : cl_gts_master.cl_iip_read.file() returns NG" );
return NG;
}
/* 読込:画像はフルカラーであること */
if (cl_gts_master.cl_iip_read.get_l_channels() < 3) {
pri_funct_err_bttvr(
"Error : cl_gts_master.cl_iip_read.get_l_channels() is less than 3" );
return NG;
}
/* Crop以外の画像表示をした場合 */
cl_gts_master.cl_area_and_rot90.reset_dpi_to_zero_by_scan_or_preview();
/* 処理:Rot90 and Effects(color Trace and Erase color dot noise) */
if (cl_gts_master.rot_and_trace_and_enoise(
&(cl_gts_master.cl_iip_read)
,0 /* 画像コンバート処理のみで、回転はしない */
) != OK) {
return NG;
}
/* 保存:番号に対するファイルパスを得る */
std::string fpath_save( this->get_save_path(file_num) );
if (fpath_save.empty()) {
pri_funct_err_bttvr(
"Error : this->get_save_path(%d) returns empty"
, file_num
);
return NG;
}
/* 保存 */
if (OK != cl_gts_master.iipg_save(
&(cl_gts_master.cl_iip_trac)
, const_cast<char *>(fpath_save.c_str())
, cl_gts_master.cl_iip_read.get_d_tif_dpi_x()
/* rot90実行後なので(デフォルト)0度とする */
/* (デフォルト)なしとする、
&(cl_gts_master.cl_iip_read)は参照しない */
)) {
pri_funct_err_bttvr(
"Error : cl_gts_master.iipg_save(-) returns NG" );
return NG;
}
/* 表示:リストにマーク付いていなければ付ける */
cl_gts_master.cl_number.add_S( list_num );
/* 表示:リストの選択解除 */
cl_gts_master.cl_number.unselect(list_num);
/* 表示:画像の再表示 */
if (cl_gts_master.redraw_image(
&(cl_gts_master.cl_iip_read)
, false /* crop sw */
, false /* force view scanimage sw */
)) {
return NG;
}
/* 表示:保存するタイプで画像を表示する */
if ( cl_gts_gui.chkbtn_trace_filter_trace_sw->value() ) {
/* TracenImage画像のみ表示 */
cl_gts_master.cb_change_wview_sub();
/* 画像表示状態をメニューに設定 */
cl_gts_gui.menite_wview_sub->setonly();
}
else {
/* ScanImage(メイン)画像のみ表示 */
cl_gts_master.cb_change_wview_main();
/* 画像表示状態をメニューに設定 */
cl_gts_gui.menite_wview_main->setonly();
}
return OK;
}
int cb_trace_files::cb_start( const bool interactive_sw )
{
if ( !cl_gts_master.cl_number.is_trace() ) {
fl_alert("Set Number for Trace");
return OK;
}
/* チェック:開くファイルのLevel名がない */
{
std::string name(cl_gts_gui.strinp_trace_open_file_head->value());
if ( name.empty() ) {
fl_alert("Need Trace Open Name!");
return NG;
}
}
/* チェック:保存ファイルのLevel名がない */
{
std::string name(cl_gts_gui.strinp_trace_save_file_head->value());
if ( name.empty() ) {
fl_alert("Need Trace Save Name!");
return NG;
}
}
/* チェック:開くファイル名がない */
if (this->get_open_path(0).empty()) {
fl_alert("Check Open Folder and File name!");
return NG;
}
/* チェック:保存ファイル名がない */
if (this->get_save_path(0).empty()) {
fl_alert("Check Save Folder and File name!");
return NG;
}
/* 順送り(start <= end)の初期位置 */
cb_number &cl_num = cl_gts_master.cl_number;
int list_num = cl_num.next_selected_list_num(1);
/* チェック:番号選択がない */
if (list_num < 1) {
fl_alert("Select Number!");
return NG;
}
/* 順送り(start <= end)の初期番号 */
int file_num = cl_num.file_num_from_list_num(list_num);
/* 実行確認 */
if (interactive_sw) {
const bool tsw =
cl_gts_gui.chkbtn_trace_filter_trace_sw->value() != 0;
const bool esw =
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->value() != 0;
if (fl_ask(
"%s%s\n%s\n-->\n%s\n..."
,tsw ?"Trace" :"Not trace"
,esw ?" and Erase Dot Noise" :""
,this->get_open_path(file_num).c_str()
,this->get_save_path(file_num).c_str()
) != 1) {
return OK; // Cancel
}
}
while (1 <= list_num) {
/* カレントの読み込みと処理と保存をして */
if (OK != this->read_and_save_crnt_( file_num ,list_num )) {
pri_funct_err_bttvr(
"Error : this->read_and_save_crnt_() returns NG" );
return NG;
}
/* 次を得る */
list_num = cl_num.next_selected_list_num( list_num + 1 );
file_num = cl_num.file_num_from_list_num( list_num );
Fl::check();
const int ekey = Fl::event_key();
/* FL_Escapeと'q'と't'は効かない */
//if (FL_Escape == ekey) {
//if ('q' == ekey) {
//if ('t' == ekey) { /* Tで開始し、tで終る */
if ('e' == ekey) {
break;
}
}
return OK;
}
//----------------------------------------------------------------------
/* rename/renumber処理実行 */
void cb_trace_files::cb_rename(void)
{
/* Openファイルのフルパスを得る */
const std::string filepath = this->get_open_path( 1 );
if (filepath.empty()) {
fl_alert( "Not set Open Folder or File name" );
return;
}
/* 連番ファイルの存在チェックして必要な情報に変える */
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
if (head.empty() || nums.size() <= 0) {
fl_alert( "Not exist files" );
return;
}
std::ostringstream numost;
for (auto nu : nums) {
numost << nu;
numost << " ";
}
/* ユーザーから新しい名前を得る */
const char* new_head_ptr = fl_input(
"Enter New Level Name" ,head.c_str()
);
if (new_head_ptr == nullptr || head == new_head_ptr ) {
return; /* Cancel or 同じ名前なら何もしない */
}
const std::string new_head(new_head_ptr);
/* ファイル毎名前を変更する */
for (size_t ii=0; ii<nums.size() ; ++ii) {
std::string opa( this->get_open_path( nums.at(ii) ) );
std::string npa( this->get_open_path_from_head_and_number_(
new_head.c_str() ,nums.at(ii)
));
/* 最初にこれでいいかユーザーに確認する */
if (ii==0) {
if (fl_ask(
"Rename\nFrom\n %s\nTo\n %s\nNumber List\n %s\nOK?"
,opa.c_str()
,npa.c_str()
,numost.str().c_str()
) != 1) {
return; // Cancel
}
}
#ifdef _WIN32
std::string opa2( osapi::cp932_from_utf8( opa ) );
std::string npa2( osapi::cp932_from_utf8( npa ) );
if (opa2.empty() || npa2.empty()) {
fl_alert("Error:rename \"%s\" \"%s\""
,opa.c_str() ,npa.c_str() );
return;
}
std::rename( opa2.c_str() ,npa2.c_str() );
#else
std::rename( opa.c_str() ,npa.c_str() );
#endif
}
/* rename成功したら、新しい名前に表示変更 */
cl_gts_gui.strinp_trace_open_file_head->value( new_head.c_str() );
}
void cb_trace_files::cb_renumber(void)
{
/* Openファイルのフルパスを得る */
const std::string filepath = this->get_open_path( 1 );
if (filepath.empty()) {
fl_alert( "Not set Open Folder or File name" );
return;
}
/* 連番ファイルの存在チェックして必要な情報に変える */
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
if (head.empty() || nums.size() <= 0) {
fl_alert( "Not exist files" );
return;
}
/* ユーザーから新しいStart番号を得る */
const char* new_start_num_ptr = fl_input(
"Enter New Start Number" ,std::to_string(nums.at(0)).c_str()
);
if (new_start_num_ptr == nullptr
|| std::stoi(std::string(new_start_num_ptr))==nums.at(0)) {
return; /* Cancel or 同じ名前なら何もしない */
}
const std::string new_start_num( new_start_num_ptr );
/* 新しいStart番号との差 */
const int diff_num = std::stoi(new_start_num) - nums.at(0);
/* エラー数値をチェックしつつ番号を文字列に入れる */
std::ostringstream numost;
bool error_sw = false;
for (auto nu : nums) {
numost << nu + diff_num;
numost << " ";
if ( nu + diff_num < 0 || 9999 < nu + diff_num ) {
error_sw = true;
}
}
/* ゼロ以下数値があるとエラーメッセージダイオローグを出して終わる */
if (error_sw) {
std::string opa( this->get_open_path( nums.at(0) ) );
std::string npa( this->get_open_path(
nums.at(0) + diff_num ) );
fl_alert(
"Error : Number need 0...9999 range\nFrom\n %s\nTo\n %s\nNumber List\n %s\n"
,opa.c_str()
,npa.c_str()
,numost.str().c_str()
);
return;
}
/* ファイル毎名前を変更する */
for (size_t ii=0; ii<nums.size() ; ++ii) {
std::string opa( this->get_open_path( nums.at(ii) ) );
std::string npa( this->get_open_path(
nums.at(ii) + diff_num ) );
/* 最初にこれでいいかユーザーに確認する */
if (ii==0) {
if (fl_ask(
"Renumber\nFrom\n %s\nTo\n %s\nNumber List\n %s\nOK?"
,opa.c_str()
,npa.c_str()
,numost.str().c_str()
) != 1) {
return; // Cancel
}
}
#ifdef _WIN32
std::string opa2( osapi::cp932_from_utf8( opa ) );
std::string npa2( osapi::cp932_from_utf8( npa ) );
if (opa2.empty() || npa2.empty()) {
fl_alert("Error:rename \"%s\" \"%s\""
,opa.c_str() ,npa.c_str() );
return;
}
std::rename( opa2.c_str() ,npa2.c_str() );
#else
std::rename( opa.c_str() ,npa.c_str() );
#endif
}
/* renumber成功したら、新しいStart,End,Numberに表示変更 */
this->cb_set_number();
this->cb_check_existing_saved_file();
}
//----------------------------------------------------------------------
/* 連番画像ファイルブラウズ */
void cb_trace_files::cb_browse_open_file( void )
{
/* NativeブラウザーOpenで開く */
int filter_current=
cl_gts_gui.choice_trace_open_image_format->value();
const std::string filepath = ids::path::fltk_native_browse_open(
"Open Images"
,cl_gts_gui.filinp_trace_open_dir_path->value()
,this->get_open_name_from_number_(
static_cast<int>(cl_gts_gui.valout_trace_num_start->value())
)
,this->ext_open.get_native_filters()
,filter_current
).at(0);
/* Cancel */
if (filepath.empty()) {
return;
}
/* 必要な情報に変える */
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
/* チェック:ファイルヘッド(file head名)が空だとなにもしない */
if (head.empty()) {
fl_alert("No Head in File");
return;
}
/* チェック:拡張子が対応した種類でないと何もしない */
const int ext_num = this->ext_open.num_from_str( ext );
if ( ext_num < 0 ) {
fl_alert("Bad Extension\"%s\" in File",ext.c_str());
return;
}
/* チェック:連番でないならなにもしない */
if (num.empty() || number == -1) {
fl_alert("No Number in File");
return;
}
/* Traceの番号であることを表示して示す */
cl_gts_master.cl_number.set_type_to_trace();
/* ファイルパスから生成した部品を、GUI、その他セット */
this->set_gui_for_open( dpath ,head ,num ,ext ,nums );
/* 連番画像読込表示 */
cl_gts_master.cb_number_read_and_trace_and_preview();
/* 画像を開いたときの初期表示を元画像の表示にする */
cl_gts_master.cb_change_wview_main();
cl_gts_gui.menite_wview_main->setonly();
}
void cb_trace_files::set_gui_for_open(
const std::string& dpath
,const std::string& head
,const std::string& num
,const std::string& ext
,const std::vector<int>& nums
)
{
/* Trace Filesウインドウ Open設定 */
cl_gts_gui.filinp_trace_open_dir_path->value(dpath.c_str());
cl_gts_gui.strinp_trace_open_file_head->value(head.c_str());
cl_gts_gui.strinp_trace_open_number_format->value(num.c_str());
int ext_num = this->ext_open.num_from_str(ext);
if (ext_num < 0) { ext_num = 0; }
cl_gts_gui.choice_trace_open_image_format->value(ext_num);
/* Trace Filesウインドウ Number設定 */
if (nums.empty()) {
cl_gts_gui.valout_trace_num_start->value( 0 );
cl_gts_gui.valout_trace_num_end->value( 0 );
}
else {
cl_gts_gui.valout_trace_num_start->value( nums.front() );
cl_gts_gui.valout_trace_num_end->value( nums.back() );
}
/* Trace Filesウインドウ 即表示 */
cl_gts_gui.window_trace_files->flush();
/* Numberウインドウ Listを操作可能にする */
cl_gts_gui.selbro_number_list->activate();
/* Numberウインドウ再構築 */
cl_gts_master.cl_number.reset_by_number_list( nums );
}
/* 保存フォルダーブラウズ */
void cb_trace_files::cb_browse_save_folder( void )
{
/* Nativeフォルダーブラウザー開く */
#ifdef _WIN32
const std::string filepath =wincom::native_browse_directory_m(
"Select Saving Folder for Trace"
,cl_gts_gui.filinp_trace_save_dir_path->value()
,::fl_xid( cl_gts_gui.window_trace_files )
);
#else
const std::string filepath =ids::path::fltk_native_browse_directory(
"Set Saving Folder for Trace"
,cl_gts_gui.filinp_trace_save_dir_path->value()
).at(0);
#endif
/* Cancel */
if (filepath.empty()) {
return;
}
cl_gts_gui.filinp_trace_save_dir_path->value( filepath.c_str() );
}
//----------------------------------------------------------------------
/* numberセット表示/file存在確認表示 */
void cb_trace_files::cb_set_number( void )
{
/* Traceの番号であることを表示して示す */
cl_gts_master.cl_number.set_type_to_trace();
/* 必要な情報に変える */
std::string filepath( this->get_open_path( 0 ) );
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
if (head.empty() || nums.empty() || nums.size() <= 0) {
fl_alert( "Not exist file about \'%s\'" ,filepath.c_str() );
return;
}
/* Trace Filesウインドウ Number設定 */
cl_gts_gui.valout_trace_num_start->value( nums.front() );
cl_gts_gui.valout_trace_num_end->value( nums.back() );
/* Trace Filesウインドウ 即表示 */
cl_gts_gui.window_trace_files->flush();
/* Numberウインドウ Listを操作可能にする */
cl_gts_gui.selbro_number_list->activate();
/* Numberウインドウ再構築 */
cl_gts_master.cl_number.reset_by_number_list( nums );
}
//----------------------------------------------------------------------
/* 保存する連番ファイルが存在するならファイル名の背景を黄色表示 */
void cb_trace_files::cb_check_existing_saved_file(void)
{
if ( !cl_gts_master.cl_number.is_trace() ) {
return;
}
this->check_existing_saved_file();
}
void cb_trace_files::check_existing_saved_file(void)
{
Fl_Color col = 0;
if ( this->is_exist_save_files_() ) { /* 上書き */
col = FL_YELLOW;
} else { /* 新規ファイル */
col = FL_WHITE;
}
cl_gts_gui.filinp_trace_save_dir_path->color(col);
cl_gts_gui.filinp_trace_save_dir_path->redraw();
cl_gts_gui.strinp_trace_save_file_head->color(col);
cl_gts_gui.strinp_trace_save_file_head->redraw();
//cl_gts_gui.strinp_trace_save_number_format->color(col);
//cl_gts_gui.strinp_trace_save_number_format->redraw();
cl_gts_gui.output_trace_save_number_format->color(col);
cl_gts_gui.output_trace_save_number_format->redraw();
cl_gts_gui.choice_trace_save_image_format->color(col);
cl_gts_gui.choice_trace_save_image_format->redraw();
}
bool cb_trace_files::is_exist_save_files_(void)
{
/* Numberの非選択含めた番号ファイルで一つでも存在するならtrueを返す */
bool sw=false;
for (int ii = 1; ii <= cl_gts_gui.selbro_number_list->size(); ++ii) {
/* リストの項目に表示した番号 */
const int file_num = std::stoi(
cl_gts_gui.selbro_number_list->text(ii)
);
/* 番号によるファイルパス */
std::string filepath( this->get_save_path( file_num ) );
/* ファイルの存在の表示チェック */
if (!filepath.empty() && osapi::exist_utf8_mbs(filepath)) {
sw = true;
cl_gts_master.cl_number.replace_with_S( file_num ,ii );
}
else {
cl_gts_master.cl_number.replace_without_S( file_num ,ii );
}
}
return sw;
}
//----------------------------------------------------------------------
/* open file/path */
const std::string cb_trace_files::get_open_path( const int number )
{
/* Folder & File名が設定していないと空を返す */
if (cl_gts_gui.filinp_trace_open_dir_path->value() == nullptr
|| this->get_open_name_from_number_( number ).empty()) {
return std::string();
}
std::string filepath;
filepath += cl_gts_gui.filinp_trace_open_dir_path->value();
filepath += '/';
filepath += this->get_open_name_from_number_( number );
return filepath;
}
const std::string cb_trace_files::get_open_name_from_number_( const int number )
{
return this->get_open_name_from_head_and_number_(
cl_gts_gui.strinp_trace_open_file_head->value() ,number );
}
const std::string cb_trace_files::get_open_name_from_head_and_number_(
const std::string& file_head
,const int number
)
{
/* 名(head,num_form,ext)が設定していないと空を返す */
if (file_head.empty()
|| (0 <= number
&& cl_gts_gui.strinp_trace_open_number_format->value() == nullptr)
|| cl_gts_gui.choice_trace_open_image_format->text() == nullptr) {
return std::string();
}
std::string filename(file_head);
if (0 <= number) {
filename += ids::path::str_from_number(
number , cl_gts_gui.strinp_trace_open_number_format->value()
);
}
filename += cl_gts_gui.choice_trace_open_image_format->text();
return filename;
}
const std::string cb_trace_files::get_open_path_from_head_and_number_(
const std::string& file_head
,const int number
)
{
/* Folder & File名が設定していないと空を返す */
if (cl_gts_gui.filinp_trace_open_dir_path->value() == nullptr
|| this->get_open_name_from_head_and_number_(
file_head,number).empty()) {
return std::string();
}
std::string filepath;
filepath += cl_gts_gui.filinp_trace_open_dir_path->value();
filepath += '/';
filepath += this->get_open_name_from_head_and_number_(
file_head ,number
);
return filepath;
}
//----------------------------------------------------------------------
/* save file/path */
const std::string cb_trace_files::get_save_path( const int number )
{
/* Folder & File名が設定していないと空を返す */
if (cl_gts_gui.filinp_trace_save_dir_path->value() == nullptr
|| this->get_save_name_( number ).empty()) {
return std::string();
}
std::string filepath;
filepath += cl_gts_gui.filinp_trace_save_dir_path->value();
filepath += '/';
filepath += this->get_save_name_( number );
return filepath;
}
const std::string cb_trace_files::get_save_name_( const int number )
{
/* 名(head,num_form,ext)が設定していないと空を返す */
if (cl_gts_gui.strinp_trace_save_file_head->value() == nullptr
|| (0 <= number
&& cl_gts_gui.output_trace_save_number_format->value() == nullptr)
|| cl_gts_gui.choice_trace_save_image_format->text() == nullptr) {
return std::string();
}
std::string filename;
filename += cl_gts_gui.strinp_trace_save_file_head->value();
if (0 <= number) {
filename += ids::path::str_from_number(
number
, cl_gts_gui.output_trace_save_number_format->value()
);
}
filename += cl_gts_gui.choice_trace_save_image_format->text();
return filename;
}
//----------------------------------------------------------------------
std::string cb_trace_files::get_open_ext_for_legacy_(const std::string& type)
{
if (type.size() == 4) { return type; }
for (int ii=0;ii<this->ext_open.size() ;++ii) {
if ( this->ext_open.get_fltk_filter( ii ) == type) {
return this->ext_open.str_from_num( ii );
}
}
return type;
}
std::string cb_trace_files::get_save_ext_for_legacy_(const std::string& type)
{
if (type.size() == 4) { return type; }
for (int ii=0;ii<this->ext_save.size() ;++ii) {
if ( this->ext_save.get_fltk_filter( ii ) == type) {
return this->ext_save.str_from_num( ii );
}
}
return type;
}
void cb_trace_files::cb_choice_open_image_format( const std::string& type )
{
std::string typestr( this->get_open_ext_for_legacy_(type) );
const Fl_Menu_Item *crnt =
cl_gts_gui.choice_trace_open_image_format->find_item(
typestr.c_str() );
if (crnt == nullptr) { return; }
cl_gts_gui.choice_trace_open_image_format->value(crnt);
}
void cb_trace_files::cb_choice_save_image_format( const std::string& type )
{
std::string typestr( this->get_save_ext_for_legacy_(type) );
const Fl_Menu_Item *crnt =
cl_gts_gui.choice_trace_save_image_format->find_item(
typestr.c_str() );
if (crnt == nullptr) { return; }
cl_gts_gui.choice_trace_save_image_format->value(crnt);
}
//----------------------------------------------------------------------
void cb_trace_files::cb_switch_trace_filter_erase_dot_noise( const bool sw )
{
if (sw) {
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->box(FL_SHADOW_BOX);
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->value(1);//ON
}
else {
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->box(FL_FLAT_BOX);
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->value(0);//OFF
}
}
//----------------------------------------------------------------------
void cb_trace_files::cb_browse_save_file( void )
{
/* Crop中は保存できない */
if (cl_gts_master.cl_ogl_view.get_crop_disp_sw()) {
fl_alert("Finish Cropping, Please Scan.");
return;
}
/* ScanもReadもまだしていない */
if (cl_gts_master.cl_iip_ro90.get_clp_parent() == nullptr ) {
fl_alert("Please Any Scan or Open.");
return;
}
/* parameter */
iip_canvas* parent = nullptr;
int rot90=0;
double dpi = 0;
iip_read* read_attr = nullptr;
/* ファイル読込後 */
if ( &(cl_gts_master.cl_iip_read)
== cl_gts_master.cl_iip_ro90.get_clp_parent() ) {
parent = &(cl_gts_master.cl_iip_read);
rot90 = 0; /* 画像コンバート処理のみで、回転はしない */
dpi = cl_gts_master.cl_iip_read.get_d_tif_dpi_x();
read_attr = &(cl_gts_master.cl_iip_read);
}
else
/* スキャン後 */
if ( cl_gts_master.cl_iip_scan.get_clp_canvas()
== cl_gts_master.cl_iip_ro90.get_clp_parent() ) {
parent = cl_gts_master.cl_iip_scan.get_clp_canvas();
rot90 = cl_gts_gui.choice_rot90->value();
dpi = cl_gts_gui.valinp_area_reso->value();
} else {
fl_alert("No Image");
return;
}
/* parameter */
std::string save_dpath;
std::string save_fname;
std::string save_filter;
int save_filter_num = 0;
/* ファイルトレスモード */
if (cl_gts_master.cl_number.is_trace()) {
save_dpath = cl_gts_gui.filinp_trace_save_dir_path->value();
save_fname = this->get_save_name_( -1 );
save_filter = this->ext_save.get_native_filters();
save_filter_num = cl_gts_gui.choice_trace_save_image_format->value();
} else
/* スキャンモード */
if (cl_gts_master.cl_number.is_scan()) {
save_dpath = cl_gts_gui.filinp_scan_save_dir_path->value();
save_fname = cl_gts_master.cl_scan_and_save.get_save_path( -1 );
save_filter = cl_gts_master.cl_scan_and_save.ext_save.get_native_filters();
save_filter_num = cl_gts_gui.choice_scan_save_image_format->value();
} else {
fl_alert("Not Scan/Trace");
return;
}
/* NativeブラウザーSaveで開く */
//std::cout << __FILE__ << " " << "save_dpath=" << save_dpath << " save_fname=" << save_fname << std::endl;
const std::string fpath_save = ids::path::fltk_native_browse_save(
"Save Image"
,save_dpath
,save_fname
,save_filter
,save_filter_num
).at(0);
/* Cancel */
if (fpath_save.empty()) {
return;
}
/* 処理:Rot90 and Effects(color Trace and Erase color dot noise) */
if (cl_gts_master.rot_and_trace_and_enoise( parent ,rot90 ) != OK) {
return;
}
/* 保存 */
if (OK != cl_gts_master.iipg_save(
&(cl_gts_master.cl_iip_edot)
, const_cast<char *>(fpath_save.c_str())
,dpi
,rot90
,read_attr
)) {
pri_funct_err_bttvr(
"Error : cl_gts_master.iipg_save(-) returns NG" );
return;
}
/* 表示:画像の再表示 */
if (cl_gts_master.redraw_image(
&(cl_gts_master.cl_iip_edot)
, false /* crop sw */
, false /* force view scanimage sw */
)) {
return;
}
}
| 26.481056 | 107 | 0.672491 | Savraska2 |
bff0b638a70ed3f6bb03a3738ba01db2d1f2880f | 997 | hpp | C++ | SFND_Camera/SFND_3D_Object_Tracking/src/lidarData.hpp | KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree | 2c6d26bee670abe2c63034d26556f99f6d77925b | [
"MIT"
] | 18 | 2020-11-12T07:13:57.000Z | 2022-03-12T18:42:13.000Z | SFND_Camera/SFND_3D_Object_Tracking/src/lidarData.hpp | KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree | 2c6d26bee670abe2c63034d26556f99f6d77925b | [
"MIT"
] | null | null | null | SFND_Camera/SFND_3D_Object_Tracking/src/lidarData.hpp | KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree | 2c6d26bee670abe2c63034d26556f99f6d77925b | [
"MIT"
] | 16 | 2020-09-29T05:27:32.000Z | 2021-11-02T18:26:53.000Z |
#ifndef lidarData_hpp
#define lidarData_hpp
#include <stdio.h>
#include <fstream>
#include <string>
#include "dataStructures.h"
void cropLidarPoints(std::vector<LidarPoint>& lidarPoints,
float minX,
float maxX,
float maxY,
float minZ,
float maxZ,
float minR);
void loadLidarFromFile(std::vector<LidarPoint>& lidarPoints,
std::string filename);
void showLidarTopview(std::vector<LidarPoint>& lidarPoints,
cv::Size worldSize,
cv::Size imageSize,
bool bWait = true);
void showLidarImgOverlay(cv::Mat& img,
std::vector<LidarPoint>& lidarPoints,
cv::Mat& P_rect_xx,
cv::Mat& R_rect_xx,
cv::Mat& RT,
cv::Mat* extVisImg = nullptr);
#endif /* lidarData_hpp */
| 31.15625 | 62 | 0.500502 | KU-AIRS-SPARK |
bff6da18a7255440fb3e7e0f1640ff19936cbfc5 | 2,261 | cpp | C++ | src/termui/terminal_mode.cpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | 1 | 2020-07-31T01:34:47.000Z | 2020-07-31T01:34:47.000Z | src/termui/terminal_mode.cpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | null | null | null | src/termui/terminal_mode.cpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <unistd.h>
#include "except.hpp"
#include "signals.hpp"
#include "terminal_mode.hpp"
namespace bandwit {
namespace termui {
void TerminalModeSetter::set() {
SignalGuard guard{signal_suspender_};
struct termios tm {};
if (tcgetattr(STDIN_FILENO, &tm) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.set failed in tcgetattr()");
}
// save the unmodified state so we can restore it
orig_termios_ = tm;
tm.c_lflag &= ~local_off_;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tm) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.set failed in tcsetattr()");
}
// Now check that the set actually set all of our flags
struct termios tm_after {};
if (tcgetattr(STDIN_FILENO, &tm_after) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.set failed in #2 tcgetattr()");
}
if ((tm_after.c_lflag & local_off_) > 0) {
THROW_MSG(std::runtime_error,
"TerminalModeSetter.set failed to actually set the flags!");
}
}
void TerminalModeSetter::reset() {
SignalGuard guard{signal_suspender_};
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios_) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.unset failed in tcsetattr()");
}
// Now check that the set actually unset all of our flags
struct termios tm_after {};
if (tcgetattr(STDIN_FILENO, &tm_after) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.unset failed in tcgetattr()");
}
if ((tm_after.c_lflag & local_off_) != local_off_) {
THROW_MSG(
std::runtime_error,
"TerminalModeSetter.unset failed to actually unset the flags!");
}
}
TerminalModeSet &TerminalModeSet::local_off(tcflag_t flag) {
flags_local_off_ |= flag;
return *this;
}
std::unique_ptr<TerminalModeSetter>
TerminalModeSet::build_setter(SignalSuspender *signal_suspender) {
return std::make_unique<TerminalModeSetter>(flags_local_off_,
signal_suspender);
}
} // namespace termui
} // namespace bandwit | 28.2625 | 78 | 0.637771 | numerodix |
bffaab10eb745e8831e5ff7e1563d01e08fe9cb4 | 621 | cpp | C++ | test/structure_size.cpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | test/structure_size.cpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | test/structure_size.cpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "mil/mil.hpp"
struct normal {
int i;
double d;
};
struct extended {
MIL_BEGIN(extended);
MIL_DEFINE_FIELD(int, i);
MIL_DEFINE_FIELD(double, d);
MIL_END;
};
TEST(structure_size, size) {
EXPECT_EQ(sizeof(normal), sizeof(extended));
}
struct inheritance : normal {
float f;
};
struct inheritance_extended : MIL_INHERITANCE(inheritance_extended, extended) {
MIL_BEGIN(inheritance_extended);
MIL_DEFINE_FIELD(float, f);
MIL_END;
};
TEST(structure_size, inheritance_size) {
EXPECT_EQ(sizeof(inheritance), sizeof(inheritance_extended));
}
| 18.264706 | 79 | 0.703704 | vhapiak |
bffbe676ba7bd90706842145f2446d111a05d93e | 1,631 | cpp | C++ | leetcode/331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | leetcode/331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | leetcode/331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isValidSerialization(string preorder) {
if (preorder.size() < 5) return preorder == "#";
stack<pair<bool, bool>> validNodes;
validNodes.push({true, false}); // dummy root with a dummy left child
auto pb = preorder.data(), pe = pb;
const auto PE = pb + preorder.size();
while (pb < PE && !validNodes.empty()) {
if (*pb != '#') { // live node
pe = find(pb, PE, ',');
validNodes.push({false, false});
} else {
pe = pb + 1; // null node
while (!validNodes.empty() && validNodes.top().first == true) validNodes.pop();
if (!validNodes.empty()) validNodes.top().first = true;
}
pb = pe + 1;
}
return pe == PE && validNodes.empty();
}
};
class Solution {
public:
bool isValidSerialization(string preorder) {
if (preorder.size() < 5) return preorder == "#";
stack<bool> leftValidated;
leftValidated.push(true);
auto pb = preorder.data();
const auto PE = pb + preorder.size();
while (pb < PE && !leftValidated.empty()) {
if (*pb != '#') {
leftValidated.push(false);
pb = find(pb, PE, ',') + 1;
} else {
while (!leftValidated.empty() && leftValidated.top() == true) leftValidated.pop();
if (!leftValidated.empty()) leftValidated.top() = true;
pb += 2;
}
}
return pb == PE + 1 && leftValidated.empty();
}
};
| 28.12069 | 98 | 0.486205 | longztian |
bffc306886feb649c5b00d30488295f23445dbd8 | 124 | cpp | C++ | epyks.cpp | whyamiroot/epyks | 45d5cde06f60110a3b3b78c189d5aeb634345593 | [
"MIT"
] | null | null | null | epyks.cpp | whyamiroot/epyks | 45d5cde06f60110a3b3b78c189d5aeb634345593 | [
"MIT"
] | null | null | null | epyks.cpp | whyamiroot/epyks | 45d5cde06f60110a3b3b78c189d5aeb634345593 | [
"MIT"
] | null | null | null | #include "epyks.h"
void encode(unsigned char* data, size_t size)
{
}
void decode(unsigned char* data, size_t size)
{
}
| 9.538462 | 45 | 0.685484 | whyamiroot |
87052cacedf3f9923dfa0202beb08fdb352c21ba | 598 | cpp | C++ | BorisEngine2/DigitSprite.cpp | Rariolu/BorisEngine2 | d98d348a85a91ed09a8e1e48dc06b26f20b6f8f7 | [
"MIT"
] | 1 | 2019-11-16T13:23:03.000Z | 2019-11-16T13:23:03.000Z | BorisEngine2/DigitSprite.cpp | chocorho/BorisEngine2 | d98d348a85a91ed09a8e1e48dc06b26f20b6f8f7 | [
"MIT"
] | 2 | 2021-05-24T23:21:49.000Z | 2021-05-26T20:41:03.000Z | BorisEngine2/DigitSprite.cpp | chocorho/BorisEngine2 | d98d348a85a91ed09a8e1e48dc06b26f20b6f8f7 | [
"MIT"
] | 1 | 2021-05-24T22:52:31.000Z | 2021-05-24T22:52:31.000Z | #include "DigitSprite.h"
DigitSprite::DigitSprite(Font* font) : Sprite(texturemanager->AddTexture("digitSprite_0",font->CreateTextTexture("0",SOLID)))
{
digitFont = font;
}
DigitSprite::~DigitSprite()
{
}
int DigitSprite::GetDisplayNumber()
{
return displayNumber;
}
void DigitSprite::SetDisplayNumber(int num)
{
displayNumber = num;
if (digitFont)
{
String str = "digitSprite_" + std::to_string(num);
Texture* t = texturemanager->GetTexture(str);
if (!t)
{
t = texturemanager->AddTexture(str,digitFont->CreateTextTexture(std::to_string(num), SOLID));
}
SetTexture(t);
}
} | 19.290323 | 125 | 0.712375 | Rariolu |
87061140c4d88ae47bd8c416a8209f37492bb54e | 4,000 | hpp | C++ | components/scream/src/share/field/field_header.hpp | ashlynrlee/scream | 3d58c32340058368bee0cb2b02457c4723fb18db | [
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null | components/scream/src/share/field/field_header.hpp | ashlynrlee/scream | 3d58c32340058368bee0cb2b02457c4723fb18db | [
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null | components/scream/src/share/field/field_header.hpp | ashlynrlee/scream | 3d58c32340058368bee0cb2b02457c4723fb18db | [
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null | #ifndef SCREAM_FIELD_HEADER_HPP
#define SCREAM_FIELD_HEADER_HPP
#include "share/field/field_identifier.hpp"
#include "share/field/field_tracking.hpp"
#include "share/field/field_alloc_prop.hpp"
#include "share/scream_types.hpp"
#include "share/util/scream_time_stamp.hpp"
#include "ekat/std_meta/ekat_std_any.hpp"
#include "ekat/std_meta/ekat_std_enable_shared_from_this.hpp"
#include <vector>
#include <map>
#include <memory> // For std::shared_ptr and std::weak_ptr
namespace scream
{
class AtmosphereProcess;
/*
* A small class to contain meta-data about a field
*
* The FieldHeader class is itself a container of other
* more speicific classes, such as FieldIdentifier
* (which contains information used to uniquely identify
* the field) or FieldTracking (which contains info used
* to track access to the field).
* There is also 'extra_data', which is a sort of fall-back
* option, for the meta-data that does not follow under
* any pre-defined category, and that is not general enough
* to warrant a new sub-object or a specific named member/method.
*/
class FieldHeader : public ekat::enable_shared_from_this<FieldHeader> {
public:
using identifier_type = FieldIdentifier;
using tracking_type = FieldTracking;
using extra_data_type = std::map<std::string,ekat::any>;
// Constructor(s)
FieldHeader (const FieldHeader&) = default;
explicit FieldHeader (const identifier_type& id);
FieldHeader (const identifier_type& id,
std::shared_ptr<FieldHeader> parent,
const int idim, const int k);
// Assignment deleted, to prevent sneaky overwrites.
FieldHeader& operator= (const FieldHeader&) = delete;
// Set extra data
void set_extra_data (const std::string& key,
const ekat::any& data,
const bool throw_if_existing = false);
template<typename T>
void set_extra_data (const std::string& key,
const T& data,
const bool throw_if_existing = false) {
ekat::any data_any;
data_any.reset<T>(data);
set_extra_data(key,data_any,throw_if_existing);
}
// ----- Getters ----- //
// Get the basic information from the identifier
const identifier_type& get_identifier () const { return m_identifier; }
// Get the tracking
const tracking_type& get_tracking () const { return *m_tracking; }
tracking_type& get_tracking () { return *m_tracking; }
const std::shared_ptr<tracking_type>& get_tracking_ptr () const { return m_tracking; }
// Get the allocation properties
const FieldAllocProp& get_alloc_properties () const { return m_alloc_prop; }
FieldAllocProp& get_alloc_properties () { return m_alloc_prop; }
// Get parent (if any)
std::weak_ptr<FieldHeader> get_parent () const { return m_parent; }
// Get children list (if any)
std::list<std::weak_ptr<FieldHeader>> get_children () const { return m_children; }
// Get the extra data
const extra_data_type& get_extra_data () const { return m_extra_data; }
protected:
// Static information about the field: name, rank, tags
identifier_type m_identifier;
// Tracking of the field
std::shared_ptr<tracking_type> m_tracking;
// Allocation properties
FieldAllocProp m_alloc_prop;
// If this field is a sub-view of another field, we keep a pointer to the parent
// OTOH, if other fields are sub-view of this field, we keep a pointer to them
std::weak_ptr<FieldHeader> m_parent;
std::list<std::weak_ptr<FieldHeader>> m_children;
// Extra data associated with this field
extra_data_type m_extra_data;
};
// Use this free function to exploit features of enable_from_this
template<typename... Args>
inline std::shared_ptr<FieldHeader>
create_header(const Args&... args) {
auto ptr = std::make_shared<FieldHeader>(args...);
ptr->setSelfPointer(ptr);
return ptr;
}
} // namespace scream
#endif // SCREAM_FIELD_HEADER_HPP
| 32.786885 | 88 | 0.706 | ashlynrlee |
87078da0692935a4d1f393f17499b89674a80efb | 29,477 | cpp | C++ | gmm-dpct/gaussian_kernel.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | gmm-dpct/gaussian_kernel.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | gmm-dpct/gaussian_kernel.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | /*
* CUDA Kernels for Expectation Maximization with Gaussian Mixture Models
*
* Author: Andrew Pangborn
*
* Department of Computer Engineering
* Rochester Institute of Technology
*/
#ifndef _TEMPLATE_KERNEL_H_
#define _TEMPLATE_KERNEL_H_
#include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include "gaussian.h"
/*
* Compute the multivariate mean of the FCS data
*/
void mvtmeans(float* fcs_data, int num_dimensions, int num_events, float* means,
sycl::nd_item<3> item_ct1) {
int tid = item_ct1.get_local_id(2);
if(tid < num_dimensions) {
means[tid] = 0.0;
// Sum up all the values for each dimension
for(int i = 0; i < num_events; i++) {
means[tid] += fcs_data[i*num_dimensions+tid];
}
// Divide by the # of elements to get the average
means[tid] /= (float) num_events;
}
}
void averageVariance(float* fcs_data, float* means, int num_dimensions, int num_events, float* avgvar,
sycl::nd_item<3> item_ct1, float *variances,
float *total_variance) {
int tid = item_ct1.get_local_id(2);
// Compute average variance for each dimension
if(tid < num_dimensions) {
variances[tid] = 0.0;
// Sum up all the variance
for(int i = 0; i < num_events; i++) {
// variance = (data - mean)^2
variances[tid] += (fcs_data[i*num_dimensions + tid])*(fcs_data[i*num_dimensions + tid]);
}
variances[tid] /= (float) num_events;
variances[tid] -= means[tid]*means[tid];
}
item_ct1.barrier();
if(tid == 0) {
*total_variance = 0.0;
for(int i=0; i<num_dimensions;i++) {
*total_variance += variances[i];
}
*avgvar = *total_variance / (float)num_dimensions;
}
}
// Inverts an NxN matrix 'data' stored as a 1D array in-place
// 'actualsize' is N
// Computes the log of the determinant of the origianl matrix in the process
void invert(float* data, int actualsize, float* log_determinant,
sycl::nd_item<3> item_ct1) {
int maxsize = actualsize;
int n = actualsize;
if (item_ct1.get_local_id(2) == 0) {
*log_determinant = 0.0;
// sanity check
if (actualsize == 1) {
*log_determinant = sycl::log(data[0]);
data[0] = 1.0 / data[0];
} else {
for (int i=1; i < actualsize; i++) data[i] /= data[0]; // normalize row 0
for (int i=1; i < actualsize; i++) {
for (int j=i; j < actualsize; j++) { // do a column of L
float sum = 0.0;
for (int k = 0; k < i; k++)
sum += data[j*maxsize+k] * data[k*maxsize+i];
data[j*maxsize+i] -= sum;
}
if (i == actualsize-1) continue;
for (int j=i+1; j < actualsize; j++) { // do a row of U
float sum = 0.0;
for (int k = 0; k < i; k++)
sum += data[i*maxsize+k]*data[k*maxsize+j];
data[i*maxsize+j] =
(data[i*maxsize+j]-sum) / data[i*maxsize+i];
}
}
for(int i=0; i<actualsize; i++) {
*log_determinant += sycl::log(sycl::fabs(data[i * n + i]));
}
for ( int i = 0; i < actualsize; i++ ) // invert L
for ( int j = i; j < actualsize; j++ ) {
float x = 1.0;
if ( i != j ) {
x = 0.0;
for ( int k = i; k < j; k++ )
x -= data[j*maxsize+k]*data[k*maxsize+i];
}
data[j*maxsize+i] = x / data[j*maxsize+j];
}
for ( int i = 0; i < actualsize; i++ ) // invert U
for ( int j = i; j < actualsize; j++ ) {
if ( i == j ) continue;
float sum = 0.0;
for ( int k = i; k < j; k++ )
sum += data[k*maxsize+j]*( (i==k) ? 1.0 : data[i*maxsize+k] );
data[i*maxsize+j] = -sum;
}
for ( int i = 0; i < actualsize; i++ ) // final inversion
for ( int j = 0; j < actualsize; j++ ) {
float sum = 0.0;
for ( int k = ((i>j)?i:j); k < actualsize; k++ )
sum += ((j==k)?1.0:data[j*maxsize+k])*data[k*maxsize+i];
data[j*maxsize+i] = sum;
}
}
}
}
void compute_pi(clusters_t* clusters, int num_clusters,
sycl::nd_item<3> item_ct1, float *sum) {
if (item_ct1.get_local_id(2) == 0) {
*sum = 0.0;
for(int i=0; i<num_clusters; i++) {
*sum += clusters->N[i];
}
}
item_ct1.barrier();
for (int c = item_ct1.get_local_id(2); c < num_clusters;
c += item_ct1.get_local_range().get(2)) {
if(clusters->N[c] < 0.5f) {
clusters->pi[item_ct1.get_local_id(2)] = 1e-10;
} else {
clusters->pi[item_ct1.get_local_id(2)] = clusters->N[c] / *sum;
}
}
item_ct1.barrier();
}
void compute_constants(clusters_t* clusters, int num_clusters, int num_dimensions,
sycl::nd_item<3> item_ct1, float *determinant_arg,
float *matrix) {
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int num_elements = num_dimensions*num_dimensions;
// only one thread computes the inverse so we need a shared argument
float log_determinant;
// Invert the matrix for every cluster
int c = item_ct1.get_group(2);
// Copy the R matrix into shared memory for doing the matrix inversion
for(int i=tid; i<num_elements; i+= num_threads ) {
matrix[i] = clusters->R[c*num_dimensions*num_dimensions+i];
}
item_ct1.barrier();
#if DIAG_ONLY
if(tid == 0) {
determinant_arg = 1.0f;
for(int i=0; i < num_dimensions; i++) {
determinant_arg *= matrix[i*num_dimensions+i];
matrix[i*num_dimensions+i] = 1.0f / matrix[i*num_dimensions+i];
}
determinant_arg = logf(determinant_arg);
}
#else
invert(matrix, num_dimensions, determinant_arg, item_ct1);
#endif
item_ct1.barrier();
log_determinant = *determinant_arg;
// Copy the matrx from shared memory back into the cluster memory
for(int i=tid; i<num_elements; i+= num_threads) {
clusters->Rinv[c*num_dimensions*num_dimensions+i] = matrix[i];
}
item_ct1.barrier();
// Compute the constant
// Equivilent to: log(1/((2*PI)^(M/2)*det(R)^(1/2)))
// This constant is used in all E-step likelihood calculations
if(tid == 0) {
clusters->constant[c] =
-num_dimensions * 0.5f * sycl::log((float)(2.0f * PI)) -
0.5f * log_determinant;
}
}
/*
* Computes the constant, pi, Rinv for each cluster
*
* Needs to be launched with the number of blocks = number of clusters
*/
SYCL_EXTERNAL void constants_kernel(clusters_t *clusters, int num_clusters,
int num_dimensions,
sycl::nd_item<3> item_ct1,
float *determinant_arg, float *sum,
float *matrix) {
// compute_constants(clusters,num_clusters,num_dimensions);
int tid = item_ct1.get_local_id(2);
int bid = item_ct1.get_group(2);
int num_threads = item_ct1.get_local_range().get(2);
int num_elements = num_dimensions*num_dimensions;
// only one thread computes the inverse so we need a shared argument
float log_determinant;
// Invert the matrix for every cluster
// Copy the R matrix into shared memory for doing the matrix inversion
for(int i=tid; i<num_elements; i+= num_threads ) {
matrix[i] = clusters->R[bid*num_dimensions*num_dimensions+i];
}
item_ct1.barrier();
#if DIAG_ONLY
if(tid == 0) {
determinant_arg = 1.0f;
for(int i=0; i < num_dimensions; i++) {
determinant_arg *= matrix[i*num_dimensions+i];
matrix[i*num_dimensions+i] = 1.0f / matrix[i*num_dimensions+i];
}
determinant_arg = logf(determinant_arg);
}
#else
invert(matrix, num_dimensions, determinant_arg, item_ct1);
#endif
item_ct1.barrier();
log_determinant = *determinant_arg;
// Copy the matrx from shared memory back into the cluster memory
for(int i=tid; i<num_elements; i+= num_threads) {
clusters->Rinv[bid*num_dimensions*num_dimensions+i] = matrix[i];
}
item_ct1.barrier();
// Compute the constant
// Equivilent to: log(1/((2*PI)^(M/2)*det(R)^(1/2)))
// This constant is used in all E-step likelihood calculations
if(tid == 0) {
clusters->constant[bid] =
-num_dimensions * 0.5f * sycl::log((float)(2.0f * PI)) -
0.5f * log_determinant;
}
item_ct1.barrier();
if(bid == 0) {
// compute_pi(clusters,num_clusters);
if(tid == 0) {
*sum = 0.0;
for(int i=0; i<num_clusters; i++) {
*sum += clusters->N[i];
}
}
item_ct1.barrier();
for(int i = tid; i < num_clusters; i += num_threads) {
if(clusters->N[i] < 0.5f) {
clusters->pi[tid] = 1e-10;
} else {
clusters->pi[tid] = clusters->N[i] / *sum;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
//! @param fcs_data FCS data: [num_events]
//! @param clusters Clusters: [num_clusters]
//! @param num_dimensions number of dimensions in an FCS event
//! @param num_events number of FCS events
////////////////////////////////////////////////////////////////////////////////
SYCL_EXTERNAL void seed_clusters_kernel(
const float *fcs_data, clusters_t *clusters, const int num_dimensions,
const int num_clusters, const int num_events, sycl::nd_item<3> item_ct1,
float *means, float *avgvar, float *variances, float *total_variance)
{
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int row, col;
float seed;
// Number of elements in the covariance matrix
int num_elements = num_dimensions*num_dimensions;
// shared memory
// Compute the means
// mvtmeans(fcs_data, num_dimensions, num_events, means);
if(tid < num_dimensions) {
means[tid] = 0.0;
// Sum up all the values for each dimension
for(int i = 0; i < num_events; i++) {
means[tid] += fcs_data[i*num_dimensions+tid];
}
// Divide by the # of elements to get the average
means[tid] /= (float) num_events;
}
item_ct1.barrier();
// Compute the average variance
// averageVariance(fcs_data, means, num_dimensions, num_events, &avgvar);
// Compute average variance for each dimension
if(tid < num_dimensions) {
variances[tid] = 0.0;
// Sum up all the variance
for(int i = 0; i < num_events; i++) {
// variance = (data - mean)^2
variances[tid] += (fcs_data[i*num_dimensions + tid])*(fcs_data[i*num_dimensions + tid]);
}
variances[tid] /= (float) num_events;
variances[tid] -= means[tid]*means[tid];
}
item_ct1.barrier();
if(tid == 0) {
*total_variance = 0.0;
for(int i=0; i<num_dimensions;i++) {
*total_variance += variances[i];
}
*avgvar = *total_variance / (float)num_dimensions;
}
item_ct1.barrier();
if(num_clusters > 1) {
seed = (num_events-1.0f)/(num_clusters-1.0f);
} else {
seed = 0.0;
}
// Seed the pi, means, and covariances for every cluster
for(int c=0; c < num_clusters; c++) {
if(tid < num_dimensions) {
clusters->means[c*num_dimensions+tid] = fcs_data[((int)(c*seed))*num_dimensions+tid];
}
for(int i=tid; i < num_elements; i+= num_threads) {
// Add the average variance divided by a constant, this keeps the cov matrix from becoming singular
row = (i) / num_dimensions;
col = (i) % num_dimensions;
if(row == col) {
clusters->R[c*num_dimensions*num_dimensions+i] = 1.0f;
} else {
clusters->R[c*num_dimensions*num_dimensions+i] = 0.0f;
}
}
if(tid == 0) {
clusters->pi[c] = 1.0f/((float)num_clusters);
clusters->N[c] = ((float) num_events) / ((float)num_clusters);
clusters->avgvar[c] = *avgvar / COVARIANCE_DYNAMIC_RANGE;
}
}
}
float parallelSum(float* data, const unsigned int ndata,
sycl::nd_item<3> item_ct1) {
const unsigned int tid = item_ct1.get_local_id(2);
float t;
item_ct1.barrier();
// Butterfly sum. ndata MUST be a power of 2.
for(unsigned int bit = ndata >> 1; bit > 0; bit >>= 1) {
t = data[tid] + data[tid ^ bit]; item_ct1.barrier();
data[tid] = t; item_ct1.barrier();
}
return data[tid];
}
void compute_indices(int num_events, int* start, int* stop,
sycl::nd_item<3> item_ct1) {
// Break up the events evenly between the blocks
int num_pixels_per_block = num_events / NUM_BLOCKS;
// Make sure the events being accessed by the block are aligned to a multiple of 16
num_pixels_per_block = num_pixels_per_block - (num_pixels_per_block % 16);
*start =
item_ct1.get_group(1) * num_pixels_per_block + item_ct1.get_local_id(2);
// Last block will handle the leftover events
if (item_ct1.get_group(1) == item_ct1.get_group_range(1) - 1) {
*stop = num_events;
} else {
*stop = (item_ct1.get_group(1) + 1) * num_pixels_per_block;
}
}
SYCL_EXTERNAL void estep1(float *data, clusters_t *clusters, int num_dimensions,
int num_events, sycl::nd_item<3> item_ct1,
float *means, float *Rinv) {
// Cached cluster parameters
float cluster_pi;
float constant;
const unsigned int tid = item_ct1.get_local_id(2);
int start_index;
int end_index;
int c = item_ct1.get_group(2);
compute_indices(num_events, &start_index, &end_index, item_ct1);
float like;
// This loop computes the expectation of every event into every cluster
//
// P(k|n) = L(x_n|mu_k,R_k)*P(k) / P(x_n)
//
// Compute log-likelihood for every cluster for each event
// L = constant*exp(-0.5*(x-mu)*Rinv*(x-mu))
// log_L = log_constant - 0.5*(x-u)*Rinv*(x-mu)
// the constant stored in clusters[c].constant is already the log of the constant
// copy the means for this cluster into shared memory
if(tid < num_dimensions) {
means[tid] = clusters->means[c*num_dimensions+tid];
}
// copy the covariance inverse into shared memory
for(int i=tid; i < num_dimensions*num_dimensions; i+= NUM_THREADS_ESTEP) {
Rinv[i] = clusters->Rinv[c*num_dimensions*num_dimensions+i];
}
cluster_pi = clusters->pi[c];
constant = clusters->constant[c];
// Sync to wait for all params to be loaded to shared memory
item_ct1.barrier();
for(int event=start_index; event<end_index; event += NUM_THREADS_ESTEP) {
like = 0.0f;
// this does the loglikelihood calculation
#if DIAG_ONLY
for(int j=0; j<num_dimensions; j++) {
like += (data[j*num_events+event]-means[j]) * (data[j*num_events+event]-means[j]) * Rinv[j*num_dimensions+j];
}
#else
for(int i=0; i<num_dimensions; i++) {
for(int j=0; j<num_dimensions; j++) {
like += (data[i*num_events+event]-means[i]) * (data[j*num_events+event]-means[j]) * Rinv[i*num_dimensions+j];
}
}
#endif
// numerator of the E-step probability computation
clusters->memberships[c * num_events + event] =
-0.5f * like + constant + sycl::log(cluster_pi);
}
}
SYCL_EXTERNAL void estep2(float *fcs_data, clusters_t *clusters,
int num_dimensions, int num_clusters, int num_events,
float *likelihood, sycl::nd_item<3> item_ct1,
float *total_likelihoods) {
float temp;
float thread_likelihood = 0.0f;
float max_likelihood;
float denominator_sum;
// Break up the events evenly between the blocks
int num_pixels_per_block = num_events / item_ct1.get_group_range(2);
// Make sure the events being accessed by the block are aligned to a multiple of 16
num_pixels_per_block = num_pixels_per_block - (num_pixels_per_block % 16);
int tid = item_ct1.get_local_id(2);
int start_index;
int end_index;
start_index = item_ct1.get_group(2) * num_pixels_per_block + tid;
// Last block will handle the leftover events
if (item_ct1.get_group(2) == item_ct1.get_group_range(2) - 1) {
end_index = num_events;
} else {
end_index = (item_ct1.get_group(2) + 1) * num_pixels_per_block;
}
total_likelihoods[tid] = 0.0;
// P(x_n) = sum of likelihoods weighted by P(k) (their probability, cluster[c].pi)
// log(a+b) != log(a) + log(b) so we need to do the log of the sum of the exponentials
// For the sake of numerical stability, we first find the max and scale the values
// That way, the maximum value ever going into the exp function is 0 and we avoid overflow
// log-sum-exp formula:
// log(sum(exp(x_i)) = max(z) + log(sum(exp(z_i-max(z))))
for(int pixel=start_index; pixel<end_index; pixel += NUM_THREADS_ESTEP) {
// find the maximum likelihood for this event
max_likelihood = clusters->memberships[pixel];
for(int c=1; c<num_clusters; c++) {
max_likelihood = sycl::fmax(
max_likelihood, clusters->memberships[c * num_events + pixel]);
}
// Compute P(x_n), the denominator of the probability (sum of weighted likelihoods)
denominator_sum = 0.0;
for(int c=0; c<num_clusters; c++) {
temp = sycl::exp(clusters->memberships[c * num_events + pixel] -
max_likelihood);
denominator_sum += temp;
}
denominator_sum = max_likelihood + sycl::log(denominator_sum);
thread_likelihood += denominator_sum;
// Divide by denominator, also effectively normalize probabilities
// exp(log(p) - log(denom)) == p / denom
for(int c=0; c<num_clusters; c++) {
clusters->memberships[c * num_events + pixel] =
sycl::exp(clusters->memberships[c * num_events + pixel] -
denominator_sum);
//printf("Probability that pixel #%d is in cluster #%d: %f\n",pixel,c,clusters->memberships[c*num_events+pixel]);
}
}
total_likelihoods[tid] = thread_likelihood;
item_ct1.barrier();
temp = parallelSum(total_likelihoods, NUM_THREADS_ESTEP, item_ct1);
if(tid == 0) {
likelihood[item_ct1.get_group(2)] = temp;
}
}
/*
* Means kernel
* MultiGPU version, sums up all of the elements, but does not divide by N.
* This task is left for the host after combing results from multiple GPUs
*
* Should be launched with [M x D] grid
*/
SYCL_EXTERNAL void mstep_means(float *fcs_data, clusters_t *clusters,
int num_dimensions, int num_clusters,
int num_events, sycl::nd_item<3> item_ct1,
float *temp_sum) {
// One block per cluster, per dimension: (M x D) grid of blocks
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int c = item_ct1.get_group(2); // cluster number
int d = item_ct1.get_group(1); // dimension number
float sum = 0.0f;
for(int event=tid; event < num_events; event+= num_threads) {
sum += fcs_data[d*num_events+event]*clusters->memberships[c*num_events+event];
}
temp_sum[tid] = sum;
item_ct1.barrier();
// Reduce partial sums
sum = parallelSum(temp_sum, NUM_THREADS_MSTEP, item_ct1);
if(tid == 0) {
clusters->means[c*num_dimensions+d] = sum;
}
/*if(tid == 0) {
for(int i=1; i < num_threads; i++) {
temp_sum[0] += temp_sum[i];
}
clusters->means[c*num_dimensions+d] = temp_sum[0];
//clusters->means[c*num_dimensions+d] = temp_sum[0] / clusters->N[c];
}*/
}
/*
* Computes the size of each cluster, N
* Should be launched with M blocks (where M = number of clusters)
*/
SYCL_EXTERNAL void mstep_N(clusters_t *clusters, int num_dimensions,
int num_clusters, int num_events,
sycl::nd_item<3> item_ct1, float *temp_sums) {
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int c = item_ct1.get_group(2);
// Need to store the sum computed by each thread so in the end
// a single thread can reduce to get the final sum
// Compute new N
float sum = 0.0f;
// Break all the events accross the threads, add up probabilities
for(int event=tid; event < num_events; event += num_threads) {
sum += clusters->memberships[c*num_events+event];
}
temp_sums[tid] = sum;
item_ct1.barrier();
sum = parallelSum(temp_sums, NUM_THREADS_MSTEP, item_ct1);
if(tid == 0) {
clusters->N[c] = sum;
clusters->pi[c] = sum;
}
// Let the first thread add up all the intermediate sums
// Could do a parallel reduction...doubt it's really worth it for so few elements though
/*if(tid == 0) {
clusters->N[c] = 0.0;
for(int j=0; j<num_threads; j++) {
clusters->N[c] += temp_sums[j];
}
//printf("clusters[%d].N = %f\n",c,clusters[c].N);
// Set PI to the # of expected items, and then normalize it later
clusters->pi[c] = clusters->N[c];
}*/
}
/*
* Computes the row and col of a square matrix based on the index into
* a lower triangular (with diagonal) matrix
*
* Used to determine what row/col should be computed for covariance
* based on a block index.
*/
void compute_row_col(int n, int* row, int* col, sycl::nd_item<3> item_ct1) {
int i = 0;
for(int r=0; r < n; r++) {
for(int c=0; c <= r; c++) {
if (i == item_ct1.get_group(1)) {
*row = r;
*col = c;
return;
}
i++;
}
}
}
/*
* Computes the covariance matrices of the data (R matrix)
* Must be launched with a M x D*D grid of blocks:
* i.e. dim3 gridDim(num_clusters,num_dimensions*num_dimensions)
*/
void
mstep_covariance1(float* fcs_data, clusters_t* clusters, int num_dimensions, int num_clusters, int num_events,
sycl::nd_item<3> item_ct1, float *means, float *temp_sums) {
int tid =
item_ct1.get_local_id(2); // easier variable name for our thread ID
// Determine what row,col this matrix is handling, also handles the symmetric element
int row,col,c;
compute_row_col(num_dimensions, &row, &col, item_ct1);
//row = blockIdx.y / num_dimensions;
//col = blockIdx.y % num_dimensions;
item_ct1.barrier();
c = item_ct1.get_group(2); // Determines what cluster this block is handling
int matrix_index = row * num_dimensions + col;
#if DIAG_ONLY
if(row != col) {
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = 0.0;
matrix_index = col*num_dimensions+row;
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = 0.0;
return;
}
#endif
// Store the means in shared memory to speed up the covariance computations
// copy the means for this cluster into shared memory
if(tid < num_dimensions) {
means[tid] = clusters->means[c*num_dimensions+tid];
}
// Sync to wait for all params to be loaded to shared memory
item_ct1.barrier();
float cov_sum = 0.0;
for(int event=tid; event < num_events; event+=NUM_THREADS_MSTEP) {
cov_sum += (fcs_data[row*num_events+event]-means[row])*
(fcs_data[col*num_events+event]-means[col])*clusters->memberships[c*num_events+event];
}
temp_sums[tid] = cov_sum;
item_ct1.barrier();
cov_sum = parallelSum(temp_sums, NUM_THREADS_MSTEP, item_ct1);
if(tid == 0) {
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = cov_sum;
// Set the symmetric value
matrix_index = col*num_dimensions+row;
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = cov_sum;
// Regularize matrix - adds some variance to the diagonal elements
// Helps keep covariance matrix non-singular (so it can be inverted)
// The amount added is scaled down based on COVARIANCE_DYNAMIC_RANGE constant defined at top of this file
if(row == col) {
clusters->R[c*num_dimensions*num_dimensions+matrix_index] += clusters->avgvar[c];
}
}
}
SYCL_EXTERNAL void mstep_covariance2(float *fcs_data, clusters_t *clusters,
int num_dimensions, int num_clusters,
int num_events, sycl::nd_item<3> item_ct1,
float *means_row, float *means_col,
float *temp_sums) {
int tid =
item_ct1.get_local_id(2); // easier variable name for our thread ID
// Determine what row,col this matrix is handling, also handles the symmetric element
int row,col,c1;
compute_row_col(num_dimensions, &row, &col, item_ct1);
item_ct1.barrier();
c1 = item_ct1.get_group(2) *
NUM_CLUSTERS_PER_BLOCK; // Determines what cluster this block is
// handling
#if DIAG_ONLY
if(row != col) {
clusters->R[c*num_dimensions*num_dimensions+row*num_dimensions+col] = 0.0f;
clusters->R[c*num_dimensions*num_dimensions+col*num_dimensions+row] = 0.0f;
return;
}
#endif
// Store the means in shared memory to speed up the covariance computations
//if(tid < NUM_CLUSTERS_PER_BLOCK) {
if ((tid < sycl::min(num_clusters, NUM_CLUSTERS_PER_BLOCK)) // c1 = 0
&& (c1 + tid < num_clusters)) {
means_row[tid] = clusters->means[(c1+tid)*num_dimensions+row];
means_col[tid] = clusters->means[(c1+tid)*num_dimensions+col];
}
// Sync to wait for all params to be loaded to shared memory
item_ct1.barrier();
// 256 * 6
float cov_sum1 = 0.0f;
float cov_sum2 = 0.0f;
float cov_sum3 = 0.0f;
float cov_sum4 = 0.0f;
float cov_sum5 = 0.0f;
float cov_sum6 = 0.0f;
float val1,val2;
for(int c=0; c < NUM_CLUSTERS_PER_BLOCK; c++) {
temp_sums[c*NUM_THREADS_MSTEP+tid] = 0.0;
}
for(int event=tid; event < num_events; event+=NUM_THREADS_MSTEP) {
val1 = fcs_data[row*num_events+event];
val2 = fcs_data[col*num_events+event];
cov_sum1 += (val1-means_row[0])*(val2-means_col[0])*clusters->memberships[c1*num_events+event];
cov_sum2 += (val1-means_row[1])*(val2-means_col[1])*clusters->memberships[(c1+1)*num_events+event];
cov_sum3 += (val1-means_row[2])*(val2-means_col[2])*clusters->memberships[(c1+2)*num_events+event];
cov_sum4 += (val1-means_row[3])*(val2-means_col[3])*clusters->memberships[(c1+3)*num_events+event];
cov_sum5 += (val1-means_row[4])*(val2-means_col[4])*clusters->memberships[(c1+4)*num_events+event];
cov_sum6 += (val1-means_row[5])*(val2-means_col[5])*clusters->memberships[(c1+5)*num_events+event];
}
temp_sums[0*NUM_THREADS_MSTEP+tid] = cov_sum1;
temp_sums[1*NUM_THREADS_MSTEP+tid] = cov_sum2;
temp_sums[2*NUM_THREADS_MSTEP+tid] = cov_sum3;
temp_sums[3*NUM_THREADS_MSTEP+tid] = cov_sum4;
temp_sums[4*NUM_THREADS_MSTEP+tid] = cov_sum5;
temp_sums[5*NUM_THREADS_MSTEP+tid] = cov_sum6;
item_ct1.barrier();
for(int c=0; c < NUM_CLUSTERS_PER_BLOCK; c++) {
temp_sums[c * NUM_THREADS_MSTEP + tid] = parallelSum(
&temp_sums[c * NUM_THREADS_MSTEP], NUM_THREADS_MSTEP, item_ct1);
item_ct1.barrier();
}
if(tid == 0) {
for(int c=0; c < NUM_CLUSTERS_PER_BLOCK && (c+c1) < num_clusters; c++) {
int offset = (c+c1)*num_dimensions*num_dimensions;
cov_sum1 = temp_sums[c*NUM_THREADS_MSTEP];
clusters->R[offset+row*num_dimensions+col] = cov_sum1;
// Set the symmetric value
clusters->R[offset+col*num_dimensions+row] = cov_sum1;
// Regularize matrix - adds some variance to the diagonal elements
// Helps keep covariance matrix non-singular (so it can be inverted)
// The amount added is scaled down based on COVARIANCE_DYNAMIC_RANGE constant defined in gaussian.h
if(row == col) {
clusters->R[offset+row*num_dimensions+col] += clusters->avgvar[c+c1];
}
}
}
}
#endif // #ifndef _TEMPLATE_KERNEL_H_
| 35.217443 | 129 | 0.585982 | jchlanda |
87081461e53cd42fa90373d68e2886e31cb176fb | 1,964 | cpp | C++ | ddynamic_reconfigure/test/dd_param/test_dd_double.cpp | manomitbal/realsense-ros | 35a6f59fdfef460bc1e9f225e1a15547e2934175 | [
"Apache-2.0"
] | 45 | 2020-03-13T00:00:36.000Z | 2021-12-14T14:12:12.000Z | ddynamic_reconfigure/test/dd_param/test_dd_double.cpp | manomitbal/realsense-ros | 35a6f59fdfef460bc1e9f225e1a15547e2934175 | [
"Apache-2.0"
] | 4 | 2021-06-08T22:12:54.000Z | 2022-03-12T00:44:32.000Z | ddynamic_reconfigure/test/dd_param/test_dd_double.cpp | manomitbal/realsense-ros | 35a6f59fdfef460bc1e9f225e1a15547e2934175 | [
"Apache-2.0"
] | 7 | 2020-03-06T05:10:41.000Z | 2021-12-14T04:38:00.000Z | #include <ros/ros.h>
#include <gtest/gtest.h>
#include <ddynamic_reconfigure/param/dd_double_param.h>
namespace ddynamic_reconfigure {
/**
* @brief preliminary test which makes sure we can use the object.
*/
TEST(DDDoubleTest, constructorTest) { // NOLINT(cert-err58-cpp,modernize-use-equals-delete)
DDDouble param1("param1",0,"param1",0.5);
DDDouble param2("",0,"",1,10);
DDDouble param3("\000",0,"\000", -0, -3.4e100, 43.5e20); // NOLINT(bugprone-string-literal-with-embedded-nul)
}
/**
* @brief a test making sure we can handle all API for handling the values of the param
*/
TEST(DDDoubleTest, valueTest) { // NOLINT(cert-err58-cpp,modernize-use-equals-delete)
DDDouble param("dd_param",0,"dd_param",1);
// we won't do any tests on getLevel or getName, as those are implicit.
Value v(1.0);
ASSERT_TRUE(param.sameType(v));
ASSERT_TRUE(param.sameValue(v));
v = Value(1);
ASSERT_FALSE(param.sameType(v));
ASSERT_TRUE(param.sameValue(v));
v = Value(2.0);
ASSERT_TRUE(param.sameType(v));
ASSERT_FALSE(param.sameValue(v));
v = Value(2);
ASSERT_FALSE(param.sameType(v));
ASSERT_FALSE(param.sameValue(v));
param.setValue(v);
v = Value(3);
ASSERT_FALSE(param.sameValue(v)); // makes sure anti-aliasing happens
ASSERT_TRUE(param.getValue().getType() == "double");
ASSERT_TRUE(param.sameValue(Value(2)));
}
TEST(DDDoubleTest, streamTest) { // NOLINT(cert-err58-cpp,modernize-use-equals-delete)
DDDouble param1("param1",0,"param1",1.0);
stringstream stream;
stream << param1;
ASSERT_EQ(param1.getName() + ":" + param1.getValue().toString(),stream.str());
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
srand((unsigned int)random());
return RUN_ALL_TESTS();
} | 32.196721 | 117 | 0.625255 | manomitbal |
87090155798e02849440b7df1a3fa33529136b2a | 269 | hpp | C++ | src/typetraits/EnableIf.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/typetraits/EnableIf.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/typetraits/EnableIf.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | // Copyright 2013, James Mitchell, All rights reserved.
#pragma once
#include "Types.hpp"
namespace util
{
template<bool, typename _Tp = void> struct enable_if { };
template<typename T> struct enable_if<true, T> { DEFINE_TYPE(T) };
}
| 22.416667 | 85 | 0.639405 | jmitchell24 |
8710a8fd5e0fbcff499b7a3a4eb52546c6d56649 | 3,331 | hpp | C++ | include/codegen/include/UnityEngine/XR/InputTracking_TrackingStateEventType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/XR/InputTracking_TrackingStateEventType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/XR/InputTracking_TrackingStateEventType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.Enum
#include "System/Enum.hpp"
// Including type: UnityEngine.XR.InputTracking
#include "UnityEngine/XR/InputTracking.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine.XR
namespace UnityEngine::XR {
// Autogenerated type: UnityEngine.XR.InputTracking/TrackingStateEventType
struct InputTracking::TrackingStateEventType : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeAdded
static constexpr const int NodeAdded = 0;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeAdded
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_NodeAdded();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeAdded
static void _set_NodeAdded(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeRemoved
static constexpr const int NodeRemoved = 1;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeRemoved
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_NodeRemoved();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType NodeRemoved
static void _set_NodeRemoved(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingAcquired
static constexpr const int TrackingAcquired = 2;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingAcquired
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_TrackingAcquired();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingAcquired
static void _set_TrackingAcquired(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// static field const value: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingLost
static constexpr const int TrackingLost = 3;
// Get static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingLost
static UnityEngine::XR::InputTracking::TrackingStateEventType _get_TrackingLost();
// Set static field: static public UnityEngine.XR.InputTracking/TrackingStateEventType TrackingLost
static void _set_TrackingLost(UnityEngine::XR::InputTracking::TrackingStateEventType value);
// Creating value type constructor for type: TrackingStateEventType
TrackingStateEventType(int value_ = {}) : value{value_} {}
}; // UnityEngine.XR.InputTracking/TrackingStateEventType
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::XR::InputTracking::TrackingStateEventType, "UnityEngine.XR", "InputTracking/TrackingStateEventType");
#pragma pack(pop)
| 62.849057 | 137 | 0.783248 | Futuremappermydud |
87163c9a64bfe7a68cf6b6a346a3343bf9c8d1de | 1,600 | cpp | C++ | HDUOJ/2110/generating_function.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/2110/generating_function.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/2110/generating_function.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#define SIZE 10001
using namespace std;
typedef struct _Prop
{
int value;
int num;
} prop;
prop arr[SIZE];
int c1[SIZE], c2[SIZE];
const int mod = 10000;
int main()
{
ios::sync_with_stdio(false);
int propNum;
while (cin >> propNum)
{
if (propNum == 0)
break;
int valueSum = 0;
for (int i = 0; i < propNum; i++)
{
cin >> arr[i].value >> arr[i].num;
valueSum += arr[i].value * arr[i].num;
}
if (valueSum % 3 > 0)
{
cout << "sorry" << endl;
}
else
{
int target = valueSum / 3;
memset(c1, 0, sizeof(c1));
c1[0] = 1;
for (int i = 0; i < propNum; i++)
{
memset(c2, 0, sizeof(c2));
for (int j = 0; j <= arr[i].num && j * arr[i].value <= target; j++)
{
for (int k = 0; k + j * arr[i].value <= target; k++)
{
c2[k + j * arr[i].value] += c1[k];
c2[k + j * arr[i].value] %= mod;
}
}
memcpy(c1, c2, sizeof(c2));
}
if (c1[target] > 0)
{
cout << c1[target] % mod << endl;
}
else
{
cout << "sorry" << endl;
}
}
}
return 0;
}
| 21.621622 | 83 | 0.3925 | codgician |
8716e23fdac924e63170d4c0a2c1618179b694c0 | 1,100 | cpp | C++ | cpp/20209.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 9 | 2021-01-15T13:36:39.000Z | 2022-02-23T03:44:46.000Z | cpp/20209.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 1 | 2021-07-31T17:11:26.000Z | 2021-08-02T01:01:03.000Z | cpp/20209.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
struct State {
vector<int> v;
State(int n) : v(n) {}
int operator() () {
int ret = 0;
for (auto& i : v) ret = ret * 5 + i;
return ret;
}
bool Check() {
for (auto& i : v) if (i != v[0]) return 0;
return 1;
}
void Flip(const vector<int>& adj, int k) {
for (auto& i : adj) v[i] = (v[i] + k) % 5;
}
};
int main() {
fastio;
int n, k; cin >> n >> k;
State S(n); vector<vector<int>> adj(k);
for (int i = 0; i < n; i++) cin >> S.v[i];
for (int i = 0; i < k; i++) {
int t; cin >> t; adj[i].resize(t);
for (auto& j : adj[i]) cin >> j, --j;
}
auto Sol = [&]() -> int {
int sz = 1;
for (int i = 0; i < n; i++) sz *= 5;
vector<int> dist(sz, -1); queue<State> Q;
Q.push(S); dist[S()] = 0;
while (Q.size()) {
auto cur = Q.front(); Q.pop();
if (cur.Check()) return dist[cur()];
for (int i = 0; i < k; i++) {
auto nxt = cur; nxt.Flip(adj[i], i + 1);
if (!~dist[nxt()]) Q.push(nxt), dist[nxt()] = dist[cur()] + 1;
}
}
return -1;
};
cout << Sol() << '\n';
} | 22.916667 | 66 | 0.490909 | jinhan814 |
871831b48c69ee39c50d0046a02517f1f5fe94b0 | 748 | hpp | C++ | engine/util/WindGenerator.hpp | isonil/survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2017-05-12T10:12:41.000Z | 2017-05-12T10:12:41.000Z | engine/util/WindGenerator.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | null | null | null | engine/util/WindGenerator.hpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2019-01-09T04:05:36.000Z | 2019-01-09T04:05:36.000Z | #ifndef ENGINE_WIND_GENERATOR_HPP
#define ENGINE_WIND_GENERATOR_HPP
#include "Vec2.hpp"
#include "Vec3.hpp"
namespace engine
{
class WindGenerator
{
public:
WindGenerator(float strength, float regularity);
float getStrength() const;
void setStrength(float strength);
float getRegularity() const;
void setRegularity(float regularity);
FloatVec2 getWind(const FloatVec3 &pos, double time);
private:
float randGenerator(int x) const;
float cosInterpolator(float a, float b, float x) const;
float windSmoother(int x) const;
float noiseInterpolate(float x) const;
float noise(float x) const;
float m_strength;
float m_regularity;
};
} // namespace engine
#endif // ENGINE_WIND_GENERATOR_HPP
| 20.216216 | 59 | 0.735294 | isonil |
8719cf93353ea539a3162d3ff80b5b06f5f6013b | 1,553 | hpp | C++ | drivers/CoreVideo/include/CoreVideo.hpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | drivers/CoreVideo/include/CoreVideo.hpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | drivers/CoreVideo/include/CoreVideo.hpp | MMyster/LekaOS | 4d7fbfe83fd222eb0fb33f1f4a3fbbdc50b25ddb | [
"Apache-2.0"
] | null | null | null | // Leka - LekaOS
// Copyright 2021 APF France handicap
// SPDX-License-Identifier: Apache-2.0
#ifndef _LEKA_OS_DRIVER_CORE_VIDEO_H_
#define _LEKA_OS_DRIVER_CORE_VIDEO_H_
#include "CoreSTM32HalBase.h"
#include "interface/DMA2D.hpp"
#include "interface/DSI.hpp"
#include "interface/Font.hpp"
#include "interface/Graphics.hpp"
#include "interface/JPEG.hpp"
#include "interface/LCD.hpp"
#include "interface/LTDC.hpp"
#include "interface/SDRAM.hpp"
namespace leka {
class CoreVideo
{
public:
CoreVideo(CoreSTM32HalBase &hal, interface::SDRAM &coresdram, interface::DMA2DBase &coredma2d,
interface::DSIBase &coredsi, interface::LTDCBase &coreltdc, interface::LCD &corelcd,
interface::Graphics &coregraphics, interface::Font &corefont, interface::JPEGBase &corejpeg);
void initialize();
void turnOff();
void turnOn();
void setBrightness(float value);
void clearScreen(CGColor color = CGColor::white);
void displayRectangle(interface::Graphics::FilledRectangle rectangle, CGColor color);
void displayImage(FIL *file);
void displayText(const char *text, uint32_t size, uint32_t starting_line, CGColor foreground = CGColor::black,
CGColor background = CGColor::white);
private:
CoreSTM32HalBase &_hal;
interface::SDRAM &_coresdram;
interface::DMA2DBase &_coredma2d;
interface::DSIBase &_coredsi;
interface::LTDCBase &_coreltdc;
interface::LCD &_corelcd;
interface::Graphics &_coregraphics;
interface::Font &_corefont;
interface::JPEGBase &_corejpeg;
};
} // namespace leka
#endif // _LEKA_OS_DRIVER_CORE_VIDEO_H_
| 28.236364 | 111 | 0.768835 | MMyster |
26bb028f4fa7e6b5a52a3612176d82174ab1587a | 310 | cpp | C++ | Src/TabelaDeSimbolos/Teste/Teste.cpp | pedrol3001/Compiler | 3e68304bb35b8e4f3f4e17030ae8c6c10da0bcb4 | [
"MIT"
] | 1 | 2022-03-01T16:57:32.000Z | 2022-03-01T16:57:32.000Z | Src/TabelaDeSimbolos/Teste/Teste.cpp | pedrol3001/Compiler | 3e68304bb35b8e4f3f4e17030ae8c6c10da0bcb4 | [
"MIT"
] | null | null | null | Src/TabelaDeSimbolos/Teste/Teste.cpp | pedrol3001/Compiler | 3e68304bb35b8e4f3f4e17030ae8c6c10da0bcb4 | [
"MIT"
] | 1 | 2022-03-23T18:35:12.000Z | 2022-03-23T18:35:12.000Z | #include "Teste.h"
#include <string>
using namespace std;
StrAtt::StrAtt(string _str, long long int _linha, long long int _coluna, long long int _posicao) :
Atributo("StrAtt"), str(_str),linha(_linha),coluna(_coluna),posicao(_posicao) {}
NameAtt::NameAtt(string _str) : Atributo("NameAtt"), str(_str) {}
| 28.181818 | 99 | 0.725806 | pedrol3001 |
26bc3aff8d23a92d56377a94beb2252256a9cf07 | 7,290 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/PrintSystemAttributeValueFactory.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | 1 | 2020-01-11T12:53:52.000Z | 2020-01-11T12:53:52.000Z | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/PrintSystemAttributeValueFactory.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | null | null | null | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/PrintSystemAttributeValueFactory.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | 1 | 2021-05-05T12:05:28.000Z | 2021-05-05T12:05:28.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "win32inc.hpp"
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
using namespace System::Collections::Specialized;
using namespace System::Xml;
using namespace System::Xml::XPath;
#ifndef __PRINTSYSTEMINTEROPINC_HPP__
#include <PrintSystemInteropInc.hpp>
#endif
#ifndef __PRINTSYSTEMINC_HPP__
#include <PrintSystemInc.hpp>
#endif
using namespace System::Printing;
#ifndef __PRINTSYSTEMATTRIBUTEVALUEFACTORY_HPP__
#include <PrintSystemAttributeValueFactory.hpp>
#endif
using namespace System::Printing::Activation;
PrintPropertyFactory::
PrintPropertyFactory(
void
):
valueDelegatesTable(nullptr),
noValueDelegatesTable(nullptr),
valueLinkedDelegatesTable(nullptr),
noValueLinkedDelegatesTable(nullptr)
{
if(!((valueDelegatesTable = gcnew Hashtable) &&
(noValueDelegatesTable = gcnew Hashtable) &&
(valueLinkedDelegatesTable = gcnew Hashtable) &&
(noValueLinkedDelegatesTable = gcnew Hashtable)))
{
}
}
PrintPropertyFactory::
~PrintPropertyFactory(
void
)
{
InternalDispose(true);
}
PrintPropertyFactory::
!PrintPropertyFactory(
void
)
{
InternalDispose(false);
}
void
PrintPropertyFactory::
InternalDispose(
bool disposing
)
{
if(!this->isDisposed)
{
System::Threading::Monitor::Enter(SyncRoot);
{
__try
{
if(!this->isDisposed)
{
if(disposing)
{
isDisposed = true;
valueDelegatesTable = nullptr;
noValueDelegatesTable = nullptr;
valueLinkedDelegatesTable = nullptr;
noValueLinkedDelegatesTable = nullptr;
}
}
}
__finally
{
System::Threading::Monitor::Exit(SyncRoot);
}
}
}
}
PrintPropertyFactory^
PrintPropertyFactory::Value::
get(
void
)
{
if(PrintPropertyFactory::value == nullptr)
{
System::Threading::Monitor::Enter(SyncRoot);
{
__try
{
if(PrintPropertyFactory::value == nullptr)
{
PrintPropertyFactory::value = gcnew PrintPropertyFactory();
}
}
__finally
{
System::Threading::Monitor::Exit(SyncRoot);
}
}
}
return const_cast<PrintPropertyFactory^>(PrintPropertyFactory::value);
}
Object^
PrintPropertyFactory::SyncRoot::
get(
void
)
{
return const_cast<Object^>(syncRoot);
}
void
PrintPropertyFactory::
RegisterValueCreationDelegate(
Type^ type,
PrintProperty::CreateWithValue^ delegate
)
{
try
{
valueDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
RegisterNoValueCreationDelegate(
Type^ type,
PrintProperty::CreateWithNoValue^ delegate
)
{
try
{
noValueDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
RegisterValueLinkedCreationDelegate(
Type^ type,
PrintProperty::CreateWithValueLinked^ delegate
)
{
try
{
valueLinkedDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
RegisterNoValueLinkedCreationDelegate(
Type^ type,
PrintProperty::CreateWithNoValueLinked^ delegate
)
{
try
{
noValueLinkedDelegatesTable->Add(type->FullName,
delegate);
}
catch(ArgumentException^)
{
//
// Nothing to do, this means that the item has been already
// added to the hashtable
//
}
}
void
PrintPropertyFactory::
UnRegisterValueCreationDelegate(
Type^ type
)
{
valueDelegatesTable->Remove(type->FullName);
}
void
PrintPropertyFactory::
UnRegisterNoValueCreationDelegate(
Type^ type
)
{
noValueDelegatesTable->Remove(type->FullName);
}
void
PrintPropertyFactory::
UnRegisterValueLinkedCreationDelegate(
Type^ type
)
{
valueLinkedDelegatesTable->Remove(type->FullName);
}
void
PrintPropertyFactory::
UnRegisterNoValueLinkedCreationDelegate(
Type^ type
)
{
noValueLinkedDelegatesTable->Remove(type->FullName);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName
)
{
PrintProperty::CreateWithNoValue^ attributeValueDelegate =
(PrintProperty::CreateWithNoValue^)noValueDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName,
Object^ attribValue
)
{
PrintProperty::CreateWithValue^ attributeValueDelegate =
(PrintProperty::CreateWithValue^)valueDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName,attribValue);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName,
MulticastDelegate^ delegate
)
{
PrintProperty::CreateWithNoValueLinked^ attributeValueDelegate =
(PrintProperty::CreateWithNoValueLinked^)noValueLinkedDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName,delegate);
}
PrintProperty^
PrintPropertyFactory::
Create(
Type^ type,
String^ attribName,
Object^ attribValue,
MulticastDelegate^ delegate
)
{
PrintProperty::CreateWithValueLinked^ attributeValueDelegate =
(PrintProperty::CreateWithValueLinked^)valueLinkedDelegatesTable[type->FullName];
return attributeValueDelegate->Invoke(attribName,attribValue,delegate);
}
IEnumerator^
PrintPropertyFactory::
GetEnumerator(
void
)
{
return nullptr;
}
| 22.639752 | 90 | 0.593141 | reyqn |
26be764d9a47683a99f73033ecfaeb1b2023ec1f | 253 | cc | C++ | src/remain.cc | xet7/JadeLib | f1b2d7d9179904103baf70c29b5029500fb55bf9 | [
"MIT"
] | null | null | null | src/remain.cc | xet7/JadeLib | f1b2d7d9179904103baf70c29b5029500fb55bf9 | [
"MIT"
] | null | null | null | src/remain.cc | xet7/JadeLib | f1b2d7d9179904103baf70c29b5029500fb55bf9 | [
"MIT"
] | null | null | null | #include "include/jade.hpp"
FUNCTION STRING REMAIN$ (STRING src, STRING match) DO
STRING tmpStr;
INTEGER pos;
pos = src.find(match);
IF (pos >= 0) THEN
tmpStr = src.substr(pos,src.size());
END
RETURN tmpStr;
END
| 15.8125 | 53 | 0.604743 | xet7 |
26c01fac9c00495d500cc22b6a3fe183185c2dc4 | 468 | cpp | C++ | UnitTest/test_math.cpp | SFCMM/GridGenerator | b9fcb6e660f0d1343c8c992234e85490514942c0 | [
"BSD-3-Clause"
] | null | null | null | UnitTest/test_math.cpp | SFCMM/GridGenerator | b9fcb6e660f0d1343c8c992234e85490514942c0 | [
"BSD-3-Clause"
] | null | null | null | UnitTest/test_math.cpp | SFCMM/GridGenerator | b9fcb6e660f0d1343c8c992234e85490514942c0 | [
"BSD-3-Clause"
] | null | null | null | #include "gtest/gtest.h"
#include "math/mathfunctions.h"
TEST(MathApprox, HandlesZeroInput) {
const double eps = std::numeric_limits<double>::epsilon();
ASSERT_TRUE(approx(1.0, 1.0, eps));
ASSERT_FALSE(approx(1.0, 1.0 + eps, eps));
const float one = 1.0;
const float epsf = std::numeric_limits<float>::epsilon();
ASSERT_TRUE(approx(one, one, epsf));
ASSERT_FALSE(approx(one, one + epsf, epsf));
ASSERT_TRUE(isEven(2));
ASSERT_FALSE(isEven(1));
}
| 27.529412 | 60 | 0.690171 | SFCMM |
26c07a555e21348d05e8a98da5b7f76539017920 | 1,598 | cpp | C++ | Latte/Latte/RenderingContext.cpp | Morkonena/Coffee-Maker | 45d91301ef497c3a009379ec4ea3bbe18ec21808 | [
"MIT"
] | null | null | null | Latte/Latte/RenderingContext.cpp | Morkonena/Coffee-Maker | 45d91301ef497c3a009379ec4ea3bbe18ec21808 | [
"MIT"
] | null | null | null | Latte/Latte/RenderingContext.cpp | Morkonena/Coffee-Maker | 45d91301ef497c3a009379ec4ea3bbe18ec21808 | [
"MIT"
] | null | null | null | #include "RenderingContext.h"
#include "Window.h"
#include <GL\glew.h>
#include <GL\wglew.h>
#include <Log.h>
#include <thread>
using namespace Core;
#define MAX_UNBIND_TRIES 10
RenderingContext::RenderingContext()
{}
RenderingContext::RenderingContext(const Window* window, const RenderingContext* share)
{
this->window = window;
const int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 5,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0
};
// Create a rendering context capable of using OpenGL 3.x or later
handle = wglCreateContextAttribsARB(window->GetDeviceContext(), (share ? share->handle : 0), attributes);
if (!handle)
{
PERROR("ERROR_CREATE_RENDERING_CONTEXT (", GetLastError(), ")");
throw;
}
}
RenderingContext::RenderingContext(RenderingContext&& rendering_context)
{
this->handle = rendering_context.handle;
this->window = rendering_context.window;
rendering_context.handle = 0;
rendering_context.window = 0;
}
RenderingContext& RenderingContext::operator=(RenderingContext&& rendering_context)
{
this->handle = rendering_context.handle;
this->window = rendering_context.window;
rendering_context.handle = 0;
rendering_context.window = 0;
return *this;
}
RenderingContext::~RenderingContext()
{
if (handle)
{
wglMakeCurrent(0, 0);
wglDeleteContext(handle);
}
}
bool RenderingContext::Bind()
{
return wglMakeCurrent(window->GetDeviceContext(), handle) == TRUE;
}
bool RenderingContext::Unbind()
{
return wglMakeCurrent(0, 0) == TRUE;
}
| 20.487179 | 107 | 0.732165 | Morkonena |
26c1518c05ad73b6cd8b78c31bc04883a04377ba | 890 | cpp | C++ | source/web.cpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 1 | 2021-02-12T23:53:55.000Z | 2021-02-12T23:53:55.000Z | source/web.cpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | source/web.cpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | #define DISH2_LOG_ENABLE
#include <emscripten.h>
#include "conduit/include/uitsl/polyfill/ompi_mpi_comm_world.hpp"
#include "Empirical/include/emp/config/ArgManager.hpp"
#include "Empirical/include/emp/web/UrlParams.hpp"
#include "dish2/config/cfg.hpp"
#include "dish2/config/make_arg_specs.hpp"
#include "dish2/config/setup.hpp"
#include "dish2/spec/Spec.hpp"
#include "dish2/web/WebInterface.hpp"
#include "dish2/world/ProcWorld.hpp"
using Spec = dish2::Spec;
thread_local dish2::WebInterface* interface;
int main() {
dish2::setup( emp::ArgManager{
emp::web::GetUrlParams(), dish2::make_arg_specs()
} );
interface = new dish2::WebInterface;
// set up web interface
interface->Redraw();
emscripten_set_main_loop([](){}, 1, true);
// once we're done setting up, turn off the loading modal
// MAIN_THREAD_EM_ASM({ $('.modal').modal('hide'); });
return 0;
}
| 23.421053 | 65 | 0.723596 | schregardusc |
26c22fb275907e1552ed3e14b095f764b6298159 | 2,341 | hh | C++ | include/memory.hh | fmatthew5876/stdcxx-align | 51cd1bd60cd3257ddc40cb4c32195e7c1f39eddd | [
"MIT"
] | 1 | 2021-06-04T13:18:13.000Z | 2021-06-04T13:18:13.000Z | include/memory.hh | fmatthew5876/stdcxx-align | 51cd1bd60cd3257ddc40cb4c32195e7c1f39eddd | [
"MIT"
] | null | null | null | include/memory.hh | fmatthew5876/stdcxx-align | 51cd1bd60cd3257ddc40cb4c32195e7c1f39eddd | [
"MIT"
] | null | null | null | #ifndef _MEMORY_HH_
#define _MEMORY_HH_
#include <cstdio>
#include <memory>
#include <type_traits>
namespace std {
template <typename T>
constexpr auto is_aligned(T x, size_t a) noexcept
-> typename std::enable_if<std::is_integral<T>::value &&!is_same<T,bool>::value, bool>::type {
return (x & (a-1)) == 0;
}
template <typename T>
constexpr auto align_up(T x, size_t a) noexcept
-> typename std::enable_if<std::is_integral<T>::value &&!is_same<T,bool>::value, bool>::type {
return (x + (a-1)) & -a;
}
template <typename T>
constexpr auto align_down(T x, size_t a) noexcept
-> typename std::enable_if<std::is_integral<T>::value &&!is_same<T,bool>::value, bool>::type {
return x & (-a);
}
inline bool is_aligned(const volatile void* p, size_t a) {
return is_aligned(reinterpret_cast<uintptr_t>(p), a);
}
template <typename T>
inline auto align_up(T p, size_t a)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_up(reinterpret_cast<uintptr_t>(p), a));
}
inline nullptr_t align_up(nullptr_t, size_t) { return nullptr; }
template <typename T>
inline auto align_down(T p, size_t a)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_down(reinterpret_cast<uintptr_t>(p), a));
}
inline nullptr_t align_down(nullptr_t, size_t) { return nullptr; }
template <typename T, typename U>
inline auto align_up_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type))
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_up(p, a));
}
template <typename T>
inline auto align_up_cast(nullptr_t p, size_t a=1)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
(void)a;
nullptr;
}
template <typename T, typename U>
inline auto align_down_cast(U* p, size_t a=alignof(typename std::remove_pointer<T>::type))
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
return reinterpret_cast<T>(align_down(p, a));
}
template <typename T>
inline auto align_down_cast(nullptr_t p, size_t a=1)
-> typename std::enable_if<std::is_pointer<T>::value, T>::type {
(void)a;
nullptr;
}
} //namespace std
#endif
| 29.632911 | 96 | 0.668518 | fmatthew5876 |
26c42b996b47698525281a1b721a154d6d7e96b0 | 1,267 | cc | C++ | examples/ui-gtk3.cc | jpcima/skeleton.lv2 | e696eb2c1c63f4fad390744d185ca230e49c59fe | [
"BSL-1.0"
] | 8 | 2019-08-22T15:17:22.000Z | 2022-02-04T04:24:28.000Z | examples/ui-gtk3.cc | jpcima/skeleton.lv2 | e696eb2c1c63f4fad390744d185ca230e49c59fe | [
"BSL-1.0"
] | 1 | 2020-05-31T10:29:09.000Z | 2020-06-01T09:57:11.000Z | examples/ui-gtk3.cc | jpcima/skeleton.lv2 | e696eb2c1c63f4fad390744d185ca230e49c59fe | [
"BSL-1.0"
] | null | null | null | #include "framework/ui.h"
#include <gtk/gtk.h>
struct UI::Impl {
static constexpr unsigned width = 600;
static constexpr unsigned height = 400;
GtkWidget *widget = nullptr;
void create_widget();
};
//==============================================================================
UI::UI(void *parent, LV2_URID_Map *map, LV2_URID_Unmap *unmap,
const char *bundle_path)
: P(new Impl) {
}
UI::~UI() {
}
void UI::option(const LV2_Options_Option &o) {
}
LV2UI_Widget UI::widget() const {
if (!P->widget)
P->create_widget();
return LV2UI_Widget(P->widget);
}
unsigned UI::width() {
return Impl::width;
}
unsigned UI::height() {
return Impl::height;
}
void UI::port_event(
uint32_t port_index, uint32_t buffer_size, uint32_t format, const void *buffer) {
}
bool UI::needs_idle_callback() {
return false;
}
bool UI::idle() {
return false;
}
//==============================================================================
void UI::Impl::create_widget() {
GtkWidget *editor = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
gtk_widget_set_size_request(editor, Impl::width, Impl::height);
GtkWidget *label = gtk_label_new("Hello, World!");
gtk_box_pack_start(GTK_BOX(editor), label, true, true, 0);
this->widget = editor;
}
| 22.22807 | 85 | 0.600631 | jpcima |
26d168de38dc22e0dc1d78a81e93904099e23ae7 | 1,319 | cpp | C++ | napi/algorithms.cpp | graeme-hill/snakebot | 21059e4b5e3153ada5e74ba2e1331c10b5142b2f | [
"MIT",
"Unlicense"
] | 8 | 2018-06-26T05:42:17.000Z | 2021-10-20T23:19:20.000Z | napi/algorithms.cpp | graeme-hill/snakebot | 21059e4b5e3153ada5e74ba2e1331c10b5142b2f | [
"MIT",
"Unlicense"
] | null | null | null | napi/algorithms.cpp | graeme-hill/snakebot | 21059e4b5e3153ada5e74ba2e1331c10b5142b2f | [
"MIT",
"Unlicense"
] | 5 | 2019-06-01T15:34:07.000Z | 2022-02-12T06:10:16.000Z | #include "algorithms.hpp"
#include "algorithms/cautious.hpp"
#include "algorithms/hungry.hpp"
#include "algorithms/terminator.hpp"
#include "algorithms/dog.hpp"
#include "algorithms/sim.hpp"
#include "algorithms/inyourface.hpp"
#include "algorithms/random.hpp"
#include "algorithms/onedirection.hpp"
Algorithms Algorithms::_instance;
Algorithms::Algorithms()
{
_algorithms["cautious"] = std::make_unique<Cautious>();
_algorithms["hungry"] = std::make_unique<Hungry>();
_algorithms["terminator"] = std::make_unique<Terminator>();
_algorithms["dog"] = std::make_unique<Dog>();
_algorithms["sim"] = std::make_unique<Sim>();
_algorithms["inyourface"] = std::make_unique<InYourFace>();
_algorithms["random"] = std::make_unique<Random>();
_algorithms["onedirection_left"] = std::make_unique<OneDirection>(Direction::Left);
_algorithms["onedirection_right"] = std::make_unique<OneDirection>(Direction::Right);
_algorithms["onedirection_up"] = std::make_unique<OneDirection>(Direction::Up);
_algorithms["onedirection_down"] = std::make_unique<OneDirection>(Direction::Down);
}
Algorithm *Algorithms::get(std::string key)
{
auto it = _instance._algorithms.find(key);
if (it == _instance._algorithms.end())
{
return nullptr;
}
return it->second.get();
}
| 35.648649 | 89 | 0.715694 | graeme-hill |
26d8f5fb3168d29084c4645ed4e692d72ea13e7f | 1,759 | cpp | C++ | src/framework/suites.cpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 8 | 2021-01-02T11:41:31.000Z | 2021-04-15T07:05:54.000Z | src/framework/suites.cpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 17 | 2021-01-08T06:52:51.000Z | 2021-04-18T20:00:28.000Z | src/framework/suites.cpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 1 | 2021-04-16T10:30:23.000Z | 2021-04-16T10:30:23.000Z | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
#include "touca/framework/suites.hpp"
#include <algorithm>
#include <fstream>
#include "touca/devkit/platform.hpp"
namespace touca {
namespace framework {
RemoteSuite::RemoteSuite(const Options& options) : Suite(), _options(options) {}
void RemoteSuite::initialize() {
// To obtain list of testcases from the server, we expect
// the following configuration options are set.
const std::vector<std::string> keys = {"api-key", "api-url", "team", "suite",
"revision"};
const auto predicate = [this](const std::string& k) {
return _options.count(k);
};
if (!std::all_of(keys.begin(), keys.end(), predicate)) {
return;
}
// authenticate to the server.
ApiUrl api_url(_options.at("api-url"));
if (!api_url.confirm(_options.at("team"), _options.at("suite"),
_options.at("revision"))) {
throw std::runtime_error(api_url._error);
}
Platform platform(api_url);
if (!platform.auth(_options.at("api-key"))) {
throw std::runtime_error(platform.get_error());
}
// ask the server for the list of elements
for (const auto& element : platform.elements()) {
push(element);
}
}
FileSuite::FileSuite(const std::string& path) : Suite(), _path(path) {}
void FileSuite::initialize() {
std::string line;
std::ifstream ifs(_path);
while (std::getline(ifs, line)) {
// skip empty lines
if (line.empty()) {
continue;
}
// skip comment lines: by default, we define comment lines as
// lines that start with two pound characters
if (line.compare(0, 2, "##") == 0) {
continue;
}
push(line);
}
}
} // namespace framework
} // namespace touca
| 25.492754 | 80 | 0.633314 | getweasel |
26d907f758509cc2a75e820b8e5d8dcbe26968a5 | 13,389 | cpp | C++ | lib/rendercore_vulkan_rt/vulkan_gl_texture_interop.cpp | vincevannoort/lighthouse2 | 31c76490e01ccdcd01766ea046d66687375c04da | [
"Apache-2.0"
] | 691 | 2019-07-10T13:46:05.000Z | 2022-03-31T05:31:56.000Z | lib/rendercore_vulkan_rt/vulkan_gl_texture_interop.cpp | vincevannoort/lighthouse2 | 31c76490e01ccdcd01766ea046d66687375c04da | [
"Apache-2.0"
] | 20 | 2019-07-11T08:16:48.000Z | 2022-02-21T17:59:28.000Z | lib/rendercore_vulkan_rt/vulkan_gl_texture_interop.cpp | vincevannoort/lighthouse2 | 31c76490e01ccdcd01766ea046d66687375c04da | [
"Apache-2.0"
] | 83 | 2019-07-11T09:55:24.000Z | 2022-03-30T03:04:01.000Z | /* vulkan_gl_texture_interop.cpp - Copyright 2019/2020 Utrecht University
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "core_settings.h"
#ifdef WIN32
static PFN_vkGetMemoryWin32HandleKHR getMemoryWin32HandleKHR = nullptr;
#else
static PFN_vkGetMemoryFdKHR getMemoryFdKHR = nullptr;
#endif
lh2core::VulkanGLTextureInterop::VulkanGLTextureInterop( const VulkanDevice &device, uint32_t width, uint32_t height )
{
m_Device = device;
m_Width = width;
m_Height = height;
if ( glCreateMemoryObjectsEXT == nullptr ||
#if WIN32
glImportMemoryWin32HandleEXT == nullptr ||
#else // LINUX
glImportMemoryFdEXT == nullptr ||
#endif
glTextureStorageMem2DEXT == nullptr )
{
FATALERROR ( "A Vulkan-OpenGL interop requires an OpenGL 4.5 context and the following extensions: GL_EXT_memory_object, GL_EXT_memory_object_fd, GL_EXT_memory_object_win32. At least 1 of these was not found" );
}
m_Width = width;
m_Height = height;
// Create Vulkan image
vk::ImageCreateInfo imageCreateInfo{};
imageCreateInfo.setPNext( nullptr );
imageCreateInfo.setArrayLayers( 1 );
imageCreateInfo.setExtent( {width, height, 1} );
imageCreateInfo.setFlags( vk::ImageCreateFlags() );
imageCreateInfo.setFormat( vk::Format::eR32G32B32A32Sfloat );
imageCreateInfo.setImageType( vk::ImageType::e2D );
imageCreateInfo.setInitialLayout( vk::ImageLayout::eUndefined );
imageCreateInfo.setMipLevels( 1 );
imageCreateInfo.setQueueFamilyIndexCount( 0 );
imageCreateInfo.setPQueueFamilyIndices( nullptr );
imageCreateInfo.setTiling( vk::ImageTiling() );
imageCreateInfo.setUsage( vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferDst );
m_Image = m_Device->createImage( imageCreateInfo );
assert( m_Image );
// Get memory requirements
auto memoryRequirements = m_Device->getImageMemoryRequirements( m_Image );
// Allocate memory for image
vk::ExportMemoryAllocateInfo exportAllocInfo{};
exportAllocInfo.setHandleTypes( vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
vk::MemoryAllocateInfo memAllocInfo{};
memAllocInfo.pNext = &exportAllocInfo;
m_BufferSize = NEXTMULTIPLEOF( vk::DeviceSize( memoryRequirements.size * 1.3f ), memoryRequirements.alignment );
memAllocInfo.setAllocationSize( m_BufferSize );
memoryRequirements.size = m_BufferSize;
memAllocInfo.setMemoryTypeIndex( m_Device.GetMemoryType( memoryRequirements, vk::MemoryPropertyFlagBits::eDeviceLocal ) );
m_Memory = m_Device->allocateMemory( memAllocInfo );
assert( m_Memory );
// Bind memory to Vulkan image
m_Device->bindImageMemory( m_Image, m_Memory, 0 );
#ifdef WIN32
HANDLE handle = INVALID_HANDLE_VALUE;
#else
int handle = 0;
#endif
#if WIN32 // WINDOWS
// Resolve extension function if needed
if ( getMemoryWin32HandleKHR == nullptr )
getMemoryWin32HandleKHR = reinterpret_cast<PFN_vkGetMemoryWin32HandleKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryWin32HandleKHR" ) );
assert( getMemoryWin32HandleKHR != nullptr );
// Acquire WIN32 handle to Vulkan initialized memory
vk::MemoryGetWin32HandleInfoKHR getMemoryHandleInfo = vk::MemoryGetWin32HandleInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
getMemoryWin32HandleKHR( m_Device.GetVkDevice(), (VkMemoryGetWin32HandleInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != INVALID_HANDLE_VALUE && handle != nullptr );
#else // LINUX
// Resolve extension function if needed
if ( getMemoryFdKHR == nullptr )
getMemoryFdKHR = reinterpret_cast<PFN_vkGetMemoryFdKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryFdKHR" ) );
assert( getMemoryFdKHR != nullptr );
// Acquire Fd handle to Vulkan initialized memory
vk::MemoryGetFdInfoKHR getMemoryHandleInfo = vk::MemoryGetFdInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueFd );
getMemoryFdKHR( m_Device.GetVkDevice(), (VkMemoryGetFdInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != 0 );
#endif
// Create a new texture object in OpenGL
glCreateTextures( GL_TEXTURE_2D, 1, &m_TexID );
// Create external memory object
glCreateMemoryObjectsEXT( 1, &m_GLMemoryObj );
// Import Vulkan memory handle into OpenGL memory object
#if _WIN32
glImportMemoryWin32HandleEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, handle );
#else
glImportMemoryFdEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_FD_EXT, handle );
#endif
CheckGL();
// Point texture object to external OpenGL memory object
m_Width = width;
m_Height = height;
glTextureStorageMem2DEXT( m_TexID, 1, GL_RGBA32F, m_Width, m_Height, m_GLMemoryObj, 0 );
// Check for any errors
CheckGL();
}
lh2core::VulkanGLTextureInterop::~VulkanGLTextureInterop()
{
Cleanup();
}
void lh2core::VulkanGLTextureInterop::RecordTransitionToVulkan( vk::CommandBuffer &cmdBuffer )
{
// Our image has 1 layer
vk::ImageSubresourceRange subresourceRange{};
subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
// Transition from color attachment to transfer destination
vk::ImageMemoryBarrier imageMemoryBarrier{};
imageMemoryBarrier.oldLayout = vk::ImageLayout::eColorAttachmentOptimal;
imageMemoryBarrier.newLayout = vk::ImageLayout::eTransferDstOptimal;
imageMemoryBarrier.image = m_Image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
imageMemoryBarrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
vk::PipelineStageFlags destStageMask = vk::PipelineStageFlagBits::eTransfer;
cmdBuffer.pipelineBarrier( srcStageMask, destStageMask, vk::DependencyFlags(), nullptr, nullptr, imageMemoryBarrier );
}
void lh2core::VulkanGLTextureInterop::RecordTransitionToGL( vk::CommandBuffer &cmdBuffer )
{
// Our image has 1 layer
vk::ImageSubresourceRange subresourceRange;
subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
// Transition our image to be used as a color attachment
vk::ImageMemoryBarrier imageMemoryBarrier;
imageMemoryBarrier.oldLayout = vk::ImageLayout::eUndefined;
imageMemoryBarrier.newLayout = vk::ImageLayout::eColorAttachmentOptimal;
imageMemoryBarrier.image = m_Image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = vk::AccessFlags();
imageMemoryBarrier.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eTopOfPipe;
vk::PipelineStageFlags destStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
cmdBuffer.pipelineBarrier( srcStageMask, destStageMask, vk::DependencyFlags(), nullptr, nullptr, imageMemoryBarrier );
}
void lh2core::VulkanGLTextureInterop::Cleanup()
{
glFlush();
glFinish();
if ( m_Image )
{
m_Device->destroyImage( m_Image );
m_Image = nullptr;
}
if ( m_Memory )
{
glDeleteMemoryObjectsEXT( 1, &m_GLMemoryObj );
m_GLMemoryObj = 0;
m_Device->freeMemory( m_Memory );
m_Memory = nullptr;
}
}
std::vector<const char *> lh2core::VulkanGLTextureInterop::GetRequiredExtensions()
{
#ifdef WIN32 // WINDOWS
return {
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME};
#else // LINUX
return {
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME};
#endif
}
void lh2core::VulkanGLTextureInterop::Resize( uint32_t width, uint32_t height, bool deleteOldGLTexture )
{
m_Width = width;
m_Height = height;
if ( m_Image ) m_Device->destroyImage( m_Image );
// Create Vulkan image
vk::ImageCreateInfo imageCreateInfo{};
imageCreateInfo.setPNext( nullptr );
imageCreateInfo.setArrayLayers( 1 );
imageCreateInfo.setExtent( {width, height, 1} );
imageCreateInfo.setFlags( vk::ImageCreateFlags() );
imageCreateInfo.setFormat( vk::Format::eR32G32B32A32Sfloat );
imageCreateInfo.setImageType( vk::ImageType::e2D );
imageCreateInfo.setInitialLayout( vk::ImageLayout::eUndefined );
imageCreateInfo.setMipLevels( 1 );
imageCreateInfo.setQueueFamilyIndexCount( 0 );
imageCreateInfo.setPQueueFamilyIndices( nullptr );
imageCreateInfo.setTiling( vk::ImageTiling() );
imageCreateInfo.setUsage( vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferDst );
m_Image = m_Device->createImage( imageCreateInfo );
assert( m_Image );
// Get memory requirements
auto memoryRequirements = m_Device->getImageMemoryRequirements( m_Image );
if ( memoryRequirements.size > m_BufferSize )
{
m_Device->freeMemory( m_Memory );
m_BufferSize = NEXTMULTIPLEOF( vk::DeviceSize( memoryRequirements.size * 1.3f ), memoryRequirements.alignment );
memoryRequirements.size = m_BufferSize;
// Allocate memory
vk::ExportMemoryAllocateInfo exportAllocInfo{};
exportAllocInfo.setHandleTypes( vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
vk::MemoryAllocateInfo memAllocInfo{};
memAllocInfo.pNext = &exportAllocInfo;
memAllocInfo.setAllocationSize( m_BufferSize );
memAllocInfo.setMemoryTypeIndex( m_Device.GetMemoryType( memoryRequirements, vk::MemoryPropertyFlagBits::eDeviceLocal ) );
m_Memory = m_Device->allocateMemory( memAllocInfo );
}
assert( m_Memory );
m_Device->bindImageMemory( m_Image, m_Memory, 0 );
#ifdef WIN32
HANDLE handle = INVALID_HANDLE_VALUE;
#else
int handle = 0;
#endif
#if _WIN32 // WINDOWS
// Resolve extension function if needed
if ( getMemoryWin32HandleKHR == nullptr )
getMemoryWin32HandleKHR = reinterpret_cast<PFN_vkGetMemoryWin32HandleKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryWin32HandleKHR" ) );
assert( getMemoryWin32HandleKHR != nullptr );
// Acquire WIN32 handle to Vulkan initialized memory
vk::MemoryGetWin32HandleInfoKHR getMemoryHandleInfo = vk::MemoryGetWin32HandleInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueWin32KHR );
getMemoryWin32HandleKHR( m_Device.GetVkDevice(), (VkMemoryGetWin32HandleInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != INVALID_HANDLE_VALUE && handle != nullptr );
#else // LINUX
// Resolve extension function if needed
if ( getMemoryFdKHR == nullptr )
getMemoryFdKHR = reinterpret_cast<PFN_vkGetMemoryFdKHR>( vkGetDeviceProcAddr( m_Device.GetVkDevice(), "vkGetMemoryFdKHR" ) );
assert( getMemoryFdKHR != nullptr );
// Acquire Fd handle to Vulkan initialized memory
vk::MemoryGetFdInfoKHR getMemoryHandleInfo = vk::MemoryGetFdInfoKHR( m_Memory, vk::ExternalMemoryHandleTypeFlagBits::eOpaqueFd );
getMemoryFdKHR( m_Device.GetVkDevice(), (VkMemoryGetFdInfoKHR *)&getMemoryHandleInfo, &handle );
assert( handle != 0 );
#endif
// Create a new texture object in OpenGL
if ( deleteOldGLTexture )
glDeleteTextures( 1, &m_TexID );
glDeleteMemoryObjectsEXT( 1, &m_GLMemoryObj );
glCreateTextures( GL_TEXTURE_2D, 1, &m_TexID );
glCreateMemoryObjectsEXT( 1, &m_GLMemoryObj );
assert( m_TexID );
assert( m_GLMemoryObj );
// Bind Vulkan memory handle to OpenGL memory object
#if _WIN32
glImportMemoryWin32HandleEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, handle );
#else
glImportMemoryFdEXT( m_GLMemoryObj, memoryRequirements.size, GL_HANDLE_TYPE_OPAQUE_FD_EXT, handle );
#endif
CheckGL();
// Point texture object to external OpenGL memory object
glTextureStorageMem2DEXT( m_TexID, 1, GL_RGBA32F, width, height, m_GLMemoryObj, 0 );
CheckGL();
auto cmdBuffer = m_Device.CreateOneTimeCmdBuffer();
auto queue = m_Device.GetGraphicsQueue();
TransitionImageToInitialState( cmdBuffer, queue );
cmdBuffer.Submit( queue, true );
}
void lh2core::VulkanGLTextureInterop::TransitionImageToInitialState( vk::CommandBuffer &cmdBuffer, vk::Queue &queue )
{
vk::ImageSubresourceRange subresourceRange;
subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
vk::ImageMemoryBarrier imageMemoryBarrier;
imageMemoryBarrier.oldLayout = vk::ImageLayout::eUndefined;
imageMemoryBarrier.newLayout = vk::ImageLayout::eColorAttachmentOptimal;
imageMemoryBarrier.image = m_Image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite;
imageMemoryBarrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
vk::PipelineStageFlags destStageMask = vk::PipelineStageFlagBits::eTransfer;
cmdBuffer.pipelineBarrier( srcStageMask, destStageMask, vk::DependencyFlags(), nullptr, nullptr, imageMemoryBarrier );
} | 40.696049 | 213 | 0.79528 | vincevannoort |
26d97328bfba1b176f4aa7358df5db6d1a413591 | 755 | cpp | C++ | test/heap_test.cpp | FrezCirno/TinySTL | f5a4d310ada5c9ffc84798162add719ad6fa7b20 | [
"MIT"
] | 1 | 2021-05-12T13:24:21.000Z | 2021-05-12T13:24:21.000Z | test/heap_test.cpp | FrezCirno/tinySTL | f5a4d310ada5c9ffc84798162add719ad6fa7b20 | [
"MIT"
] | 1 | 2020-04-29T10:01:18.000Z | 2020-05-01T08:47:27.000Z | test/heap_test.cpp | FrezCirno/tinySTL | f5a4d310ada5c9ffc84798162add719ad6fa7b20 | [
"MIT"
] | null | null | null | #include "vector.hpp"
#include "heap.hpp"
// #include <queue>
#include <iostream>
using namespace std;
template <typename T>
void print(T &vec)
{
for (auto it = vec.begin(); it < vec.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main(int argc, char const *argv[])
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
tinySTL::vector<int> ivec(a, a + 9);
print(ivec);
tinySTL::make_heap(ivec.begin(), ivec.end());
print(ivec);
ivec.push_back(999);
print(ivec);
tinySTL::push_heap(ivec.begin(), ivec.end());
print(ivec);
tinySTL::pop_heap(ivec.begin(), ivec.end());
print(ivec);
ivec.pop_back();
print(ivec);
return 0;
}
| 17.55814 | 54 | 0.519205 | FrezCirno |
26dc81775866ef94723349774409c2a3709b5db9 | 4,609 | hpp | C++ | DoodleJump/src/include/game_play.hpp | PashaBarahimi/DoodleJump | 2cd34368022347d4ae2015f30ea8425d8c9b6310 | [
"MIT"
] | 1 | 2021-05-15T05:28:02.000Z | 2021-05-15T05:28:02.000Z | DoodleJump/src/include/game_play.hpp | PashaBarahimi/DoodleJump | 2cd34368022347d4ae2015f30ea8425d8c9b6310 | [
"MIT"
] | null | null | null | DoodleJump/src/include/game_play.hpp | PashaBarahimi/DoodleJump | 2cd34368022347d4ae2015f30ea8425d8c9b6310 | [
"MIT"
] | 1 | 2021-07-29T14:21:06.000Z | 2021-07-29T14:21:06.000Z | #ifndef GAME_PLAY_HPP
#define GAME_PLAY_HPP
#include "rsdl.hpp"
#include "game_board.hpp"
#include "doodler.hpp"
#include "platform.hpp"
#include "normal_platform.hpp"
#include "movable_platform.hpp"
#include "breakable_platform.hpp"
#include "spring.hpp"
#include "enemy.hpp"
#include "normal_enemy.hpp"
#include "movable_enemy.hpp"
#include "pistol.hpp"
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
typedef Point sizeVector;
constexpr int DELAY = 15; // in milliseconds
constexpr int BUTTON_PRESS_DELAY = 200; // in milliseconds
constexpr int NAME_LENGTH = 10;
class GamePlay
{
public:
struct Addresses
{
string background;
string normalPlatform;
string MovablePlatform;
vector<string> breakablePlatform;
vector<string> doodler;
vector<string> enemies;
string comicFont;
string scoreBackground;
string gameOver;
vector<string> springs;
vector<string> stars;
string pauseButton;
string pauseMenu;
vector<string> resumeButton;
vector<string> menuButton;
vector<string> playAgainButton;
string mainMenu;
vector<string> playButton;
vector<string> spaceship;
string nameAndScore;
string staticMap;
string dynamicMap;
string pistol;
string jumpEffect;
string springEffect;
string monsterCrashEffect;
string jumpOnMonsterEffect;
string breakPlatformEffect;
string fallEffect;
string nearEnemyEffect;
string pistolShootEffect;
string pistolKilledMonsterEffect;
};
struct Sizes
{
sizeVector background;
sizeVector normalAndMovablePlatforms;
vector<sizeVector> breakablePlatform;
vector<sizeVector> doodler;
vector<sizeVector> enemies;
sizeVector scoreBackground;
vector<sizeVector> springs;
sizeVector stars;
sizeVector pauseButton;
sizeVector resumeButton;
sizeVector menuButton;
sizeVector playAgainButton;
sizeVector nameEdit;
sizeVector playButton;
sizeVector spaceship;
sizeVector pistol;
};
struct Locations
{
Point scoreLocation;
Point stars;
Point pauseButton;
Point resumeButton;
Point menuButton;
Point playAgainButton;
Point gameOverScore;
Point overallHighScore;
Point name;
Point playButton;
Point menuPlatform;
Point spaceship;
};
enum class Actions
{
PlayAgain,
Menu,
Quit
};
GamePlay(const Addresses addresses, const Sizes sizes, Locations location, Window *window, int &highScore, string &name);
~GamePlay();
Actions process();
private:
struct Sequence
{
int start_;
int end_;
int totalHeight_;
vector<string> types_;
vector<int> x_;
vector<int> y_;
Sequence(int start, int end, int totalHeight, vector<string> types, vector<int> x, vector<int> y);
};
vector<Platform *> platforms_;
vector<Spring *> springs_;
vector<Enemy *> enemies_;
vector<Pistol *> pistols_;
Doodler *doodler_;
GameBoard *board_;
Addresses addresses_;
Sizes sizes_;
Locations locations_;
Window *window_;
bool gameOver_;
bool fellAfterGameOver_;
int &highScore_;
string &name_;
vector<Sequence> sequences_;
int sequenceStart_;
int sequenceHeight_;
void printOnScreen() const;
void processPlatformChanges();
void processSpringChanges();
void processEnemyChanges();
void processPistolChanges();
bool checkForInGameEvents();
void moveCamera(int pixel);
void checkForCollision();
bool checkForPlatformCollision();
bool checkForSpringCollision();
bool checkForEnemyCollision();
void printDoodler() const;
void printPlatforms() const;
void printSprings() const;
void printEnemies() const;
void printStars() const;
void printPistols() const;
int getHighScore() const { return doodler_->getScoreInScreen() + board_->getBase(); }
bool fallingHandler();
void moveCameraUp();
Actions gameOverEvent() const;
void printGameOver() const;
static int getAppropriateDelay(unsigned int prevTime);
void processPossibleChanges();
static bool checkForButtonPress(Point topLeftLocation, sizeVector size, const Event &event);
bool pause();
void menuButton() const;
void playAgainButton() const;
int checkForOverallHighScore() const;
void editName() const;
void endEditingName(const ostringstream &nameStream, const string &prevName) const;
bool update();
void readStaticMap();
void readValuesFromStaticMap(ifstream &input);
Point getTopLeftFromMiddleDown(int x, int y, sizeVector size) const;
bool readDynamicMap();
void readValuesFromDynamicMap(ifstream &input);
void addDataFromMap(int x, int y, string type, int base);
void inGameSequenceAdd(int index, int base);
void checkForNewSequence();
void findSuitableSequence();
bool isEnemyNear();
void makePistol();
};
#endif | 24.647059 | 122 | 0.765459 | PashaBarahimi |
26e87f84de5d70c5e017f668a260d085aca36ef5 | 719 | inl | C++ | src/Core/Geometry/DCEL/Iterator/Face/FFEIterator.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | 1 | 2018-04-16T13:55:45.000Z | 2018-04-16T13:55:45.000Z | src/Core/Geometry/DCEL/Iterator/Face/FFEIterator.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | src/Core/Geometry/DCEL/Iterator/Face/FFEIterator.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | #include <Core/Geometry/DCEL/Iterator/Face/FFEIterator.hpp>
#include <Core/Geometry/DCEL/Face.hpp>
#include <Core/Geometry/DCEL/FullEdge.hpp>
#include <Core/Geometry/DCEL/HalfEdge.hpp>
namespace Ra {
namespace Core {
/// CONSTRUCTOR
FFEIterator::FFEIterator( Face_ptr& f ) : FIterator<FullEdge>( f ) {}
/// DESTRUCTOR
FFEIterator::~FFEIterator() {}
/// LIST
inline FullEdgeList FFEIterator::list() const {
FullEdgeList L;
HalfEdge_ptr it = m_f->HE();
do
{
L.push_back( it->FE() );
it = it->Next();
} while ( it != m_f->HE() );
return L;
}
/// OPERATOR
inline FullEdge* FFEIterator::operator->() const {
return m_he->FE().get();
}
} // namespace Core
} // namespace Ra
| 20.542857 | 69 | 0.646732 | sylvaindeker |
26ee413da88a0613a08a7d7190aa25937bf8af91 | 2,835 | hpp | C++ | src/object.hpp | rokashevich/cp19 | ce63a3f31797795b25a23dda7e75748c098d3e4f | [
"Zlib",
"Apache-2.0"
] | 2 | 2020-11-17T18:40:04.000Z | 2021-02-23T15:18:47.000Z | src/object.hpp | rokashevich/cp19 | ce63a3f31797795b25a23dda7e75748c098d3e4f | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/object.hpp | rokashevich/cp19 | ce63a3f31797795b25a23dda7e75748c098d3e4f | [
"Zlib",
"Apache-2.0"
] | 1 | 2020-09-19T19:24:40.000Z | 2020-09-19T19:24:40.000Z | #pragma once
#include <array>
#include <cstddef>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <iostream>
#include <vector>
#include "t.hpp"
struct ShapeInfo {
std::vector<float> vertices_buffer;
const char* vertex_shader;
const char* pixel_shader;
};
template <class T>
class Shape {
static const ShapeInfo objects_static_info_;
static const std::vector<float> vertices_buffer_;
public:
static auto& ShapeVerticesBuffer2() { return Shape::vertices_buffer_; }
static auto& StaticInfo() { return objects_static_info_; }
};
// Базовый класс физического объекта игрового мира.
class Object {
unsigned int id_;
protected:
static constexpr int num_instances_ = 1;
std::vector<float> coords_;
std::vector<float> angles_;
std::vector<float> params_;
public:
static constexpr int num_coords = 3;
static constexpr int num_angles = 3;
static constexpr int num_params = 4;
Object(glm::vec3 coords = {0, 0, 0}, glm::vec3 angles = {0, 0, 0},
glm::vec4 params = {0, 0, 0, 0});
virtual ~Object() {}
const auto& Coords() { return coords_; }
const auto& Angles() { return angles_; }
const auto& Params() { return params_; }
// Из скольки однотипных фигур составлен объект. Например в стене или в
// снараяде по одной. Человек же состоит из 8: голова, туловище, два плеча,
// два предплечья, два бедра, две голени.
virtual int NumInstances() { return Object::num_instances_; }
// Для обновления параметров для шейдера.
virtual void Step() {}
void Move(tribool backward_forward, tribool left_right, tribool down_up);
unsigned int id() { return id_; }
public:
// TODO OLD
// P orientation_; // В какую сторону смотрит объект.
// P motion_external_; // Запрошенное движение извне (кнопками, Ai).
// P motion_internal_; // Фактическое движение (блокируемое анимацией).
int timer_inertia_; // Таймер отработки анимации.
V v_;
int weight_; // >0 обычный объект, =0 стена, <0 артефактphy
// std::vector<std::array<float, 3>> offsets_old_;
// std::vector<std::array<float, 3>> angles_old_;
// std::vector<std::array<float, 3>> params_old_;
// // Object(V v = V(), float weight = 0, glm::vec3 angles = {0, 0, 0},
// glm::vec3 params = {0, 0, 0});
// P& GetOrientation() { return orientation_; }
// void SetOrientation(P p) { orientation_ = p; }
// void SetMotion(P& p) { motion_external_ = p; }
V& v() { return v_; }
// Возвращает координты вершин базовой формы: параллелепипеда, куба, шара, и
// т.д. в виде: x1,y1,z1,x2,y2,z2,..., где каждая тройка координат
// представляет собой тругольник. Передаётся в рендер.
virtual const std::vector<float>* ShapeVerticesBuffer() = 0;
// virtual const std::vector<std::array<float, 3>>& Offsets() {
// return offsets_old_;
// }
int Weight() { return weight_; }
};
| 32.215909 | 78 | 0.682187 | rokashevich |
26f18562c0d46bd6a5ee111b283e22dab8445d79 | 10,245 | hpp | C++ | RockportEd/Extensions/InGame Menu/Items/TimeOfDayEditor.hpp | berkayylmao/RockportEd | eb99bf5ed2d60eedf86e38e164e04b0e46b47d1f | [
"MIT"
] | null | null | null | RockportEd/Extensions/InGame Menu/Items/TimeOfDayEditor.hpp | berkayylmao/RockportEd | eb99bf5ed2d60eedf86e38e164e04b0e46b47d1f | [
"MIT"
] | null | null | null | RockportEd/Extensions/InGame Menu/Items/TimeOfDayEditor.hpp | berkayylmao/RockportEd | eb99bf5ed2d60eedf86e38e164e04b0e46b47d1f | [
"MIT"
] | 1 | 2021-06-03T09:17:20.000Z | 2021-06-03T09:17:20.000Z | /*
MIT License
Copyright (c) 2019 Berkay Yigit <berkay2578@gmail.com>
Copyright holder detail: Nickname(s) used by the copyright holder: 'berkay2578', 'berkayylmao'.
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 "stdafx.h"
#include "Extensions\Extensions.h"
using GameInternals::TimeOfDay;
using GameInternals::TimeOfDayLighting;
using GameInternals::TimeOfDayLightingData;
namespace Extensions {
namespace InGameMenu {
class TimeOfDayEditor : public _BaseInGameMenuItem {
int32_t curLightingIndex = 0;
TimeOfDayLighting* pEditTimeOfDayLighting = nullptr;
std::vector<std::string> vStrLightingHashes;
TimeOfDay* pTimeOfDay = nullptr;
public:
const virtual void loadData() override {
while (!pTimeOfDay) {
pTimeOfDay = TimeOfDayInternals::getTimeOfDay();
Sleep(100);
}
while (!TimeOfDayInternals::loadLightingDefinitions()) {
Sleep(100);
}
int count = TimeOfDayInternals::lightingDefinitions.size();
for (int lightingIndex = 0; lightingIndex < count; lightingIndex++)
{
TimeOfDayInternals::TimeOfDayLightingDefinition* pDefinition = TimeOfDayInternals::lightingDefinitions[lightingIndex];
TimeOfDayLighting* pDefinitionLighting = pDefinition->pTimeOfDayLighting;
std::string lightingHash = pDefinition->getHashAsString();
vStrLightingHashes.push_back(lightingHash);
if (Settings::settingsType.todPresets.size() != 0) {
auto iter = Settings::settingsType.todPresets.find(lightingHash);
if (iter != Settings::settingsType.todPresets.end()) {
auto* pSettingsInstance = &iter->second;
*pDefinitionLighting->pLightingData = pSettingsInstance->LightingDataPreset.getGameInternalsCompliantData();
pDefinitionLighting->FogInLightScatter = pSettingsInstance->FogInLightScatter;
pDefinitionLighting->FogSunFalloff = pSettingsInstance->FogSunFalloff;
}
}
if (pDefinitionLighting == pTimeOfDay->pTimeOfDayLighting)
curLightingIndex = lightingIndex;
}
pEditTimeOfDayLighting = TimeOfDayInternals::lightingDefinitions[curLightingIndex]->pTimeOfDayLighting;
hasLoadedData = true;
}
const virtual void onFrame() override {}
const virtual bool displayMenuItem(const ImVec2& buttonSize) override {
return ImGui::Button("Time of day and lighting editor", buttonSize);
}
const virtual bool displayMenu() override {
static float lineDiff = 0.0f;
lineDiff = ImGui::CalcTextSize("Time of day progression speed multiplier...").x + ImGui::GetStyle().WindowPadding.x;
ImGui::PushItemWidth(lineDiff * 0.625f);
ImGui::Text("Skybox animation speed multiplier"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##SkySpeedMult", &pTimeOfDay->SkyboxSpeedMultiplier, -100.0f, 100.0f);
ImGui::Text("Time of day progression speed multiplier"); ImGui::SameLine(lineDiff);
ImGui::SliderInt("##ToDSpeedMult", &pTimeOfDay->TimeOfDaySpeedMultiplier, -100, 100);
ImGui::Text("Time of day"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##ToDValue", &pTimeOfDay->TimeOfDayValue, 0.05f, 0.95f);
ImGui::Text("Sun default orbit X-Axis (Horizontal)"); ImGui::SameLine(lineDiff);
ImGui::SliderAngle("##SunOrbitXAxis", &pTimeOfDay->SunDefaultOrbitAxisX);
ImGui::Text("Sun default orbit Y-Axis (Vertical)"); ImGui::SameLine(lineDiff);
ImGui::SliderAngle("##SunOrbitYAxis", &pTimeOfDay->SunDefaultOrbitAxisY);
ImGui::PopItemWidth();
ImGui::Separator();
if (pEditTimeOfDayLighting) {
ImGui::Text("Lighting "); ImGui::SameLine();
if (ImGui::Combo("##ActiveLighting", &curLightingIndex, vStrLightingHashes)) {
pEditTimeOfDayLighting = TimeOfDayInternals::lightingDefinitions[curLightingIndex]->pTimeOfDayLighting;
} ImGui::SameLine();
if (ImGui::Button("Set active")) {
pTimeOfDay->pTimeOfDayLighting = pEditTimeOfDayLighting;
pTimeOfDay->pTimeOfDayLightingData = pEditTimeOfDayLighting->pLightingData;
pTimeOfDay->TimeOfDayValue = 0.5f;
}
if (ImGui::Button("Save preset")) {
Settings::TimeOfDayLightingPreset* pSettingsInstance = &Settings::settingsType.todPresets[vStrLightingHashes[curLightingIndex]];
pSettingsInstance->setTo(pEditTimeOfDayLighting);
Settings::saveSettings();
} ImGui::SameLine(); ImGui::VerticalSeparator(); ImGui::SameLine();
if (ImGui::Button("Override all and save")) {
int index = 0;
for (const auto* def : TimeOfDayInternals::lightingDefinitions) {
// save
Settings::TimeOfDayLightingPreset* pSettingsInstance = &Settings::settingsType.todPresets[vStrLightingHashes[index]];
pSettingsInstance->setTo(pEditTimeOfDayLighting);
// apply
def->pTimeOfDayLighting->FogInLightScatter = pEditTimeOfDayLighting->FogInLightScatter;
def->pTimeOfDayLighting->FogSunFalloff = pEditTimeOfDayLighting->FogSunFalloff;
def->pTimeOfDayLighting->pLightingData->setTo(pEditTimeOfDayLighting->pLightingData);
index++;
}
Settings::saveSettings();
}
if (ImGui::Button("Restore all to defaults")) {
TimeOfDayInternals::restoreAll();
Settings::settingsType.todPresets.clear();
Settings::saveSettings();
}
lineDiff = ImGui::CalcTextSize("FixedFunctionSkyColour...").x + ImGui::GetStyle().WindowPadding.x;
ImGui::PushItemWidth(-1.0f);
ImGui::Text("SpecularColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##SpecularColour", pEditTimeOfDayLighting->pLightingData->SpecularColour);
ImGui::Text("DiffuseColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##DiffuseColour", pEditTimeOfDayLighting->pLightingData->DiffuseColour);
ImGui::Text("AmbientColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##AmbientColour", pEditTimeOfDayLighting->pLightingData->AmbientColour);
ImGui::Text("FogHazeColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##FogHazeColour", pEditTimeOfDayLighting->pLightingData->FogHazeColour);
ImGui::Text("FixedFunctionSkyColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##FixedFunctionSkyColour", pEditTimeOfDayLighting->pLightingData->FixedFunctionSkyColour);
ImGui::Text("FogDistanceScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##FogDistanceScale", &pEditTimeOfDayLighting->pLightingData->FogDistanceScale, 10.0f, -100.0f, 1000.0f);
ImGui::Text("FogHazeColourScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##FogHazeColourScale", &pEditTimeOfDayLighting->pLightingData->FogHazeColourScale, 10.0f, 0.0f, 1000.0f);
ImGui::Text("FogSkyColourScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##FogSkyColourScale", &pEditTimeOfDayLighting->pLightingData->FogSkyColourScale, 10.0f, 0.0f, 1000.0f);
ImGui::Text("EnvSkyBrightness"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##EnvSkyBrightness", &pEditTimeOfDayLighting->pLightingData->EnvSkyBrightness, 0.0f, 10.0f);
ImGui::Text("CarSpecScale"); ImGui::SameLine(lineDiff);
ImGui::DragFloat("##CarSpecScale", &pEditTimeOfDayLighting->pLightingData->CarSpecScale, 0.25f, 0.0f, 100.0f);
ImGui::Text("FogSkyColour"); ImGui::SameLine(lineDiff);
ImGui::ColorEdit4("##FogSkyColour", pEditTimeOfDayLighting->pLightingData->FogSkyColour);
ImGui::Text("FogInLightScatter"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##FogInLightScatter", &pEditTimeOfDayLighting->FogInLightScatter, -100.0f, 100.0f);
ImGui::Text("FogSunFalloff"); ImGui::SameLine(lineDiff);
ImGui::SliderFloat("##FogSunFalloff", &pEditTimeOfDayLighting->FogSunFalloff, -100.0f, 100.0f);
ImGui::PopItemWidth();
} else {
ImGui::Text("There was an issue setting up the lighting info.");
pEditTimeOfDayLighting = TimeOfDayInternals::lightingDefinitions[curLightingIndex]->pTimeOfDayLighting;
}
return true;
}
};
}
} | 52.809278 | 146 | 0.638555 | berkayylmao |
26fa3a90f5743067b3238a06e3e07f5a5d96047b | 1,107 | cpp | C++ | PrimaLezione/sortPairs.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | PrimaLezione/sortPairs.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | PrimaLezione/sortPairs.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | /*
Data una lista di cognomi di studenti e la loro relativa media,
ordinali con ordine non crescente in base alla loro media,
in caso di parità ordinali in ordine alfabetico in base al cognome.
Input:
n (numero di studenti)
[cognome] [media]
...
Output:
[cognome] [media]
...
Esempio di input:
4
Verdi 19
Bianchi 27
Rossi 28
Gialli 27
Esempio di output:
Rossi 28
Gialli 27
Bianchi 27
Verdi 19
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool sortByAscendingIntAndDescendingString(const pair<string,int>& a, const pair<string,int>& b){
if(a.second == b.second) return a.first > b.first;
return a.second > b.second;
}
int main(){
vector<pair<string,int>> v;
int n;
cin >> n;
string name;
int avg;
while(n--){
cin >> name >> avg;
v.push_back({name, avg});
}
sort(v.begin(), v.end(), sortByAscendingIntAndDescendingString);
for(const pair<string,int>& el : v){
cout << el.first << ' ' << el.second << "\n";
}
} | 20.5 | 97 | 0.606143 | NeverMendel |
26ff00b0b16c6de003fb8dba67241c373dc32529 | 29,588 | cc | C++ | helpers.cc | rbhambriiit/deeptorch | 77f04f850da36ee11303b8647dda5025e039d444 | [
"Apache-2.0"
] | null | null | null | helpers.cc | rbhambriiit/deeptorch | 77f04f850da36ee11303b8647dda5025e039d444 | [
"Apache-2.0"
] | null | null | null | helpers.cc | rbhambriiit/deeptorch | 77f04f850da36ee11303b8647dda5025e039d444 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "helpers.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include "Linear.h"
#include "MemoryXFile.h"
namespace Torch {
DiskXFile* InitResultsFile(Allocator* allocator,std::string expdir, std::string type)
{
std::stringstream ss;
ss.str("");
ss.clear();
std::string expdirprefix = expdir.substr(0,expdir.length()-1);
ss << expdirprefix << "_" << type << "_results.txt";
DiskXFile *resultsfile = new(allocator) DiskXFile(ss.str().c_str(),"w");
return resultsfile;
}
void AddClassificationMeasurers(Allocator* allocator, std::string expdir,
MeasurerList *measurers, Machine *machine,
DataSet *train, DataSet *valid, DataSet *test,
ClassFormat *class_format, bool disk_results)
{
std::stringstream ss;
XFile* tfile_mentor_train_nll;
XFile* tfile_mentor_train_class;
XFile* tfile_mentor_valid_nll;
XFile* tfile_mentor_valid_class;
XFile* tfile_mentor_test_nll;
XFile* tfile_mentor_test_class;
// train
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_train_nll.txt";
ss << expdir << "train_nll.txt";
if (disk_results) {
DiskXFile *file_mentor_train_nll = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_train_nll = file_mentor_train_nll;
}
else {
MemoryXFile *file_mentor_train_nll = new(allocator) MemoryXFile();
tfile_mentor_train_nll = file_mentor_train_nll;
}
ClassNLLMeasurer *measurer_mentor_train_nll = new(allocator) ClassNLLMeasurer(machine->outputs, train,
class_format, tfile_mentor_train_nll);
measurers->addNode(measurer_mentor_train_nll);
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_train_class.txt";
ss << expdir << "train_class.txt";
if (disk_results) {
DiskXFile *file_mentor_train_class = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_train_class = file_mentor_train_class;
}
else {
MemoryXFile *file_mentor_train_class = new(allocator) MemoryXFile();
tfile_mentor_train_class = file_mentor_train_class;
}
ClassMeasurer *measurer_mentor_train_class = new(allocator) ClassMeasurer(machine->outputs, train,
class_format, tfile_mentor_train_class);
measurers->addNode(measurer_mentor_train_class);
// valid
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_valid_nll.txt";
ss << expdir << "valid_nll.txt";
if (disk_results) {
DiskXFile *file_mentor_valid_nll = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_valid_nll = file_mentor_valid_nll;
}
else {
MemoryXFile *file_mentor_valid_nll = new(allocator) MemoryXFile();
tfile_mentor_valid_nll = file_mentor_valid_nll;
}
ClassNLLMeasurer *measurer_mentor_valid_nll = new(allocator) ClassNLLMeasurer(machine->outputs, valid,
class_format, tfile_mentor_valid_nll);
measurers->addNode(measurer_mentor_valid_nll);
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_valid_class.txt";
ss << expdir << "valid_class.txt";
if (disk_results) {
DiskXFile *file_mentor_valid_class = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_valid_class = file_mentor_valid_class;
}
else {
MemoryXFile *file_mentor_valid_class = new(allocator) MemoryXFile();
tfile_mentor_valid_class = file_mentor_valid_class;
}
ClassMeasurer *measurer_mentor_valid_class = new(allocator) ClassMeasurer(machine->outputs, valid,
class_format, tfile_mentor_valid_class);
measurers->addNode(measurer_mentor_valid_class);
// test
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_test_nll.txt";
ss << expdir << "test_nll.txt";
if (disk_results) {
DiskXFile *file_mentor_test_nll = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_test_nll = file_mentor_test_nll;
}
else {
MemoryXFile *file_mentor_test_nll = new(allocator) MemoryXFile();
tfile_mentor_test_nll = file_mentor_test_nll;
}
ClassNLLMeasurer *measurer_mentor_test_nll = new(allocator) ClassNLLMeasurer(machine->outputs, test,
class_format, tfile_mentor_test_nll);
measurers->addNode(measurer_mentor_test_nll);
ss.str("");
ss.clear();
//ss << expdir << machine->name << "_test_class.txt";
ss << expdir << "test_class.txt";
if (disk_results) {
DiskXFile *file_mentor_test_class = new(allocator) DiskXFile(ss.str().c_str(),"w");
tfile_mentor_test_class = file_mentor_test_class;
}
else {
MemoryXFile *file_mentor_test_class = new(allocator) MemoryXFile();
tfile_mentor_test_class = file_mentor_test_class;
}
ClassMeasurer *measurer_mentor_test_class = new(allocator) ClassMeasurer(machine->outputs, test,
class_format, tfile_mentor_test_class);
measurers->addNode(measurer_mentor_test_class);
}
Criterion* NewUnsupCriterion(Allocator* allocator, std::string recons_cost, int size)
{
if(recons_cost=="xentropy") {
return new(allocator) CrossEntropyCriterion(size);
} else if(recons_cost=="mse") {
return new(allocator) MSECriterion(size);
} else {
error("%s is not a valid reconstruction cost!", recons_cost.c_str());
return NULL;
}
}
Measurer* NewUnsupMeasurer(Allocator* allocator, std::string recons_cost,
Sequence *inputs_, DataSet *data_, XFile *file_)
{
if(recons_cost=="xentropy") {
return new(allocator) CrossEntropyMeasurer(inputs_, data_, file_);
} else if(recons_cost=="mse") {
return new(allocator) MSEMeasurer(inputs_, data_, file_);
} else {
error("%s is not a valid reconstruction measurer!", recons_cost.c_str());
return NULL;
}
}
void BuildSaeUnsupDataSetsCriteriaMeasurers(Allocator *allocator,
std::string expdir,
StackedAutoencoder *sae,
DataSet *supervised_train_data,
Criterion *supervised_criterion,
std::string recons_cost,
bool criterion_avg_frame_size,
DataSet **unsup_datasets,
Criterion **unsup_criterions,
Measurer **unsup_measurers,
bool disk_results)
{
std::stringstream ss;
XFile* thefile;
for(int i=0; i<sae->n_hidden_layers; i++) {
// DataSet
// The first dataset is special, as it can't just monitor a memory
// location. The examples are each at different locations.
if(i==0)
unsup_datasets[0] = new(allocator) InputAsTargetDataSet(supervised_train_data);
else
unsup_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, sae->encoders[i-1]->outputs);
// Criterion
unsup_criterions[i] = NewUnsupCriterion(allocator, recons_cost, sae->decoders[i]->n_outputs);
unsup_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
unsup_criterions[i]->setDataSet(unsup_datasets[i]);
// Measurer
ss.str("");
ss.clear();
if (disk_results) {
ss << expdir << sae->name << "_unsup_" << recons_cost << "_layer_" << i << ".txt";
DiskXFile *file = new(allocator) DiskXFile(ss.str().c_str(),"w");
thefile = file;
}
else {
MemoryXFile *file = new(allocator) MemoryXFile();
thefile = file;
}
unsup_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
sae->decoders[i]->outputs,
unsup_datasets[i],
thefile);
}
}
/*
void StackedAutoencoderTrainer::FreeUnsupDataSetsCriteriaMeasurers()
{
for(int i=0; i<sae->n_hidden_layers; i++) {
allocator->free(unsup_datasets[i]);
allocator->free(unsup_criterions[i]);
allocator->free(unsup_measurers[i]->file);
allocator->free(unsup_measurers[i]);
}
allocator->free(unsup_datasets);
allocator->free(unsup_criterions);
allocator->free(unsup_measurers);
}
*/
// We don't know what to agree with yet, so agree with ourself.
// -> the datasets' targets will need to be set!
void BuildSaeComAgreeDatasetsCriteriaMeasurers(Allocator *allocator,
std::string expdir,
CommunicatingStackedAutoencoder *csae,
DataSet *supervised_train_data,
Criterion *supervised_criterion,
std::string recons_cost,
int communication_type,
bool criterion_avg_frame_size,
DataSet **agree_datasets,
Criterion **agree_criterions,
Measurer **agree_measurers,
bool disk_results,
int n_communication_layers)
{
std::stringstream ss;
XFile *file;
for(int i=0; i<n_communication_layers; i++) {
ss.str("");
ss.clear();
if (disk_results) {
ss << expdir << csae->name << "_comAgree_" << recons_cost << "_layer_" << i << ".txt";
file = new(allocator) DiskXFile(ss.str().c_str(),"w");
}
else
file = new(allocator) MemoryXFile();
// *** Com0 and Com1 - We try to match the other guy's hidden units...
if( communication_type==0 || communication_type==1 ) {
agree_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, csae->encoders[i]->outputs);
agree_criterions[i] = NewUnsupCriterion(allocator, recons_cost, csae->encoders[i]->n_outputs);
agree_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
agree_criterions[i]->setDataSet(agree_datasets[i]);
// ... with our own units
if(communication_type==0) {
agree_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
csae->encoders[i]->outputs,
agree_datasets[i], file);
}
// ... with our speech
else {
agree_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
csae->speakers[i]->outputs,
agree_datasets[i], file);
}
}
// *** Com2 - We try to match the other guy's speech with our speech
else {
agree_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, csae->speakers[i]->outputs);
agree_criterions[i] = NewUnsupCriterion(allocator, recons_cost, csae->speakers[i]->n_outputs);
agree_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
agree_criterions[i]->setDataSet(agree_datasets[i]);
agree_measurers[i] = NewUnsupMeasurer(allocator, recons_cost,
csae->speakers[i]->outputs,
agree_datasets[i], file);
}
}
}
void BuildSaeComContentDatasetsCriteriaMeasurers(Allocator *allocator,
std::string expdir,
CommunicatingStackedAutoencoder *csae,
DataSet *supervised_train_data,
Criterion *supervised_criterion,
std::string recons_cost,
bool criterion_avg_frame_size,
DataSet **content_datasets,
Criterion **content_criterions,
Measurer **content_measurers,
bool disk_results,
int n_communication_layers)
{
std::stringstream ss;
XFile *file;
for(int i=0; i<n_communication_layers; i++) {
content_datasets[i] = new(allocator) DynamicDataSet(supervised_train_data, (Sequence*)NULL, csae->encoders[i]->outputs);
content_criterions[i] = NewUnsupCriterion(allocator, recons_cost, csae->encoders[i]->n_outputs);
content_criterions[i]->setBOption("average frame size", criterion_avg_frame_size);
content_criterions[i]->setDataSet(content_datasets[i]);
ss.str("");
ss.clear();
if (disk_results) {
ss << expdir << csae->name << "_comContent_" << recons_cost << "_layer_" << i << ".txt";
file = new(allocator) DiskXFile(ss.str().c_str(),"w");
}
else
file = new(allocator) MemoryXFile();
content_measurers[i] = NewUnsupMeasurer(allocator, recons_cost, csae->listeners[i]->outputs,
content_datasets[i], file);
}
}
/*
void CommunicatingSaePairTrainer::FreeComDataSetsCriteriaMeasurers()
{
}
*/
void SaveCoder(std::string expdir, std::string filename, Coder *coder)
{
warning("SaveCoder(...) - implements a partial save only.");
std::string model_filename = expdir + filename;
DiskXFile xfile_model(model_filename.c_str(), "w");
xfile_model.taggedWrite(&coder->n_inputs, sizeof(int), 1, "n_inputs");
xfile_model.taggedWrite(&coder->n_outputs, sizeof(int), 1, "n_outputs");
int nonlinearity_length = coder->nonlinearity.length()+1;
xfile_model.taggedWrite(&nonlinearity_length, sizeof(int), 1, "nonlinearity_length");
xfile_model.taggedWrite((char*)coder->nonlinearity.c_str(), sizeof(char), nonlinearity_length, "nonlinearity");
coder->saveXFile(&xfile_model);
}
Coder* LoadCoder(Allocator* allocator, std::string filename)
{
warning("LoadCoder(...) - implements a partial load only.");
XFile *m = new(allocator) DiskXFile(filename.c_str(), "r");
int n_inputs=0;
m->taggedRead(&n_inputs, sizeof(int), 1, "n_inputs");
int n_outputs=0;
m->taggedRead(&n_outputs, sizeof(int), 1, "n_outputs");
int nonlinearity_length=0;
m->taggedRead(&nonlinearity_length, sizeof(int), 1, "nonlinearity_length");
char *nonlinearity = new char[nonlinearity_length];
m->taggedRead(nonlinearity, sizeof(char), nonlinearity_length, "nonlinearity");
Coder *coder = new(allocator) Coder(n_inputs, n_outputs, false, NULL, false, false, nonlinearity);
coder->loadXFile(m);
delete nonlinearity;
return coder;
}
void SaveCSAE(std::string expdir, std::string type, int n_layers, int n_inputs, int *units_per_hidden_layer, int *units_per_speech_layer,
int n_classes,
bool tied_weights, std::string nonlinearity, std::string recons_cost,
real corrupt_prob, real corrupt_value,
CommunicatingStackedAutoencoder *csae)
{
std::string model_filename = expdir + type + "model.save";
DiskXFile model_(model_filename.c_str(), "w");
// save whar's necessary to rebuilding the architecture
model_.taggedWrite(&n_inputs, sizeof(int), 1, "n_inputs");
model_.taggedWrite(&n_classes, sizeof(int), 1, "n_classes");
model_.taggedWrite(&n_layers, sizeof(int), 1, "n_layers");
model_.taggedWrite(units_per_hidden_layer, sizeof(int), n_layers, "units_per_hidden_layer");
model_.taggedWrite(units_per_speech_layer, sizeof(int), n_layers, "units_per_speech_layer");
model_.taggedWrite(&tied_weights, sizeof(bool), 1, "tied_weights");
model_.taggedWrite(&csae->reparametrize_tied, sizeof(bool), 1, "reparametrize_tied");
model_.taggedWrite(&csae->communication_type, sizeof(int), 1, "communication_type");
model_.taggedWrite(&csae->n_communication_layers, sizeof(int), 1, "n_communication_layers");
int nonlinearity_integer;
if(nonlinearity=="tanh") {
nonlinearity_integer = 0;
} else if(nonlinearity=="sigmoid") {
nonlinearity_integer = 1;
} else if (nonlinearity=="nonlinear") {
nonlinearity_integer = 2;
} else {
nonlinearity_integer = -1;
error("SaveCSAE - Unrecognized nonlinearity!");
}
model_.taggedWrite(&nonlinearity_integer, sizeof(int), 1, "nonlinearity: 0 tanh, 1 sigmoid, 2 nonlinear");
int recons_cost_integer;
if(recons_cost=="xentropy") {
recons_cost_integer = 0;
} else if(recons_cost=="mse") {
recons_cost_integer = 1;
} else {
error("SaveCSAE - %s is not a valid reconstruction cost!", recons_cost.c_str());
}
model_.taggedWrite(&recons_cost_integer, sizeof(int), 1, "recons_cost: 0 xentropy, 1 tanh");
model_.taggedWrite(&corrupt_prob, sizeof(real), 1, "corrupt_prob");
model_.taggedWrite(&corrupt_value, sizeof(real), 1, "corrupt_value");
csae->saveXFile(&model_);
}
CommunicatingStackedAutoencoder* LoadCSAE(Allocator* allocator, std::string filename)
{
int n_layers;
int n_inputs;
int *units_per_hidden_layer;
int *units_per_speech_layer;
int n_classes;
bool tied_weights;
bool reparametrize_tied;
int nonlinearity_integer;
std::string nonlinearity;
int recons_cost_integer;
std::string recons_cost;
real corrupt_prob;
real corrupt_value;
int communication_type;
int n_communication_layers;
CommunicatingStackedAutoencoder *csae;
XFile *m = new(allocator) DiskXFile(filename.c_str(), "r");
m->taggedRead(&n_inputs, sizeof(int), 1, "n_inputs");
m->taggedRead(&n_classes, sizeof(int), 1, "n_classes");
m->taggedRead(&n_layers, sizeof(int), 1, "n_layers");
units_per_hidden_layer = (int*)malloc(sizeof(int)*(n_layers));
m->taggedRead(units_per_hidden_layer, sizeof(int), n_layers, "units_per_hidden_layer");
units_per_speech_layer = (int*)malloc(sizeof(int)*(n_layers));
m->taggedRead(units_per_speech_layer, sizeof(int), n_layers, "units_per_speech_layer");
m->taggedRead(&tied_weights, sizeof(bool), 1, "tied_weights");
warning("Ignoring reparametrize_tied's value");
//m->taggedRead(&reparametrize_tied, sizeof(bool), 1, "reparametrize_tied");
reparametrize_tied = false;
m->taggedRead(&communication_type, sizeof(int), 1, "communication_type");
m->taggedRead(&n_communication_layers, sizeof(int), 1, "n_communication_layers");
m->taggedRead(&nonlinearity_integer, sizeof(int), 1, "nonlinearity: 0 tanh, 1 sigmoid, 2 nonlinear");
if(nonlinearity_integer==0) {
nonlinearity = "tanh";
} else if(nonlinearity_integer==1) {
nonlinearity = "sigmoid";
} else if (nonlinearity_integer==2) {
nonlinearity = "nonlinear";
} else {
nonlinearity = "";
error("LoadCSAE - Unrecognized nonlinearity!");
}
m->taggedRead(&recons_cost_integer, sizeof(int), 1, "recons_cost: 0 xentropy, 1 tanh");
if(recons_cost_integer==0) {
recons_cost = "xentropy";
} else if(recons_cost_integer==1) {
recons_cost = "mse";
} else {
error("LoadCSAE - Unrecognized reconstruction cost!");
}
m->taggedRead(&corrupt_prob, sizeof(real), 1, "corrupt_prob");
m->taggedRead(&corrupt_value, sizeof(real), 1, "corrupt_value");
// ------
/*
cout << "n_layers=" << n_layers << std::endl;
cout << "units_per_hidden_layer";
for(int i=0; i<n_layers; i++) {
cout << " " << units_per_hidden_layer[i];
}
cout << std::endl;
cout << "units_per_speech_layer";
for(int i=0; i<n_layers; i++) {
cout << " " << units_per_speech_layer[i];
}
cout << std::endl;
cout << "tied_weights " << tied_weights << std::endl;
cout << "nonlinearity " << nonlinearity << std::endl;
cout << "recons_cost " << recons_cost << std::endl;
cout << "corrupt_prob " << corrupt_prob << std::endl;
cout << "corrupt_value " << corrupt_value << std::endl;
*/
// ------
warning("should do a lean construction of csae here...");
warning("Ignoring first_layer_smoothed's value");
// Are the autoencoders noisy?
bool is_noisy = false;
if(corrupt_prob>0.0)
is_noisy = true;
csae = new(allocator) CommunicatingStackedAutoencoder("csae", nonlinearity, tied_weights, reparametrize_tied, n_inputs,
n_layers, units_per_hidden_layer, n_classes,
is_noisy, false, units_per_speech_layer, communication_type, n_communication_layers);
csae->loadXFile(m);
return csae;
}
void saveWeightMatrix(std::string filename, Coder* the_coder, bool is_transposed)
{
// find the first linear machine
Linear *linear = the_coder->linear_layer;
int n_inputs = linear->n_inputs;
int n_outputs = linear->n_outputs;
real *weights = linear->weights;
real *bias = linear->bias;
// Open the output file
std::ofstream fd(filename.c_str());
if(!fd.is_open())
error("saveWeightMatrix - can't open %s", filename.c_str());
if(!is_transposed) {
for(int j=0; j<n_outputs; j++) {
for(int k=0; k<n_inputs; k++) {
fd << weights[k] << " ";
}
fd << bias[j] << std::endl;
weights += n_inputs;
}
// these weights are stored transposed
} else {
for(int j=0; j<n_outputs; j++) {
for(int k=0; k<n_inputs; k++) {
fd << weights[k*n_outputs + j] << " ";
}
fd << bias[j] << std::endl;
}
}
fd.close();
}
void saveWeightMatrices(CommunicatingStackedAutoencoder* csae, std::string dir, bool is_transposed)
{
std::stringstream ss;
// save the number of layers in a file
std::string filename_nlayers = dir + "nlayers.txt";
std::ofstream fd_nlayers(filename_nlayers.c_str());
if(!fd_nlayers.is_open()) {
error("saveWeightMatrices - can't open %s", filename_nlayers.c_str());
}
fd_nlayers << csae->n_hidden_layers;
fd_nlayers.close();
// for all hidden layers output the 4 weight matrices (possibly 2 equal)
for(int i=0; i<csae->n_hidden_layers; i++) {
// W
ss.str("");
ss.clear();
ss << dir << "W" << i << ".txt";
saveWeightMatrix(ss.str(), csae->encoders[i], false);
// V
ss.str("");
ss.clear();
ss << dir << "V" << i << ".txt";
saveWeightMatrix(ss.str(), csae->decoders[i], is_transposed);
// F
if (csae->communication_type > 0) {
ss.str("");
ss.clear();
ss << dir << "F" << i << ".txt";
saveWeightMatrix(ss.str(), csae->speakers[i], false);
}
// G
if (csae->communication_type > 1) {
ss.str("");
ss.clear();
ss << dir << "G" << i << ".txt";
saveWeightMatrix(ss.str(), csae->listeners[i], is_transposed);
}
}
// output the output layer
ss.str("");
ss.clear();
ss << dir << "W" << csae->n_hidden_layers << ".txt";
saveWeightMatrix(ss.str(), csae->outputer, false);
}
void saveRepresentation(std::ofstream *fd, real *ptr, int n) {
for(int i=0; i<n; i++) {
*fd << ptr[i] << " ";
}
*fd << std::endl;
}
void openNumberedRepresentationFile(std::ofstream *fd, std::string dir, std::string name, int number)
{
std::stringstream ss;
ss << dir << name << number << ".txt";
fd->open(ss.str().c_str());
if(!fd->is_open()) {
error("openNumberedRepresentationFile - couldn't open %s", ss.str().c_str());
}
}
void saveRepresentations(CommunicatingStackedAutoencoder* csae, std::string dir,
DataSet *data, int n_examples)
{
int nhid = csae->n_hidden_layers;
// open all the necessary files
std::ofstream fd_input;
std::ofstream fd_output;
std::ofstream* fds_hidden = new std::ofstream[nhid];
std::ofstream* fds_speech = new std::ofstream[nhid];
std::ofstream* fds_recons_from_hidden = new std::ofstream[nhid];
std::ofstream* fds_recons_from_speech = new std::ofstream[nhid];
std::string filename;
filename = dir + "input.txt";
fd_input.open(filename.c_str());
filename = dir + "output.txt";
fd_output.open(filename.c_str());
if(!fd_input.is_open() || !fd_output.is_open())
error("saveRepresentations - problem opening a file.");
std::stringstream ss;
for(int i=0; i<nhid; i++) {
openNumberedRepresentationFile(&fds_hidden[i], dir, "hidden_l", i);
openNumberedRepresentationFile(&fds_recons_from_hidden[i], dir, "recons_from_hidden_l", i);
if (csae->communication_type > 0)
openNumberedRepresentationFile(&fds_speech[i], dir, "speech_l", i);
if (csae->communication_type > 1)
openNumberedRepresentationFile(&fds_recons_from_speech[i], dir, "recons_from_speech_l", i);
}
// create a place to exponentiate the outputs (logsoftmax)
real *exp_output = (real*) malloc(sizeof(real)*csae->n_outputs);
// for each example fprop and then print everything
for(int i=0; i<n_examples; i++) {
data->setExample(i);
if (csae->communication_type == 0) {
csae->sup_unsup_comA_machine->forward(data->inputs);
} else if (csae->communication_type == 1) {
csae->sup_unsup_comB_machine->forward(data->inputs);
} else if (csae->communication_type == 2) {
csae->sup_unsup_comC_machine->forward(data->inputs);
} else {
error("saveRepresentations - invalid communication_type.");
}
saveRepresentation(&fd_input, data->inputs->frames[0], data->n_inputs);
for(int j=0; j<csae->n_outputs; j++) {
exp_output[j] = exp(csae->outputs->frames[0][j]);
}
saveRepresentation(&fd_output, exp_output, csae->n_outputs);
for(int l=0; l<nhid; l++) {
saveRepresentation(&fds_hidden[l], csae->encoders[l]->outputs->frames[0], csae->encoders[l]->n_outputs);
saveRepresentation(&fds_recons_from_hidden[l], csae->decoders[l]->outputs->frames[0], csae->decoders[l]->n_outputs);
if (csae->communication_type > 0)
saveRepresentation(&fds_speech[l], csae->speakers[l]->outputs->frames[0], csae->speakers[l]->n_outputs);
if (csae->communication_type > 1)
saveRepresentation(&fds_recons_from_speech[l], csae->listeners[l]->outputs->frames[0], csae->listeners[l]->n_outputs);
}
}
// close all files
fd_input.close();
fd_output.close();
for(int i=0; i<nhid; i++) {
fds_hidden[i].close();
fds_recons_from_hidden[i].close();
if (csae->communication_type > 0)
fds_speech[i].close();
if (csae->communication_type > 1)
fds_recons_from_speech[i].close();
}
}
void saveOutputs(CommunicatingStackedAutoencoder* csae, DataSet *data, int n_outputs,
std::string dir, std::string data_label)
{
csae->setDataSet(data);
std::stringstream ss_outputs;
// Iterate over the data, putting the outputs in a stringstream
for (int i=0; i<data->n_examples; i++) {
data->setExample(i);
csae->forward(data->inputs);
for (int j=0; j<n_outputs; j++)
ss_outputs << csae->outputs->frames[0][j] << " ";
}
// Save the outputs to a file
std::ofstream fd_outputs;
std::stringstream ss_filename;
ss_filename << dir << data_label << n_outputs << "outputs.txt";
fd_outputs.open(ss_filename.str().c_str());
if (!fd_outputs.is_open())
error("saveOutputs(...) - cannot open the file.");
fd_outputs << ss_outputs.str() << std::endl;
fd_outputs.close();
}
void LoadBinners(Allocator* allocator, char* flag_binners_location,
CommunicatingStackedAutoencoder *csae,
Binner **w_binners, Binner **b_binners)
{
std::stringstream filename;
XFile *the_xfile;
for (int i=0; i<csae->n_hidden_layers; i++) {
filename.str("");
filename.clear();
filename << flag_binners_location << "binner_w" << i << ".save";
the_xfile = new(allocator) DiskXFile(filename.str().c_str(), "r");
w_binners[i] = new(allocator) Binner();
w_binners[i]->loadXFile(the_xfile);
allocator->free(the_xfile);
filename.str("");
filename.clear();
filename << flag_binners_location << "binner_b" << i << ".save";
the_xfile = new(allocator) DiskXFile(filename.str().c_str(), "r");
b_binners[i] = new(allocator) Binner();
b_binners[i]->loadXFile(the_xfile);
allocator->free(the_xfile);
}
}
void ReInitCsaeFromBinners(CommunicatingStackedAutoencoder *csae,
Binner **w_binners, Binner **b_binners)
{
for (int i=0; i<csae->n_hidden_layers; i++) {
Linear *linear_layer = csae->encoders[i]->linear_layer;
real *weights_ = linear_layer->weights;
real *bias_ = linear_layer->bias;
for (int j=0; j<linear_layer->n_outputs; j++) {
for (int k=0; k<linear_layer->n_inputs; k++)
weights_[k] = w_binners[i]->draw();
bias_[j] = b_binners[i]->draw();
weights_ += linear_layer->n_inputs;
}
}
}
}
| 37.031289 | 137 | 0.62958 | rbhambriiit |
f8024ae5c224530eb96e8621ece5add32201f971 | 6,686 | cpp | C++ | Frame/OpenGL/Fill.cpp | anirul/ShaderGL | 1de7d6cad8e2acd974e89040c9b1b41e4ae3870d | [
"MIT"
] | 1 | 2020-06-15T15:58:05.000Z | 2020-06-15T15:58:05.000Z | Frame/OpenGL/Fill.cpp | anirul/ShaderGL | 1de7d6cad8e2acd974e89040c9b1b41e4ae3870d | [
"MIT"
] | 3 | 2020-06-21T09:08:21.000Z | 2020-06-24T08:14:23.000Z | Frame/OpenGL/Fill.cpp | anirul/ShaderGL | 1de7d6cad8e2acd974e89040c9b1b41e4ae3870d | [
"MIT"
] | null | null | null | #include "Fill.h"
#include <array>
#include <assert.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Frame/Error.h"
#include "Frame/OpenGL/FrameBuffer.h"
#include "Frame/OpenGL/RenderBuffer.h"
#include "Frame/OpenGL/Renderer.h"
#include "Frame/OpenGL/StaticMesh.h"
namespace frame::opengl {
namespace {
// Get the 6 view for the cube map.
const std::array<glm::mat4, 6> views_cubemap =
{
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(1.0f, 0.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(-1.0f, 0.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 1.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, -1.0f, 0.0f),
glm::vec3(0.0f, 0.0f, -1.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 1.0f),
glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, -1.0f),
glm::vec3(0.0f, -1.0f, 0.0f))
};
}
void FillProgramMultiTexture(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface)
{
FillProgramMultiTextureMipmap(
level,
program,
uniform_interface,
0,
[](const int, const std::shared_ptr<ProgramInterface>) {});
}
void FillProgramMultiTextureMipmap(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface,
const int mipmap,
const std::function<void(
const int mipmap,
const std::shared_ptr<ProgramInterface> program)> func /*=
[](const int, const std::shared_ptr<sgl::ProgramInterface>) {}*/)
{
auto& error = Error::GetInstance();
assert(program->GetOutputTextureIds().size());
auto texture_out_ids = program->GetOutputTextureIds();
auto texture_ref = level->GetTextureMap().at(*texture_out_ids.cbegin());
auto size = texture_ref->GetSize();
FrameBuffer frame{};
RenderBuffer render{};
ScopedBind scoped_frame(frame);
ScopedBind scoped_render(render);
render.CreateStorage(size);
frame.AttachRender(render);
frame.DrawBuffers(static_cast<std::uint32_t>(texture_out_ids.size()));
int max_mipmap = (mipmap <= 0) ? 1 : mipmap;
if (max_mipmap > 1)
{
for (const auto& texture_id : texture_out_ids)
{
auto texture = level->GetTextureMap().at(texture_id);
texture->Bind();
texture->EnableMipmap();
}
}
glm::mat4 projection = glm::perspective(
glm::radians(90.0f),
1.0f,
0.1f,
10.0f);
std::pair<uint32_t, uint32_t> temporary_size = size;
for (int mipmap_level = 0; mipmap_level < max_mipmap; ++mipmap_level)
{
func(mipmap_level, program);
double fact = std::pow(0.5, mipmap_level);
temporary_size.first =
static_cast<std::uint32_t>(size.first * fact);
temporary_size.second =
static_cast<std::uint32_t>(size.second * fact);
glViewport(0, 0, temporary_size.first, temporary_size.second);
error.Display(__FILE__, __LINE__ - 1);
int i = 0;
for (const auto& texture_id : program->GetOutputTextureIds())
{
frame.AttachTexture(
level->GetTextureMap().at(texture_id)->GetId(),
FrameBuffer::GetFrameColorAttachment(i),
mipmap_level);
i++;
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
error.Display(__FILE__, __LINE__ - 1);
Renderer renderer(
level.get(),
uniform_interface.get(),
temporary_size);
renderer.SetProjection(projection);
renderer.RenderMesh(
level->GetStaticMeshMap().at(
level->GetDefaultStaticMeshQuadId()).get());
}
}
void FillProgramMultiTextureCubeMap(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface)
{
FillProgramMultiTextureCubeMapMipmap(
level,
program,
uniform_interface,
0,
[](const int, const std::shared_ptr<ProgramInterface>) {});
}
void FillProgramMultiTextureCubeMapMipmap(
const std::shared_ptr<LevelInterface> level,
const std::shared_ptr<ProgramInterface> program,
const std::shared_ptr<UniformInterface> uniform_interface,
const int mipmap,
const std::function<void(
const int mipmap,
const std::shared_ptr<ProgramInterface> program)> func /*=
[](const int, const std::shared_ptr<sgl::ProgramInterface>) {}*/)
{
auto& error = Error::GetInstance();
assert(program->GetOutputTextureIds().size());
auto texture_out_ids = program->GetOutputTextureIds();
auto texture_ref = level->GetTextureMap().at(*texture_out_ids.cbegin());
auto size = texture_ref->GetSize();
FrameBuffer frame{};
RenderBuffer render{};
ScopedBind scoped_frame(frame);
ScopedBind scoped_render(render);
frame.AttachRender(render);
frame.DrawBuffers(static_cast<std::uint32_t>(texture_out_ids.size()));
int max_mipmap = (mipmap <= 0) ? 1 : mipmap;
if (max_mipmap > 1)
{
for (const auto& texture_id : texture_out_ids)
{
auto texture = level->GetTextureMap().at(texture_id);
texture->Bind();
texture->EnableMipmap();
}
}
glm::mat4 projection = glm::perspective(
glm::radians(90.0f),
1.0f,
0.1f,
10.0f);
std::pair<std::uint32_t, std::uint32_t> temporary_size = { 0, 0 };
for (int mipmap_level = 0; mipmap_level < max_mipmap; ++mipmap_level)
{
func(mipmap_level, program);
double fact = std::pow(0.5, mipmap_level);
temporary_size.first =
static_cast<std::uint32_t>(size.first * fact);
temporary_size.second =
static_cast<std::uint32_t>(size.second * fact);
render.CreateStorage(temporary_size);
frame.AttachRender(render);
glViewport(0, 0, temporary_size.first, temporary_size.second);
error.Display(__FILE__, __LINE__ - 1);
int cubemap_element = 0;
for (const auto& view : views_cubemap)
{
int i = 0;
for (const auto& texture_id : program->GetOutputTextureIds())
{
frame.AttachTexture(
level->GetTextureMap().at(texture_id)->GetId(),
FrameBuffer::GetFrameColorAttachment(i),
mipmap_level);
}
cubemap_element++;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
error.Display(__FILE__, __LINE__ - 1);
Renderer renderer(
level.get(),
uniform_interface.get(),
temporary_size);
renderer.SetProjection(projection);
renderer.SetView(view);
renderer.RenderMesh(
level->GetStaticMeshMap().at(
level->GetDefaultStaticMeshCubeId()).get());
}
}
}
} // End namespace frame::opengl.
| 30.669725 | 74 | 0.680826 | anirul |
f8045d31dce06b3b78588f61714667125d276cbd | 4,875 | cpp | C++ | Assigment 12/Numbermaze.cpp | UrfanAlvany/Algorithms-and-Data-Structures | 263dced4a24df11dad61ab6f8ed9561eb3f44b8f | [
"MIT"
] | null | null | null | Assigment 12/Numbermaze.cpp | UrfanAlvany/Algorithms-and-Data-Structures | 263dced4a24df11dad61ab6f8ed9561eb3f44b8f | [
"MIT"
] | null | null | null | Assigment 12/Numbermaze.cpp | UrfanAlvany/Algorithms-and-Data-Structures | 263dced4a24df11dad61ab6f8ed9561eb3f44b8f | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
typedef pair<int, int> iPair;
class PuzzleBoard
{
private:
int **graph;
int graphsize;
int cuurentY;
int currentX;
public:
PuzzleBoard(int boardSize, int **fields = nullptr);
bool makeMove(int direction);
bool getResult();
friend ostream &operator<<(ostream &os, PuzzleBoard const &m);
int solve();
~PuzzleBoard();
};
PuzzleBoard::PuzzleBoard(int boardSize, int **fields)
{
currentX = 0;
cuurentY = 0;
graphsize = boardSize * boardSize;
graph = new int *[graphsize];
for (int i = 0; i < graphsize; i++)
{
graph[i] = new int[graphsize];
}
srand(time(0));
if (fields == NULL)
{
fields = new int *[boardSize];
for (int i = 0; i < boardSize; i++)
{
fields[i] = new int[boardSize];
}
}
cout<<"Your Maze looks like this"<<endl;
for (int i = 0; i < boardSize; i++)
{
for (int j = 0; j < boardSize; j++)
{
fields[i][j] = (rand() % boardSize - 1) + 1;
cout<<fields[i][j]<<" ";
}
cout<<endl;
}
for (int i = 0; i < graphsize; i++)
{
for (int j = 0; j < graphsize; j++)
{
graph[i][j] = 0;
}
}
//Creating a type of Adjacency Matrix
for (int i = 0; i < boardSize; i++)
{
for (int j = 0; j < boardSize; j++)
{
int value = fields[i][j];
if (i - value > 0)
{
int x = i * boardSize + j; //Wouldnt require a 2d matrix this way
int y = (i - value) * boardSize + j;
graph[x][y]= 1;
}
if (j - value > 0)
{
int x = i * boardSize + j;
int y = i * boardSize + (j - value);
graph[x][y] = 1;
}
if (i + value < boardSize)
{
int x = i * boardSize + j;
int y = (i + value) * boardSize + j;
graph[x][y] = 1;
}
if (j + value < boardSize)
{
int x = i * boardSize + j;
int y = i * boardSize + (j + value);
graph[x][y] = 1;
}
}
}
}
PuzzleBoard::~PuzzleBoard()
{
for (int i = 0; i < graphsize; i++)
{
delete[] graph[i];
}
delete[] graph;
}
bool PuzzleBoard::getResult()
{
if (solve()==-1)
{
cout<<"Not Solvable"<<endl;
return false;
}
else
{
cout<<"Minimum Number of steps taken to solve the maze is "<<solve()<<endl;
return true;
}
}
ostream &operator<<(ostream &os, PuzzleBoard const &m)
{
for (int i = 0; i < m.graphsize; i++)
{
for (int j = 0; j < m.graphsize; j++)
{
os << m.graph[i][j] << " ";
}
os << endl;
}
return os;
}
int PuzzleBoard::solve()
{
int dist[graphsize];
for (int i = 0; i < graphsize; i++)
{
dist[i] = INF;
}
int start = 0;
dist[start] = 0;
priority_queue<iPair, vector<iPair>, greater<iPair> > pq;
pq.push(make_pair(0, start));
while (!pq.empty())
{
int node = pq.top().second;
pq.pop();
for (int i = 0; i < graphsize; i++)
{
int weight = graph[node][i];
if ((dist[i] > dist[node] + weight) && (weight != 0))
{
dist[i] = dist[node] + weight;
pq.push(make_pair(dist[i], i));
}
}
}
if (dist[graphsize - 1] == INF)
{
return -1;
}
else
{
return dist[graphsize - 1];
}
}
bool PuzzleBoard::makeMove(int direction)
{
int i = currentX;
int j = cuurentY;
int value = graph[i][j];
if (direction == 0)
{
if (i - value > 0)
{
currentX = i - value;
return true;
}
}
else if (direction == 1)
{
if (j + value < graphsize)
{
cuurentY = j + value;
return true;
}
}
else if (direction == 2)
{
if (i + value < graphsize)
{
currentX = i + value;
return true;
}
}
else if (direction == 3)
{
if (j - value > 0)
{
cuurentY = j - value;
return true;
}
}
return false;
}
int main()
{
int **fields = NULL;
int n;
cout << "Welcome to the Puzzle Game" << endl;
cout<<"Enter the size"<<endl;
cin >> n;
PuzzleBoard puzzle(n, fields);
cout<<"A type of Adjacency graph of the maze"<<endl;
cout << puzzle << endl;
puzzle.getResult();
return 0;
} | 20.744681 | 84 | 0.442872 | UrfanAlvany |
f805ea225187bddb821299d8da798e0cfa5c1863 | 137 | cpp | C++ | src/main.cpp | zedrex/algosketch | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 16 | 2021-03-27T06:20:42.000Z | 2022-03-31T16:30:37.000Z | src/main.cpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 1 | 2021-07-13T07:57:41.000Z | 2021-07-13T07:57:41.000Z | src/main.cpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 3 | 2021-04-03T02:58:56.000Z | 2021-06-04T18:23:49.000Z | #include <managers/application.hpp>
using namespace std;
int main()
{
Application algoSketch;
algoSketch.run();
return 0;
} | 13.7 | 35 | 0.686131 | zedrex |
f80a6b9eb32daca9e2594a462c011ec4273909b8 | 2,995 | hpp | C++ | AudioKit/Common/Nodes/Mixing/Panner/AKPannerDSP.hpp | MattTolleson/AudioKit | 796c974e5f6ea00fdacca062f20f01bfb4689de8 | [
"MIT"
] | 1,699 | 2017-05-06T02:22:00.000Z | 2022-03-30T07:51:03.000Z | Pods/AudioKit/macOS/AudioKit.framework/Versions/A/Headers/AKPannerDSP.hpp | guruantree/MacAssistant | 21c4537fbedaab1a3be28daef578ad8d91cf8604 | [
"MIT"
] | 85 | 2017-05-08T18:48:44.000Z | 2022-03-07T05:30:01.000Z | Pods/AudioKit/macOS/AudioKit.framework/Versions/A/Headers/AKPannerDSP.hpp | guruantree/MacAssistant | 21c4537fbedaab1a3be28daef578ad8d91cf8604 | [
"MIT"
] | 180 | 2017-05-18T22:28:37.000Z | 2022-03-28T12:28:04.000Z | //
// AKPannerDSP.hpp
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once
#import <AVFoundation/AVFoundation.h>
typedef NS_ENUM(AUParameterAddress, AKPannerParameter) {
AKPannerParameterPan,
AKPannerParameterRampDuration
};
#import "AKLinearParameterRamp.hpp" // have to put this here to get it included in umbrella header
#ifndef __cplusplus
AKDSPRef createPannerDSP(int channelCount, double sampleRate);
#else
#import "AKSoundpipeDSPBase.hpp"
class AKPannerDSP : public AKSoundpipeDSPBase {
sp_panst *panst;
private:
AKLinearParameterRamp panRamp;
public:
AKPannerDSP() {
panRamp.setTarget(0, true);
panRamp.setDurationInSamples(10000);
}
/** Uses the ParameterAddress as a key */
void setParameter(AUParameterAddress address, float value, bool immediate) override {
switch (address) {
case AKPannerParameterPan:
panRamp.setTarget(value, immediate);
break;
case AKPannerParameterRampDuration:
panRamp.setRampDuration(value, sampleRate);
break;
}
}
/** Uses the ParameterAddress as a key */
float getParameter(AUParameterAddress address) override {
switch (address) {
case AKPannerParameterPan:
return panRamp.getTarget();
case AKPannerParameterRampDuration:
return panRamp.getRampDuration(sampleRate);
}
return 0;
}
void init(int channelCount, double sampleRate) override {
AKSoundpipeDSPBase::init(channelCount, sampleRate);
sp_panst_create(&panst);
sp_panst_init(sp, panst);
panst->pan = 0;
}
void deinit() override {
sp_panst_destroy(&panst);
}
void process(uint32_t frameCount, uint32_t bufferOffset) override {
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int frameOffset = int(frameIndex + bufferOffset);
// do ramping every 8 samples
if ((frameOffset & 0x7) == 0) {
panRamp.advanceTo(now + frameOffset);
}
panst->pan = panRamp.getValue();
float *tmpin[2];
float *tmpout[2];
for (int channel = 0; channel < channelCount; ++channel) {
float *in = (float *)inBufferListPtr->mBuffers[channel].mData + frameOffset;
float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
if (channel < 2) {
tmpin[channel] = in;
tmpout[channel] = out;
}
if (!isStarted) {
*out = *in;
}
}
if (isStarted) {
sp_panst_compute(sp, panst, tmpin[0], tmpin[1], tmpout[0], tmpout[1]);
}
}
}
};
#endif
| 27.477064 | 99 | 0.589649 | MattTolleson |
f80ddc18169a57b6eb52ab5e40b3d31efed68896 | 1,972 | cpp | C++ | codeforces/59E/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | codeforces/59E/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | codeforces/59E/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | // https://codeforces.com/contest/59/problem/E
#include <iostream>
#include <vector>
#include <map>
#include <tuple>
#include <queue>
#include <algorithm>
using namespace std;
int N;
vector<vector<int>> adj;
map<tuple<int,int,int>,bool> prohibit;
vector<int> solve() {
tuple<int,int,int> last;
map<pair<int,int>,int> prev;
map<pair<int,int>,bool> used;
queue<tuple<int,int,int>> Q;
Q.push({0, 0, 0});
while (!Q.empty()) {
auto now = Q.front(); Q.pop();
int a = get<0>(now), b = get<1>(now), c = get<2>(now);
if (c == N-1) {
last = now;
break;
}
for (auto u : adj[c]) {
if (used[{c,u}]) continue;
if (prohibit[{b,c,u}]) continue;
used[{c,u}] = true;
prev[{b,c}] = a;
Q.push({b,c,u});
}
}
// No path
if (get<2>(last) != N-1) {
return vector<int>();
}
vector<int> ans;
while (true) {
int a = get<0>(last), b = get<1>(last), c = get<2>(last);
ans.push_back(c);
if (c == 0) {
break;
}
last = {prev[{a,b}],a,b};
}
reverse(ans.begin(), ans.end());
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int M, K;
cin >> N >> M >> K;
adj.assign(N, vector<int>());
for (int i = 0; i < M; ++i) {
int a, b;
cin >> a >> b;
--a, --b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int i = 0; i < K; ++i) {
int a, b, c;
cin >> a >> b >> c;
--a, --b, --c;
prohibit[{a,b,c}] = true;
}
auto ans = solve();
if (ans.size() == 0) {
cout << -1 << endl;
} else {
cout << ans.size() - 1 << endl;
for (int i = 0; i < ans.size(); ++i) {
if (i > 0) cout << " ";
cout << ans[i] + 1;
}
cout << endl;
}
return 0;
} | 21.911111 | 65 | 0.43002 | xirc |
f8136c19f7063125f0532ef70d598dc3146fe837 | 2,249 | cpp | C++ | data-plane/config/tests/ESActionTest.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | data-plane/config/tests/ESActionTest.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | data-plane/config/tests/ESActionTest.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | #ifndef ES_ACTION_H
#include <ESAction.h>
#endif
#ifndef ES_ENTITY_TEST_H
#include "ESEntityTest.h"
#endif
#include <gtest/gtest.h>
#define UUID "0f42a1d1-cb6e-4a7b-be44-35fe34c6d5e1"
using namespace ES;
class ActionTest : public EntityTest {
public:
ActionTest() {}
virtual ~ActionTest() {}
virtual void SetUp() { ASSERT_EQ(ESB_SUCCESS, ESB::UniqueId::Parse(UUID, _uuid)); }
protected:
ESB::UniqueId _uuid;
ESB_DISABLE_AUTO_COPY(ActionTest);
};
TEST_F(ActionTest, ParseTransition) {
const char *conf =
" {"
" \"type\": \"TRANSITION\","
" \"destination\": \"" UUID
"\""
" }";
ESB::AST::Tree tree;
ASSERT_EQ(ESB_SUCCESS, parseString(conf, tree));
ASSERT_TRUE(tree.root());
ASSERT_EQ(tree.root()->type(), ESB::AST::Element::MAP);
ESB::AST::Map &map = *(ESB::AST::Map *)tree.root();
Action *action = NULL;
ASSERT_EQ(ESB_SUCCESS, Action::Build(map, ESB::SystemAllocator::Instance(), &action));
ASSERT_TRUE(action);
ASSERT_TRUE(action->cleanupHandler());
ASSERT_EQ(Action::TRANSITION, action->type());
TransitionAction *transition = (TransitionAction *)action;
ASSERT_EQ(_uuid, transition->destination());
action->cleanupHandler()->destroy(action);
}
TEST_F(ActionTest, ParseSendResponse) {
const char *conf =
" {"
" \"type\": \"SEND_RESPONSE\","
" \"status_code\": 404,"
" \"reason_phrase\": \"Not Found\""
" }";
ESB::AST::Tree tree;
ASSERT_EQ(ESB_SUCCESS, parseString(conf, tree));
ASSERT_TRUE(tree.root());
ASSERT_EQ(tree.root()->type(), ESB::AST::Element::MAP);
ESB::AST::Map &map = *(ESB::AST::Map *)tree.root();
Action *action = NULL;
ASSERT_EQ(ESB_SUCCESS, Action::Build(map, ESB::SystemAllocator::Instance(), &action));
ASSERT_TRUE(action);
ASSERT_TRUE(action->cleanupHandler());
ASSERT_EQ(Action::SEND_RESPONSE, action->type());
SendResponseAction *sendResponse = (SendResponseAction *)action;
ASSERT_EQ(404, sendResponse->statusCode());
const char *reasonPhrase = sendResponse->reasonPhrase();
ASSERT_EQ(0, strcmp("Not Found", reasonPhrase));
action->cleanupHandler()->destroy(action);
} | 28.833333 | 88 | 0.640285 | duderino |
f81b9243dee9c450c31d3a4a10bf7af796d89a30 | 562 | hpp | C++ | library/ATF/CNetTimer.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CNetTimer.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CNetTimer.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>
START_ATF_NAMESPACE
#pragma pack(push, 4)
struct CNetTimer
{
int m_nTickTerm;
unsigned int m_dwTickOld;
bool m_bOper;
public:
void BeginTimer(unsigned int dwTerm);
CNetTimer();
void ctor_CNetTimer();
bool CountingTimer();
};
#pragma pack(pop)
static_assert(ATF::checkSize<CNetTimer, 12>(), "CNetTimer");
END_ATF_NAMESPACE
| 24.434783 | 108 | 0.653025 | lemkova |
f81ca2d3a28a56ad94fc4e7bc20523a4ef0a0365 | 555 | hpp | C++ | src/cuda/n_body.hpp | savcardamone/tyche- | ea89edea89a607291e4fe0ba738d75522f54dc1a | [
"MIT"
] | null | null | null | src/cuda/n_body.hpp | savcardamone/tyche- | ea89edea89a607291e4fe0ba738d75522f54dc1a | [
"MIT"
] | 1 | 2018-12-28T13:30:16.000Z | 2018-12-29T10:30:33.000Z | src/cuda/n_body.hpp | savcardamone/tyche | ea89edea89a607291e4fe0ba738d75522f54dc1a | [
"MIT"
] | null | null | null | /**
* @file n_body.hpp
* @author Salvatore Cardamone
* @brief Basic N-Body implementation using CUDA.
*/
#ifndef N_BODY_CUDA_HPP__
#define N_BODY_CUDA_HPP__
// See https://stackoverflow.com/a/6978720
#ifdef __CUDACC__
#define CUDA_MEMBER __host__ __device__
#else
#define CUDA_MEMBER
#endif /* #ifdef __CUDACC__ */
class NBody {
public:
private:
unsigned int nParticles_;
std::vector<float4> particle_, acc_;
CUDA_MEMBER void PairwiseInteraction( const unsigned int& i, const unsigned int& j );
};
#endif /* #ifndef N_BODY_CUDA_HPP__ */
| 18.5 | 87 | 0.744144 | savcardamone |
f81e00fd1c7e53cdf2a97abdb19467afff9085bc | 1,164 | cpp | C++ | main.cpp | TomasDmArg/bulkwebpconverter | 7c82cfbd6b47b8b3ae1d62990ebdf69963050bbe | [
"MIT"
] | null | null | null | main.cpp | TomasDmArg/bulkwebpconverter | 7c82cfbd6b47b8b3ae1d62990ebdf69963050bbe | [
"MIT"
] | null | null | null | main.cpp | TomasDmArg/bulkwebpconverter | 7c82cfbd6b47b8b3ae1d62990ebdf69963050bbe | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
int n, lang;
string textos[] = {"De: (ej. jpg/png/etc) ", "Cantidad de archivos: ", "Nombre de archivo: "};
string texts[] = {"From: (e.g. jpg/png/etc) ","File quantity: ", "filename: "};
string actual[] = {""};
vector<string> files;
cout<<"Idioma/Language\n Spanish: 0 \n English: 1 \n"; cin>>lang;
if(lang == 0){
for (int i = 0; i < sizeof(textos)/sizeof(textos[0]); i++){
actual[i] = textos[i];
}
}else{
for (int i = 0; i < sizeof(texts)/sizeof(texts[0]); i++){
actual[i] = texts[i];
}
}
string type, from, to, res;
cout<<actual[0];
cin>>type;
cout<<actual[1];
cin>>n;
for (int i = 0; i < n; i++){
cout<<actual[2]<<" ";
string file;
cin>>file;
files.push_back(file);
}
system("mkdir output");
for(int i = 0; i < n; i++){
from = files[i] + "." + type;
to = files[i] + ".webp";
res = "cwebp " + from + " -o output/" + to;
system(res.c_str());
}
system("start output");
} | 29.1 | 99 | 0.49055 | TomasDmArg |
f81e85c2db0556c68b7556aa87c71f1899ad4e71 | 6,954 | cpp | C++ | editor/widgets/DebugWidgets.cpp | gan74/yave | c71b5dd7c05b1aa39c59a8071fc243c1472e71d1 | [
"MIT"
] | null | null | null | editor/widgets/DebugWidgets.cpp | gan74/yave | c71b5dd7c05b1aa39c59a8071fc243c1472e71d1 | [
"MIT"
] | null | null | null | editor/widgets/DebugWidgets.cpp | gan74/yave | c71b5dd7c05b1aa39c59a8071fc243c1472e71d1 | [
"MIT"
] | null | null | null | /*******************************
Copyright (c) 2016-2022 Grégoire Angerand
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 <editor/Widget.h>
#include <editor/EditorWorld.h>
#include <editor/utils/memory.h>
#include <yave/scene/SceneView.h>
#include <yave/systems/OctreeSystem.h>
#include <yave/graphics/device/MeshAllocator.h>
#include <editor/utils/ui.h>
#include <external/imgui/yave_imgui.h>
namespace editor {
class CameraDebug : public Widget {
editor_widget(CameraDebug, "View", "Debug")
public:
CameraDebug() : Widget(ICON_FA_VIDEO " Camera debug", ImGuiWindowFlags_AlwaysAutoResize) {
}
protected:
void on_gui() override {
const Camera& camera = scene_view().camera();
const math::Vec3 pos = camera.position();
const math::Vec3 fwd = camera.forward();
const math::Vec3 rht = camera.right();
const math::Vec3 up = fwd.cross(rht);
const math::Quaternion<> rot = math::Quaternion<>::from_base(fwd, rht, up);
ImGui::Text("FoV: %.1f", camera.field_of_view());
ImGui::Text("Aspect ratio: %.2f", camera.aspect_ratio());
ImGui::Separator();
ImGui::Text("position: %.1f, %.1f, %.1f", pos.x(), pos.y(), pos.z());
ImGui::Text("forward : %.1f, %.1f, %.1f", fwd.x(), fwd.y(), fwd.z());
ImGui::Text("right : %.1f, %.1f, %.1f", rht.x(), rht.y(), rht.z());
ImGui::Text("up : %.1f, %.1f, %.1f", up.x(), up.y(), up.z());
ImGui::Text("rotation: %.1f, %.1f, %.1f, %.1f", rot.x(), rot.y(), rot.z(), rot.w());
if(ImGui::CollapsingHeader("Rotation")) {
const math::Vec3 x = rot({1.0f, 0.0f, 0.0f});
const math::Vec3 y = rot({0.0f, 1.0f, 0.0f});
const math::Vec3 z = rot({0.0f, 0.0f, 1.0f});
ImGui::Text("X axis: %.1f, %.1f, %.1f", x.x(), x.y(), x.z());
ImGui::Text("Y axis: %.1f, %.1f, %.1f", y.x(), y.y(), y.z());
ImGui::Text("Z axis: %.1f, %.1f, %.1f", z.x(), z.y(), z.z());
ImGui::Separator();
auto euler = rot.to_euler();
ImGui::Text("pitch: %.1f°", math::to_deg(euler[math::Quaternion<>::PitchIndex]));
ImGui::Text("yaw : %.1f°", math::to_deg(euler[math::Quaternion<>::YawIndex]));
ImGui::Text("roll : %.1f°", math::to_deg(euler[math::Quaternion<>::RollIndex]));
}
}
};
class CullingDebug : public Widget {
editor_widget(CullingDebug, "View", "Debug")
public:
CullingDebug() : Widget("Culling debug", ImGuiWindowFlags_AlwaysAutoResize) {
}
protected:
void on_gui() override {
const EditorWorld& world = current_world();
const Camera& camera = scene_view().camera();
core::Vector<ecs::EntityId> visible;
const OctreeSystem* octree_system = world.find_system<OctreeSystem>();
if(octree_system) {
visible = octree_system->octree().find_entities(camera.frustum());
}
const usize in_frustum = visible.size();
const usize total = world.component_ids<TransformableComponent>().size();
ImGui::Text("%u entities in octree", u32(total));
ImGui::Text("%u entities in frustum", u32(in_frustum));
ImGui::Text("%u%% culled", u32(float(total - in_frustum) / float(total) * 100.0f));
}
};
class MemoryDebug : public Widget {
editor_widget(MemoryDebug, "View", "Debug")
public:
MemoryDebug() : Widget("Memory debug", ImGuiWindowFlags_AlwaysAutoResize) {
}
protected:
void on_gui() override {
const u64 total_allocs = memory::total_allocations();
ImGui::TextUnformatted(fmt_c_str("% live allocations", memory::live_allocations()));
ImGui::TextUnformatted(fmt_c_str("% allocations per frame", total_allocs - _last_total));
_last_total = total_allocs;
}
private:
u64 _last_total = 0;
};
class EcsDebug : public Widget {
editor_widget(EcsDebug, "View", "Debug")
public:
EcsDebug() : Widget("ECS Debug") {
}
protected:
void on_gui() override {
const EditorWorld& world = current_world();
if(ImGui::CollapsingHeader("Systems")) {
ImGui::BeginChild("##systems", ImVec2(0, 0), true);
imgui::alternating_rows_background();
for(const auto& system : world.systems()) {
ImGui::Selectable(system->name().data());
}
ImGui::EndChild();
}
}
};
class MeshAllocatorDebug : public Widget {
editor_widget(MeshAllocatorDebug, "View", "Debug")
public:
MeshAllocatorDebug() : Widget("Mesh allocator debug") {
}
protected:
void on_gui() override {
auto [vert, tris] = mesh_allocator().allocated();
{
ImGui::TextUnformatted("Vertex buffer:");
ImGui::SameLine();
ImGui::ProgressBar(float(vert) / MeshAllocator::default_vertex_count, ImVec2(-1.0f, 0.0f),
fmt_c_str("%k / %k", vert / 1000, MeshAllocator::default_vertex_count / 1000)
);
}
{
ImGui::TextUnformatted("Triangle buffer:");
ImGui::SameLine();
ImGui::ProgressBar(float(tris) / MeshAllocator::default_triangle_count, ImVec2(-1.0f, 0.0f),
fmt_c_str("%k / %k", tris / 1000, MeshAllocator::default_triangle_count / 1000)
);
}
}
};
}
| 36.793651 | 109 | 0.563129 | gan74 |
f81f92fe645075b68e828b219b6060e97187c699 | 518 | cpp | C++ | csacademy/fenwick.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | csacademy/fenwick.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | csacademy/fenwick.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define LSB(i) ((i)&-(i))
const int SIZE = 5;
int A[SIZE];
int sum(int i)
{
int sum = 0;
while(i > 0){
sum += A[i], i -= LSB(i);
}
return sum;
}
void add(int i, int p)
{
while(i < SIZE){
A[i] += p, i += LSB(i);
}
}
int main()
{
for(int i = 1; i < SIZE; i++)
add(i, i);
for(int i = 1; i < SIZE; i++)
cout<<sum(i)<<endl;
return 0;
}
| 15.69697 | 41 | 0.388031 | freedomDR |
f8264539778f2687084a99144e72cea6aaaee963 | 25,196 | cpp | C++ | source/games/blood/src/aicult.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | 1 | 2022-03-30T15:53:09.000Z | 2022-03-30T15:53:09.000Z | source/games/blood/src/aicult.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | null | null | null | source/games/blood/src/aicult.cpp | Quake-Backup/Raze | 16c81f0b1f409436ebf576d2c23f2459a29b34b4 | [
"RSA-MD"
] | null | null | null | //-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT
This file is part of NBlood.
NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h" // Must come before everything else!
#include "build.h"
#include "blood.h"
BEGIN_BLD_NS
static void cultThinkSearch(DBloodActor*);
static void cultThinkGoto(DBloodActor*);
static void cultThinkChase(DBloodActor*);
AISTATE cultistIdle = { kAiStateIdle, 0, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistProneIdle = { kAiStateIdle, 17, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE fanaticProneIdle = { kAiStateIdle, 17, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistProneIdle3 = { kAiStateIdle, 17, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistChase = { kAiStateChase, 9, -1, 0, NULL, aiMoveForward, cultThinkChase, NULL };
AISTATE fanaticChase = { kAiStateChase, 0, -1, 0, NULL, aiMoveTurn, cultThinkChase, NULL };
AISTATE cultistDodge = { kAiStateMove, 9, -1, 90, NULL, aiMoveDodge, NULL, &cultistChase };
AISTATE cultistGoto = { kAiStateMove, 9, -1, 600, NULL, aiMoveForward, cultThinkGoto, &cultistIdle };
AISTATE cultistProneChase = { kAiStateChase, 14, -1, 0, NULL, aiMoveForward, cultThinkChase, NULL };
AISTATE cultistProneDodge = { kAiStateMove, 14, -1, 90, NULL, aiMoveDodge, NULL, &cultistProneChase };
AISTATE cultistTThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistTFire };
AISTATE cultistSThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistSFire };
AISTATE cultistTsThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistTsFire };
AISTATE cultistDThrow = { kAiStateChase, 7, nThrowClient, 120, NULL, NULL, NULL, &cultistChase };
AISTATE cultist139A78 = { kAiStateChase, 7, n68170Client, 120, NULL, NULL, NULL, &cultistChase };
AISTATE cultist139A94 = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, NULL, &cultistIdle };
AISTATE cultist139AB0 = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, cultThinkSearch, &cultist139A94 };
AISTATE cultist139ACC = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, cultThinkSearch, &cultist139AB0 };
AISTATE cultist139AE8 = { kAiStateChase, 7, n68230Client, 120, NULL, NULL, cultThinkSearch, &cultist139AE8 };
AISTATE cultistSearch = { kAiStateSearch, 9, -1, 1800, NULL, aiMoveForward, cultThinkSearch, &cultistIdle };
AISTATE cultistSFire = { kAiStateChase, 6, nShotClient, 60, NULL, NULL, NULL, &cultistChase };
AISTATE cultistTFire = { kAiStateChase, 6, nTommyClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTFire };
AISTATE cultistTsFire = { kAiStateChase, 6, nTeslaClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistChase };
AISTATE cultistSProneFire = { kAiStateChase, 8, nShotClient, 60, NULL, NULL, NULL, &cultistProneChase };
AISTATE cultistTProneFire = { kAiStateChase, 8, nTommyClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTProneFire };
AISTATE cultistTsProneFire = { kAiStateChase, 8, nTeslaClient, 0, NULL, aiMoveTurn, NULL, &cultistTsProneFire }; // vanilla, broken
AISTATE cultistTsProneFireFixed = { kAiStateChase, 8, nTeslaClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTsProneFireFixed };
AISTATE cultistRecoil = { kAiStateRecoil, 5, -1, 0, NULL, NULL, NULL, &cultistDodge };
AISTATE cultistProneRecoil = { kAiStateRecoil, 5, -1, 0, NULL, NULL, NULL, &cultistProneDodge };
AISTATE cultistTeslaRecoil = { kAiStateRecoil, 4, -1, 0, NULL, NULL, NULL, &cultistDodge };
AISTATE cultistSwimIdle = { kAiStateIdle, 13, -1, 0, NULL, NULL, aiThinkTarget, NULL };
AISTATE cultistSwimChase = { kAiStateChase, 13, -1, 0, NULL, aiMoveForward, cultThinkChase, NULL };
AISTATE cultistSwimDodge = { kAiStateMove, 13, -1, 90, NULL, aiMoveDodge, NULL, &cultistSwimChase };
AISTATE cultistSwimGoto = { kAiStateMove, 13, -1, 600, NULL, aiMoveForward, cultThinkGoto, &cultistSwimIdle };
AISTATE cultistSwimSearch = { kAiStateSearch, 13, -1, 1800, NULL, aiMoveForward, cultThinkSearch, &cultistSwimIdle };
AISTATE cultistSSwimFire = { kAiStateChase, 8, nShotClient, 60, NULL, NULL, NULL, &cultistSwimChase };
AISTATE cultistTSwimFire = { kAiStateChase, 8, nTommyClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTSwimFire };
AISTATE cultistTsSwimFire = { kAiStateChase, 8, nTeslaClient, 0, NULL, aiMoveTurn, cultThinkChase, &cultistTsSwimFire };
AISTATE cultistSwimRecoil = { kAiStateRecoil, 5, -1, 0, NULL, NULL, NULL, &cultistSwimDodge };
void TommySeqCallback(int, DBloodActor* actor)
{
int dx = bcos(actor->spr.ang);
int dy = bsin(actor->spr.ang);
int dz = actor->dudeSlope;
dx += Random3((5 - gGameOptions.nDifficulty) * 1000);
dy += Random3((5 - gGameOptions.nDifficulty) * 1000);
dz += Random3((5 - gGameOptions.nDifficulty) * 500);
actFireVector(actor, 0, 0, dx, dy, dz, kVectorBullet);
sfxPlay3DSound(actor, 4001, -1, 0);
}
void TeslaSeqCallback(int, DBloodActor* actor)
{
if (Chance(dword_138BB0[gGameOptions.nDifficulty]))
{
int dx = bcos(actor->spr.ang);
int dy = bsin(actor->spr.ang);
int dz = actor->dudeSlope;
dx += Random3((5 - gGameOptions.nDifficulty) * 1000);
dy += Random3((5 - gGameOptions.nDifficulty) * 1000);
dz += Random3((5 - gGameOptions.nDifficulty) * 500);
actFireMissile(actor, 0, 0, dx, dy, dz, kMissileTeslaRegular);
sfxPlay3DSound(actor, 470, -1, 0);
}
}
void ShotSeqCallback(int, DBloodActor* actor)
{
int dx = bcos(actor->spr.ang);
int dy = bsin(actor->spr.ang);
int dz = actor->dudeSlope;
dx += Random2((5 - gGameOptions.nDifficulty) * 1000 - 500);
dy += Random2((5 - gGameOptions.nDifficulty) * 1000 - 500);
dz += Random2((5 - gGameOptions.nDifficulty) * 500);
for (int i = 0; i < 8; i++)
{
int r1 = Random3(500);
int r2 = Random3(1000);
int r3 = Random3(1000);
actFireVector(actor, 0, 0, dx + r3, dy + r2, dz + r1, kVectorShell);
}
if (Chance(0x8000))
sfxPlay3DSound(actor, 1001, -1, 0);
else
sfxPlay3DSound(actor, 1002, -1, 0);
}
void cultThrowSeqCallback(int, DBloodActor* actor)
{
int nMissile = kThingArmedTNTStick;
if (gGameOptions.nDifficulty > 2)
nMissile = kThingArmedTNTBundle;
uint8_t v4 = Chance(0x6000);
sfxPlay3DSound(actor, 455, -1, 0);
if (!actor->ValidateTarget(__FUNCTION__)) return;
auto target = actor->GetTarget();
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
int dx = target->spr.pos.X - actor->spr.pos.X;
int dy = target->spr.pos.Y - actor->spr.pos.Y;
int dz = target->spr.pos.Z - actor->spr.pos.Z;
int nDist = approxDist(dx, dy);
int nDist2 = nDist / 540;
if (nDist > 0x1e00)
v4 = 0;
auto* pMissile = actFireThing(actor, 0, 0, dz / 128 - 14500, nMissile, (nDist2 << 23) / 120);
if (v4)
pMissile->xspr.Impact = 1;
else
evPostActor(pMissile, 120 * (1 + Random(2)), kCmdOn);
}
void sub_68170(int, DBloodActor* actor)
{
int nMissile = kThingArmedTNTStick;
if (gGameOptions.nDifficulty > 2)
nMissile = kThingArmedTNTBundle;
sfxPlay3DSound(actor, 455, -1, 0);
auto pMissile = actFireThing(actor, 0, 0, actor->dudeSlope - 9460, nMissile, 0x133333);
evPostActor(pMissile, 120 * (2 + Random(2)), kCmdOn);
}
void sub_68230(int, DBloodActor* actor)
{
int nMissile = kThingArmedTNTStick;
if (gGameOptions.nDifficulty > 2)
nMissile = kThingArmedTNTBundle;
sfxPlay3DSound(actor, 455, -1, 0);
if (!actor->ValidateTarget(__FUNCTION__)) return;
auto target = actor->GetTarget();
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
int dx = target->spr.pos.X - actor->spr.pos.X;
int dy = target->spr.pos.Y - actor->spr.pos.Y;
int dz = target->spr.pos.Z - actor->spr.pos.Z;
int nDist = approxDist(dx, dy);
int nDist2 = nDist / 540;
auto pMissile = actFireThing(actor, 0, 0, dz / 128 - 14500, nMissile, (nDist2 << 17) / 120);
pMissile->xspr.Impact = 1;
}
static bool TargetNearExplosion(sectortype* sector)
{
BloodSectIterator it(sector);
while (auto actor = it.Next())
{
if (actor->spr.type == kThingArmedTNTStick || actor->spr.statnum == kStatExplosion)
return true;
}
return false;
}
static void cultThinkSearch(DBloodActor* actor)
{
aiChooseDirection(actor, actor->xspr.goalAng);
aiLookForTarget(actor);
}
static void cultThinkGoto(DBloodActor* actor)
{
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
DUDEINFO* pDudeInfo = getDudeInfo(actor->spr.type);
int dx = actor->xspr.TargetPos.X - actor->spr.pos.X;
int dy = actor->xspr.TargetPos.Y - actor->spr.pos.Y;
int nAngle = getangle(dx, dy);
int nDist = approxDist(dx, dy);
aiChooseDirection(actor, nAngle);
if (nDist < 5120 && abs(actor->spr.ang - nAngle) < pDudeInfo->periphery)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistSearch);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimSearch);
break;
}
}
aiThinkTarget(actor);
}
static void cultThinkChase(DBloodActor* actor)
{
if (actor->GetTarget() == nullptr)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistGoto);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimGoto);
break;
}
return;
}
assert(actor->spr.type >= kDudeBase && actor->spr.type < kDudeMax);
DUDEINFO* pDudeInfo = getDudeInfo(actor->spr.type);
auto target = actor->GetTarget();
int dx = target->spr.pos.X - actor->spr.pos.X;
int dy = target->spr.pos.Y - actor->spr.pos.Y;
aiChooseDirection(actor, getangle(dx, dy));
if (target->xspr.health == 0)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistSearch);
if (actor->spr.type == kDudeCultistTommy)
aiPlay3DSound(actor, 4021 + Random(4), AI_SFX_PRIORITY_1, -1);
else
aiPlay3DSound(actor, 1021 + Random(4), AI_SFX_PRIORITY_1, -1);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimSearch);
break;
}
return;
}
if (target->IsPlayerActor() && powerupCheck(&gPlayer[target->spr.type - kDudePlayer1], kPwUpShadowCloak) > 0)
{
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistSearch);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimSearch);
break;
}
return;
}
int nDist = approxDist(dx, dy);
if (nDist > 0 && nDist <= pDudeInfo->seeDist)
{
int nDeltaAngle = ((getangle(dx, dy) + 1024 - actor->spr.ang) & 2047) - 1024;
int height = (pDudeInfo->eyeHeight * actor->spr.yrepeat) << 2;
if (cansee(target->spr.pos.X, target->spr.pos.Y, target->spr.pos.Z, target->sector(), actor->spr.pos.X, actor->spr.pos.Y, actor->spr.pos.Z - height, actor->sector()))
{
if (nDist < pDudeInfo->seeDist && abs(nDeltaAngle) <= pDudeInfo->periphery)
{
aiSetTarget(actor, actor->GetTarget());
actor->dudeSlope = nDist == 0 ? 0 : DivScale(target->spr.pos.Z - actor->spr.pos.Z, nDist, 10);
switch (actor->spr.type) {
case kDudeCultistTommy:
if (nDist < 0x1e00 && nDist > 0xe00 && abs(nDeltaAngle) < 85 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty > 2 && target->IsPlayerActor() && gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTThrow);
break;
default:
aiNewState(actor, &cultistTThrow);
break;
}
}
else if (nDist < 0x4600 && abs(nDeltaAngle) < 28)
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTProneFire);
else if (dudeIsPlayingSeq(actor, 13) && (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo))
aiNewState(actor, &cultistTSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTSwimFire);
break;
}
}
break;
case kDudeCultistShotgun:
if (nDist < 0x2c00 && nDist > 0x1400 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty >= 2 && target->IsPlayerActor() && !gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
default:
aiNewState(actor, &cultistSThrow);
break;
}
}
else if (nDist < 0x3200 && abs(nDeltaAngle) < 28)
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistTommy)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
}
}
break;
case kDudeCultistTesla:
if (nDist < 0x1e00 && nDist > 0xe00 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty > 2 && target->IsPlayerActor() && gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTsThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistTsThrow);
break;
default:
aiNewState(actor, &cultistTsThrow);
break;
}
}
else if (nDist < 0x3200 && abs(nDeltaAngle) < 28)
{
AISTATE *pCultistTsProneFire = !cl_bloodvanillaenemies && !VanillaMode() ? &cultistTsProneFireFixed : &cultistTsProneFire;
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTsFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, pCultistTsProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTsSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistTommy)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTsFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, pCultistTsProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTsSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistTsFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, pCultistTsProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistTsSwimFire);
break;
}
}
break;
case kDudeCultistTNT:
if (nDist < 0x2c00 && nDist > 0x1400 && abs(nDeltaAngle) < 85
&& (target->spr.flags & 2) && target->IsPlayerActor())
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistDThrow);
break;
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistDThrow);
break;
default:
aiNewState(actor, &cultistDThrow);
break;
}
}
else if (nDist < 0x1400 && abs(nDeltaAngle) < 85
&& (target->spr.flags & 2) && target->IsPlayerActor())
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != 1 && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultist139A78);
break;
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultist139A78);
break;
default:
aiNewState(actor, &cultist139A78);
break;
}
}
break;
case kDudeCultistBeast:
if (nDist < 0x1e00 && nDist > 0xe00 && !TargetNearExplosion(target->sector())
&& (target->spr.flags & 2) && gGameOptions.nDifficulty > 2 && target->IsPlayerActor() && gPlayer[target->spr.type - kDudePlayer1].isRunning
&& Chance(0x8000))
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
case 0:
case 4:
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistShotgun && actor->xspr.medium != kMediumWater && actor->xspr.medium != kMediumGoo)
aiNewState(actor, &cultistSThrow);
break;
default:
aiNewState(actor, &cultistSThrow);
break;
}
}
else if (nDist < 0x3200 && abs(nDeltaAngle) < 28)
{
int hit = HitScan(actor, actor->spr.pos.Z, dx, dy, 0, CLIPMASK1, 0);
switch (hit)
{
case -1:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
case 3:
if (actor->spr.type != gHitInfo.actor()->spr.type && gHitInfo.actor()->spr.type != kDudeCultistTommy)
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
}
else
{
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistDodge);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistProneDodge);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSwimDodge);
}
break;
default:
if (!dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSFire);
else if (dudeIsPlayingSeq(actor, 14) && actor->xspr.medium == kMediumNormal)
aiNewState(actor, &cultistSProneFire);
else if (actor->xspr.medium == kMediumWater || actor->xspr.medium == kMediumGoo)
aiNewState(actor, &cultistSSwimFire);
break;
}
}
break;
}
return;
}
}
}
switch (actor->xspr.medium)
{
case kMediumNormal:
aiNewState(actor, &cultistGoto);
break;
case kMediumWater:
case kMediumGoo:
aiNewState(actor, &cultistSwimGoto);
break;
}
actor->SetTarget(nullptr);
}
END_BLD_NS
| 40.573269 | 184 | 0.65173 | Quake-Backup |
f82cae8e8b8d25cdcefc2cffde99716d5148896e | 1,528 | hpp | C++ | src/popup/popup-stage-system-error.hpp | tilnewman/heroespath-src | a7784e44d8b5724f305ef8b8671fed54e2e5fd69 | [
"BSL-1.0",
"Beerware"
] | 2 | 2019-02-28T00:28:08.000Z | 2019-10-20T14:39:48.000Z | src/popup/popup-stage-system-error.hpp | tilnewman/heroespath-src | a7784e44d8b5724f305ef8b8671fed54e2e5fd69 | [
"BSL-1.0",
"Beerware"
] | null | null | null | src/popup/popup-stage-system-error.hpp | tilnewman/heroespath-src | a7784e44d8b5724f305ef8b8671fed54e2e5fd69 | [
"BSL-1.0",
"Beerware"
] | null | null | null | // ----------------------------------------------------------------------------
// "THE BEER-WARE LICENSE" (Revision 42):
// <ztn@zurreal.com> wrote this file. As long as you retain this notice you
// can do whatever you want with this stuff. If we meet some day, and you think
// this stuff is worth it, you can buy me a beer in return. Ziesche Til Newman
// ----------------------------------------------------------------------------
#ifndef HEROESPATH_POPUP_POPUPSTAGESYSTEMERROR_HPP_INCLUDED
#define HEROESPATH_POPUP_POPUPSTAGESYSTEMERROR_HPP_INCLUDED
//
// popup-stage-system-error.hpp
//
#include "popup/popup-stage-base.hpp"
namespace heroespath
{
namespace popup
{
// Responsible for implementing the System Error Popup Stage.
class PopupStageSystemError : public PopupStageBase
{
public:
PopupStageSystemError(const PopupStageSystemError &) = delete;
PopupStageSystemError(PopupStageSystemError &&) = delete;
PopupStageSystemError & operator=(const PopupStageSystemError &) = delete;
PopupStageSystemError & operator=(PopupStageSystemError &&) = delete;
explicit PopupStageSystemError(const PopupInfo &);
virtual ~PopupStageSystemError();
void Setup() override;
void draw(sf::RenderTarget &, sf::RenderStates) const override;
private:
gui::CachedTexture bgCachedTexture_;
sf::Sprite bgSprite_;
};
} // namespace popup
} // namespace heroespath
#endif // HEROESPATH_POPUP_POPUPSTAGESYSTEMERROR_HPP_INCLUDED
| 36.380952 | 82 | 0.656414 | tilnewman |
f82d257f89575fff02afb18bb59610c72de43037 | 11,545 | cpp | C++ | tests/test_basic.cpp | preet/libobdref | 9282b2e30ef97578b3d17eeb757090b001809972 | [
"Apache-2.0"
] | 2 | 2015-11-07T18:32:10.000Z | 2017-11-20T21:13:22.000Z | tests/test_basic.cpp | preet/libobdref | 9282b2e30ef97578b3d17eeb757090b001809972 | [
"Apache-2.0"
] | null | null | null | tests/test_basic.cpp | preet/libobdref | 9282b2e30ef97578b3d17eeb757090b001809972 | [
"Apache-2.0"
] | null | null | null | /*
This source is part of libobdref
Copyright (C) 2012,2013 Preet Desai (preet.desai@gmail.com)
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 "obdreftest.h"
bool test_legacy(obdref::Parser & parser,
bool const randomizeHeader=false);
bool test_iso14230(obdref::Parser & parser,
bool const randomizeHeader=false,
int const headerLength=3,
bool const checkHeaderFormatByte=true);
bool test_iso15765(obdref::Parser & parser,
bool const randomizeHeader=false,
bool const extendedId=false);
int main(int argc, char* argv[])
{
// we expect a single argument that specifies
// the path to the test definitions file
bool opOk = false;
QString filePath(argv[1]);
if(filePath.isEmpty()) {
qDebug() << "Pass the test definitions file in as an argument:";
qDebug() << "./test_basic /path/to/test.xml";
return -1;
}
// read in xml definitions file
obdref::Parser parser(filePath,opOk);
if(!opOk) { return -1; }
g_debug_output = false;
bool randHeaders=true;
g_test_desc = "test legacy (sae j1850, iso 9141)";
if(!test_legacy(parser,randHeaders)) {
return -1;
}
g_test_desc = "test iso 14230 (1 byte header)";
if(!test_iso14230(parser,randHeaders,1,false)) {
return -1;
}
g_test_desc = "test iso 14230 (2 byte header)";
if(!test_iso14230(parser,randHeaders,2,false)) {
return -1;
}
g_test_desc = "test iso 14230 (3 byte header)";
if(!test_iso14230(parser,randHeaders,3,true)) {
return -1;
}
g_test_desc = "test iso 14230 (4 byte header)";
if(!test_iso14230(parser,randHeaders,4,true)) {
return -1;
}
g_test_desc = "test iso 15765 (standard ids)";
if(!test_iso15765(parser,randHeaders,false)) {
return -1;
}
g_test_desc = "test iso 15765 (extended ids)";
if(!test_iso15765(parser,randHeaders,true)) {
return -1;
}
return 0;
}
// ========================================================================== //
// ========================================================================== //
bool test_legacy(obdref::Parser & parser,
bool const randomizeHeader)
{
QStringList listParams =
parser.GetParameterNames("TEST","ISO 9141-2","Default");
for(int i=0; i < listParams.size(); i++) {
obdref::ParameterFrame param;
param.spec = "TEST";
param.protocol = "ISO 9141-2";
param.address = "Default";
param.name = listParams[i];
if(!parser.BuildParameterFrame(param)) {
qDebug() << "Error: could not build frame "
"for param:" << listParams[i];
}
else {
if( param.name == "T_REQ_NONE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_NON_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
sim_vehicle_message_legacy(param,1,randomizeHeader);
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_MF_PARSE_SEP") {
sim_vehicle_message_legacy(param,2,randomizeHeader);
sim_vehicle_message_legacy(param,2,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_SEP") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_COMBINED") {
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_legacy(param,2,randomizeHeader);
sim_vehicle_message_legacy(param,1,randomizeHeader);
}
else {
continue;
}
QList<obdref::Data> listData;
if(parser.ParseParameterFrame(param,listData)) {
if(g_debug_output) {
print_message_frame(param);
print_parsed_data(listData);
}
continue;
}
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "failed!";
return false;
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "passed!";
return true;
}
// ========================================================================== //
// ========================================================================== //
bool test_iso14230(obdref::Parser & parser,
bool const randomizeHeader,
int const headerLength,
bool const checkHeaderFormatByte)
{
QStringList listParams =
parser.GetParameterNames("TEST","ISO 14230","Default");
for(int i=0; i < listParams.size(); i++) {
obdref::ParameterFrame param;
param.spec = "TEST";
param.protocol = "ISO 14230";
param.address = "Default";
param.name = listParams[i];
if(!parser.BuildParameterFrame(param)) {
qDebug() << "Error: could not build frame "
"for param:" << listParams[i];
}
else {
if(checkHeaderFormatByte==false) {
// just makes testing multiple header lengths
// at once a bit easier
for(int j=0; j < param.listMessageData.size(); j++) {
param.listMessageData[j].expHeaderMask[0] = 0x00;
}
}
if( param.name == "T_REQ_NONE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_NON_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
sim_vehicle_message_iso14230(param,1,randomizeHeader);
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_MF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,2,randomizeHeader);
sim_vehicle_message_iso14230(param,2,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_COMBINED") {
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso14230(param,2,randomizeHeader);
sim_vehicle_message_iso14230(param,1,randomizeHeader);
}
else {
continue;
}
QList<obdref::Data> listData;
if(parser.ParseParameterFrame(param,listData)) {
if(g_debug_output) {
print_message_frame(param);
print_parsed_data(listData);
}
continue;
}
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "failed!";
return false;
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "passed!";
return true;
}
// ========================================================================== //
// ========================================================================== //
bool test_iso15765(obdref::Parser & parser,
bool const randomizeHeader,
bool const extendedId)
{
QString protocol = (extendedId) ?
"ISO 15765 Extended Id" : "ISO 15765 Standard Id";
QStringList listParams =
parser.GetParameterNames("TEST",protocol,"Default");
for(int i=0; i < listParams.size(); i++) {
obdref::ParameterFrame param;
param.spec = "TEST";
param.protocol = protocol;
param.address = "Default";
param.name = listParams[i];
if(!parser.BuildParameterFrame(param)) {
qDebug() << "Error: could not build frame "
"for param:" << listParams[i];
}
else {
if( param.name == "T_REQ_NONE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_NON_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
sim_vehicle_message_iso15765(param,1,randomizeHeader);
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_SINGLE_RESP_MF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,3,randomizeHeader);
sim_vehicle_message_iso15765(param,4,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_SEP") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_SF_PARSE_COMBINED") {
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else if(param.name == "T_REQ_MULTI_RESP_MF_PARSE_COMBINED") {
sim_vehicle_message_iso15765(param,2,randomizeHeader);
sim_vehicle_message_iso15765(param,1,randomizeHeader);
}
else {
continue;
}
QList<obdref::Data> listData;
if(parser.ParseParameterFrame(param,listData)) {
if(g_debug_output) {
print_message_frame(param);
print_parsed_data(listData);
}
continue;
}
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "failed!";
return false;
}
qDebug() << "////////////////////////////////////////////////";
qDebug() << g_test_desc << "passed!";
return true;
}
| 37.36246 | 80 | 0.532438 | preet |
f830701d4dd232a2392ad1c173ac9dd1cb5d1655 | 1,029 | cpp | C++ | src/VkRenderer/Image.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | 2 | 2020-05-31T19:54:19.000Z | 2021-09-14T12:00:12.000Z | src/VkRenderer/Image.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | src/VkRenderer/Image.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | #include "Image.hpp"
#include <cassert>
#include <stdexcept>
namespace cdm
{
Image::Image(const VulkanDevice& device_, VkFormat format)
: AbstractImage(device_, format)
{
}
Image::~Image() { device().destroy(m_image.get()); }
VkImage Image::image()
{
if (outdated())
recreate();
return m_image.get();
}
bool Image::outdated() const
{
assert(false && "not implemented yet");
return true;
}
void Image::recreate()
{
assert(false && "not implemented yet");
setCreationTime();
}
SwapchainImage::SwapchainImage(const VulkanDevice& device_, VkImage image_,
VkFormat format)
: Image(device_, format),
m_image(image_)
{
setCreationTime();
}
SwapchainImage::~SwapchainImage()
{
// The parent class can not destroy the image if there's no image
m_image = nullptr;
}
void SwapchainImage::setImage(VkImage image_)
{
m_image = image_;
setCreationTime();
}
void SwapchainImage::setFormat(VkFormat format_)
{
m_format = format_;
setCreationTime();
}
} // namespace cdm
| 16.078125 | 75 | 0.683188 | WubiCookie |
f830aa215f418e783a4e7a32c67d379d189fbae3 | 19,991 | cpp | C++ | Steamhammer/Source/ScoutManager.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | 10 | 2017-07-06T18:47:02.000Z | 2019-03-22T04:49:41.000Z | Steamhammer/Source/ScoutManager.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | null | null | null | Steamhammer/Source/ScoutManager.cpp | kant2002/steamhammer | 375756e40f427faf3496fcf5da20955720ceda0a | [
"MIT"
] | 6 | 2017-09-05T14:40:19.000Z | 2018-11-01T08:00:53.000Z | #include "ScoutManager.h"
#include "Bases.h"
#include "GameCommander.h"
#include "MapGrid.h"
#include "MapTools.h"
#include "Micro.h"
#include "OpponentModel.h"
#include "ProductionManager.h"
#include "The.h"
// This class is responsible for early game scouting.
// It controls any scouting worker and scouting overlord that it is given.
using namespace UAlbertaBot;
ScoutManager::ScoutManager()
: _overlordScout(nullptr)
, _workerScout(nullptr)
, _scoutStatus("None")
, _gasStealStatus("None")
, _scoutCommand(MacroCommandType::None)
, _overlordAtEnemyBase(false)
, _overlordAtBaseTarget(BWAPI::Positions::Invalid)
, _scoutUnderAttack(false)
, _tryGasSteal(false)
, _enemyGeyser(nullptr)
, _startedGasSteal(false)
, _queuedGasSteal(false)
, _gasStealOver(false)
, _previousScoutHP(0)
, _nextDestination(BWAPI::Positions::Invalid)
{
setScoutTargets();
}
ScoutManager & ScoutManager::Instance()
{
static ScoutManager instance;
return instance;
}
// Target locations are set while we are still looking for the enemy base.
// After the enemy base is found, we unset the targets and go to or ignore the enemy base as appropriate.
// If we have both an overlord and a worker, send them to search different places.
// Guarantee: We only set a target if the scout for the target is set.
void ScoutManager::setScoutTargets()
{
Base * enemyBase = the.bases.enemyStart();
if (enemyBase)
{
_overlordScoutTarget = BWAPI::TilePositions::Invalid;
_workerScoutTarget = BWAPI::TilePositions::Invalid;
return;
}
if (!_overlordScout)
{
_overlordScoutTarget = BWAPI::TilePositions::Invalid;
}
if (!_workerScout)
{
_workerScoutTarget = BWAPI::TilePositions::Invalid;
}
// Unset any targets that we have searched.
for (BWAPI::TilePosition pos : BWAPI::Broodwar->getStartLocations())
{
if (BWAPI::Broodwar->isExplored(pos))
{
// We've seen it. No need to look there any more.
if (_overlordScoutTarget == pos)
{
_overlordScoutTarget = BWAPI::TilePositions::Invalid;
}
if (_workerScoutTarget == pos)
{
_workerScoutTarget = BWAPI::TilePositions::Invalid;
}
}
}
// Set any target that we need to search.
for (BWAPI::TilePosition pos : BWAPI::Broodwar->getStartLocations())
{
if (!BWAPI::Broodwar->isExplored(pos))
{
if (_overlordScout && !_overlordScoutTarget.isValid() && _workerScoutTarget != pos)
{
_overlordScoutTarget = pos;
}
else if (_workerScout && !_workerScoutTarget.isValid() && _overlordScoutTarget != pos)
{
_workerScoutTarget = pos;
}
}
}
// NOTE There cannot be only one target. We found the base, or there are >= 2 possibilities.
// If there is one place left to search, then the enemy base is there and we know it,
// because InformationManager infers the enemy base position by elimination.
}
// Should we send out a worker scout now?
bool ScoutManager::shouldScout()
{
// If we're stealing gas, it doesn't matter what the scout command is: We need to send a worker.
if (wantGasSteal())
{
return true;
}
if (_scoutCommand == MacroCommandType::None)
{
return false;
}
// If we only want to find the enemy base location and we already know it, don't send a worker.
if (_scoutCommand == MacroCommandType::ScoutIfNeeded || _scoutCommand == MacroCommandType::ScoutLocation)
{
return !the.bases.enemyStart();
}
return true;
}
void ScoutManager::update()
{
// If we're not scouting now, minimum effort.
if (!_workerScout && !_overlordScout)
{
return;
}
// If a scout is gone, admit it.
if (_workerScout &&
(!_workerScout->exists() || _workerScout->getHitPoints() <= 0 || // it died (or became a zerg extractor)
_workerScout->getPlayer() != the.self())) // it got mind controlled!
{
_workerScout = nullptr;
}
if (_overlordScout &&
(!_overlordScout->exists() || _overlordScout->getHitPoints() <= 0 || // it died
_overlordScout->getPlayer() != the.self())) // it got mind controlled!
{
_overlordScout = nullptr;
}
// Release the overlord scout if the enemy has mobile or static anti-air.
if (_overlordScout && (InformationManager::Instance().enemyHasAntiAir() || overlordBlockedByAirDefense()))
{
releaseOverlordScout();
}
// If we only want to locate the enemy base and we have, release the scout worker.
if (_scoutCommand == MacroCommandType::ScoutLocation &&
the.bases.enemyStart() &&
!wantGasSteal())
{
releaseWorkerScout();
}
// If we're done with a gas steal and we don't want to keep scouting, release the worker.
// If we're zerg, the worker may have turned into an extractor. That is handled elsewhere.
if (_scoutCommand == MacroCommandType::None && _gasStealOver)
{
releaseWorkerScout();
}
// Release the worker if it can no longer help: Enemy has combat units to chase it,
// we have combat units to keep watch.
if (_workerScout &&
the.bases.enemyStart() &&
_workerScout->getDistance(the.bases.enemyStart()->getCenter()) < 40 * 32 &&
the.info.enemyHasCombatUnits() &&
friendlyUnitNear(_workerScout))
{
releaseWorkerScout();
}
// Do the actual scouting. Also steal gas if called for.
setScoutTargets();
if (_workerScout)
{
bool moveScout = true;
if (wantGasSteal()) // implies !_gasStealOver
{
if (gasSteal())
{
moveScout = false;
}
else if (_queuedGasSteal) // gas steal queued but not finished
{
// We're in the midst of stealing gas. Let BuildingManager control the worker.
moveScout = false;
_gasStealStatus = "Stealing gas";
}
}
else
{
if (_gasStealOver)
{
_gasStealStatus = "Finished or failed";
}
else
{
_gasStealStatus = "Not planned";
}
}
if (moveScout)
{
moveGroundScout();
}
}
else if (_gasStealOver)
{
// We get here if we're stealing gas as zerg when the worker turns into an extractor.
_gasStealStatus = "Finished or failed";
}
if (_overlordScout)
{
moveAirScout();
}
drawScoutInformation(200, 320);
}
// If zerg, our first overlord is used to scout immediately at the start of the game.
void ScoutManager::setOverlordScout(BWAPI::Unit unit)
{
_overlordScout = unit;
}
// The worker scout is assigned only when it is time to go scout.
void ScoutManager::setWorkerScout(BWAPI::Unit unit)
{
releaseWorkerScout();
_workerScout = unit;
WorkerManager::Instance().setScoutWorker(_workerScout);
}
// Send the worker scout home.
void ScoutManager::releaseWorkerScout()
{
if (_workerScout)
{
WorkerManager::Instance().finishedWithWorker(_workerScout);
_gasStealOver = true;
_workerScout = nullptr;
}
}
// The scouting overlord is near enemy static air defense.
bool ScoutManager::overlordBlockedByAirDefense() const
{
if (the.now() % 3 != 0) // check once each 3 frames
{
return false;
}
// Notice a turret, cannon, spore starting nearby.
BWAPI::Unit enemy = BWAPI::Broodwar->getClosestUnit(
_overlordScout->getPosition(),
BWAPI::Filter::IsEnemy && BWAPI::Filter::AirWeapon != BWAPI::WeaponTypes::None,
8 * 32
);
return enemy != nullptr;
}
// Send the overlord scout home.
void ScoutManager::releaseOverlordScout()
{
if (_overlordScout)
{
GameCommander::Instance().releaseOverlord(_overlordScout);
_overlordScout = nullptr;
}
}
void ScoutManager::setScoutCommand(MacroCommandType cmd)
{
UAB_ASSERT(
cmd == MacroCommandType::Scout ||
cmd == MacroCommandType::ScoutIfNeeded ||
cmd == MacroCommandType::ScoutLocation ||
cmd == MacroCommandType::ScoutOnceOnly,
"bad scout command");
_scoutCommand = cmd;
}
void ScoutManager::drawScoutInformation(int x, int y)
{
if (!Config::Debug::DrawScoutInfo)
{
return;
}
BWAPI::Broodwar->drawTextScreen(x, y, "Scout info: %s", _scoutStatus.c_str());
BWAPI::Broodwar->drawTextScreen(x, y+10, "Gas steal: %s", _gasStealStatus.c_str());
std::string more = "not yet";
if (_scoutCommand == MacroCommandType::Scout)
{
more = "and stay";
}
else if (_scoutCommand == MacroCommandType::ScoutLocation)
{
more = "location";
}
else if (_scoutCommand == MacroCommandType::ScoutOnceOnly)
{
more = "once around";
}
else if (_scoutCommand == MacroCommandType::ScoutWhileSafe)
{
more = "while safe";
}
else if (wantGasSteal())
{
more = "to steal gas";
}
// NOTE "go scout if needed" doesn't need to be represented here.
BWAPI::Broodwar->drawTextScreen(x, y + 20, "Go scout: %s", more.c_str());
if (_workerScout && _nextDestination.isValid())
{
BWAPI::Broodwar->drawLineMap(_workerScout->getPosition(), _nextDestination, BWAPI::Colors::Green);
}
}
// Move the worker scout.
void ScoutManager::moveGroundScout()
{
const int scoutDistanceThreshold = 30; // in tiles
if (_workerScoutTarget.isValid())
{
// The target is valid exactly when we are still looking for the enemy base.
_scoutStatus = "Seeking enemy base";
the.micro.MoveSafely(_workerScout, BWAPI::Position(_workerScoutTarget));
}
else
{
const Base * enemyBase = the.bases.enemyStart();
UAB_ASSERT(enemyBase, "no enemy base");
int scoutDistanceToEnemy = the.map.getGroundTileDistance(_workerScout->getPosition(), enemyBase->getCenter());
bool scoutInRangeOfenemy = scoutDistanceToEnemy <= scoutDistanceThreshold;
int scoutHP = _workerScout->getHitPoints() + _workerScout->getShields();
if (scoutHP < _previousScoutHP)
{
_scoutUnderAttack = true;
}
_previousScoutHP = scoutHP;
if (!_workerScout->isUnderAttack() && !enemyWorkerInRadius())
{
_scoutUnderAttack = false;
}
if (scoutInRangeOfenemy)
{
if (_scoutUnderAttack)
{
_scoutStatus = "Under attack, fleeing";
followGroundPath();
}
else
{
BWAPI::Unit closestWorker = enemyWorkerToHarass();
// If configured and reasonable, harass an enemy worker.
if (Config::Skills::ScoutHarassEnemy && closestWorker &&
!wantGasSteal() &&
_workerScout->getHitPoints() + _workerScout->getShields() > 20)
{
_scoutStatus = "Harass enemy worker";
the.micro.CatchAndAttackUnit(_workerScout, closestWorker);
}
// otherwise keep circling the enemy region
else
{
_scoutStatus = "Following perimeter";
followGroundPath();
}
}
}
// if the scout is not in the enemy region
else if (_scoutUnderAttack)
{
_scoutStatus = "Under attack, fleeing";
followGroundPath();
}
else
{
_scoutStatus = "Enemy located, going there";
followGroundPath();
}
}
}
// Explore inside the enemy base. Or, if not there yet, move toward it.
// NOTE This may release the worker scout if scouting is complete!
void ScoutManager::followGroundPath()
{
// Called only after the enemy base is found.
Base * enemyBase = the.bases.enemyStart();
if (the.zone.at(enemyBase->getTilePosition()) != the.zone.at(_workerScout->getTilePosition()))
{
// We're not there yet. Go there.
the.micro.MoveSafely(_workerScout, enemyBase->getCenter());
return;
}
// NOTE Sight range of a worker is 224, except a probe which has 256.
if (_nextDestination.isValid() && _workerScout->getDistance(_nextDestination) > 96)
{
// We're still a fair distance from the next waypoint. Stay the course.
if (Config::Debug::DrawScoutInfo)
{
BWAPI::Broodwar->drawCircleMap(_nextDestination, 3, BWAPI::Colors::Yellow, true);
BWAPI::Broodwar->drawLineMap(_workerScout->getPosition(), _nextDestination, BWAPI::Colors::Yellow);
}
the.micro.MoveSafely(_workerScout, _nextDestination);
return;
}
// We're at the enemy base and need another waypoint.
BWAPI::Position destination = the.grid.getLeastExploredNear(enemyBase->getPosition(), true);
if (destination.isValid())
{
_nextDestination = destination;
if (_scoutCommand == MacroCommandType::ScoutOnceOnly && !wantGasSteal())
{
if (BWAPI::Broodwar->isExplored(BWAPI::TilePosition(_nextDestination)))
{
releaseWorkerScout();
return;
}
}
}
else
{
_nextDestination = enemyBase->getCenter();
}
the.micro.MoveSafely(_workerScout, _nextDestination);
}
// Move the overlord scout.
void ScoutManager::moveAirScout()
{
const Base * enemyBase = the.bases.enemyStart();
if (enemyBase)
{
// We know where the enemy base is.
_overlordScoutTarget = BWAPI::TilePositions::Invalid; // it's only set while we are seeking the enemy base
if (!_overlordAtEnemyBase)
{
if (!_workerScout)
{
_scoutStatus = "Overlord to enemy base";
}
the.micro.MoveSafely(_overlordScout, enemyBase->getCenter());
if (_overlordScout->getDistance(enemyBase->getCenter()) < 8)
{
_overlordAtEnemyBase = true;
}
}
if (_overlordAtEnemyBase)
{
if (!_workerScout)
{
_scoutStatus = "Overlord at enemy base";
}
moveAirScoutAroundEnemyBase();
}
}
else
{
// We haven't found the enemy base yet.
if (!_workerScout) // give the worker priority in reporting status
{
_scoutStatus = "Overlord scouting";
}
if (_overlordScoutTarget.isValid())
{
the.micro.MoveSafely(_overlordScout, BWAPI::Position(_overlordScoutTarget));
}
}
}
// Called after the overlord has reached the enemy resource depot,
// or has been turned away from it by static defense.
void ScoutManager::moveAirScoutAroundEnemyBase()
{
const Base * enemyBase = the.bases.enemyStart();
//UAB_ASSERT(enemyBase, "no enemy base");
//UAB_ASSERT(_overlordAtEnemyBase, "not at enemy base");
if (!_overlordAtBaseTarget.isValid())
{
// Choose a new destination in or near the enemy base.
if (_overlordScout->getDistance(enemyBase->getCenter()) < 8)
{
// We're at the enemy resource depot. Choose somewhere else.
if (enemyBase->getNatural() && !enemyBase->getNatural()->isExplored())
{
enemyBase->getNatural()->getCenter();
}
else
{
_overlordAtBaseTarget = the.grid.getLeastExploredNear(enemyBase->getPosition(), false);
}
}
else
{
// We're somewhere else. Go back to the enemy resource depot.
_overlordAtBaseTarget = enemyBase->getCenter();
}
}
if (_overlordAtBaseTarget.isValid())
{
the.micro.MoveSafely(_overlordScout, _overlordAtBaseTarget);
// If we arrived, choose somewhere else next time.
if (_overlordScout->getDistance(_overlordAtBaseTarget) < 8)
{
_overlordAtBaseTarget = BWAPI::Positions::Invalid;
}
}
else
{
// We apparently can't go anywhere. Let the overlord run free.
releaseOverlordScout();
}
}
// Called only when a gas steal is requested.
// Return true to say that gas stealing controls the worker, and
// false if the caller gets control.
bool ScoutManager::gasSteal()
{
Base * enemyBase = the.bases.enemyStart();
if (!enemyBase)
{
_gasStealStatus = "Enemy base not found";
return false;
}
_enemyGeyser = getTheEnemyGeyser();
if (!_enemyGeyser || !_enemyGeyser->getInitialTilePosition().isValid())
{
// No need to set status. It will change on the next frame.
_gasStealOver = true;
return false;
}
// The conditions are met. Do it!
_startedGasSteal = true;
if (_enemyGeyser->isVisible() && _enemyGeyser->getType() != BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
// We can see the geyser and it has become something else.
// That should mean that the geyser has been taken since we first saw it.
_gasStealOver = true; // give up
// No need to set status. It will change on the next frame.
return false;
}
else if (_enemyGeyser->isVisible() && _workerScout->getDistance(_enemyGeyser) < 300)
{
// We see the geyser. Queue the refinery, if it's not already done.
// We can't rely on _queuedGasSteal to know, because the queue may be cleared
// if a surprise occurs.
// Therefore _queuedGasSteal affects mainly the debug display for the UI.
if (!ProductionManager::Instance().isGasStealInQueue())
{
// NOTE Queueing the gas steal orders the building constructed.
// Control of the worker passes to the BuildingManager until it releases the
// worker with a call to setGasStealOver().
ProductionManager::Instance().queueGasSteal();
_queuedGasSteal = true;
// Regardless, make sure we are moving toward the geyser.
// It makes life easier on the building manager.
the.micro.Move(_workerScout, _enemyGeyser->getInitialPosition());
}
_gasStealStatus = "Stealing gas";
}
else
{
// We don't see the geyser yet. Move toward it.
the.micro.MoveSafely(_workerScout, _enemyGeyser->getInitialPosition());
_gasStealStatus = "Moving to steal gas";
}
return true;
}
// Choose an enemy worker to harass, or none.
BWAPI::Unit ScoutManager::enemyWorkerToHarass() const
{
// First look for any enemy worker that is building.
for (BWAPI::Unit unit : the.enemy()->getUnits())
{
if (unit->getType().isWorker() && unit->isConstructing())
{
return unit;
}
}
BWAPI::Unit enemyWorker = nullptr;
int maxDist = 500; // ignore any beyond this range
// Failing that, find the enemy worker closest to the gas.
BWAPI::Unit geyser = getAnyEnemyGeyser();
if (geyser)
{
for (BWAPI::Unit unit : the.enemy()->getUnits())
{
if (unit->getType().isWorker())
{
int dist = unit->getDistance(geyser->getInitialPosition());
if (dist < maxDist)
{
maxDist = dist;
enemyWorker = unit;
}
}
}
}
return enemyWorker;
}
// Used in choosing an enemy worker to harass.
// Find an enemy geyser and return it, if there is one.
BWAPI::Unit ScoutManager::getAnyEnemyGeyser() const
{
Base * enemyBase = the.bases.enemyStart();
BWAPI::Unitset geysers = enemyBase->getGeysers();
if (geysers.size() > 0)
{
return *(geysers.begin());
}
return nullptr;
}
// Used in stealing gas. Only called after the enemy base is found.
// If there is exactly 1 geyser in the enemy base and it may be untaken, return it.
// If 0 we can't steal it, and if >1 then it's no use to steal one.
BWAPI::Unit ScoutManager::getTheEnemyGeyser() const
{
Base * enemyBase = the.bases.enemyStart();
BWAPI::Unitset geysers = enemyBase->getGeysers();
if (geysers.size() == 1)
{
BWAPI::Unit geyser = *(geysers.begin());
// If the geyser is visible, we may be able to reject it as already taken.
// TODO get the last known status from the.info.isGeyserTaken()
if (!geyser->isVisible() || geyser->getType() == BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
// We see it is untaken, or we don't see the geyser. Assume the best.
return geyser;
}
}
return nullptr;
}
// Is a friendly combat unit nearby?
bool ScoutManager::friendlyUnitNear(BWAPI::Unit unit) const
{
return
BWAPI::Broodwar->getClosestUnit(
unit->getPosition(),
BWAPI::Filter::CanAttack && BWAPI::Filter::GetPlayer == the.self() && !BWAPI::Filter::IsWorker,
6 * 32
) != nullptr;
}
bool ScoutManager::enemyWorkerInRadius()
{
for (BWAPI::Unit unit : the.enemy()->getUnits())
{
if (unit->getType().isWorker() && unit->getDistance(_workerScout) < 300)
{
return true;
}
}
return false;
}
| 28.4367 | 113 | 0.656045 | kant2002 |
f83956db74d79cb7106e8f6c9cfb6716adfaaea0 | 987 | hpp | C++ | src/PlaylistsPage/PlaylistsPage.hpp | AlexeyGurevsky/bbtube | d7329b52cec08cdc80c521e8f3d4f5de746639e7 | [
"Apache-2.0"
] | 15 | 2020-07-13T03:51:10.000Z | 2022-03-16T13:56:28.000Z | src/PlaylistsPage/PlaylistsPage.hpp | AlexeyGurevsky/bbtube | d7329b52cec08cdc80c521e8f3d4f5de746639e7 | [
"Apache-2.0"
] | 2 | 2021-01-07T20:31:29.000Z | 2021-12-15T21:20:34.000Z | src/PlaylistsPage/PlaylistsPage.hpp | AlexeyGurevsky/bbtube | d7329b52cec08cdc80c521e8f3d4f5de746639e7 | [
"Apache-2.0"
] | 4 | 2020-08-15T01:52:31.000Z | 2022-03-16T13:56:30.000Z | #ifndef PlaylistsPage_HPP_
#define PlaylistsPage_HPP_
#include "src/utils/BasePage.hpp"
#include "src/parser/models/StorageData.hpp"
#include "src/parser/models/VideoMetadata.hpp"
#include "src/models/PlaylistVideoModel.hpp"
#include "src/models/PlaylistListItemModel.hpp"
#include <bb/cascades/Page>
#include <bb/cascades/ListView>
#include <bb/cascades/NavigationPane>
#include <QVariantList>
class PlaylistsPage: public BasePage
{
Q_OBJECT
private slots:
void onPlaylistsListItemClick(QVariantList indexPath);
void onPlaylistVideoAdded(PlaylistVideoModel* video);
void onPlaylistVideoDeleted(QString videoId, PlaylistListItemModel::Type playlistType);
void onPlaylistVideoDeletedAll(PlaylistListItemModel::Type playlistType);
private:
bb::cascades::ListView *playlistsList;
public:
PlaylistsPage(bb::cascades::NavigationPane *navigationPane);
virtual ~PlaylistsPage()
{
}
void playVideo(QString videoId);
};
#endif /* PlaylistsPage_HPP_ */
| 29.029412 | 91 | 0.787234 | AlexeyGurevsky |
f8414574671acb0dd73638b76e08400db7c9e0da | 2,224 | cpp | C++ | source/Tokens.cpp | KaloyanKaludov/Element | fbe675301d04f0a62497d8f05e7bcbaeba72d102 | [
"MIT"
] | 1 | 2016-05-15T21:17:26.000Z | 2016-05-15T21:17:26.000Z | source/Tokens.cpp | KaloyanKaludov/Element | fbe675301d04f0a62497d8f05e7bcbaeba72d102 | [
"MIT"
] | 1 | 2016-05-19T12:39:58.000Z | 2016-09-19T07:37:50.000Z | source/Tokens.cpp | KaloyanKaludov/Element | fbe675301d04f0a62497d8f05e7bcbaeba72d102 | [
"MIT"
] | null | null | null | #include "Tokens.h"
namespace element
{
const char* TokenAsString(Token token)
{
switch(token)
{
case T_EOF: return "EOF";
case T_NewLine: return "\\n";
case T_Identifier: return "identifier";
case T_Integer: return "integer";
case T_Float: return "float";
case T_String: return "string";
case T_Bool: return "bool";
case T_If: return "if";
case T_Else: return "else";
case T_Elif: return "elif";
case T_For: return "for";
case T_In: return "in";
case T_While: return "while";
case T_This: return "this";
case T_Nil: return "nil";
case T_Return: return "return";
case T_Break: return "break";
case T_Continue: return "continue";
case T_Yield: return "yield ";
case T_And: return "and";
case T_Or: return "or";
case T_Xor: return "xor";
case T_Not: return "not";
case T_SizeOf: return "#";
case T_Underscore: return "_";
case T_LeftParent: return "(";
case T_RightParent: return ")";
case T_LeftBrace: return "{";
case T_RightBrace: return "}";
case T_LeftBracket: return "[";
case T_RightBracket: return "]";
case T_Column: return ":";
case T_Semicolumn: return ";";
case T_Comma: return ",";
case T_Dot: return ".";
case T_Add: return "+";
case T_Subtract: return "-";
case T_Divide: return "/";
case T_Multiply: return "*";
case T_Power: return "^";
case T_Modulo: return "%%";
case T_Concatenate: return "~";
case T_AssignAdd: return "+=";
case T_AssignSubtract: return "-=";
case T_AssignDivide: return "/=";
case T_AssignMultiply: return "*=";
case T_AssignPower: return "^=";
case T_AssignModulo: return "%%=";
case T_AssignConcatenate: return "~=";
case T_Assignment: return "=";
case T_Equal: return "==";
case T_NotEqual: return "!=";
case T_Less: return "<";
case T_Greater: return ">";
case T_LessEqual: return "<=";
case T_GreaterEqual: return ">=";
case T_Argument: return "$N";
case T_ArgumentList: return "$$";
case T_Arrow: return "->";
case T_ArrayPushBack: return "<<";
case T_ArrayPopBack: return ">>";
default:
case T_InvalidToken: return "InvalidToken";
}
}
}
| 23.659574 | 45 | 0.627698 | KaloyanKaludov |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.